Skip to content

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

feat(mobile): offline reading (#2957)

Mohamed Bassem2075c33a7f81
diff --git a/apps/mobile/app/dashboard/(tabs)/(highlights)/index.tsx b/apps/mobile/app/dashboard/(tabs)/(highlights)/index.tsx
index 48a190c1..21b94f03 100644
--- a/apps/mobile/app/dashboard/(tabs)/(highlights)/index.tsx
+++ b/apps/mobile/app/dashboard/(tabs)/(highlights)/index.tsx
@@ -1,6 +1,5 @@
-import FullPageError from "@/components/FullPageError";
import HighlightList from "@/components/highlights/HighlightList";
-import FullPageSpinner from "@/components/ui/FullPageSpinner";
+import QueryPageState from "@/components/QueryPageState";
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { useTRPC } from "@karakeep/shared-react/trpc";
@@ -26,12 +25,8 @@ export default function Highlights() {
),
);
- if (error) {
- return <FullPageError error={error.message} onRetry={() => refetch()} />;
- }
-
- if (isPending || !data) {
- return <FullPageSpinner />;
+ if (!data) {
+ return <QueryPageState error={error} onRetry={() => refetch()} />;
}
const onRefresh = () => {
diff --git a/apps/mobile/app/dashboard/(tabs)/(lists)/index.tsx b/apps/mobile/app/dashboard/(tabs)/(lists)/index.tsx
index 4e28b146..db6af022 100644
--- a/apps/mobile/app/dashboard/(tabs)/(lists)/index.tsx
+++ b/apps/mobile/app/dashboard/(tabs)/(lists)/index.tsx
@@ -8,10 +8,9 @@ import {
} from "react-native";
import * as Haptics from "expo-haptics";
import { Link, router } from "expo-router";
-import FullPageError from "@/components/FullPageError";
+import QueryPageState from "@/components/QueryPageState";
import ChevronRight from "@/components/ui/ChevronRight";
import { FAB } from "@/components/ui/FAB";
-import FullPageSpinner from "@/components/ui/FullPageSpinner";
import { Text } from "@/components/ui/Text";
import { useColorScheme } from "@/lib/useColorScheme";
import { condProps } from "@/lib/utils";
@@ -100,12 +99,8 @@ export default function Lists() {
setRefreshing(isPending);
}, [isPending]);
- if (error) {
- return <FullPageError error={error.message} onRetry={() => refetch()} />;
- }
-
if (!lists) {
- return <FullPageSpinner />;
+ return <QueryPageState error={error} onRetry={() => refetch()} />;
}
const onRefresh = () => {
diff --git a/apps/mobile/app/dashboard/(tabs)/(tags)/index.tsx b/apps/mobile/app/dashboard/(tabs)/(tags)/index.tsx
index c0162263..01a232cf 100644
--- a/apps/mobile/app/dashboard/(tabs)/(tags)/index.tsx
+++ b/apps/mobile/app/dashboard/(tabs)/(tags)/index.tsx
@@ -1,10 +1,9 @@
import { useEffect, useState } from "react";
import { FlatList, Pressable, View } from "react-native";
import { Link } from "expo-router";
-import FullPageError from "@/components/FullPageError";
+import QueryPageState from "@/components/QueryPageState";
import ChevronRight from "@/components/ui/ChevronRight";
import EmptyState from "@/components/ui/EmptyState";
-import FullPageSpinner from "@/components/ui/FullPageSpinner";
import { SearchInput } from "@/components/ui/SearchInput";
import { Text } from "@/components/ui/Text";
import { useQueryClient } from "@tanstack/react-query";
@@ -49,12 +48,8 @@ export default function Tags() {
setRefreshing(isPending);
}, [isPending]);
- if (error) {
- return <FullPageError error={error.message} onRetry={() => refetch()} />;
- }
-
if (!data) {
- return <FullPageSpinner />;
+ return <QueryPageState error={error} onRetry={() => refetch()} />;
}
const onRefresh = () => {
diff --git a/apps/mobile/app/dashboard/_layout.tsx b/apps/mobile/app/dashboard/_layout.tsx
index ea52aa9d..bb6e060f 100644
--- a/apps/mobile/app/dashboard/_layout.tsx
+++ b/apps/mobile/app/dashboard/_layout.tsx
@@ -212,6 +212,14 @@ export default function Dashboard() {
headerBackTitle: "Back",
}}
/>
+ <Stack.Screen
+ name="settings/offline"
+ options={{
+ title: "Offline Content",
+ headerTitle: "Offline Content",
+ headerBackTitle: "Back",
+ }}
+ />
<Stack.Screen
name="settings/toolbar-settings"
options={{
diff --git a/apps/mobile/app/dashboard/bookmarks/[slug]/highlights.tsx b/apps/mobile/app/dashboard/bookmarks/[slug]/highlights.tsx
index 6a01e110..e28f2e2d 100644
--- a/apps/mobile/app/dashboard/bookmarks/[slug]/highlights.tsx
+++ b/apps/mobile/app/dashboard/bookmarks/[slug]/highlights.tsx
@@ -1,6 +1,5 @@
-import FullPageError from "@/components/FullPageError";
import HighlightList from "@/components/highlights/HighlightList";
-import FullPageSpinner from "@/components/ui/FullPageSpinner";
+import QueryPageState from "@/components/QueryPageState";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useLocalSearchParams } from "expo-router";
@@ -21,12 +20,8 @@ export default function BookmarkHighlightsPage() {
}),
);
- if (error) {
- return <FullPageError error={error.message} onRetry={() => refetch()} />;
- }
-
- if (isPending || !data) {
- return <FullPageSpinner />;
+ if (!data) {
+ return <QueryPageState error={error} onRetry={() => refetch()} />;
}
const onRefresh = () => {
diff --git a/apps/mobile/app/dashboard/bookmarks/[slug]/index.tsx b/apps/mobile/app/dashboard/bookmarks/[slug]/index.tsx
index a9b3cc7f..128e5276 100644
--- a/apps/mobile/app/dashboard/bookmarks/[slug]/index.tsx
+++ b/apps/mobile/app/dashboard/bookmarks/[slug]/index.tsx
@@ -9,10 +9,14 @@ import BookmarkLinkTypeSelector, {
import BookmarkLinkView from "@/components/bookmarks/BookmarkLinkView";
import BookmarkTextView from "@/components/bookmarks/BookmarkTextView";
import BottomActions from "@/components/bookmarks/BottomActions";
-import FullPageError from "@/components/FullPageError";
-import FullPageSpinner from "@/components/ui/FullPageSpinner";
+import QueryPageState from "@/components/QueryPageState";
import { shouldUseGlassPill } from "@/lib/ios";
+import {
+ getOfflineLibraryScope,
+ useOfflineArticle,
+} from "@/lib/offlineLibrary";
import useAppSettings from "@/lib/settings";
+import { useConnectionStatus } from "@/lib/useConnectionStatus";
import { useQuery } from "@tanstack/react-query";
import { Settings } from "lucide-react-native";
import { useColorScheme } from "nativewind";
@@ -32,6 +36,7 @@ export default function BookmarkView() {
const { colorScheme } = useColorScheme();
const isDark = colorScheme === "dark";
const { settings } = useAppSettings();
+ const connectionStatus = useConnectionStatus();
const api = useTRPC();
const [bookmarkLinkType, setBookmarkLinkType] = useState<BookmarkLinkType>(
@@ -44,6 +49,11 @@ export default function BookmarkView() {
throw new Error("Unexpected param type");
}
+ const offlineArticle = useOfflineArticle(
+ getOfflineLibraryScope(settings),
+ slug,
+ );
+
const {
data: bookmark,
error,
@@ -63,34 +73,36 @@ export default function BookmarkView() {
},
),
);
+ const displayedBookmark = bookmark ?? offlineArticle?.bookmark;
+ const isOffline =
+ connectionStatus === "device-offline" ||
+ connectionStatus === "server-unreachable";
+ const displayedBookmarkLinkType: BookmarkLinkType =
+ isOffline && offlineArticle ? "reader" : bookmarkLinkType;
- if (error) {
- return <FullPageError error={error.message} onRetry={refetch} />;
- }
-
- if (!bookmark) {
- return <FullPageSpinner />;
+ if (!displayedBookmark) {
+ return <QueryPageState error={error} onRetry={refetch} />;
}
let comp;
let title = null;
- switch (bookmark.content.type) {
+ switch (displayedBookmark.content.type) {
case BookmarkTypes.LINK:
- title = bookmark.title ?? bookmark.content.title;
+ title = displayedBookmark.title ?? displayedBookmark.content.title;
comp = (
<BookmarkLinkView
- bookmark={bookmark}
- bookmarkPreviewType={bookmarkLinkType}
+ bookmark={displayedBookmark}
+ bookmarkPreviewType={displayedBookmarkLinkType}
/>
);
break;
case BookmarkTypes.TEXT:
- title = bookmark.title;
- comp = <BookmarkTextView bookmark={bookmark} />;
+ title = displayedBookmark.title;
+ comp = <BookmarkTextView bookmark={displayedBookmark} />;
break;
case BookmarkTypes.ASSET:
- title = bookmark.title ?? bookmark.content.fileName;
- comp = <BookmarkAssetView bookmark={bookmark} />;
+ title = displayedBookmark.title ?? displayedBookmark.content.fileName;
+ comp = <BookmarkAssetView bookmark={displayedBookmark} />;
break;
}
return (
@@ -112,11 +124,11 @@ export default function BookmarkView() {
},
headerTintColor: isDark ? "#fff" : "#000",
headerRight: () =>
- bookmark.content.type === BookmarkTypes.LINK ? (
+ displayedBookmark.content.type === BookmarkTypes.LINK ? (
<View
className={`flex-row items-center gap-3${shouldUseGlassPill ? " px-2" : ""}`}
>
- {bookmarkLinkType === "reader" && (
+ {displayedBookmarkLinkType === "reader" && (
<Pressable
onPress={() =>
router.push("/dashboard/settings/reader-settings")
@@ -126,9 +138,9 @@ export default function BookmarkView() {
</Pressable>
)}
<BookmarkLinkTypeSelector
- type={bookmarkLinkType}
+ type={displayedBookmarkLinkType}
onChange={(type) => setBookmarkLinkType(type)}
- bookmark={bookmark}
+ bookmark={displayedBookmark}
/>
</View>
) : undefined,
@@ -137,10 +149,10 @@ export default function BookmarkView() {
{comp}
{shouldUseGlassPill ? (
<View style={{ position: "absolute", left: 0, right: 0, bottom: 0 }}>
- <BottomActions bookmark={bookmark} />
+ <BottomActions bookmark={displayedBookmark} />
</View>
) : (
- <BottomActions bookmark={bookmark} />
+ <BottomActions bookmark={displayedBookmark} />
)}
</KeyboardAvoidingView>
);
diff --git a/apps/mobile/app/dashboard/bookmarks/[slug]/info.tsx b/apps/mobile/app/dashboard/bookmarks/[slug]/info.tsx
index ff63c4a3..f0e8b5d6 100644
--- a/apps/mobile/app/dashboard/bookmarks/[slug]/info.tsx
+++ b/apps/mobile/app/dashboard/bookmarks/[slug]/info.tsx
@@ -15,9 +15,8 @@ import * as Haptics from "expo-haptics";
import { router, Stack, useLocalSearchParams } from "expo-router";
import BookmarkTextMarkdown from "@/components/bookmarks/BookmarkTextMarkdown";
import TagPill from "@/components/bookmarks/TagPill";
-import FullPageError from "@/components/FullPageError";
+import QueryPageState from "@/components/QueryPageState";
import ChevronRight from "@/components/ui/ChevronRight";
-import FullPageSpinner from "@/components/ui/FullPageSpinner";
import {
GroupedSection,
NavigationRow,
@@ -471,7 +470,7 @@ const ViewBookmarkPage = () => {
const {
data: bookmark,
- isPending,
+ error,
refetch,
} = useAutoRefreshingBookmarkQuery({
bookmarkId: slug,
@@ -495,14 +494,8 @@ const ViewBookmarkPage = () => {
}
};
- if (isPending) {
- return <FullPageSpinner />;
- }
-
if (!bookmark) {
- return (
- <FullPageError error="Bookmark not found" onRetry={() => refetch()} />
- );
+ return <QueryPageState error={error} onRetry={() => refetch()} />;
}
const handleDeleteBookmark = () => {
diff --git a/apps/mobile/app/dashboard/bookmarks/[slug]/manage_lists.tsx b/apps/mobile/app/dashboard/bookmarks/[slug]/manage_lists.tsx
index 51a16b77..3a55eea3 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 React from "react";
import { ActivityIndicator, Pressable, ScrollView, View } from "react-native";
import { Stack, useLocalSearchParams } from "expo-router";
+import QueryPageState from "@/components/QueryPageState";
import { RowSeparator } from "@/components/ui/GroupedList";
import { Text } from "@/components/ui/Text";
import { useToast } from "@/components/ui/Toast";
@@ -36,7 +37,11 @@ const ListPickerPage = () => {
});
};
- const { data: existingLists } = useQuery(
+ const {
+ data: existingLists,
+ error: existingListsError,
+ refetch: refetchExistingLists,
+ } = useQuery(
api.lists.getListsOfBookmark.queryOptions(
{ bookmarkId },
{
@@ -46,7 +51,7 @@ const ListPickerPage = () => {
),
);
- const { data } = useBookmarkLists();
+ const { data, error: listsError, refetch: refetchLists } = useBookmarkLists();
const {
mutate: addToList,
@@ -85,6 +90,18 @@ const ListPickerPage = () => {
?.filter((path) => path[path.length - 1].userRole !== "viewer")
.filter((path) => path[path.length - 1].type !== "smart");
+ if (!existingLists || !data) {
+ return (
+ <QueryPageState
+ error={existingListsError ?? listsError}
+ onRetry={() => {
+ void refetchExistingLists();
+ void refetchLists();
+ }}
+ />
+ );
+ }
+
return (
<>
<Stack.Screen
diff --git a/apps/mobile/app/dashboard/bookmarks/[slug]/manage_tags.tsx b/apps/mobile/app/dashboard/bookmarks/[slug]/manage_tags.tsx
index 7c0f255b..0e215980 100644
--- a/apps/mobile/app/dashboard/bookmarks/[slug]/manage_tags.tsx
+++ b/apps/mobile/app/dashboard/bookmarks/[slug]/manage_tags.tsx
@@ -1,7 +1,7 @@
import React, { useMemo } from "react";
import { Pressable, ScrollView, View } from "react-native";
import { Stack, useLocalSearchParams } from "expo-router";
-import FullPageSpinner from "@/components/ui/FullPageSpinner";
+import QueryPageState from "@/components/QueryPageState";
import { useTagAutocomplete } from "@karakeep/shared-react/hooks/tags";
import { GroupedSection, RowSeparator } from "@/components/ui/GroupedList";
import { Text } from "@/components/ui/Text";
@@ -39,7 +39,11 @@ const TagPickerPage = () => {
const searchQueryDebounced = useDebounce(search, 200);
- const { data: allTags, isLoading: isAllTagsPending } = useTagAutocomplete({
+ const {
+ data: allTags,
+ error: tagsError,
+ refetch: refetchTags,
+ } = useTagAutocomplete({
nameContains: searchQueryDebounced,
select: (data) =>
data.tags.map((tag) => ({
@@ -49,7 +53,11 @@ const TagPickerPage = () => {
})),
});
- const { data: bookmark } = useAutoRefreshingBookmarkQuery({
+ const {
+ data: bookmark,
+ error: bookmarkError,
+ refetch: refetchBookmark,
+ } = useAutoRefreshingBookmarkQuery({
bookmarkId,
});
const existingTags = bookmark?.tags;
@@ -177,8 +185,16 @@ const TagPickerPage = () => {
});
};
- if (isAllTagsPending) {
- return <FullPageSpinner />;
+ if (!allTags || !bookmark) {
+ return (
+ <QueryPageState
+ error={tagsError ?? bookmarkError}
+ onRetry={() => {
+ void refetchTags();
+ void refetchBookmark();
+ }}
+ />
+ );
}
return (
diff --git a/apps/mobile/app/dashboard/lists/[slug]/edit.tsx b/apps/mobile/app/dashboard/lists/[slug]/edit.tsx
index 449e03f2..01a431bb 100644
--- a/apps/mobile/app/dashboard/lists/[slug]/edit.tsx
+++ b/apps/mobile/app/dashboard/lists/[slug]/edit.tsx
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import { View } from "react-native";
import { router, useLocalSearchParams } from "expo-router";
+import QueryPageState from "@/components/QueryPageState";
import { Button } from "@/components/ui/Button";
import FullPageSpinner from "@/components/ui/FullPageSpinner";
import { Input } from "@/components/ui/Input";
@@ -42,7 +43,11 @@ const EditListPage = () => {
throw new Error("Unexpected param type");
}
- const { data: list, isLoading: fetchIsPending } = useQuery(
+ const {
+ data: list,
+ error,
+ refetch,
+ } = useQuery(
api.lists.get.queryOptions({
listId,
}),
@@ -79,11 +84,13 @@ const EditListPage = () => {
});
};
- const isPending = fetchIsPending || editIsPending;
+ if (!list) {
+ return <QueryPageState error={error} onRetry={() => refetch()} />;
+ }
return (
<>
- {isPending ? (
+ {editIsPending ? (
<FullPageSpinner />
) : (
<View className="gap-3 px-4">
@@ -143,7 +150,7 @@ const EditListPage = () => {
</View>
)}
- <Button disabled={isPending} onPress={onSubmit}>
+ <Button disabled={editIsPending} onPress={onSubmit}>
<Text>Save</Text>
</Button>
</View>
diff --git a/apps/mobile/app/dashboard/lists/[slug]/index.tsx b/apps/mobile/app/dashboard/lists/[slug]/index.tsx
index 0ddad6eb..a37cb1ee 100644
--- a/apps/mobile/app/dashboard/lists/[slug]/index.tsx
+++ b/apps/mobile/app/dashboard/lists/[slug]/index.tsx
@@ -3,7 +3,7 @@ import * as Haptics from "expo-haptics";
import { router, Stack, useLocalSearchParams } from "expo-router";
import { useBookmarkListLayoutMenu } from "@/components/bookmarks/BookmarkListHeader";
import UpdatingBookmarkList from "@/components/bookmarks/UpdatingBookmarkList";
-import FullPageError from "@/components/FullPageError";
+import QueryPageState from "@/components/QueryPageState";
import FullPageSpinner from "@/components/ui/FullPageSpinner";
import { useArchiveFilter } from "@/lib/hooks";
import { useColorScheme } from "@/lib/useColorScheme";
@@ -39,9 +39,9 @@ export default function ListView() {
),
}}
/>
- {error ? (
- <FullPageError error={error.message} onRetry={() => refetch()} />
- ) : list && !isSettingsLoading ? (
+ {!list ? (
+ <QueryPageState error={error} onRetry={() => refetch()} />
+ ) : !isSettingsLoading ? (
<UpdatingBookmarkList
query={{
listId: list.id,
diff --git a/apps/mobile/app/dashboard/settings/index.tsx b/apps/mobile/app/dashboard/settings/index.tsx
index b151e89b..7a707c88 100644
--- a/apps/mobile/app/dashboard/settings/index.tsx
+++ b/apps/mobile/app/dashboard/settings/index.tsx
@@ -18,6 +18,10 @@ import ChevronRight from "@/components/ui/ChevronRight";
import { Divider } from "@/components/ui/Divider";
import { Text } from "@/components/ui/Text";
import { useServerVersion } from "@/lib/hooks";
+import {
+ getOfflineLibraryScope,
+ useOfflineLibrary,
+} from "@/lib/offlineLibrary";
import { useSession } from "@/lib/session";
import useAppSettings from "@/lib/settings";
import { useMutation, useQuery } from "@tanstack/react-query";
@@ -41,6 +45,7 @@ export default function Settings() {
isLoading: isSettingsLoading,
} = useAppSettings();
const api = useTRPC();
+ const offlineLibrary = useOfflineLibrary(getOfflineLibraryScope(settings));
const [imageQuality, setImageQuality] = useState<number | null>(null);
@@ -238,6 +243,20 @@ export default function Settings() {
}}
/>
</View>
+ <Divider orientation="horizontal" className="mx-6 my-1" />
+ <View className="flex flex-row items-center justify-between gap-8 px-4 py-1">
+ <Link asChild href="/dashboard/settings/offline" className="flex-1">
+ <Pressable className="flex flex-row items-center">
+ <Text className="mr-2 flex-1" numberOfLines={1}>
+ Offline content
+ </Text>
+ <Text className="mr-1 text-muted-foreground">
+ {offlineLibrary.length}
+ </Text>
+ <ChevronRight />
+ </Pressable>
+ </Link>
+ </View>
</View>
<SectionHeader title="Media" />
diff --git a/apps/mobile/app/dashboard/settings/offline.tsx b/apps/mobile/app/dashboard/settings/offline.tsx
new file mode 100644
index 00000000..1e30479d
--- /dev/null
+++ b/apps/mobile/app/dashboard/settings/offline.tsx
@@ -0,0 +1,179 @@
+import { useEffect } from "react";
+import { Alert, Pressable, ScrollView, View } from "react-native";
+import { useRouter } from "expo-router";
+import { useHeaderHeight } from "expo-router/react-navigation";
+import EmptyState from "@/components/ui/EmptyState";
+import { Divider } from "@/components/ui/Divider";
+import { Text } from "@/components/ui/Text";
+import { useToast } from "@/components/ui/Toast";
+import { clearPersistedCache } from "@/lib/offlineCache";
+import {
+ getOfflineLibraryScope,
+ reconcileOfflineLibrary,
+ removeAllOfflineArticles,
+ removeOfflineArticle,
+ useOfflineLibrary,
+} from "@/lib/offlineLibrary";
+import useAppSettings from "@/lib/settings";
+import { useColorScheme } from "@/lib/useColorScheme";
+import { useQueryClient } from "@tanstack/react-query";
+import { formatDistanceToNow } from "date-fns";
+import { BookOpen, Trash2 } from "lucide-react-native";
+
+export default function OfflineContent() {
+ const router = useRouter();
+ const headerHeight = useHeaderHeight();
+ const queryClient = useQueryClient();
+ const { toast } = useToast();
+ const { settings } = useAppSettings();
+ const { colors } = useColorScheme();
+ const scope = getOfflineLibraryScope(settings);
+ const offlineLibrary = useOfflineLibrary(scope);
+
+ 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 confirmRemoveAll = () => {
+ Alert.alert(
+ "Remove all offline content?",
+ "This removes every article you explicitly saved for offline reading.",
+ [
+ { text: "Cancel", style: "cancel" },
+ {
+ text: "Remove All",
+ style: "destructive",
+ onPress: () => removeAllOfflineArticles(scope),
+ },
+ ],
+ );
+ };
+
+ const confirmClearRecentCache = () => {
+ Alert.alert(
+ "Clear recent cache?",
+ "Saved offline articles will be kept. Anything else will be re-cached as you browse.",
+ [
+ { text: "Cancel", style: "cancel" },
+ {
+ text: "Clear Cache",
+ style: "destructive",
+ onPress: () => {
+ queryClient.clear();
+ clearPersistedCache();
+ toast({ message: "Recent cache cleared" });
+ },
+ },
+ ],
+ );
+ };
+
+ return (
+ <ScrollView
+ contentInsetAdjustmentBehavior="automatic"
+ contentContainerStyle={{
+ paddingHorizontal: 16,
+ paddingBottom: 40 + headerHeight,
+ }}
+ >
+ <Text className="px-1 pb-3 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.
+ </Text>
+
+ {offlineLibrary.length === 0 ? (
+ <EmptyState
+ icon={BookOpen}
+ title="No saved offline articles"
+ subtitle="Open an article and choose Make available offline."
+ />
+ ) : (
+ <View
+ className="w-full rounded-xl bg-card py-1"
+ style={{ borderCurve: "continuous" }}
+ >
+ {offlineLibrary.map((item, index) => (
+ <View key={item.bookmarkId}>
+ <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>
+ )}
+ <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>
+ {index < offlineLibrary.length - 1 && (
+ <Divider orientation="horizontal" className="mx-6" />
+ )}
+ </View>
+ ))}
+ </View>
+ )}
+
+ {offlineLibrary.length > 0 && (
+ <Pressable
+ className="mt-4 rounded-xl bg-card px-4 py-3"
+ onPress={confirmRemoveAll}
+ >
+ <Text className="text-center text-destructive">
+ Remove all offline content
+ </Text>
+ </Pressable>
+ )}
+
+ <View className="mt-8">
+ <Text className="px-1 pb-2 text-xs uppercase tracking-wide text-muted-foreground">
+ Recent cache
+ </Text>
+ <Pressable
+ className="rounded-xl bg-card px-4 py-3"
+ onPress={confirmClearRecentCache}
+ >
+ <Text className="text-center text-destructive">
+ Clear recent cache
+ </Text>
+ </Pressable>
+ </View>
+ </ScrollView>
+ );
+}
diff --git a/apps/mobile/app/dashboard/tags/[slug].tsx b/apps/mobile/app/dashboard/tags/[slug].tsx
index 4906d058..9d0878d7 100644
--- a/apps/mobile/app/dashboard/tags/[slug].tsx
+++ b/apps/mobile/app/dashboard/tags/[slug].tsx
@@ -1,7 +1,7 @@
import { Stack, useLocalSearchParams } from "expo-router";
import BookmarkListHeader from "@/components/bookmarks/BookmarkListHeader";
import UpdatingBookmarkList from "@/components/bookmarks/UpdatingBookmarkList";
-import FullPageError from "@/components/FullPageError";
+import QueryPageState from "@/components/QueryPageState";
import FullPageSpinner from "@/components/ui/FullPageSpinner";
import { useArchiveFilter } from "@/lib/hooks";
import { useQuery } from "@tanstack/react-query";
@@ -31,9 +31,9 @@ export default function TagView() {
headerRight: () => <BookmarkListHeader />,
}}
/>
- {error ? (
- <FullPageError error={error.message} onRetry={() => refetch()} />
- ) : tag && !isSettingsLoading ? (
+ {!tag ? (
+ <QueryPageState error={error} onRetry={() => refetch()} />
+ ) : !isSettingsLoading ? (
<UpdatingBookmarkList
query={{
tagId: tag.id,
diff --git a/apps/mobile/components/ConnectionStatusIndicator.tsx b/apps/mobile/components/ConnectionStatusIndicator.tsx
new file mode 100644
index 00000000..98e6e516
--- /dev/null
+++ b/apps/mobile/components/ConnectionStatusIndicator.tsx
@@ -0,0 +1,27 @@
+import { View } from "react-native";
+import { CloudOff } from "lucide-react-native";
+
+import { useConnectionStatus } from "@/lib/useConnectionStatus";
+
+export function ConnectionStatusIndicator() {
+ const status = useConnectionStatus();
+
+ if (status === "online" || status === "checking") {
+ return null;
+ }
+
+ const label =
+ status === "device-offline" ? "Offline" : "Karakeep unavailable";
+
+ return (
+ <View
+ pointerEvents="none"
+ accessibilityLiveRegion="polite"
+ accessibilityLabel={label}
+ accessibilityRole="text"
+ className="absolute -bottom-1 -right-1 h-4 w-4 items-center justify-center rounded-full border border-background bg-muted"
+ >
+ <CloudOff size={10} strokeWidth={2.5} className="text-muted-foreground" />
+ </View>
+ );
+}
diff --git a/apps/mobile/components/FullPageError.tsx b/apps/mobile/components/FullPageError.tsx
index f340d052..4823ed58 100644
--- a/apps/mobile/components/FullPageError.tsx
+++ b/apps/mobile/components/FullPageError.tsx
@@ -1,24 +1,53 @@
-import { View } from "react-native";
+import type { LucideIcon } from "lucide-react-native";
+import { Platform, View } from "react-native";
import { Text } from "@/components/ui/Text";
+import { useColorScheme } from "@/lib/useColorScheme";
+import { CircleAlert } from "lucide-react-native";
import { Button } from "./ui/Button";
export default function FullPageError({
error,
onRetry,
+ title = "Couldn't load this page",
+ icon: Icon = CircleAlert,
+ detail,
}: {
error: string;
onRetry: () => void;
+ title?: string;
+ icon?: LucideIcon;
+ detail?: string;
}) {
+ const { colors } = useColorScheme();
+
return (
- <View className="size-full items-center justify-center">
- <View className="h-1/4 items-center justify-between rounded-lg border border-gray-500 border-transparent bg-background px-10 py-4">
- <Text className="text-bold text-3xl text-foreground">
- Something Went Wrong
+ <View className="flex-1 items-center justify-center px-8 py-12">
+ <View className="w-full max-w-sm items-center">
+ <View className="mb-4 h-16 w-16 items-center justify-center rounded-full bg-muted">
+ <Icon size={28} color={colors.grey} />
+ </View>
+ <Text variant="title2" className="text-center">
+ {title}
+ </Text>
+ <Text className="mt-2 text-center leading-5 text-muted-foreground">
+ {error}
</Text>
- <Text className="text-foreground"> {error}</Text>
- <Button onPress={onRetry}>
- <Text>Retry</Text>
+ {detail ? (
+ <Text
+ className="mt-2 text-center text-xs text-muted-foreground"
+ numberOfLines={3}
+ >
+ {detail}
+ </Text>
+ ) : null}
+ <Button
+ className="mt-6"
+ variant={Platform.OS === "android" ? "plain" : "tonal"}
+ size={Platform.OS === "android" ? "sm" : "md"}
+ onPress={onRetry}
+ >
+ <Text>Try again</Text>
</Button>
</View>
</View>
diff --git a/apps/mobile/components/QueryPageState.tsx b/apps/mobile/components/QueryPageState.tsx
new file mode 100644
index 00000000..56a1c984
--- /dev/null
+++ b/apps/mobile/components/QueryPageState.tsx
@@ -0,0 +1,44 @@
+import FullPageError from "@/components/FullPageError";
+import FullPageSpinner from "@/components/ui/FullPageSpinner";
+import { useConnectionStatus } from "@/lib/useConnectionStatus";
+import { CloudOff, WifiOff } from "lucide-react-native";
+
+export default function QueryPageState({
+ error,
+ onRetry,
+}: {
+ error?: { message: string } | null;
+ onRetry: () => void;
+}) {
+ const connectionStatus = useConnectionStatus();
+
+ if (connectionStatus === "device-offline") {
+ return (
+ <FullPageError
+ icon={WifiOff}
+ title="You're offline"
+ error="This page isn't available while you're offline. Reconnect to load it."
+ detail={error?.message}
+ onRetry={onRetry}
+ />
+ );
+ }
+
+ if (connectionStatus === "server-unreachable") {
+ return (
+ <FullPageError
+ icon={CloudOff}
+ title="Karakeep is unavailable"
+ error="Karakeep couldn't be reached. Try again in a moment."
+ detail={error?.message}
+ onRetry={onRetry}
+ />
+ );
+ }
+
+ if (error) {
+ return <FullPageError error={error.message} onRetry={onRetry} />;
+ }
+
+ return <FullPageSpinner />;
+}
diff --git a/apps/mobile/components/bookmarks/BookmarkLinkPreview.tsx b/apps/mobile/components/bookmarks/BookmarkLinkPreview.tsx
index c1e1f154..3ddd6477 100644
--- a/apps/mobile/components/bookmarks/BookmarkLinkPreview.tsx
+++ b/apps/mobile/components/bookmarks/BookmarkLinkPreview.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useState } from "react";
+import { useCallback, useMemo, useState } from "react";
import { Linking, Pressable, TouchableOpacity, View } from "react-native";
import ImageView from "react-native-image-viewing";
import WebView from "react-native-webview";
@@ -7,9 +7,15 @@ import {
WebViewSourceUri,
} from "react-native-webview/lib/WebViewTypes";
import * as WebBrowser from "expo-web-browser";
+import QueryPageState from "@/components/QueryPageState";
import { Text } from "@/components/ui/Text";
import { useAssetUrl } from "@/lib/hooks";
+import {
+ getOfflineLibraryScope,
+ useOfflineArticleContent,
+} from "@/lib/offlineLibrary";
import { useReaderSettings, WEBVIEW_FONT_FAMILIES } from "@/lib/readerSettings";
+import useAppSettings from "@/lib/settings";
import { useColorScheme } from "@/lib/useColorScheme";
import { useQuery } from "@tanstack/react-query";
import { BookOpen, X } from "lucide-react-native";
@@ -23,8 +29,6 @@ import { useReadingProgress } from "@karakeep/shared-react/hooks/reading-progres
import { useTRPC } from "@karakeep/shared-react/trpc";
import { BookmarkTypes, ZBookmark } from "@karakeep/shared/types/bookmarks";
-import FullPageError from "../FullPageError";
-import FullPageSpinner from "../ui/FullPageSpinner";
import BookmarkAssetImage from "./BookmarkAssetImage";
import BookmarkHtmlHighlighterDom from "./BookmarkHtmlHighlighterDom";
import { PDFViewer } from "./PDFViewer";
@@ -107,12 +111,16 @@ export function BookmarkLinkReaderPreview({
}) {
const { isDarkColorScheme: isDark } = useColorScheme();
const { settings: readerSettings } = useReaderSettings();
+ const { settings } = useAppSettings();
const api = useTRPC();
+ const offlineHtmlContent = useOfflineArticleContent(
+ getOfflineLibraryScope(settings),
+ bookmark.id,
+ );
const {
data: bookmarkWithContent,
error,
- isLoading,
refetch,
} = useQuery(
api.bookmarks.getBookmark.queryOptions({
@@ -120,6 +128,23 @@ export function BookmarkLinkReaderPreview({
includeContent: true,
}),
);
+ // The offline body is stored on its own, so fold it back into the bookmark
+ // this component was already handed rather than reading the saved metadata.
+ const displayedBookmarkWithContent = useMemo(() => {
+ if (bookmarkWithContent) {
+ return bookmarkWithContent;
+ }
+ if (
+ offlineHtmlContent === undefined ||
+ bookmark.content.type !== BookmarkTypes.LINK
+ ) {
+ return undefined;
+ }
+ return {
+ ...bookmark,
+ content: { ...bookmark.content, htmlContent: offlineHtmlContent },
+ };
+ }, [bookmark, bookmarkWithContent, offlineHtmlContent]);
const { data: highlights } = useQuery(
api.highlights.getForBookmark.queryOptions({
@@ -155,15 +180,11 @@ export function BookmarkLinkReaderPreview({
setViewingImage(src);
}, []);
- if (isLoading) {
- return <FullPageSpinner />;
- }
-
- if (error) {
- return <FullPageError error={error.message} onRetry={refetch} />;
+ if (!displayedBookmarkWithContent) {
+ return <QueryPageState error={error} onRetry={refetch} />;
}
- if (bookmarkWithContent?.content.type !== BookmarkTypes.LINK) {
+ if (displayedBookmarkWithContent.content.type !== BookmarkTypes.LINK) {
throw new Error("Wrong content type rendered");
}
@@ -207,7 +228,7 @@ export function BookmarkLinkReaderPreview({
</View>
)}
<BookmarkHtmlHighlighterDom
- htmlContent={bookmarkWithContent.content.htmlContent ?? ""}
+ htmlContent={displayedBookmarkWithContent.content.htmlContent ?? ""}
contentStyle={contentStyle}
highlights={highlights?.highlights ?? []}
readingProgressOffset={readingProgressOffset}
diff --git a/apps/mobile/components/bookmarks/UpdatingBookmarkList.tsx b/apps/mobile/components/bookmarks/UpdatingBookmarkList.tsx
index 617d2310..df95a93d 100644
--- a/apps/mobile/components/bookmarks/UpdatingBookmarkList.tsx
+++ b/apps/mobile/components/bookmarks/UpdatingBookmarkList.tsx
@@ -1,12 +1,11 @@
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import useAppSettings from "@/lib/settings";
+import QueryPageState from "@/components/QueryPageState";
import type { ZGetBookmarksRequest } from "@karakeep/shared/types/bookmarks";
import { useTRPC } from "@karakeep/shared-react/trpc";
import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";
-import FullPageError from "../FullPageError";
-import FullPageSpinner from "../ui/FullPageSpinner";
import BookmarkList from "./BookmarkList";
export default function UpdatingBookmarkList({
@@ -42,12 +41,8 @@ export default function UpdatingBookmarkList({
),
);
- if (error) {
- return <FullPageError error={error.message} onRetry={() => refetch()} />;
- }
-
- if (isPending || !data) {
- return <FullPageSpinner />;
+ if (!data) {
+ return <QueryPageState error={error} onRetry={() => refetch()} />;
}
const onRefresh = () => {
diff --git a/apps/mobile/components/bookmarks/card/ActionBar.tsx b/apps/mobile/components/bookmarks/card/ActionBar.tsx
index ef3fb602..ea91a38c 100644
--- a/apps/mobile/components/bookmarks/card/ActionBar.tsx
+++ b/apps/mobile/components/bookmarks/card/ActionBar.tsx
@@ -1,7 +1,8 @@
+import { useOfflineAvailability } from "@/components/bookmarks/useOfflineAvailability";
import useAppSettings from "@/lib/settings";
import { shareBookmark } from "@/lib/shareBookmark";
import { useMenuIconColors } from "@/lib/useMenuIconColors";
-import { MenuView } from "@react-native-menu/menu";
+import { MenuAction, MenuView } from "@react-native-menu/menu";
import * as Haptics from "expo-haptics";
import { router } from "expo-router";
import { Ellipsis, ShareIcon, Star } from "lucide-react-native";
@@ -19,6 +20,7 @@ import {
} from "@karakeep/shared-react/hooks/bookmarks";
import { useWhoAmI } from "@karakeep/shared-react/hooks/users";
import type { ZBookmark } from "@karakeep/shared/types/bookmarks";
+import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";
import { useToast } from "../../ui/Toast";
@@ -33,9 +35,13 @@ export default function ActionBar({
const { settings } = useAppSettings();
const { data: currentUser } = useWhoAmI();
const { menuIconColor, destructiveMenuIconColor } = useMenuIconColors();
+ const offlineAvailability = useOfflineAvailability(bookmark.id);
// Check if the current user owns this bookmark
const isOwner = currentUser?.id === bookmark.userId;
+ const supportsOfflineReading =
+ bookmark.content.type === BookmarkTypes.LINK ||
+ bookmark.content.type === BookmarkTypes.TEXT;
const onError = () => {
toast({
@@ -88,7 +94,7 @@ export default function ActionBar({
const handleShare = () => shareBookmark(bookmark, settings, toast);
// Build actions array based on ownership
- const menuActions = [];
+ const menuActions: MenuAction[] = [];
if (isOwner) {
menuActions.push(
{
@@ -131,20 +137,88 @@ export default function ActionBar({
ios: menuIconColor,
}),
},
- {
- id: "delete",
- title: "Delete",
- attributes: {
- destructive: true,
- },
+ );
+ }
+
+ if (supportsOfflineReading) {
+ if (offlineAvailability.isAvailableOffline) {
+ menuActions.push({
+ id: "offline-group",
+ title: "Available offline",
image: Platform.select({
- ios: "trash",
+ ios: "checkmark.circle",
}),
imageColor: Platform.select({
- ios: destructiveMenuIconColor,
+ ios: menuIconColor,
}),
+ subactions: [
+ {
+ id: "update-offline-copy",
+ title: offlineAvailability.isSaving
+ ? "Saving offline copy..."
+ : "Update offline copy",
+ image: Platform.select({
+ ios: "arrow.clockwise",
+ }),
+ imageColor: Platform.select({
+ ios: menuIconColor,
+ }),
+ attributes: {
+ ...(offlineAvailability.isSaving && {
+ disabled: true,
+ }),
+ },
+ },
+ {
+ id: "remove-offline-copy",
+ title: "Remove offline copy",
+ attributes: {
+ destructive: true,
+ },
+ image: Platform.select({
+ ios: "trash",
+ }),
+ imageColor: Platform.select({
+ ios: destructiveMenuIconColor,
+ }),
+ },
+ ],
+ });
+ } else {
+ menuActions.push({
+ id: "make-available-offline",
+ title: offlineAvailability.isSaving
+ ? "Saving offline copy..."
+ : "Make available offline",
+ image: Platform.select({
+ ios: "arrow.down.circle",
+ }),
+ imageColor: Platform.select({
+ ios: menuIconColor,
+ }),
+ attributes: {
+ ...(offlineAvailability.isSaving && {
+ disabled: true,
+ }),
+ },
+ });
+ }
+ }
+
+ if (isOwner) {
+ menuActions.push({
+ id: "delete",
+ title: "Delete",
+ attributes: {
+ destructive: true,
},
- );
+ image: Platform.select({
+ ios: "trash",
+ }),
+ imageColor: Platform.select({
+ ios: destructiveMenuIconColor,
+ }),
+ });
}
return (
@@ -177,11 +251,18 @@ export default function ActionBar({
<ShareIcon color="gray" size={compact ? 20 : 24} />
</Pressable>
- {isOwner && menuActions.length > 0 && (
+ {menuActions.length > 0 && (
<MenuView
onPressAction={({ nativeEvent }) => {
Haptics.selectionAsync();
- if (nativeEvent.event === "delete") {
+ if (
+ nativeEvent.event === "make-available-offline" ||
+ nativeEvent.event === "update-offline-copy"
+ ) {
+ void offlineAvailability.save();
+ } else if (nativeEvent.event === "remove-offline-copy") {
+ offlineAvailability.confirmRemove();
+ } else if (nativeEvent.event === "delete") {
deleteBookmarkAlert();
} else if (nativeEvent.event === "archive") {
archiveBookmark({
diff --git a/apps/mobile/components/bookmarks/useOfflineAvailability.ts b/apps/mobile/components/bookmarks/useOfflineAvailability.ts
new file mode 100644
index 00000000..e54f096b
--- /dev/null
+++ b/apps/mobile/components/bookmarks/useOfflineAvailability.ts
@@ -0,0 +1,101 @@
+import { useState } from "react";
+import { Alert } from "react-native";
+import { onlineManager, useQueryClient } from "@tanstack/react-query";
+
+import { useTRPC } from "@karakeep/shared-react/trpc";
+
+import { useToast } from "../ui/Toast";
+import {
+ getOfflineLibraryScope,
+ OFFLINE_LIBRARY_SCHEMA_VERSION,
+ removeOfflineArticle,
+ saveOfflineArticle,
+ useIsAvailableOffline,
+} from "../../lib/offlineLibrary";
+import useAppSettings from "../../lib/settings";
+
+export function useOfflineAvailability(bookmarkId: string) {
+ const api = useTRPC();
+ const queryClient = useQueryClient();
+ const { settings } = useAppSettings();
+ const { toast } = useToast();
+ const scope = getOfflineLibraryScope(settings);
+ const isAvailableOffline = useIsAvailableOffline(scope, bookmarkId);
+ const [isSaving, setIsSaving] = useState(false);
+
+ const save = async () => {
+ if (isSaving) {
+ return;
+ }
+
+ setIsSaving(true);
+ // The content-bearing response is a superset of the metadata-only one, so
+ // this is the only bookmark the offline record needs.
+ const contentOptions = api.bookmarks.getBookmark.queryOptions(
+ {
+ bookmarkId,
+ includeContent: true,
+ },
+ // An explicit "save"/"update" must not be answered from a stale cache.
+ { staleTime: 0 },
+ );
+
+ try {
+ const bookmark = onlineManager.isOnline()
+ ? await queryClient.fetchQuery(contentOptions)
+ : queryClient.getQueryData(contentOptions.queryKey);
+
+ if (!bookmark) {
+ throw new Error("Connect to the internet to save this article.");
+ }
+
+ saveOfflineArticle(scope, {
+ schemaVersion: OFFLINE_LIBRARY_SCHEMA_VERSION,
+ bookmarkId,
+ savedAt: Date.now(),
+ bookmark,
+ });
+ toast({
+ message: isAvailableOffline
+ ? "Offline copy updated"
+ : "Available offline",
+ variant: "success",
+ });
+ } catch (error) {
+ toast({
+ message:
+ error instanceof Error
+ ? error.message
+ : "Could not save this article for offline reading.",
+ variant: "destructive",
+ });
+ } finally {
+ setIsSaving(false);
+ }
+ };
+
+ const confirmRemove = () => {
+ Alert.alert(
+ "Remove offline copy?",
+ "The article may remain temporarily cached, but it will no longer be kept for offline reading.",
+ [
+ { text: "Cancel", style: "cancel" },
+ {
+ text: "Remove",
+ style: "destructive",
+ onPress: () => {
+ removeOfflineArticle(scope, bookmarkId);
+ toast({ message: "Offline copy removed" });
+ },
+ },
+ ],
+ );
+ };
+
+ return {
+ confirmRemove,
+ isAvailableOffline,
+ isSaving,
+ save,
+ };
+}
diff --git a/apps/mobile/components/search/BookmarkSearchResults.tsx b/apps/mobile/components/search/BookmarkSearchResults.tsx
index 35be38db..cdabbfce 100644
--- a/apps/mobile/components/search/BookmarkSearchResults.tsx
+++ b/apps/mobile/components/search/BookmarkSearchResults.tsx
@@ -1,7 +1,6 @@
import { FlatList, Pressable, View } from "react-native";
import BookmarkList from "@/components/bookmarks/BookmarkList";
-import FullPageError from "@/components/FullPageError";
-import FullPageSpinner from "@/components/ui/FullPageSpinner";
+import QueryPageState from "@/components/QueryPageState";
import { Text } from "@/components/ui/Text";
import type { BookmarkSearchState } from "@/lib/useBookmarkSearchState";
@@ -31,10 +30,6 @@ export default function BookmarkSearchResults({
onRefresh,
} = state;
- if (error) {
- return <FullPageError error={error.message} onRetry={() => refetch()} />;
- }
-
const renderHistoryItem = ({ item }: { item: string }) => (
<Pressable
onPress={() => onSelectHistory(item)}
@@ -73,21 +68,17 @@ export default function BookmarkSearchResults({
);
}
- if (isPending) {
- return <FullPageSpinner />;
- }
-
- if (data) {
- return (
- <BookmarkList
- bookmarks={data.pages.flatMap((p) => p.bookmarks)}
- fetchNextPage={fetchNextPage}
- isFetchingNextPage={isFetchingNextPage}
- onRefresh={onRefresh}
- isRefreshing={isPending}
- />
- );
+ if (!data) {
+ return <QueryPageState error={error} onRetry={() => refetch()} />;
}
- return null;
+ return (
+ <BookmarkList
+ bookmarks={data.pages.flatMap((p) => p.bookmarks)}
+ fetchNextPage={fetchNextPage}
+ isFetchingNextPage={isFetchingNextPage}
+ onRefresh={onRefresh}
+ isRefreshing={isPending}
+ />
+ );
}
diff --git a/apps/mobile/components/settings/ProfileAvatarButton.tsx b/apps/mobile/components/settings/ProfileAvatarButton.tsx
index b7ddb8a7..14e3f48e 100644
--- a/apps/mobile/components/settings/ProfileAvatarButton.tsx
+++ b/apps/mobile/components/settings/ProfileAvatarButton.tsx
@@ -1,5 +1,6 @@
import { Pressable } from "react-native";
import { useRouter } from "expo-router";
+import { ConnectionStatusIndicator } from "@/components/ConnectionStatusIndicator";
import { Avatar } from "@/components/ui/Avatar";
import { useQuery } from "@tanstack/react-query";
@@ -22,8 +23,10 @@ export function ProfileAvatarButton() {
hitSlop={(HIT_TARGET - AVATAR_SIZE) / 2}
accessibilityLabel="Open profile settings"
accessibilityRole="button"
+ className="relative"
>
<Avatar image={data?.image} name={data?.name} size={AVATAR_SIZE} />
+ <ConnectionStatusIndicator />
</Pressable>
);
}
diff --git a/apps/mobile/lib/offlineCache.ts b/apps/mobile/lib/offlineCache.ts
new file mode 100644
index 00000000..41831d30
--- /dev/null
+++ b/apps/mobile/lib/offlineCache.ts
@@ -0,0 +1,313 @@
+import type { DehydratedState, Query } from "@tanstack/react-query";
+import type {
+ PersistedClient,
+ Persister,
+} from "@tanstack/react-query-persist-client";
+import {
+ defaultShouldDehydrateQuery,
+ onlineManager,
+ QueryClient,
+} from "@tanstack/react-query";
+import { AppState } from "react-native";
+import * as Network from "expo-network";
+import { createMMKV } from "react-native-mmkv";
+import superjson from "superjson";
+
+// In-memory garbage collection must not evict entries before persistence does.
+export const CACHE_MAX_AGE = 1000 * 60 * 60 * 24 * 7;
+
+export function makeMobileQueryClient() {
+ return new QueryClient({
+ defaultOptions: {
+ queries: {
+ staleTime: 60_000,
+ gcTime: CACHE_MAX_AGE,
+ },
+ },
+ });
+}
+
+type DehydratedQuery = DehydratedState["queries"][number];
+
+interface PersistedIndex {
+ timestamp: number;
+ buster: string;
+ hashes: string[];
+}
+
+const INDEX_KEY = "index:v1";
+const QUERY_PREFIX = "query:v1:";
+// persistQueryClientSubscribe saves on every single cache event; the stock
+// persister throttled internally, so a hand-rolled one has to do it itself.
+const PERSIST_THROTTLE = 5_000;
+
+const queryCacheStorage = createMMKV({
+ id: "karakeep-query-cache",
+});
+
+function shardKey(queryHash: string) {
+ return `${QUERY_PREFIX}${queryHash}`;
+}
+
+// queryHash -> the dataUpdatedAt already on disk. This is what keeps a save
+// from re-serializing queries whose data did not move.
+const persistedAt = new Map<string, number>();
+
+// This MMKV instance belongs entirely to the query cache, so anything that is
+// neither the index nor a live shard is garbage — orphaned shards, and the
+// single blob written by the previous persister.
+function removeStaleKeys(keep: ReadonlySet<string>) {
+ for (const key of queryCacheStorage.getAllKeys()) {
+ if (key !== INDEX_KEY && !keep.has(key)) {
+ queryCacheStorage.remove(key);
+ }
+ }
+}
+
+// A guard rather than a zod schema: QueryState is react-query's type, not ours.
+// Modelling it would mean mirroring 12 internal fields (including `error:
+// Error | null`, which no schema round-trips cleanly) and silently dropping any
+// field a future version adds, since zod objects strip unknown keys. Checking
+// the fields we depend on and passing the value through avoids both.
+function isDehydratedQuery(value: unknown): value is DehydratedQuery {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ "queryHash" in value &&
+ typeof value.queryHash === "string" &&
+ "queryKey" in value &&
+ Array.isArray(value.queryKey) &&
+ "state" in value &&
+ typeof value.state === "object" &&
+ value.state !== null &&
+ "dataUpdatedAt" in value.state &&
+ typeof value.state.dataUpdatedAt === "number"
+ );
+}
+
+function parseIndex(value: unknown): PersistedIndex | undefined {
+ if (
+ typeof value !== "object" ||
+ value === null ||
+ !("timestamp" in value) ||
+ typeof value.timestamp !== "number" ||
+ !("buster" in value) ||
+ typeof value.buster !== "string" ||
+ !("hashes" in value) ||
+ !Array.isArray(value.hashes)
+ ) {
+ return undefined;
+ }
+
+ return {
+ timestamp: value.timestamp,
+ buster: value.buster,
+ hashes: value.hashes.filter(
+ (hash: unknown): hash is string => typeof hash === "string",
+ ),
+ };
+}
+
+function writeClient(client: PersistedClient) {
+ const hashes: string[] = [];
+ const live = new Set<string>();
+
+ for (const query of client.clientState.queries) {
+ const { queryHash } = query;
+ hashes.push(queryHash);
+ live.add(queryHash);
+ // Only successful queries are dehydrated, so data is the thing worth
+ // tracking; a changed error on an already-cached query does not matter.
+ if (persistedAt.get(queryHash) === query.state.dataUpdatedAt) {
+ continue;
+ }
+ queryCacheStorage.set(shardKey(queryHash), superjson.stringify(query));
+ persistedAt.set(queryHash, query.state.dataUpdatedAt);
+ }
+
+ // Queries that left the cache leave their shard behind: nothing reports a
+ // removal, they simply stop appearing here. Deleting the entry being visited
+ // is well defined for a Map iterator.
+ for (const queryHash of persistedAt.keys()) {
+ if (!live.has(queryHash)) {
+ queryCacheStorage.remove(shardKey(queryHash));
+ persistedAt.delete(queryHash);
+ }
+ }
+
+ const index: PersistedIndex = {
+ timestamp: client.timestamp,
+ buster: client.buster,
+ hashes,
+ };
+ // Written last: a torn save leaves unreferenced shards, which the next
+ // restore sweeps, rather than an index pointing at data that never landed.
+ queryCacheStorage.set(INDEX_KEY, superjson.stringify(index));
+}
+
+let pendingClient: PersistedClient | undefined;
+let flushTimer: ReturnType<typeof setTimeout> | undefined;
+
+function flushPendingClient() {
+ if (flushTimer) {
+ clearTimeout(flushTimer);
+ }
+ flushTimer = undefined;
+ const client = pendingClient;
+ pendingClient = undefined;
+ if (client) {
+ writeClient(client);
+ }
+}
+
+function discardPersistedCache() {
+ pendingClient = undefined;
+ if (flushTimer) {
+ clearTimeout(flushTimer);
+ flushTimer = undefined;
+ }
+ persistedAt.clear();
+ queryCacheStorage.clearAll();
+}
+
+// One MMKV entry per query instead of one blob for the whole cache, so a save
+// rewrites only what changed. The index is the authority on what exists:
+// restoring from a key scan would resurrect queries that were evicted.
+export const queryPersister: Persister = {
+ persistClient: (client) => {
+ pendingClient = client;
+ if (!flushTimer) {
+ flushTimer = setTimeout(flushPendingClient, PERSIST_THROTTLE);
+ }
+ },
+
+ restoreClient: () => {
+ const rawIndex = queryCacheStorage.getString(INDEX_KEY);
+ if (!rawIndex) {
+ removeStaleKeys(new Set());
+ return undefined;
+ }
+
+ let index: PersistedIndex | undefined;
+ try {
+ index = parseIndex(superjson.parse<unknown>(rawIndex));
+ } catch {
+ index = undefined;
+ }
+ if (!index) {
+ discardPersistedCache();
+ return undefined;
+ }
+
+ const queries: DehydratedQuery[] = [];
+ const live = new Set<string>();
+ persistedAt.clear();
+
+ for (const queryHash of index.hashes) {
+ const raw = queryCacheStorage.getString(shardKey(queryHash));
+ if (!raw) {
+ continue;
+ }
+
+ let query: DehydratedQuery | undefined;
+ try {
+ const parsed = superjson.parse<unknown>(raw);
+ query =
+ isDehydratedQuery(parsed) && parsed.queryHash === queryHash
+ ? parsed
+ : undefined;
+ } catch {
+ query = undefined;
+ }
+ if (!query) {
+ continue;
+ }
+
+ queries.push(query);
+ live.add(shardKey(queryHash));
+ persistedAt.set(queryHash, query.state.dataUpdatedAt);
+ }
+
+ // Cold start is the only chance to notice shards orphaned by the previous
+ // run, since persistedAt starts empty.
+ removeStaleKeys(live);
+
+ return {
+ timestamp: index.timestamp,
+ buster: index.buster,
+ clientState: { mutations: [], queries },
+ };
+ },
+
+ removeClient: discardPersistedCache,
+};
+
+export function clearPersistedCache() {
+ discardPersistedCache();
+}
+
+export function setupCachePersistence() {
+ const subscription = AppState.addEventListener("change", (state) => {
+ if (state !== "active") {
+ flushPendingClient();
+ }
+ });
+
+ return () => {
+ subscription.remove();
+ flushPendingClient();
+ };
+}
+
+// The persister keys by query, but a query's own value is still written whole.
+// Article bodies are megabytes each; durable copies of those belong in the
+// offline library instead.
+function fetchesArticleContent(queryKey: readonly unknown[]) {
+ return queryKey.some(
+ (part) =>
+ typeof part === "object" &&
+ part !== null &&
+ "input" in part &&
+ typeof part.input === "object" &&
+ part.input !== null &&
+ "includeContent" in part.input &&
+ part.input.includeContent === true,
+ );
+}
+
+export const dehydrateOptions = {
+ // Mutation functions are not serializable, and this app does not register
+ // resumable mutation defaults after hydration.
+ shouldDehydrateMutation: () => false,
+ shouldDehydrateQuery: (query: Query) =>
+ defaultShouldDehydrateQuery(query) &&
+ !fetchesArticleContent(query.queryKey),
+};
+
+// React Query otherwise assumes React Native is always online.
+export function setupOnlineManager() {
+ onlineManager.setEventListener((setOnline) => {
+ let active = true;
+ const updateOnlineState = (state: Network.NetworkState) => {
+ setOnline(state.isInternetReachable ?? state.isConnected ?? true);
+ };
+
+ void Network.getNetworkStateAsync()
+ .then((state) => {
+ if (active) {
+ updateOnlineState(state);
+ }
+ })
+ .catch(() => {
+ if (active) {
+ setOnline(true);
+ }
+ });
+
+ const subscription = Network.addNetworkStateListener(updateOnlineState);
+ return () => {
+ active = false;
+ subscription.remove();
+ };
+ });
+}
diff --git a/apps/mobile/lib/offlineLibrary.ts b/apps/mobile/lib/offlineLibrary.ts
new file mode 100644
index 00000000..db4dd1af
--- /dev/null
+++ b/apps/mobile/lib/offlineLibrary.ts
@@ -0,0 +1,417 @@
+import { useMemo } from "react";
+import { createMMKV, useMMKVString } from "react-native-mmkv";
+import superjson from "superjson";
+import { z } from "zod";
+
+import {
+ BookmarkTypes,
+ zBookmarkSchema,
+} from "@karakeep/shared/types/bookmarks";
+import {
+ getBookmarkTitle,
+ getSourceUrl,
+} from "@karakeep/shared/utils/bookmarkUtils";
+
+import type { Settings } from "./settings";
+
+// The article body lives under its own key so that callers who only need the
+// bookmark's metadata never pay to deserialize megabytes of HTML.
+export const OFFLINE_LIBRARY_SCHEMA_VERSION = 3 as const;
+// Versioned keys: records written by an older schema are simply invisible, so a
+// stale manifest can never claim an article the current parser would reject.
+const MANIFEST_PREFIX = `manifest:v${OFFLINE_LIBRARY_SCHEMA_VERSION}:`;
+const ARTICLE_PREFIX = `article:v${OFFLINE_LIBRARY_SCHEMA_VERSION}:`;
+const CONTENT_PREFIX = `content:v${OFFLINE_LIBRARY_SCHEMA_VERSION}:`;
+
+const offlineLibraryStorage = createMMKV({
+ id: "karakeep-offline-library",
+});
+
+// Callers hand this in with the content populated; the body is split out before
+// it is stored, so the persisted record always carries a null htmlContent.
+const zOfflineArticle = z.object({
+ schemaVersion: z.literal(OFFLINE_LIBRARY_SCHEMA_VERSION),
+ bookmarkId: z.string(),
+ savedAt: z.number(),
+ bookmark: zBookmarkSchema,
+});
+
+const zOfflineArticleContent = z.object({
+ schemaVersion: z.literal(OFFLINE_LIBRARY_SCHEMA_VERSION),
+ bookmarkId: z.string(),
+ htmlContent: z.string(),
+});
+
+const zOfflineLibraryItem = z.object({
+ bookmarkId: z.string(),
+ savedAt: z.number(),
+ displayTitle: z.string(),
+ url: z.string().optional(),
+});
+
+const zOfflineLibraryManifest = z.array(zOfflineLibraryItem);
+
+export type OfflineArticle = z.infer<typeof zOfflineArticle>;
+export type OfflineLibraryItem = z.infer<typeof zOfflineLibraryItem>;
+
+function encodeKeyPart(value: string) {
+ return encodeURIComponent(value);
+}
+
+function manifestKey(scope: string) {
+ return `${MANIFEST_PREFIX}${encodeKeyPart(scope)}`;
+}
+
+function articleKey(scope: string, bookmarkId: string) {
+ return `${ARTICLE_PREFIX}${encodeKeyPart(scope)}:${encodeKeyPart(bookmarkId)}`;
+}
+
+function articlePrefix(scope: string) {
+ return `${ARTICLE_PREFIX}${encodeKeyPart(scope)}:`;
+}
+
+function contentKey(scope: string, bookmarkId: string) {
+ return `${CONTENT_PREFIX}${encodeKeyPart(scope)}:${encodeKeyPart(bookmarkId)}`;
+}
+
+function contentPrefix(scope: string) {
+ return `${CONTENT_PREFIX}${encodeKeyPart(scope)}:`;
+}
+
+function parseManifest(raw: string | undefined): OfflineLibraryItem[] {
+ if (!raw) {
+ return [];
+ }
+
+ try {
+ const result = zOfflineLibraryManifest.safeParse(
+ superjson.parse<unknown>(raw),
+ );
+ return result.success ? result.data : [];
+ } catch {
+ return [];
+ }
+}
+
+// Every bookmark card reads the manifest, so parse each revision only once.
+let lastParsedManifest:
+ | { raw: string | undefined; items: OfflineLibraryItem[] }
+ | undefined;
+
+function parseManifestMemoized(raw: string | undefined): OfflineLibraryItem[] {
+ // Not `lastParsedManifest?.raw === raw`: an empty library has raw ===
+ // undefined, which would match an unset cache and dereference it.
+ if (lastParsedManifest !== undefined && lastParsedManifest.raw === raw) {
+ return lastParsedManifest.items;
+ }
+
+ const items = parseManifest(raw).sort(
+ (left, right) => right.savedAt - left.savedAt,
+ );
+ lastParsedManifest = { raw, items };
+ return items;
+}
+
+function writeManifest(scope: string, items: OfflineLibraryItem[]) {
+ offlineLibraryStorage.set(
+ manifestKey(scope),
+ superjson.stringify(
+ [...items].sort((left, right) => right.savedAt - left.savedAt),
+ ),
+ );
+}
+
+function parseOfflineArticle(
+ raw: string | undefined,
+ expectedBookmarkId: string,
+): OfflineArticle | undefined {
+ if (!raw) {
+ return undefined;
+ }
+
+ try {
+ const result = zOfflineArticle.safeParse(superjson.parse<unknown>(raw));
+ if (
+ !result.success ||
+ result.data.bookmarkId !== expectedBookmarkId ||
+ result.data.bookmark.id !== expectedBookmarkId
+ ) {
+ return undefined;
+ }
+ return result.data;
+ } catch {
+ return undefined;
+ }
+}
+
+function readOfflineArticle(scope: string, bookmarkId: string) {
+ return parseOfflineArticle(
+ offlineLibraryStorage.getString(articleKey(scope, bookmarkId)),
+ bookmarkId,
+ );
+}
+
+function parseOfflineArticleContent(
+ raw: string | undefined,
+ expectedBookmarkId: string,
+): string | undefined {
+ if (!raw) {
+ return undefined;
+ }
+
+ try {
+ const result = zOfflineArticleContent.safeParse(
+ superjson.parse<unknown>(raw),
+ );
+ if (!result.success || result.data.bookmarkId !== expectedBookmarkId) {
+ return undefined;
+ }
+ return result.data.htmlContent;
+ } catch {
+ return undefined;
+ }
+}
+
+function readOfflineArticleContent(scope: string, bookmarkId: string) {
+ return parseOfflineArticleContent(
+ offlineLibraryStorage.getString(contentKey(scope, bookmarkId)),
+ bookmarkId,
+ );
+}
+
+// Text bodies are small and already inline on the bookmark; only links keep a
+// separate content record.
+function isRenderableArticle(article: OfflineArticle, hasContent: boolean) {
+ const { content } = article.bookmark;
+ if (content.type === BookmarkTypes.TEXT) {
+ return true;
+ }
+
+ return content.type === BookmarkTypes.LINK && hasContent;
+}
+
+function splitArticleContent(bookmark: OfflineArticle["bookmark"]) {
+ if (bookmark.content.type === BookmarkTypes.TEXT) {
+ return { bookmark, htmlContent: undefined };
+ }
+
+ if (
+ bookmark.content.type === BookmarkTypes.LINK &&
+ typeof bookmark.content.htmlContent === "string"
+ ) {
+ return {
+ bookmark: {
+ ...bookmark,
+ content: { ...bookmark.content, htmlContent: null },
+ },
+ htmlContent: bookmark.content.htmlContent,
+ };
+ }
+
+ return undefined;
+}
+
+function getDisplayTitle(bookmark: OfflineArticle["bookmark"]) {
+ const title = getBookmarkTitle(bookmark)?.trim();
+ if (title) {
+ return title;
+ }
+
+ if (bookmark.content.type === BookmarkTypes.TEXT) {
+ const firstLine = bookmark.content.text.trim().split("\n", 1)[0];
+ if (firstLine) {
+ return firstLine.slice(0, 120);
+ }
+ }
+
+ return "Untitled bookmark";
+}
+
+export function getOfflineLibraryScope(
+ settings: Pick<Settings, "address" | "apiKeyId">,
+) {
+ return `${settings.address}|${settings.apiKeyId ?? "anon"}`;
+}
+
+function restoreKey(key: string, raw: string | undefined) {
+ if (raw !== undefined) {
+ offlineLibraryStorage.set(key, raw);
+ } else {
+ offlineLibraryStorage.remove(key);
+ }
+}
+
+export function saveOfflineArticle(scope: string, article: OfflineArticle) {
+ const parsed = zOfflineArticle.safeParse(article);
+ const split = parsed.success
+ ? splitArticleContent(parsed.data.bookmark)
+ : undefined;
+ if (
+ !parsed.success ||
+ !split ||
+ parsed.data.bookmarkId !== parsed.data.bookmark.id
+ ) {
+ throw new Error("The article does not contain a complete offline copy.");
+ }
+
+ const key = articleKey(scope, article.bookmarkId);
+ const bodyKey = contentKey(scope, article.bookmarkId);
+ const currentManifestRaw = offlineLibraryStorage.getString(
+ manifestKey(scope),
+ );
+ const currentArticleRaw = offlineLibraryStorage.getString(key);
+ const currentContentRaw = offlineLibraryStorage.getString(bodyKey);
+
+ try {
+ if (split.htmlContent !== undefined) {
+ offlineLibraryStorage.set(
+ bodyKey,
+ superjson.stringify({
+ schemaVersion: OFFLINE_LIBRARY_SCHEMA_VERSION,
+ bookmarkId: parsed.data.bookmarkId,
+ htmlContent: split.htmlContent,
+ }),
+ );
+ } else {
+ offlineLibraryStorage.remove(bodyKey);
+ }
+
+ offlineLibraryStorage.set(
+ key,
+ superjson.stringify({ ...parsed.data, bookmark: split.bookmark }),
+ );
+
+ const stored = readOfflineArticle(scope, article.bookmarkId);
+ const storedContent = readOfflineArticleContent(scope, article.bookmarkId);
+ if (!stored || !isRenderableArticle(stored, storedContent !== undefined)) {
+ throw new Error("The offline copy could not be verified.");
+ }
+
+ const current = parseManifest(currentManifestRaw);
+ const sourceUrl = getSourceUrl(parsed.data.bookmark);
+ const item: OfflineLibraryItem = {
+ bookmarkId: parsed.data.bookmarkId,
+ savedAt: parsed.data.savedAt,
+ displayTitle: getDisplayTitle(parsed.data.bookmark),
+ ...(sourceUrl ? { url: sourceUrl } : {}),
+ };
+ writeManifest(scope, [
+ item,
+ ...current.filter((entry) => entry.bookmarkId !== parsed.data.bookmarkId),
+ ]);
+ } catch (error) {
+ restoreKey(key, currentArticleRaw);
+ restoreKey(bodyKey, currentContentRaw);
+ restoreKey(manifestKey(scope), currentManifestRaw);
+ throw error;
+ }
+}
+
+export function removeOfflineArticle(scope: string, bookmarkId: string) {
+ const current = parseManifest(
+ offlineLibraryStorage.getString(manifestKey(scope)),
+ );
+ writeManifest(
+ scope,
+ current.filter((entry) => entry.bookmarkId !== bookmarkId),
+ );
+ offlineLibraryStorage.remove(articleKey(scope, bookmarkId));
+ offlineLibraryStorage.remove(contentKey(scope, bookmarkId));
+}
+
+export function removeAllOfflineArticles(scope: string) {
+ writeManifest(scope, []);
+ for (const key of offlineLibraryStorage.getAllKeys()) {
+ if (
+ key.startsWith(articlePrefix(scope)) ||
+ key.startsWith(contentPrefix(scope))
+ ) {
+ offlineLibraryStorage.remove(key);
+ }
+ }
+}
+
+export function clearOfflineLibrary() {
+ offlineLibraryStorage.clearAll();
+}
+
+export function reconcileOfflineLibrary(scope: string) {
+ const current = parseManifest(
+ offlineLibraryStorage.getString(manifestKey(scope)),
+ );
+ const storedKeys = new Set(offlineLibraryStorage.getAllKeys());
+ const validItems: OfflineLibraryItem[] = [];
+ const validKeys = new Set<string>();
+
+ for (const item of current) {
+ const key = articleKey(scope, item.bookmarkId);
+ const bodyKey = contentKey(scope, item.bookmarkId);
+ const article = readOfflineArticle(scope, item.bookmarkId);
+ // Presence is checked by key rather than by parsing: this runs over the
+ // whole library, and the bodies are the thing worth not reading.
+ if (article && isRenderableArticle(article, storedKeys.has(bodyKey))) {
+ validItems.push(item);
+ validKeys.add(key);
+ if (storedKeys.has(bodyKey)) {
+ validKeys.add(bodyKey);
+ }
+ } else {
+ offlineLibraryStorage.remove(key);
+ offlineLibraryStorage.remove(bodyKey);
+ }
+ }
+
+ for (const key of storedKeys) {
+ if (
+ (key.startsWith(articlePrefix(scope)) ||
+ key.startsWith(contentPrefix(scope))) &&
+ !validKeys.has(key)
+ ) {
+ offlineLibraryStorage.remove(key);
+ }
+ }
+
+ writeManifest(scope, validItems);
+}
+
+// Metadata only — the article body is not read. Use useOfflineArticleContent
+// when you actually need to render it.
+export function useOfflineArticle(scope: string, bookmarkId: string) {
+ const [rawArticle] = useMMKVString(
+ articleKey(scope, bookmarkId),
+ offlineLibraryStorage,
+ );
+ return useMemo(
+ () => parseOfflineArticle(rawArticle, bookmarkId),
+ [bookmarkId, rawArticle],
+ );
+}
+
+export function useOfflineArticleContent(scope: string, bookmarkId: string) {
+ const [rawContent] = useMMKVString(
+ contentKey(scope, bookmarkId),
+ offlineLibraryStorage,
+ );
+ return useMemo(
+ () => parseOfflineArticleContent(rawContent, bookmarkId),
+ [bookmarkId, rawContent],
+ );
+}
+
+export function useOfflineLibrary(scope: string) {
+ const [rawManifest] = useMMKVString(
+ manifestKey(scope),
+ offlineLibraryStorage,
+ );
+ return useMemo(() => parseManifestMemoized(rawManifest), [rawManifest]);
+}
+
+// Deliberately manifest-based: this runs once per rendered bookmark card, so it
+// must not deserialize the (potentially multi-megabyte) article records.
+export function useIsAvailableOffline(scope: string, bookmarkId: string) {
+ const items = useOfflineLibrary(scope);
+ return useMemo(
+ () => items.some((item) => item.bookmarkId === bookmarkId),
+ [items, bookmarkId],
+ );
+}
diff --git a/apps/mobile/lib/providers.tsx b/apps/mobile/lib/providers.tsx
index 4a7def1d..77aa4f02 100644
--- a/apps/mobile/lib/providers.tsx
+++ b/apps/mobile/lib/providers.tsx
@@ -1,30 +1,62 @@
-import { useEffect } from "react";
+import { useEffect, useMemo, useState } from "react";
import FullPageSpinner from "@/components/ui/FullPageSpinner";
+import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client";
import { Toaster } from "sonner-native";
import { TRPCSettingsProvider } from "@karakeep/shared-react/providers/trpc-provider";
+import {
+ CACHE_MAX_AGE,
+ dehydrateOptions,
+ makeMobileQueryClient,
+ queryPersister,
+ setupCachePersistence,
+ setupOnlineManager,
+} from "./offlineCache";
+import { ConnectionStatusProvider } from "./useConnectionStatus";
import { ReaderSettingsProvider } from "./readerSettings";
import useAppSettings from "./settings";
export function Providers({ children }: { children: React.ReactNode }) {
const { settings, isLoading, load } = useAppSettings();
+ const [queryClient] = useState(() => makeMobileQueryClient());
useEffect(() => {
load();
+ setupOnlineManager();
+ return setupCachePersistence();
}, []);
+ const buster = `${settings.address}|${settings.apiKeyId ?? "anon"}`;
+ const persistOptions = useMemo(
+ () => ({
+ persister: queryPersister,
+ maxAge: CACHE_MAX_AGE,
+ buster,
+ dehydrateOptions,
+ }),
+ [buster],
+ );
+
if (isLoading) {
// Don't render anything if the settings still hasn't been loaded
return <FullPageSpinner />;
}
return (
- <TRPCSettingsProvider settings={settings}>
- <ReaderSettingsProvider>
- {children}
- <Toaster />
- </ReaderSettingsProvider>
- </TRPCSettingsProvider>
+ <PersistQueryClientProvider
+ key={buster}
+ client={queryClient}
+ persistOptions={persistOptions}
+ >
+ <TRPCSettingsProvider settings={settings} queryClient={queryClient}>
+ <ConnectionStatusProvider enabled={!!settings.apiKey}>
+ <ReaderSettingsProvider>
+ {children}
+ <Toaster />
+ </ReaderSettingsProvider>
+ </ConnectionStatusProvider>
+ </TRPCSettingsProvider>
+ </PersistQueryClientProvider>
);
}
diff --git a/apps/mobile/lib/session.ts b/apps/mobile/lib/session.ts
index d6470145..c87625be 100644
--- a/apps/mobile/lib/session.ts
+++ b/apps/mobile/lib/session.ts
@@ -1,13 +1,16 @@
import { useCallback } from "react";
-import { useMutation } from "@tanstack/react-query";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useTRPC } from "@karakeep/shared-react/trpc";
+import { clearPersistedCache } from "./offlineCache";
+import { clearOfflineLibrary } from "./offlineLibrary";
import useAppSettings from "./settings";
export function useSession() {
const { settings, setSettings } = useAppSettings();
const api = useTRPC();
+ const queryClient = useQueryClient();
const { mutate: deleteKey } = useMutation(
api.apiKeys.revoke.mutationOptions(),
@@ -18,7 +21,10 @@ export function useSession() {
deleteKey({ id: settings.apiKeyId });
}
setSettings({ ...settings, apiKey: undefined, apiKeyId: undefined });
- }, [settings, setSettings]);
+ queryClient.clear();
+ clearPersistedCache();
+ clearOfflineLibrary();
+ }, [deleteKey, queryClient, settings, setSettings]);
return {
logout,
diff --git a/apps/mobile/lib/useConnectionStatus.tsx b/apps/mobile/lib/useConnectionStatus.tsx
new file mode 100644
index 00000000..ec230a4a
--- /dev/null
+++ b/apps/mobile/lib/useConnectionStatus.tsx
@@ -0,0 +1,139 @@
+import type { ReactNode } from "react";
+import { createContext, useContext, useEffect, useState } from "react";
+import { AppState } from "react-native";
+import { fetch } from "expo/fetch";
+import { onlineManager } from "@tanstack/react-query";
+
+import { buildApiHeaders } from "./utils";
+import useAppSettings from "./settings";
+
+export type ConnectionStatus =
+ | "checking"
+ | "online"
+ | "device-offline"
+ | "server-unreachable";
+
+const HEALTH_CHECK_INTERVAL = 30_000;
+const HEALTH_CHECK_TIMEOUT = 5_000;
+
+const ConnectionStatusContext = createContext<ConnectionStatus>("checking");
+
+function useConnectionStatusMonitor(enabled: boolean): ConnectionStatus {
+ const { settings } = useAppSettings();
+ const [status, setStatus] = useState<ConnectionStatus>(() =>
+ onlineManager.isOnline() ? "checking" : "device-offline",
+ );
+
+ useEffect(() => {
+ if (!enabled) {
+ setStatus("checking");
+ return;
+ }
+
+ let active = true;
+ let currentRequest: AbortController | undefined;
+
+ const checkServer = async () => {
+ if (!onlineManager.isOnline()) {
+ currentRequest?.abort();
+ if (active) {
+ setStatus("device-offline");
+ }
+ return;
+ }
+
+ currentRequest?.abort();
+ const controller = new AbortController();
+ currentRequest = controller;
+ const timeout = setTimeout(
+ () => controller.abort(),
+ HEALTH_CHECK_TIMEOUT,
+ );
+
+ try {
+ const response = await fetch(`${settings.address}/api/health`, {
+ headers: buildApiHeaders(settings.apiKey, settings.customHeaders),
+ signal: controller.signal,
+ });
+ const result: unknown = await response.json();
+ const healthy =
+ response.ok &&
+ typeof result === "object" &&
+ result !== null &&
+ "status" in result &&
+ result.status === "ok";
+
+ if (active && currentRequest === controller) {
+ setStatus(healthy ? "online" : "server-unreachable");
+ }
+ } catch {
+ if (
+ active &&
+ currentRequest === controller &&
+ onlineManager.isOnline()
+ ) {
+ setStatus("server-unreachable");
+ }
+ } finally {
+ clearTimeout(timeout);
+ }
+ };
+
+ const onConnectivityChange = (online: boolean) => {
+ if (!online) {
+ currentRequest?.abort();
+ setStatus("device-offline");
+ return;
+ }
+
+ setStatus("checking");
+ void checkServer();
+ };
+
+ void checkServer();
+ const unsubscribe = onlineManager.subscribe(onConnectivityChange);
+ const interval = setInterval(() => {
+ if (AppState.currentState === "active") {
+ void checkServer();
+ }
+ }, HEALTH_CHECK_INTERVAL);
+ const appStateSubscription = AppState.addEventListener(
+ "change",
+ (nextState) => {
+ if (nextState === "active") {
+ void checkServer();
+ }
+ },
+ );
+
+ return () => {
+ active = false;
+ currentRequest?.abort();
+ clearInterval(interval);
+ unsubscribe();
+ appStateSubscription.remove();
+ };
+ }, [enabled, settings.address, settings.apiKey, settings.customHeaders]);
+
+ return status;
+}
+
+export function ConnectionStatusProvider({
+ children,
+ enabled,
+}: {
+ children: ReactNode;
+ enabled: boolean;
+}) {
+ const status = useConnectionStatusMonitor(enabled);
+
+ return (
+ <ConnectionStatusContext.Provider value={status}>
+ {children}
+ </ConnectionStatusContext.Provider>
+ );
+}
+
+export function useConnectionStatus(): ConnectionStatus {
+ return useContext(ConnectionStatusContext);
+}
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index e49c62ff..fb1c33a3 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -34,6 +34,7 @@
"@sentry/react-native": "^8.14.0",
"@shopify/flash-list": "2.0.2",
"@tanstack/react-query": "5.90.2",
+ "@tanstack/react-query-persist-client": "5.90.2",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"date-fns": "^3.6.0",
@@ -52,6 +53,7 @@
"expo-keep-awake": "~56.0.3",
"expo-linking": "~56.0.15",
"expo-navigation-bar": "~56.0.3",
+ "expo-network": "~56.0.5",
"expo-router": "~56.2.14",
"expo-secure-store": "~56.0.4",
"expo-share-intent": "^7.0.0",
@@ -71,6 +73,8 @@
"react-native-image-viewing": "^0.2.2",
"react-native-keyboard-controller": "^1.21.6",
"react-native-markdown-display": "^7.0.2",
+ "react-native-mmkv": "^4.3.2",
+ "react-native-nitro-modules": "^0.36.1",
"react-native-pdf": "7.0.3",
"react-native-reanimated": "~4.3.1",
"react-native-safe-area-context": "~5.7.0",
@@ -80,6 +84,7 @@
"react-native-webview": "13.16.1",
"react-native-worklets": "0.8.3",
"sonner-native": "^0.22.2",
+ "superjson": "^2.2.1",
"tailwind-merge": "^2.2.1",
"zod": "^4.0.0",
"zustand": "^5.0.5"
diff --git a/apps/mobile/tsconfig.json b/apps/mobile/tsconfig.json
index 77379cd1..723255ec 100644
--- a/apps/mobile/tsconfig.json
+++ b/apps/mobile/tsconfig.json
@@ -10,5 +10,5 @@
"@/*": ["./*"]
}
},
- "exclude": ["node_modules"]
+ "exclude": ["node_modules", "android", "ios"]
}
diff --git a/packages/shared-react/providers/trpc-provider.tsx b/packages/shared-react/providers/trpc-provider.tsx
index a23be81e..853fb9ad 100644
--- a/packages/shared-react/providers/trpc-provider.tsx
+++ b/packages/shared-react/providers/trpc-provider.tsx
@@ -95,12 +95,14 @@ function getTRPCClient(settings: Settings) {
export function TRPCSettingsProvider({
settings,
+ queryClient: providedQueryClient,
children,
}: {
settings: Settings;
+ queryClient?: QueryClient;
children: React.ReactNode;
}) {
- const queryClient = getQueryClient();
+ const queryClient = providedQueryClient ?? getQueryClient();
const trpcClient = useMemo(() => getTRPCClient(settings), [settings]);
return (
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5e4e4d57..b71aac4d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -366,6 +366,9 @@ importers:
'@tanstack/react-query':
specifier: 5.90.2
version: 5.90.2([email protected])
+ '@tanstack/react-query-persist-client':
+ specifier: 5.90.2
class-variance-authority:
specifier: ^0.7.0
version: 0.7.0
@@ -420,6 +423,9 @@ importers:
expo-navigation-bar:
specifier: ~56.0.3
version: 56.0.3([email protected])([email protected](patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ expo-network:
+ specifier: ~56.0.5
expo-router:
specifier: ~56.2.14
version: 56.2.14(02bb8983b1bf8a55a1df2fd1b8822fa7)
@@ -477,6 +483,12 @@ importers:
react-native-markdown-display:
specifier: ^7.0.2
version: 7.0.2([email protected](patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ react-native-mmkv:
+ specifier: ^4.3.2
+ version: 4.3.2([email protected]([email protected](patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ react-native-nitro-modules:
+ specifier: ^0.36.1
+ version: 0.36.1([email protected](patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
react-native-pdf:
specifier: 7.0.3
version: 7.0.3([email protected]([email protected](patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
@@ -504,6 +516,9 @@ importers:
sonner-native:
specifier: ^0.22.2
version: 0.22.2(3ea0e606763481413bcc032c6c5d5292)
+ superjson:
+ specifier: ^2.2.1
+ version: 2.2.1
tailwind-merge:
specifier: ^2.2.1
version: 2.2.1
@@ -10479,6 +10494,12 @@ packages:
react: 19.2.3
react-native: '*'
+ resolution: {integrity: sha512-zmuyO95jayDY9jyUfOAlNp9XXJrJaAOkBXXLy0TS/nh2kppj7CHirRPkQ/tf0rsxhIL3AEd9nsRTiPtNsGT9Lw==}
+ peerDependencies:
+ expo: '*'
+ react: 19.2.3
+
resolution: {integrity: sha512-zhJ0YgMxzosxPVTqPJTzTwOCvY06+uFJSW93vFYpF+AyMSZ/DCT+iQew0bwGky6dmWrrIjLBbZ/bv/CdaEdAEg==}
peerDependencies:
@@ -14973,6 +14994,19 @@ packages:
react: 19.2.3
react-native: '>=0.50.4'
+ resolution: {integrity: sha512-49OAyfkg0/TMWiWELZN6VuVQPZPhizwL4DTmp8b7B1md3dB/s3LH3mGfC3T+lp9W0y/rqxZMEnotLFTIbOAenQ==}
+ peerDependencies:
+ react: 19.2.3
+ react-native: '*'
+ react-native-nitro-modules: '*'
+
+ resolution: {integrity: sha512-kBv/VvKqAmkXAvP1DxJMC9b/fRhh7JdSO4EUnPP46hJjrIFeFR8AwKm8mYaKZEuF014M/TVdv2vomVUW0umsQQ==}
+ peerDependencies:
+ react: 19.2.3
+ react-native: '*'
+
resolution: {integrity: sha512-zDtF6CGXPAfGptQZqX7LQK3CVQrIGsD+rYuBnMK0sVmd8mrq7ciwmWXINT+d92emMtZ7+PLnx1IQZIdsh0fphA==}
peerDependencies:
@@ -28153,6 +28187,11 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ expo: 56.0.15(b13258c14f5b3daa9ef39660e3360b0d)
+ react: 19.2.3
+
[email protected](02bb8983b1bf8a55a1df2fd1b8822fa7):
dependencies:
'@expo/log-box': 56.0.14(@expo/[email protected])([email protected])([email protected](patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
@@ -33748,6 +33787,17 @@ snapshots:
react-native: 0.85.3(patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
react-native-fit-image: 1.5.5
+ [email protected]([email protected]([email protected](patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
+ dependencies:
+ react: 19.2.3
+ react-native: 0.85.3(patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native-nitro-modules: 0.36.1([email protected](patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+
+ [email protected]([email protected](patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
+ dependencies:
+ react: 19.2.3
+ react-native: 0.85.3(patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+
[email protected]([email protected]([email protected](patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
crypto-js: 4.2.0