⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.
TypeScript bookmarkbookmark-managercollaborationnextjsreact-nativeread-it-laterself-hostedtypescript
feat(mobile): add persistence
daniel31x1361ca5cf3e51e
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsxindex 708794a3..c5d434bd 100644--- a/apps/mobile/app/_layout.tsx+++ b/apps/mobile/app/_layout.tsx@@ -1,34 +1,51 @@import { Stack } from "expo-router";-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { QueryClient } from "@tanstack/react-query";+import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client";+import { mmkvPersister } from "@/lib/queryPersister";+import { useState } from "react";const queryClient = new QueryClient({defaultOptions: {queries: {- staleTime: 1000 * 30,+ staleTime: 1000 * 60 * 60 * 24, // never refetch for 24h+ refetchOnMount: false,+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,},},});export default function RootLayout() {+ const [isLoading, setIsLoading] = useState(true);+return (- <QueryClientProvider client={queryClient}>- <Stack- screenOptions={{- headerShown: false,- }}- >- {/* <Stack.Screen name="(tabs)" /> */}- <Stack.Screen- name="links/[id]"- options={{- headerBackTitle: "Back",- headerShown: true,- headerTitle: "",+ <PersistQueryClientProvider+ client={queryClient}+ persistOptions={{+ persister: mmkvPersister,+ maxAge: Infinity,+ }}+ onSuccess={() => setIsLoading(false)}+ >+ {!isLoading && (+ <Stack+ screenOptions={{+ headerShown: false,}}- />- <Stack.Screen name="login" />- <Stack.Screen name="+not-found" />- </Stack>- </QueryClientProvider>+ >+ {/* <Stack.Screen name="(tabs)" /> */}+ <Stack.Screen+ name="links/[id]"+ options={{+ headerBackTitle: "Back",+ headerShown: true,+ headerTitle: "",+ }}+ />+ <Stack.Screen name="login" />+ <Stack.Screen name="+not-found" />+ </Stack>+ )}+ </PersistQueryClientProvider>);}diff --git a/apps/mobile/app/links/[id].tsx b/apps/mobile/app/links/[id].tsxindex 99a1cd10..d4ff6712 100644--- a/apps/mobile/app/links/[id].tsx+++ b/apps/mobile/app/links/[id].tsx@@ -1,4 +1,4 @@-import React, { useEffect, useState } from "react";+import React, { useEffect, useMemo, useState } from "react";import {View,ActivityIndicator,@@ -7,73 +7,104 @@ import {TouchableOpacity,} from "react-native";import { WebView } from "react-native-webview";+import * as FileSystem from "expo-file-system";+import NetInfo from "@react-native-community/netinfo";import useAuthStore from "@/store/auth";import { useLocalSearchParams, useRouter } from "expo-router";-import { useGetLink } from "@linkwarden/router/links";import { useUser } from "@linkwarden/router/user";import { generateLinkHref } from "@linkwarden/lib/generateLinkHref";import { useWindowDimensions } from "react-native";import RenderHtml from "@linkwarden/react-native-render-html";import ElementNotSupported from "@/components/ElementNotSupported";-import { LinkIncludingShortenedCollectionAndTags } from "@linkwarden/types";import { decode } from "html-entities";import { IconSymbol } from "@/components/ui/IconSymbol";+import { useLinks } from "@linkwarden/router/links";++const CACHE_DIR = FileSystem.documentDirectory + "archivedData/readable/";+const htmlPath = (id: string) => `${CACHE_DIR}link_${id}.html`;++async function ensureCacheDir() {+ const info = await FileSystem.getInfoAsync(CACHE_DIR);+ if (!info.exists) {+ await FileSystem.makeDirectoryAsync(CACHE_DIR, { intermediates: true });+ }+}export default function LinkScreen() {const { auth } = useAuthStore();const { id, format } = useLocalSearchParams();- const getLink = useGetLink(false, auth);const { data: user } = useUser(auth);const [url, setUrl] = useState<string>();const [htmlContent, setHtmlContent] = useState<string>("");- const [link, setLink] = useState<LinkIncludingShortenedCollectionAndTags>();const [isLoading, setIsLoading] = useState(true);const { width } = useWindowDimensions();const router = useRouter();+ const { links } = useLinks(+ {+ sort: 0,+ },+ auth+ );++ const link = useMemo(() => {+ return links?.find((link) => link.id === Number(id));+ }, [links, id]);useEffect(() => {- async function fetchLinkData() {- const link = await getLink.mutateAsync({ id: Number(id) });+ async function loadCacheOrFetch() {+ await ensureCacheDir();+ const htmlFile = htmlPath(id as string);++ const [htmlInfo] = await Promise.all([FileSystem.getInfoAsync(htmlFile)]);- setLink(link);+ if (format === "3" && htmlInfo.exists) {+ const rawHtml = await FileSystem.readAsStringAsync(htmlFile);+ setHtmlContent(rawHtml);+ setIsLoading(false);+ }- if (link && format === "3") {- const apiUrl = `${auth.instance}/api/v1/archives/${link.id}?format=${format}`;- setUrl(apiUrl);- try {- const response = await fetch(apiUrl, {- headers: { Authorization: `Bearer ${auth.session}` },- });- const html = (await response.json()).content;- setHtmlContent(html);- } catch (e) {- console.error("Failed to fetch HTML content", e);- } finally {- setIsLoading(false);- }- } else if (link && !format) {- setUrl(generateLinkHref(link, user[0], auth.instance, true));- } else if (link && format) {- setUrl(`${auth.instance}/api/v1/archives/${link.id}?format=${format}`);+ const net = await NetInfo.fetch();+ if (net.isConnected) {+ await fetchLinkData();}}- if (user[0]?.id && !url) {- fetchLinkData();+ if (user && user[0]?.id && !url) {+ loadCacheOrFetch();}}, [user, url]);+ async function fetchLinkData() {+ if (link?.id && format === "3") {+ const apiUrl = `${auth.instance}/api/v1/archives/${link.id}?format=${format}`;+ setUrl(apiUrl);+ try {+ const response = await fetch(apiUrl, {+ headers: { Authorization: `Bearer ${auth.session}` },+ });+ const html = (await response.json()).content;+ setHtmlContent(html);+ await FileSystem.writeAsStringAsync(htmlPath(id as string), html, {+ encoding: FileSystem.EncodingType.UTF8,+ });+ } catch (e) {+ console.error("Failed to fetch HTML content", e);+ } finally {+ setIsLoading(false);+ }+ } else if (link?.id && !format) {+ setUrl(generateLinkHref(link, user[0], auth.instance, true));+ } else if (link?.id && format) {+ setUrl(`${auth.instance}/api/v1/archives/${link.id}?format=${format}`);+ }+ }+return (<>{format === "3" && htmlContent ? (<ScrollView- style={{- flex: 1,- backgroundColor: "#fff",- }}- contentContainerStyle={{- padding: 16,- }}+ style={{ flex: 1, backgroundColor: "#fff" }}+ contentContainerStyle={{ padding: 16 }}nestedScrollEnabled><Text style={{ fontSize: 24, fontWeight: "bold", marginBottom: 10 }}>@@ -91,11 +122,7 @@ export default function LinkScreen() {><IconSymbol name="link" size={16} color="gray" /><Text- style={{- fontSize: 16,- color: "gray",- paddingRight: 20,- }}+ style={{ fontSize: 16, color: "gray", paddingRight: 20 }}numberOfLines={1}>{link?.url}@@ -111,12 +138,7 @@ export default function LinkScreen() {}}><IconSymbol name="calendar" size={16} color="gray" />- <Text- style={{- fontSize: 16,- color: "gray",- }}- >+ <Text style={{ fontSize: 16, color: "gray" }}>{new Date((link?.importDate || link?.createdAt) as string).toLocaleString("en-US", {@@ -134,7 +156,7 @@ export default function LinkScreen() {marginTop: 10,marginBottom: 20,}}- ></View>+ /><RenderHtmlcontentWidth={width}@@ -147,32 +169,15 @@ export default function LinkScreen() {),}}tagsStyles={{- p: {- fontSize: 16,- lineHeight: 24,- marginVertical: 10,- },+ p: { fontSize: 16, lineHeight: 24, marginVertical: 10 },}}/></ScrollView>) : (- <View- style={{- flex: 1,- backgroundColor: "#fff",- }}- >+ <View style={{ flex: 1, backgroundColor: "#fff" }}>{url && (<WebView- style={{- ...(isLoading- ? {- opacity: 0,- }- : {- flex: 1,- }),- }}+ style={{ ...(isLoading ? { opacity: 0 } : { flex: 1 }) }}source={{uri: url,headers: { Authorization: `Bearer ${auth.session}` },@@ -198,13 +203,7 @@ export default function LinkScreen() {}}><ActivityIndicator size="large" color="gray" />- <Text- style={{- fontSize: 16,- marginTop: 10,- color: "gray",- }}- >+ <Text style={{ fontSize: 16, marginTop: 10, color: "gray" }}>Loading...</Text></View>diff --git a/apps/mobile/ios/Podfile.lock b/apps/mobile/ios/Podfile.lockindex 798a8656..004a0d50 100644--- a/apps/mobile/ios/Podfile.lock+++ b/apps/mobile/ios/Podfile.lock@@ -1582,6 +1582,29 @@ PODS:- ReactCommon/turbomodule/bridging- ReactCommon/turbomodule/core- Yoga+ - react-native-mmkv (3.2.0):+ - DoubleConversion+ - glog+ - hermes-engine+ - RCT-Folly (= 2024.01.01.00)+ - RCTRequired+ - RCTTypeSafety+ - React-Core+ - React-debug+ - React-Fabric+ - React-featureflags+ - React-graphics+ - React-ImageManager+ - React-NativeModulesApple+ - React-RCTFabric+ - React-rendererdebug+ - React-utils+ - ReactCodegen+ - ReactCommon/turbomodule/bridging+ - ReactCommon/turbomodule/core+ - Yoga+ - react-native-netinfo (11.4.1):+ - React-Core- react-native-safe-area-context (4.12.0):- DoubleConversion- glog@@ -2156,6 +2179,8 @@ DEPENDENCIES:- react-native-ios-context-menu (from `../../../node_modules/react-native-ios-context-menu`)- react-native-ios-utilities (from `../../../node_modules/react-native-ios-utilities`)- "react-native-menu (from `../../../node_modules/@react-native-menu/menu`)"+ - react-native-mmkv (from `../../../node_modules/react-native-mmkv`)+ - "react-native-netinfo (from `../../../node_modules/@react-native-community/netinfo`)"- react-native-safe-area-context (from `../../../node_modules/react-native-safe-area-context`)- react-native-webview (from `../../../node_modules/react-native-webview`)- React-nativeconfig (from `../../../node_modules/react-native/ReactCommon`)@@ -2321,6 +2346,10 @@ EXTERNAL SOURCES::path: "../../../node_modules/react-native-ios-utilities"react-native-menu::path: "../../../node_modules/@react-native-menu/menu"+ react-native-mmkv:+ :path: "../../../node_modules/react-native-mmkv"+ react-native-netinfo:+ :path: "../../../node_modules/@react-native-community/netinfo"react-native-safe-area-context::path: "../../../node_modules/react-native-safe-area-context"react-native-webview:@@ -2453,6 +2482,8 @@ SPEC CHECKSUMS:react-native-ios-context-menu: 626eeee8ec17d97ca4afea3340f60c8fb3705d5freact-native-ios-utilities: 0ba38ec0e525de57ca206366ee56ff87c0524073react-native-menu: bd7ae6c2e88ec505a4e0e098f0683b27195b2d12+ react-native-mmkv: 21d0f6ed2d9532f2370cef81eca4ccbef7350441+ react-native-netinfo: f0a9899081c185db1de5bb2fdc1c88c202a059acreact-native-safe-area-context: 458f6b948437afcb59198016b26bbd02ff9c3b47react-native-webview: 40b8823be3fac70f0404016e6aed754ef4307517React-nativeconfig: f7ab6c152e780b99a8c17448f2d99cf5f69a2311diff --git a/apps/mobile/ios/mobileapp/Info.plist b/apps/mobile/ios/mobileapp/Info.plistindex b793c6dd..21573615 100644--- a/apps/mobile/ios/mobileapp/Info.plist+++ b/apps/mobile/ios/mobileapp/Info.plist@@ -83,5 +83,9 @@<string>Automatic</string><key>UIViewControllerBasedStatusBarAppearance</key><false/>+ <key>UIFileSharingEnabled</key>+ <true/>+ <key>LSSupportsOpeningDocumentsInPlace</key>+ <true/></dict></plist>\ No newline at end of filediff --git a/apps/mobile/lib/queryPersister.ts b/apps/mobile/lib/queryPersister.tsnew file mode 100644index 00000000..c26b552f--- /dev/null+++ b/apps/mobile/lib/queryPersister.ts@@ -0,0 +1,31 @@+import { MMKV } from "react-native-mmkv";+import { Persister } from "@tanstack/react-query-persist-client";++const storage = new MMKV({ id: "react-query" });++export const mmkvPersister: Persister = {+ persistClient: async (client) => {+ try {+ const json = JSON.stringify(client);+ storage.set("REACT_QUERY_CACHE", json);+ } catch (e) {+ console.error("Error persisting client:", e);+ }+ },+ restoreClient: async () => {+ try {+ const json = storage.getString("REACT_QUERY_CACHE");+ return json ? JSON.parse(json) : undefined;+ } catch (e) {+ console.error("Error restoring client:", e);+ return undefined;+ }+ },+ removeClient: async () => {+ try {+ storage.delete("REACT_QUERY_CACHE");+ } catch (e) {+ console.error("Error removing client:", e);+ }+ },+};diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex d9d3ca23..e32c8efe 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -20,14 +20,17 @@"@linkwarden/react-native-render-html": "^6.3.4","@linkwarden/router": "*","@linkwarden/types": "*",+ "@react-native-community/netinfo": "11.4.1","@react-native-menu/menu": "1.2.2","@react-navigation/bottom-tabs": "^7.0.0","@react-navigation/native": "^7.0.0","@tanstack/react-query": "^5.51.15",+ "@tanstack/react-query-persist-client": "^5.51.15","expo": "~52.0.18","expo-blur": "~14.0.1","expo-constants": "~17.0.3","expo-dev-client": "~5.0.6",+ "expo-file-system": "~18.0.12","expo-font": "~13.0.1","expo-haptics": "~14.0.0","expo-linking": "~7.0.3",@@ -45,6 +48,7 @@"react-native-gesture-handler": "~2.20.2","react-native-ios-context-menu": "3.1.0","react-native-ios-utilities": "5.1.2",+ "react-native-mmkv": "^3.2.0","react-native-reanimated": "~3.16.1","react-native-safe-area-context": "4.12.0","react-native-screens": "~4.1.0",diff --git a/apps/mobile/store/auth.ts b/apps/mobile/store/auth.tsindex fa03b7c5..376e2b9e 100644--- a/apps/mobile/store/auth.ts+++ b/apps/mobile/store/auth.ts@@ -57,6 +57,7 @@ const useAuthStore = create<AuthStore>((set) => ({"Content-Type": "application/json",},}).then(async (res) => {+ console.log("Response", res);if (res.ok) {const data = await res.json();const session = (data as any).response.token;diff --git a/apps/web/lib/api/controllers/links/linkId/getLinkById.ts b/apps/web/lib/api/controllers/links/linkId/getLinkById.tsindex df6aa07f..627e3331 100644--- a/apps/web/lib/api/controllers/links/linkId/getLinkById.ts+++ b/apps/web/lib/api/controllers/links/linkId/getLinkById.ts@@ -1,5 +1,5 @@import { prisma } from "@linkwarden/prisma";-import { Collection, UsersAndCollections } from "@linkwarden/prisma/client";+import { UsersAndCollections } from "@linkwarden/prisma/client";import getPermission from "@/lib/api/getPermission";export default async function getLinkById(userId: number, linkId: number) {diff --git a/yarn.lock b/yarn.lockindex 11c7c99f..4f6ee5f5 100644--- a/yarn.lock+++ b/yarn.lock@@ -3436,6 +3436,11 @@resolved "https://registry.yarnpkg.com/@radix-ui/rect/-/rect-1.1.1.tgz#78244efe12930c56fd255d7923865857c41ac8cb"integrity sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw==+"@react-native-community/[email protected]":+ version "11.4.1"+ resolved "https://registry.yarnpkg.com/@react-native-community/netinfo/-/netinfo-11.4.1.tgz#a3c247aceab35f75dd0aa4bfa85d2be5a4508688"+ integrity sha512-B0BYAkghz3Q2V09BF88RA601XursIEA111tnc2JOaN7axJWmNefmfjZqw/KdSxKZp7CZUuPpjBmz/WCR9uaHYg==+"@react-native-menu/[email protected]":version "1.2.2"resolved "https://registry.yarnpkg.com/@react-native-menu/menu/-/menu-1.2.2.tgz#550d158f1496ae27cb68424d540d74ee08f6c181"@@ -4230,11 +4235,23 @@resolved "https://registry.yarnpkg.com/@tanstack/query-core/-/query-core-5.51.15.tgz#7aee6a2d5d3f64de3e54096607233b1132dc6afd"integrity sha512-xyobHDJ0yhPE3+UkSQ2/4X1fLSg7ICJI5J1JyU9yf7F3deQfEwSImCDrB1WSRrauJkMtXW7YIEcC0oA6ZZWt5A==+"@tanstack/[email protected]":+ version "5.76.0"+ resolved "https://registry.yarnpkg.com/@tanstack/query-core/-/query-core-5.76.0.tgz#3b4d5d34ce307ba0cf7d1a3e90d7adcdc6c46be0"+ integrity sha512-FN375hb8ctzfNAlex5gHI6+WDXTNpe0nbxp/d2YJtnP+IBM6OUm7zcaoCW6T63BawGOYZBbKC0iPvr41TteNVg==+"@tanstack/[email protected]":version "5.51.15"resolved "https://registry.yarnpkg.com/@tanstack/query-devtools/-/query-devtools-5.51.15.tgz#81c5c28231adc4b95fe4a5e1004020fdca5ea447"integrity sha512-1oSCl+PsCa/aBCGVM2ZdcQLuQ0QYmKXJJB264twEMVM1M0n5CI40trtywORPF+wLGuZNIZzkKL7j/98mOLAIag==+"@tanstack/[email protected]":+ version "5.76.1"+ resolved "https://registry.yarnpkg.com/@tanstack/query-persist-client-core/-/query-persist-client-core-5.76.1.tgz#82df844e3eb1870838873d81954cf46f7d6323ec"+ integrity sha512-BkNL5QMXLwTMv5po6Ex68/xWCWdnjxx2rWeRf/we6hCI5dCN5Yf+GCbsJcSuc27I2paQJ1xFbfYs18Zmc1kJmA==+ dependencies:+ "@tanstack/query-core" "5.76.0"+"@tanstack/react-query-devtools@^5.51.15":version "5.51.15"resolved "https://registry.yarnpkg.com/@tanstack/react-query-devtools/-/react-query-devtools-5.51.15.tgz#5c4d21305fd25c35dc88bd280304f77a45554fc2"@@ -4242,6 +4259,13 @@dependencies:"@tanstack/query-devtools" "5.51.15"+"@tanstack/react-query-persist-client@^5.51.15":+ version "5.76.1"+ resolved "https://registry.yarnpkg.com/@tanstack/react-query-persist-client/-/react-query-persist-client-5.76.1.tgz#d4badc3d23d74eb10991761d3f4d0b29c026c9f6"+ integrity sha512-LN8LLBDyQLTBifbL3HIAOPh48MNw2y5ff49nBUsJO6nwpl3iRKp6qwQ58rGUqHflvuAfKQKeJIvwSXMvckxJMg==+ dependencies:+ "@tanstack/query-persist-client-core" "5.76.1"+"@tanstack/react-query@^5.51.15":version "5.51.15"resolved "https://registry.yarnpkg.com/@tanstack/react-query/-/react-query-5.51.15.tgz#059bb2966f828263adb355de81410d107e22b5bc"@@ -10980,6 +11004,11 @@ react-native-is-edge-to-edge@^1.1.6:resolved "https://registry.yarnpkg.com/react-native-is-edge-to-edge/-/react-native-is-edge-to-edge-1.1.7.tgz#28947688f9fafd584e73a4f935ea9603bd9b1939"integrity sha512-EH6i7E8epJGIcu7KpfXYXiV2JFIYITtq+rVS8uEb+92naMRBdxhTuS8Wn2Q7j9sqyO0B+Xbaaf9VdipIAmGW4w==+react-native-mmkv@^3.2.0:+ version "3.2.0"+ resolved "https://registry.yarnpkg.com/react-native-mmkv/-/react-native-mmkv-3.2.0.tgz#460723eb23b9cc92c65b0416eae9874a6ddf5b82"+ integrity sha512-9y7K//1MaU46TFrXkyU0wT5VGk9Y2FDLFV6NPl+z3jTbm2G7SC1UIxneF6CfhSmBX5CfKze9SO7kwDuRx7flpQ==+react-native-reanimated@~3.16.1:version "3.16.7"resolved "https://registry.yarnpkg.com/react-native-reanimated/-/react-native-reanimated-3.16.7.tgz#6c7fa516f62c6743c24d955dada00e3c5323d50d"