Skip to content

⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.

feat: unify preservation polling (no more refreshes to load formats)

daniel31x13e0b89b193c42
diff --git a/apps/mobile/app/links/[id].tsx b/apps/mobile/app/links/[id].tsx
index 34844eea..79be6b57 100644
--- a/apps/mobile/app/links/[id].tsx
+++ b/apps/mobile/app/links/[id].tsx
@@ -86,18 +86,8 @@ export default function LinkScreen() {
!formatAvailable(link, linkType);
useEffect(() => {
- if (!formatPending) return;
-
- setIsLoading(true);
-
- const interval = setInterval(() => {
- refetchLink().catch((error) => {
- console.error("Error refetching link:", error);
- });
- }, 5000);
-
- return () => clearInterval(interval);
- }, [formatPending, refetchLink]);
+ if (formatPending) setIsLoading(true);
+ }, [formatPending]);
useEffect(() => {
if (link?.id && user?.id)
diff --git a/apps/mobile/components/ActionSheets/LinkDetailsSheet.tsx b/apps/mobile/components/ActionSheets/LinkDetailsSheet.tsx
index 9f1df66b..07a676ed 100644
--- a/apps/mobile/components/ActionSheets/LinkDetailsSheet.tsx
+++ b/apps/mobile/components/ActionSheets/LinkDetailsSheet.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState, type ReactNode } from "react";
+import { type ReactNode } from "react";
import {
ActivityIndicator,
Linking,
@@ -31,10 +31,11 @@ import { Button } from "@/components/ui/Button";
import { rawTheme, ThemeName } from "@/lib/colors";
import useAuthStore from "@/store/auth";
import useDataStore from "@/store/data";
-import { useUser } from "@linkwarden/router/user";
+import { useGetLink } from "@linkwarden/router/links";
import {
atLeastOneFormatAvailable,
formatAvailable,
+ isPreservationPending,
} from "@linkwarden/lib/formatStats";
import getOriginalFormat from "@linkwarden/lib/getOriginalFormat";
import {
@@ -43,26 +44,6 @@ import {
} from "@linkwarden/types/global";
import SheetHeader from "./SheetHeader";
-type CollectionOwner = {
- id: number | null;
- name: string;
- username: string;
- image: string;
- archiveAsScreenshot?: boolean;
- archiveAsMonolith?: boolean;
- archiveAsPDF?: boolean;
-};
-
-const initialCollectionOwner: CollectionOwner = {
- id: null,
- name: "",
- username: "",
- image: "",
- archiveAsScreenshot: undefined,
- archiveAsMonolith: undefined,
- archiveAsPDF: undefined,
-};
-
function SectionLabel({ children }: { children: string }) {
return <Text className="mb-2 text-sm text-neutral">{children}</Text>;
}
@@ -92,79 +73,19 @@ export default function LinkDetailsSheet(
) {
const { auth } = useAuthStore();
const { data } = useDataStore();
- const { data: user } = useUser(auth);
const { colorScheme } = useColorScheme();
const insets = useSafeAreaInsets();
const { height } = useWindowDimensions();
const router = useRouter();
const theme = rawTheme[colorScheme as ThemeName];
- const [link, setLink] =
- useState<LinkIncludingShortenedCollectionAndTags | null>(
- props.payload?.link ?? null
- );
- const [collectionOwner, setCollectionOwner] = useState<CollectionOwner>(
- initialCollectionOwner
- );
-
- useEffect(() => {
- setLink(props.payload?.link ?? null);
- }, [props.payload?.link]);
-
- useEffect(() => {
- if (!link?.collection.ownerId || !auth.instance) {
- setCollectionOwner(initialCollectionOwner);
- return;
- }
-
- let cancelled = false;
-
- const fetchOwner = async () => {
- if (link.collection.ownerId === user?.id) {
- if (!cancelled) {
- setCollectionOwner({
- id: user.id,
- name: user.name || "",
- username: user.username || "",
- image: user.image || "",
- archiveAsScreenshot: user.archiveAsScreenshot,
- archiveAsMonolith: user.archiveAsMonolith,
- archiveAsPDF: user.archiveAsPDF,
- });
- }
-
- return;
- }
-
- try {
- const response = await fetch(
- `${auth.instance}/api/v1/public/users/${link.collection.ownerId}`,
- auth.session
- ? {
- headers: {
- Authorization: `Bearer ${auth.session}`,
- },
- }
- : undefined
- );
-
- const payload = await response.json();
-
- if (!response.ok || cancelled) {
- return;
- }
-
- setCollectionOwner(payload.response as CollectionOwner);
- } catch (error) {
- console.error("Failed to load collection owner", error);
- }
- };
-
- fetchOwner();
-
- return () => {
- cancelled = true;
- };
- }, [auth.instance, auth.session, link?.collection.ownerId, user]);
+ const payloadLink = props.payload?.link ?? null;
+ const { data: fetchedLink } = useGetLink({
+ id: payloadLink?.id as number,
+ auth,
+ enabled: payloadLink?.id != null,
+ });
+ const link: LinkIncludingShortenedCollectionAndTags | null =
+ fetchedLink?.id != null ? fetchedLink : payloadLink;
const closeSheet = () => {
SheetManager.hide("link-details-sheet");
@@ -223,16 +144,7 @@ export default function LinkDetailsSheet(
);
};
- const isReady = () => {
- if (!link) return false;
-
- return (
- (collectionOwner.archiveAsScreenshot === true ? link.image : true) &&
- (collectionOwner.archiveAsMonolith === true ? link.monolith : true) &&
- (collectionOwner.archiveAsPDF === true ? link.pdf : true) &&
- link.readable
- );
- };
+ const isReady = () => Boolean(link?.id) && !isPreservationPending(link);
const formattedSavedDate = link?.createdAt
? new Date(link.createdAt).toLocaleDateString("en-US", {
@@ -259,10 +171,6 @@ export default function LinkDetailsSheet(
backgroundColor: theme["base-200"],
}}
safeAreaInsets={insets}
- onClose={() => {
- setLink(null);
- setCollectionOwner(initialCollectionOwner);
- }}
>
<SheetHeader title="Link Details" onClose={closeSheet} />
diff --git a/apps/mobile/components/ActionSheets/RefreshPreservedFormatsSheet.tsx b/apps/mobile/components/ActionSheets/RefreshPreservedFormatsSheet.tsx
index 57da2dd2..2829c803 100644
--- a/apps/mobile/components/ActionSheets/RefreshPreservedFormatsSheet.tsx
+++ b/apps/mobile/components/ActionSheets/RefreshPreservedFormatsSheet.tsx
@@ -1,4 +1,4 @@
-import { useRef, useState } from "react";
+import { useRef } from "react";
import { Alert, Text, View } from "react-native";
import ActionSheet, {
ActionSheetRef,
@@ -7,7 +7,7 @@ import ActionSheet, {
} from "react-native-actions-sheet";
import { useColorScheme } from "nativewind";
import { useSafeAreaInsets } from "react-native-safe-area-context";
-import { useQueryClient } from "@tanstack/react-query";
+import { useUpdateArchive } from "@linkwarden/router/links";
import useAuthStore from "@/store/auth";
import { rawTheme, ThemeName } from "@/lib/colors";
import { deleteLinkCache } from "@/lib/cache";
@@ -23,9 +23,11 @@ export default function RefreshPreservedFormatsSheet(
const insets = useSafeAreaInsets();
const { auth } = useAuthStore();
- const queryClient = useQueryClient();
- const [loading, setLoading] = useState(false);
+ const updateArchive = useUpdateArchive({
+ auth,
+ onAfterSuccess: (id) => deleteLinkCache(id),
+ });
const linkId = props.payload?.linkId;
@@ -34,39 +36,16 @@ export default function RefreshPreservedFormatsSheet(
};
const handleRefresh = async () => {
- if (!linkId || loading) return;
-
- setLoading(true);
+ if (!linkId || updateArchive.isPending) return;
try {
- const response = await fetch(
- `${auth.instance}/api/v1/links/${linkId}/archive`,
- {
- method: "PUT",
- headers: {
- Authorization: `Bearer ${auth.session}`,
- },
- }
- );
-
- if (!response.ok) {
- const data = await response.json().catch(() => ({}));
- throw new Error(
- data?.response || "Could not refresh the preserved formats."
- );
- }
-
- await deleteLinkCache(linkId);
- queryClient.invalidateQueries({ queryKey: ["link", linkId] });
-
+ await updateArchive.mutateAsync(linkId);
await SheetManager.hide(props.sheetId);
} catch (error: any) {
Alert.alert(
"Error",
error?.message || "Could not refresh the preserved formats."
);
- } finally {
- setLoading(false);
}
};
@@ -92,7 +71,7 @@ export default function RefreshPreservedFormatsSheet(
<Button
onPress={handleRefresh}
- isLoading={loading}
+ isLoading={updateArchive.isPending}
variant="destructive"
className="mt-5"
>
diff --git a/apps/mobile/components/DashboardSection.tsx b/apps/mobile/components/DashboardSection.tsx
index 11f81264..0e8a3c91 100644
--- a/apps/mobile/components/DashboardSection.tsx
+++ b/apps/mobile/components/DashboardSection.tsx
@@ -1,10 +1,4 @@
-import {
- FlatList,
- Text,
- TouchableOpacity,
- View,
- ViewToken,
-} from "react-native";
+import { FlatList, Text, TouchableOpacity, View } from "react-native";
import React from "react";
import clsx from "clsx";
import DashboardItem from "@/components/DashboardItem";
@@ -21,7 +15,6 @@ import { LinkIncludingShortenedCollectionAndTags } from "@linkwarden/types/globa
import LinkListing from "@/components/LinkListing";
import { useColorScheme } from "nativewind";
import { useRouter } from "expo-router";
-import { hasOptimisticLink } from "@/lib/utils";
// Don't use prisma client's DashboardSectionType, it'll crash in production (React Native)
type DashboardSectionType =
@@ -140,26 +133,6 @@ const DashboardSection: React.FC<DashboardSectionProps> = ({
contentContainerStyle={{
paddingHorizontal: 20,
}}
- onViewableItemsChanged={({
- viewableItems,
- }: {
- viewableItems: ViewToken[];
- }) => {
- const links = viewableItems.map(
- (e) => e.item
- ) as LinkIncludingShortenedCollectionAndTags[];
-
- if (
- !dashboardData.isRefetching &&
- !hasOptimisticLink(links) &&
- links.some(
- (e) => typeof e.id === "number" && e.id > 0 && !e.preview
- )
- ) {
- dashboardData.refetch();
- }
- }}
- viewabilityConfig={{ itemVisiblePercentThreshold: 50 }}
/>
) : (
<View className="flex-col gap-2 justify-center items-center h-40 p-10 rounded-xl bg-base-200 mx-5">
@@ -226,26 +199,6 @@ const DashboardSection: React.FC<DashboardSectionProps> = ({
contentContainerStyle={{
paddingHorizontal: 20,
}}
- onViewableItemsChanged={({
- viewableItems,
- }: {
- viewableItems: ViewToken[];
- }) => {
- const links = viewableItems.map(
- (e) => e.item
- ) as LinkIncludingShortenedCollectionAndTags[];
-
- if (
- !dashboardData.isRefetching &&
- !hasOptimisticLink(links) &&
- links.some(
- (e) => typeof e.id === "number" && e.id > 0 && !e.preview
- )
- ) {
- dashboardData.refetch();
- }
- }}
- viewabilityConfig={{ itemVisiblePercentThreshold: 50 }}
/>
) : (
<View className="flex-col gap-2 justify-center items-center h-40 p-10 rounded-xl bg-base-200 mx-5">
@@ -311,26 +264,6 @@ const DashboardSection: React.FC<DashboardSectionProps> = ({
contentContainerStyle={{
paddingHorizontal: 20,
}}
- onViewableItemsChanged={({
- viewableItems,
- }: {
- viewableItems: ViewToken[];
- }) => {
- const links = viewableItems.map(
- (e) => e.item
- ) as LinkIncludingShortenedCollectionAndTags[];
-
- if (
- !dashboardData.isRefetching &&
- !hasOptimisticLink(links) &&
- links.some(
- (e) => typeof e.id === "number" && e.id > 0 && !e.preview
- )
- ) {
- dashboardData.refetch();
- }
- }}
- viewabilityConfig={{ itemVisiblePercentThreshold: 50 }}
/>
) : (
<View className="flex-col gap-2 justify-center items-center h-40 p-10 rounded-xl bg-base-200 mx-5">
diff --git a/apps/mobile/components/Links.tsx b/apps/mobile/components/Links.tsx
index a4e8d191..a2f23759 100644
--- a/apps/mobile/components/Links.tsx
+++ b/apps/mobile/components/Links.tsx
@@ -1,4 +1,4 @@
-import { View, FlatList, Text, ActivityIndicator, ViewToken } from "react-native";
+import { View, FlatList, Text, ActivityIndicator } from "react-native";
import LinkListing from "@/components/LinkListing";
import EmptyState from "@/components/EmptyState";
import React, { useState } from "react";
@@ -8,7 +8,6 @@ import { rawTheme, ThemeName } from "@/lib/colors";
import { useColorScheme } from "nativewind";
import { useQueryClient } from "@tanstack/react-query";
import { resetInfiniteQueryPagination } from "@linkwarden/router/lib";
-import { hasOptimisticLink } from "@/lib/utils";
const RenderItem = React.memo(
({ item }: { item: LinkIncludingShortenedCollectionAndTags }) => {
@@ -70,23 +69,6 @@ export default function Links({ links, data }: Props) {
</View>
) : null
}
- onViewableItemsChanged={({
- viewableItems,
- }: {
- viewableItems: ViewToken[];
- }) => {
- const links = viewableItems.map(
- (e) => e.item
- ) as LinkIncludingShortenedCollectionAndTags[];
-
- if (
- !data.isRefetching &&
- !hasOptimisticLink(links) &&
- links.some((e) => typeof e.id === "number" && e.id > 0 && !e.preview)
- )
- data.refetch();
- }}
- viewabilityConfig={{ itemVisiblePercentThreshold: 50 }}
/>
);
}
diff --git a/apps/mobile/lib/utils.ts b/apps/mobile/lib/utils.ts
deleted file mode 100644
index 4c4aa632..00000000
--- a/apps/mobile/lib/utils.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { LinkIncludingShortenedCollectionAndTags } from "@linkwarden/types/global";
-
-/**
- * Optimistic (just-added) links carry a temporary negative id and only exist
- * in the local cache until the create mutation resolves. While one is present
- * we must avoid full-list refetches, which would replace the cache with a server snapshot
- * that doesn't include it yet, making it flash out and back in.
- */
-export const hasOptimisticLink = (
- links: LinkIncludingShortenedCollectionAndTags[]
-) => links.some((e) => typeof e.id === "number" && e.id < 0);
diff --git a/apps/web/components/DashboardLinks.tsx b/apps/web/components/DashboardLinks.tsx
index 8ef80529..a45714f3 100644
--- a/apps/web/components/DashboardLinks.tsx
+++ b/apps/web/components/DashboardLinks.tsx
@@ -4,7 +4,7 @@ import {
ArchivedFormat,
CollectionIncludingMembersAndLinkCount,
} from "@linkwarden/types/global";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useState } from "react";
import unescapeString from "@/lib/client/unescapeString";
import LinkActions from "@/components/LinkViews/LinkComponents/LinkActions";
import LinkDate from "@/components/LinkViews/LinkComponents/LinkDate";
@@ -14,10 +14,8 @@ import {
atLeastOneFormatAvailable,
formatAvailable,
} from "@linkwarden/lib/formatStats";
-import useOnScreen from "@/hooks/useOnScreen";
import { useCollections } from "@linkwarden/router/collections";
import { useUser } from "@linkwarden/router/user";
-import { useGetLink } from "@linkwarden/router/links";
import { useRouter } from "next/router";
import openLink from "@/lib/client/openLink";
import LinkIcon from "./LinkViews/LinkComponents/LinkIcon";
@@ -85,8 +83,6 @@ export function Card({ link, editMode, dashboardType }: Props) {
const router = useRouter();
const isPublicRoute = router.pathname.startsWith("/public") ? true : false;
- const { refetch } = useGetLink({ id: link.id as number, isPublicRoute });
-
const [collection, setCollection] =
useState<CollectionIncludingMembersAndLinkCount>(
collections.find(
@@ -102,33 +98,8 @@ export function Card({ link, editMode, dashboardType }: Props) {
);
}, [collections, link]);
- const ref = useRef<HTMLDivElement>(null);
- const isVisible = useOnScreen(ref);
-
const [linkModal, setLinkModal] = useState(false);
- useEffect(() => {
- let interval: ReturnType<typeof setInterval> | null = null;
-
- if (
- isVisible &&
- !link.preview?.startsWith("archives") &&
- link.preview !== "unavailable"
- ) {
- interval = setInterval(async () => {
- refetch().catch((error) => {
- console.error("Error refetching link:", error);
- });
- }, 5000);
- }
-
- return () => {
- if (interval) {
- clearInterval(interval);
- }
- };
- }, [isVisible, link.preview]);
-
return (
<div
ref={setNodeRef}
@@ -138,7 +109,6 @@ export function Card({ link, editMode, dashboardType }: Props) {
)}
>
<div
- ref={ref}
className={`min-w-60 w-60 border border-solid border-neutral-content bg-base-200 duration-100 rounded-xl relative group h-full`}
>
<div
diff --git a/apps/web/components/LinkDetails.tsx b/apps/web/components/LinkDetails.tsx
index 84553d75..5ed182ed 100644
--- a/apps/web/components/LinkDetails.tsx
+++ b/apps/web/components/LinkDetails.tsx
@@ -7,6 +7,7 @@ import Link from "next/link";
import {
atLeastOneFormatAvailable,
formatAvailable,
+ isPreservationPending,
} from "@linkwarden/lib/formatStats";
import PreservedFormatRow from "@/components/PreserverdFormatRow";
import getPublicUserData from "@/lib/client/getPublicUserData";
@@ -103,15 +104,7 @@ export default function LinkDetails({
fetchOwner();
}, [link.collection.ownerId]);
- const isReady = () => {
- return (
- link &&
- (collectionOwner.archiveAsScreenshot === true ? link.pdf : true) &&
- (collectionOwner.archiveAsMonolith === true ? link.monolith : true) &&
- (collectionOwner.archiveAsPDF === true ? link.pdf : true) &&
- link.readable
- );
- };
+ const isReady = () => Boolean(link?.id) && !isPreservationPending(link);
const updateLink = useUpdateLink({ toast, t });
const updateFile = useUpdateFile();
diff --git a/apps/web/components/LinkViews/LinkComponents/LinkActions.tsx b/apps/web/components/LinkViews/LinkComponents/LinkActions.tsx
index e3d6bebd..54534486 100644
--- a/apps/web/components/LinkViews/LinkComponents/LinkActions.tsx
+++ b/apps/web/components/LinkViews/LinkComponents/LinkActions.tsx
@@ -2,7 +2,7 @@ import { useState } from "react";
import { LinkIncludingShortenedCollectionAndTags } from "@linkwarden/types/global";
import usePermissions from "@/hooks/usePermissions";
import DeleteLinkModal from "@/components/ModalContent/DeleteLinkModal";
-import { useDeleteLink, useGetLink } from "@linkwarden/router/links";
+import { useDeleteLink, useUpdateArchive } from "@linkwarden/router/links";
import toast from "react-hot-toast";
import LinkModal from "@/components/ModalContent/LinkModal";
import { useRouter } from "next/router";
@@ -42,10 +42,7 @@ export default function LinkActions({
const isPublicRoute = router.pathname.startsWith("/public");
- const { refetch } = useGetLink({
- id: link.id as number,
- isPublicRoute,
- });
+ const updateArchiveMutation = useUpdateArchive();
const pinLink = usePinLink();
@@ -59,20 +56,14 @@ export default function LinkActions({
const updateArchive = async () => {
const load = toast.loading(t("sending_request"));
- const response = await fetch(`/api/v1/links/${link?.id}/archive`, {
- method: "PUT",
- });
-
- const data = await response.json();
- toast.dismiss(load);
-
- if (response.ok) {
- refetch().catch((error) => {
- console.error("Error fetching link:", error);
- });
-
+ try {
+ await updateArchiveMutation.mutateAsync(link.id as number);
toast.success(t("link_being_archived"));
- } else toast.error(data.response);
+ } catch (error: any) {
+ toast.error(error.message);
+ } finally {
+ toast.dismiss(load);
+ }
};
return (
diff --git a/apps/web/components/LinkViews/Links.tsx b/apps/web/components/LinkViews/Links.tsx
index 9dacd62d..c0946b0c 100644
--- a/apps/web/components/LinkViews/Links.tsx
+++ b/apps/web/components/LinkViews/Links.tsx
@@ -402,28 +402,6 @@ export default function Links({
}
}, [editMode]);
- useEffect(() => {
- let interval: ReturnType<typeof setInterval> | null = null;
-
- if (
- links?.some(
- (e) => !e.preview?.startsWith("archives") && e.preview !== "unavailable"
- )
- ) {
- interval = setInterval(async () => {
- useData.refetch().catch((error: any) => {
- console.error("Error refetching link:", error);
- });
- }, 5000);
- }
-
- return () => {
- if (interval) {
- clearInterval(interval);
- }
- };
- }, [links]);
-
const disableDraggable = useMediaQuery("(max-width: 1023px)");
const { data: user } = useUser();
diff --git a/apps/web/components/Preservation/PreservationPageContent.tsx b/apps/web/components/Preservation/PreservationPageContent.tsx
index f71c2b90..12aad78e 100644
--- a/apps/web/components/Preservation/PreservationPageContent.tsx
+++ b/apps/web/components/Preservation/PreservationPageContent.tsx
@@ -1,43 +1,22 @@
-import React, { useEffect, useRef, useState } from "react";
+import React, { useRef } from "react";
import { useRouter } from "next/router";
-import { useGetLink, useLinks } from "@linkwarden/router/links";
+import { useGetLink } from "@linkwarden/router/links";
import { PreservationContent } from "./PreservationContent";
import PreservationNavbar from "./PreservationNavbar";
export default function PreservationPageContent() {
const router = useRouter();
- const { links } = useLinks();
const scrollRef = useRef<HTMLDivElement>(null);
let isPublicRoute = router.pathname.startsWith("/public") ? true : undefined;
- const { data: link, refetch } = useGetLink({
+ const { data: link } = useGetLink({
id: Number(router.query.id),
isPublicRoute,
enabled: true,
});
- useEffect(() => {
- let interval: ReturnType<typeof setInterval> | null = null;
- if (
- link &&
- (!link?.image || !link?.pdf || !link?.readable || !link?.monolith)
- ) {
- interval = setInterval(() => {
- refetch().catch((error) => {
- console.error("Error refetching link:", error);
- });
- }, 5000);
- } else if (interval) {
- clearInterval(interval);
- }
-
- return () => {
- if (interval) clearInterval(interval);
- };
- }, [links]);
-
return (
<div>
{link?.id && (
diff --git a/apps/web/hooks/useOnScreen.tsx b/apps/web/hooks/useOnScreen.tsx
deleted file mode 100644
index 053a6128..00000000
--- a/apps/web/hooks/useOnScreen.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-import { RefObject, useEffect, useMemo, useState } from "react";
-
-export default function useOnScreen(ref: RefObject<HTMLElement | null>) {
- const [isIntersecting, setIntersecting] = useState(false);
-
- const observer = useMemo(
- () =>
- new IntersectionObserver(([entry]) =>
- setIntersecting(entry.isIntersecting)
- ),
- [ref]
- );
-
- useEffect(() => {
- observer.observe(ref.current as HTMLElement);
- return () => observer.disconnect();
- }, []);
-
- return isIntersecting;
-}
diff --git a/packages/lib/formatStats.ts b/packages/lib/formatStats.ts
index c1ee4dff..bede2686 100644
--- a/packages/lib/formatStats.ts
+++ b/packages/lib/formatStats.ts
@@ -18,3 +18,28 @@ export const atLeastOneFormatAvailable = (
formatAvailable(link, "monolith")
);
};
+
+export const isPreservationPending = (
+ link?: Partial<Link> | LinkIncludingShortenedCollectionAndTags | null
+) =>
+ Boolean(
+ link &&
+ typeof link.id === "number" &&
+ link.id > 0 &&
+ link.url &&
+ !link.lastPreserved
+ );
+
+/**
+ * Optimistic (just-added) links carry a temporary negative id and only exist
+ * in the local cache until the create mutation resolves. While one is present
+ * we must avoid full-list refetches, which would replace the cache with a
+ * server snapshot that doesn't include it yet, making it flash out and back in.
+ */
+export const hasOptimisticLink = (
+ links: (Partial<Link> | LinkIncludingShortenedCollectionAndTags)[]
+) => links.some((e) => typeof e.id === "number" && e.id < 0);
+
+export const anyPreservationPending = (
+ links: (Partial<Link> | LinkIncludingShortenedCollectionAndTags)[]
+) => !hasOptimisticLink(links) && links.some(isPreservationPending);
diff --git a/packages/router/dashboardData.tsx b/packages/router/dashboardData.tsx
index 07b91a64..9818b00a 100644
--- a/packages/router/dashboardData.tsx
+++ b/packages/router/dashboardData.tsx
@@ -1,5 +1,10 @@
import { UpdateDashboardLayoutSchemaType } from "@linkwarden/lib/schemaValidation";
-import { MobileAuth } from "@linkwarden/types/global";
+import {
+ LinkIncludingShortenedCollectionAndTags,
+ MobileAuth,
+} from "@linkwarden/types/global";
+import { anyPreservationPending } from "@linkwarden/lib/formatStats";
+import { PRESERVATION_POLL_INTERVAL } from "./links";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useSession } from "next-auth/react";
@@ -34,6 +39,23 @@ const useDashboardData = (auth?: MobileAuth) => {
return data.data;
},
enabled: status === "authenticated",
+ refetchInterval: (query) => {
+ const data = query.state.data as
+ | {
+ links?: LinkIncludingShortenedCollectionAndTags[];
+ collectionLinks?: Record<
+ number,
+ LinkIncludingShortenedCollectionAndTags[]
+ >;
+ }
+ | undefined;
+ if (!data) return false;
+ const links = [
+ ...(data.links ?? []),
+ ...Object.values(data.collectionLinks ?? {}).flat(),
+ ];
+ return anyPreservationPending(links) ? PRESERVATION_POLL_INTERVAL : false;
+ },
});
};
diff --git a/packages/router/links.tsx b/packages/router/links.tsx
index 824b1417..31a12e34 100644
--- a/packages/router/links.tsx
+++ b/packages/router/links.tsx
@@ -20,9 +20,15 @@ import {
} from "@linkwarden/lib/schemaValidation";
import getFormatFromContentType from "@linkwarden/lib/getFormatFromContentType";
import getLinkTypeFromFormat from "@linkwarden/lib/getLinkTypeFromFormat";
+import {
+ anyPreservationPending,
+ isPreservationPending,
+} from "@linkwarden/lib/formatStats";
import type toaster from "react-hot-toast";
import { TFunction } from "next-i18next";
+export const PRESERVATION_POLL_INTERVAL = 5000;
+
const useLinks = (params: LinkRequestQuery = {}, auth?: MobileAuth) => {
const sort =
params.sort ??
@@ -100,6 +106,11 @@ const useFetchLinks = (params: string, auth?: MobileAuth) => {
refetchOnWindowFocus: false,
getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
enabled: status === "authenticated",
+ refetchInterval: (query) => {
+ const links =
+ query.state.data?.pages?.flatMap((p) => p?.links ?? []) ?? [];
+ return anyPreservationPending(links) ? PRESERVATION_POLL_INTERVAL : false;
+ },
});
};
@@ -831,6 +842,10 @@ const useGetLink = ({
queryKey: ["link", id, isPublicRoute],
placeholderData: {} as LinkIncludingShortenedCollectionAndTags,
enabled: id != null && enabled,
+ refetchInterval: (query) =>
+ isPreservationPending(query.state.data)
+ ? PRESERVATION_POLL_INTERVAL
+ : false,
queryFn: async () => {
const base = auth?.instance ?? "";
const route = isPublicRoute
@@ -1117,6 +1132,44 @@ const useBulkEditLinks = () => {
});
};
+const useUpdateArchive = ({
+ auth,
+ onAfterSuccess,
+}: {
+ auth?: MobileAuth;
+ onAfterSuccess?: (linkId: number) => void | Promise<void>;
+} = {}) => {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: async (linkId: number) => {
+ const response = await fetch(
+ (auth?.instance ?? "") + `/api/v1/links/${linkId}/archive`,
+ {
+ method: "PUT",
+ headers: auth?.session
+ ? { Authorization: `Bearer ${auth.session}` }
+ : undefined,
+ }
+ );
+
+ const data = await response.json().catch(() => ({}));
+ if (!response.ok)
+ throw new Error(
+ data?.response || "Failed to refresh preserved formats."
+ );
+
+ return linkId;
+ },
+ onSuccess: async (linkId) => {
+ await onAfterSuccess?.(linkId);
+ queryClient.invalidateQueries({ queryKey: ["link", linkId] });
+ queryClient.invalidateQueries({ queryKey: ["links"] });
+ queryClient.invalidateQueries({ queryKey: ["dashboardData"] });
+ },
+ });
+};
+
const useArchiveAction = () => {
const queryClient = useQueryClient();
@@ -1154,5 +1207,6 @@ export {
useGetLink,
useBulkEditLinks,
useArchiveAction,
+ useUpdateArchive,
useUpdateFile,
};
diff --git a/packages/router/publicLinks.tsx b/packages/router/publicLinks.tsx
index 27595c16..d1c74876 100644
--- a/packages/router/publicLinks.tsx
+++ b/packages/router/publicLinks.tsx
@@ -4,6 +4,8 @@ import {
LinkIncludingShortenedCollectionAndTags,
LinkRequestQuery,
} from "@linkwarden/types/global";
+import { anyPreservationPending } from "@linkwarden/lib/formatStats";
+import { PRESERVATION_POLL_INTERVAL } from "./links";
import { useRouter } from "next/router";
const usePublicLinks = (params: LinkRequestQuery = {}) => {
@@ -65,6 +67,11 @@ const useFetchLinks = (params: string) => {
}
return lastPage.nextCursor;
},
+ refetchInterval: (query) => {
+ const links =
+ query.state.data?.pages?.flatMap((p) => p?.links ?? []) ?? [];
+ return anyPreservationPending(links) ? PRESERVATION_POLL_INTERVAL : false;
+ },
});
};
diff --git a/packages/types/global.ts b/packages/types/global.ts
index b30b7b3b..e8739f0a 100644
--- a/packages/types/global.ts
+++ b/packages/types/global.ts
@@ -24,6 +24,7 @@ export interface LinkIncludingShortenedCollectionAndTags
id?: number;
createdAt?: string;
importDate?: string;
+ lastPreserved?: string | Date | null;
collectionId?: number;
tags: Tag[];
pinnedBy?: {