Skip to content

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

feat: implement infinite scrolling for tags in Sidebar and Tags page

daniel31x1382f97b10956d
diff --git a/apps/mobile/app/(tabs)/dashboard/index.tsx b/apps/mobile/app/(tabs)/dashboard/index.tsx
index 19f734c1..8f058e8e 100644
--- a/apps/mobile/app/(tabs)/dashboard/index.tsx
+++ b/apps/mobile/app/(tabs)/dashboard/index.tsx
@@ -8,6 +8,7 @@ import {
} from "react-native";
import React, { useEffect, useMemo, useState } from "react";
import { useDashboardData } from "@linkwarden/router/dashboardData";
+import { isAtLeastInstanceVersion, useConfig } from "@linkwarden/router/config";
import useAuthStore from "@/store/auth";
import { DashboardSection as DashboardSectionType } from "@linkwarden/prisma/client";
import { useUser } from "@linkwarden/router/user";
@@ -18,17 +19,33 @@ import { useColorScheme } from "nativewind";
import Spinner from "@/components/ui/Spinner";
import DashboardSection from "@/components/DashboardSection";
+const DASHBOARD_TAG_COUNT_VERSION = "2.13.5";
+
export default function DashboardScreen() {
const { auth } = useAuthStore();
const {
- data: { links = [], numberOfPinnedLinks, collectionLinks = {} } = {
+ data: {
+ links = [],
+ numberOfPinnedLinks,
+ numberOfTags = 0,
+ collectionLinks = {},
+ } = {
links: [],
},
...dashboardData
} = useDashboardData(auth);
const { data: user, ...userData } = useUser(auth);
const { data: collections = [], ...collectionsData } = useCollections(auth);
- const { data: tags = [], ...tagsData } = useTags(auth);
+ const config = useConfig(auth);
+ const supportsDashboardTagCount = isAtLeastInstanceVersion(
+ config.data?.INSTANCE_VERSION,
+ DASHBOARD_TAG_COUNT_VERSION
+ );
+ const shouldUseLegacyTagsCount =
+ config.isError || (config.isSuccess && !supportsDashboardTagCount);
+ const legacyTags = useTags(auth, {
+ enabled: shouldUseLegacyTagsCount,
+ });
const { colorScheme } = useColorScheme();
@@ -61,6 +78,9 @@ export default function DashboardScreen() {
}, [dashboardSections]);
const [pullRefreshing, setPullRefreshing] = useState(false);
+ const resolvedNumberOfTags = shouldUseLegacyTagsCount
+ ? legacyTags.data.length
+ : numberOfTags;
const onRefresh = async () => {
setPullRefreshing(true);
@@ -69,7 +89,7 @@ export default function DashboardScreen() {
dashboardData.refetch(),
userData.refetch(),
collectionsData.refetch(),
- tagsData.refetch(),
+ ...(shouldUseLegacyTagsCount ? [legacyTags.refetch()] : []),
]);
} finally {
setPullRefreshing(false);
@@ -118,7 +138,7 @@ export default function DashboardScreen() {
: []
}
links={links}
- tagsLength={tags.length}
+ numberOfTags={resolvedNumberOfTags}
numberOfLinks={numberOfLinks}
collectionsLength={collections.length}
numberOfPinnedLinks={numberOfPinnedLinks}
diff --git a/apps/mobile/app/(tabs)/tags/[id].tsx b/apps/mobile/app/(tabs)/tags/[id].tsx
index bfc1706e..9400b7a4 100644
--- a/apps/mobile/app/(tabs)/tags/[id].tsx
+++ b/apps/mobile/app/(tabs)/tags/[id].tsx
@@ -3,7 +3,7 @@ import { View, StyleSheet, Platform } from "react-native";
import useAuthStore from "@/store/auth";
import { useLocalSearchParams, useNavigation } from "expo-router";
import React, { useEffect } from "react";
-import { useTags } from "@linkwarden/router/tags";
+import { useTag } from "@linkwarden/router/tags";
import Links from "@/components/Links";
export default function LinksScreen() {
@@ -12,36 +12,37 @@ export default function LinksScreen() {
search?: string;
id: string;
}>();
+ const parsedTagId = Number(id);
+ const tagId =
+ Number.isFinite(parsedTagId) && parsedTagId > 0 ? parsedTagId : undefined;
const { links, data } = useLinks(
{
sort: 0,
searchQueryString: decodeURIComponent(search ?? ""),
- tagId: Number(id),
+ tagId,
},
auth
);
- const tags = useTags(auth);
+ const tag = useTag(tagId, auth);
const navigation = useNavigation();
const isIOS26Plus = Platform.OS === "ios" && Number(Platform.Version) >= 26;
useEffect(() => {
- const activeTag = tags.data?.filter((e) => e.id === Number(id))[0];
-
- if (activeTag?.name)
+ if (tag.data?.name)
navigation?.setOptions?.({
- headerTitle: activeTag?.name,
+ headerTitle: tag.data.name,
headerSearchBarOptions: {
- placeholder: `Search ${activeTag.name}`,
+ placeholder: `Search ${tag.data.name}`,
...(isIOS26Plus && {
allowToolbarIntegration: false,
placement: "integratedButton",
}),
},
});
- }, [navigation]);
+ }, [navigation, tag.data?.name, isIOS26Plus]);
return (
<View
diff --git a/apps/mobile/app/(tabs)/tags/index.tsx b/apps/mobile/app/(tabs)/tags/index.tsx
index 290e499b..e5722058 100644
--- a/apps/mobile/app/(tabs)/tags/index.tsx
+++ b/apps/mobile/app/(tabs)/tags/index.tsx
@@ -13,7 +13,7 @@ import React, { useEffect, useState } from "react";
import Spinner from "@/components/ui/Spinner";
import { rawTheme, ThemeName } from "@/lib/colors";
import { useColorScheme } from "nativewind";
-import { TagIncludingLinkCount } from "@linkwarden/types/global";
+import { TagIncludingLinkCount, TagSort } from "@linkwarden/types/global";
import { useTags } from "@linkwarden/router/tags";
export default function TagsScreen() {
@@ -21,7 +21,9 @@ export default function TagsScreen() {
const { auth } = useAuthStore();
const { search } = useLocalSearchParams<{ search?: string }>();
- const tags = useTags(auth);
+ const tags = useTags(auth, {
+ sort: TagSort.NameAZ,
+ });
const [filteredTags, setFilteredTags] = useState<TagIncludingLinkCount[]>([]);
@@ -65,10 +67,21 @@ export default function TagsScreen() {
initialNumToRender={4}
keyExtractor={(item) => item.id?.toString() || ""}
renderItem={({ item }) => <TagListing tag={item} />}
+ onEndReached={() => {
+ if (!tags.hasNextPage || tags.isFetchingNextPage) return;
+ tags.fetchNextPage();
+ }}
onEndReachedThreshold={0.5}
ItemSeparatorComponent={() => (
<View className="bg-neutral-content h-px" />
)}
+ ListFooterComponent={
+ tags.isFetchingNextPage ? (
+ <View className="py-4 items-center">
+ <ActivityIndicator size="small" />
+ </View>
+ ) : null
+ }
ListEmptyComponent={
<View className="flex justify-center py-10 items-center">
<Text className="text-center text-xl text-neutral">
diff --git a/apps/mobile/components/ActionSheets/EditLinkSheet.tsx b/apps/mobile/components/ActionSheets/EditLinkSheet.tsx
index 8df91c89..f1c92322 100644
--- a/apps/mobile/components/ActionSheets/EditLinkSheet.tsx
+++ b/apps/mobile/components/ActionSheets/EditLinkSheet.tsx
@@ -16,6 +16,7 @@ import {
CollectionIncludingMembersAndLinkCount,
LinkIncludingShortenedCollectionAndTags,
TagIncludingLinkCount,
+ TagSort,
} from "@linkwarden/types/global";
import { useCollections } from "@linkwarden/router/collections";
import { rawTheme, ThemeName } from "@/lib/colors";
@@ -266,17 +267,29 @@ const Tags = () => {
const [searchQuery, setSearchQuery] = useState("");
const router = useSheetRouter("edit-link-sheet");
const params = useSheetRouteParams("edit-link-sheet", "tags");
- const tags = useTags(auth);
+ const tags = useTags(auth, {
+ sort: TagSort.NameAZ,
+ });
const { colorScheme } = useColorScheme();
const [updatedLink, setUpdatedLink] =
useState<LinkIncludingShortenedCollectionAndTags>(params.link);
const filteredTags = useMemo(() => {
- if (!tags.data) return [];
+ const tagsById = new Map<number, TagIncludingLinkCount>();
+
+ for (const tag of updatedLink?.tags || []) {
+ tagsById.set(tag.id, tag as TagIncludingLinkCount);
+ }
+
+ for (const tag of tags.data || []) {
+ tagsById.set(tag.id, tag);
+ }
+
+ const availableTags = Array.from(tagsById.values());
const q = searchQuery.trim().toLowerCase();
- if (q === "") return tags.data;
- return tags.data.filter((tag) => tag.name.toLowerCase().includes(q));
- }, [tags.data, searchQuery]);
+ if (q === "") return availableTags;
+ return availableTags.filter((tag) => tag.name.toLowerCase().includes(q));
+ }, [updatedLink?.tags, tags.data, searchQuery]);
const renderItem = useCallback(
({ item: tag }: { item: TagIncludingLinkCount }) => {
@@ -345,6 +358,21 @@ const Tags = () => {
data={filteredTags}
keyExtractor={(e, i) => i.toString()}
renderItem={renderItem}
+ onEndReached={() => {
+ if (!tags.hasNextPage || tags.isFetchingNextPage) return;
+ tags.fetchNextPage();
+ }}
+ onEndReachedThreshold={0.5}
+ ListFooterComponent={
+ tags.isFetchingNextPage ? (
+ <Text
+ style={{ textAlign: "center", marginTop: 20 }}
+ className="text-neutral"
+ >
+ Loading...
+ </Text>
+ ) : null
+ }
ListEmptyComponent={
<Text
style={{ textAlign: "center", marginTop: 20 }}
diff --git a/apps/mobile/components/DashboardSection.tsx b/apps/mobile/components/DashboardSection.tsx
index 378864fa..95f088db 100644
--- a/apps/mobile/components/DashboardSection.tsx
+++ b/apps/mobile/components/DashboardSection.tsx
@@ -33,7 +33,7 @@ type DashboardSectionProps = {
sectionData: { type: DashboardSectionType };
collection?: any;
links?: any[];
- tagsLength: number;
+ numberOfTags: number;
numberOfLinks: number;
collectionsLength: number;
numberOfPinnedLinks: number;
@@ -49,7 +49,7 @@ const DashboardSection: React.FC<DashboardSectionProps> = ({
sectionData,
collection,
links = [],
- tagsLength,
+ numberOfTags,
numberOfLinks,
collectionsLength,
numberOfPinnedLinks,
@@ -80,8 +80,8 @@ const DashboardSection: React.FC<DashboardSectionProps> = ({
</View>
<View className="flex-row gap-4">
<DashboardItem
- name={tagsLength === 1 ? "Tag" : "Tags"}
- value={tagsLength}
+ name={numberOfTags === 1 ? "Tag" : "Tags"}
+ value={numberOfTags}
icon={<Hash size={23} color="white" />}
color="#00cc99"
/>
diff --git a/apps/web/components/InputSelect/TagSelection.tsx b/apps/web/components/InputSelect/TagSelection.tsx
index 9ed81419..851a5e8a 100644
--- a/apps/web/components/InputSelect/TagSelection.tsx
+++ b/apps/web/components/InputSelect/TagSelection.tsx
@@ -4,6 +4,7 @@ import { styles } from "./styles";
import { ArchivalTagOption, Option } from "@linkwarden/types/inputSelect";
import { useTags } from "@linkwarden/router/tags";
import { useTranslation } from "next-i18next";
+import { TagSort } from "@linkwarden/types/global";
type Props = {
onChange: (e: any) => void;
@@ -25,7 +26,14 @@ export default function TagSelection({
autoFocus,
onBlur,
}: Props) {
- const { data: tags = [] } = useTags();
+ const {
+ data: tags = [],
+ hasNextPage,
+ isFetchingNextPage,
+ fetchNextPage,
+ } = useTags(undefined, {
+ sort: TagSort.NameAZ,
+ });
const { t } = useTranslation();
const [tagOptions, setTagOptions] = useState<Option[]>([]);
@@ -52,6 +60,11 @@ export default function TagSelection({
isMulti
autoFocus={autoFocus}
onBlur={onBlur}
+ isLoading={isFetchingNextPage}
+ onMenuScrollToBottom={() => {
+ if (!hasNextPage || isFetchingNextPage) return;
+ fetchNextPage();
+ }}
/>
);
}
diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx
index 865c2f3c..c1376d6d 100644
--- a/apps/web/components/Sidebar.tsx
+++ b/apps/web/components/Sidebar.tsx
@@ -17,6 +17,8 @@ import {
TooltipTrigger,
} from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
+import { TagSort } from "@linkwarden/types/global";
+import { useInView } from "react-intersection-observer";
export default function Sidebar({
className,
@@ -28,6 +30,7 @@ export default function Sidebar({
sidebarIsCollapsed?: boolean;
}) {
const { t } = useTranslation();
+ const { ref, inView } = useInView();
const [tagDisclosure, setTagDisclosure] = useState<boolean>(() => {
const storedValue = localStorage.getItem("tagDisclosure");
return storedValue ? storedValue === "true" : true;
@@ -42,7 +45,15 @@ export default function Sidebar({
const { data: collections } = useCollections();
- const { data: tags = [], isLoading } = useTags();
+ const {
+ data: tags = [],
+ isLoading,
+ hasNextPage,
+ isFetchingNextPage,
+ fetchNextPage,
+ } = useTags(undefined, {
+ sort: TagSort.NameAZ,
+ });
const [active, setActive] = useState("");
const router = useRouter();
@@ -64,6 +75,14 @@ export default function Sidebar({
setActive(router.asPath);
}, [router, collections]);
+ useEffect(() => {
+ if (!inView) return;
+ if (!hasNextPage) return;
+ if (isFetchingNextPage) return;
+
+ fetchNextPage();
+ }, [inView, hasNextPage, isFetchingNextPage, fetchNextPage]);
+
return (
<div
id="sidebar"
@@ -252,13 +271,22 @@ export default function Sidebar({
>
<Disclosure.Panel className="flex flex-col gap-1">
{isLoading ? (
- <div className="flex flex-col gap-4">
- <div className="skeleton h-4 w-full"></div>
- <div className="skeleton h-4 w-full"></div>
- <div className="skeleton h-4 w-full"></div>
+ <div className="flex flex-col gap-1">
+ {Array.from({ length: 3 }).map((_, index) => (
+ <div
+ key={index}
+ className="skeleton h-8 w-full rounded-md"
+ ></div>
+ ))}
</div>
) : (
- <TagListing tags={tags} active={active} />
+ <>
+ <TagListing tags={tags} active={active} />
+ {hasNextPage && <div ref={ref} className="h-1 w-full" />}
+ {isFetchingNextPage && (
+ <div className="skeleton h-7 w-full rounded-lg"></div>
+ )}
+ </>
)}
</Disclosure.Panel>
</Transition>
diff --git a/apps/web/lib/api/controllers/dashboard/getDashboardDataV2.ts b/apps/web/lib/api/controllers/dashboard/getDashboardDataV2.ts
index 3288dba6..3df3223a 100644
--- a/apps/web/lib/api/controllers/dashboard/getDashboardDataV2.ts
+++ b/apps/web/lib/api/controllers/dashboard/getDashboardDataV2.ts
@@ -3,22 +3,42 @@ import { Order } from "@linkwarden/types/global";
export default async function getDashboardData(userId: number) {
const order: Order = { id: "desc" };
-
- const [dashboardSections, numberOfPinnedLinks] = await Promise.all([
- prisma.dashboardSection.findMany({ where: { userId } }),
- prisma.link.count({
- where: {
- AND: [
- {
+ const accessibleTagsWhere = {
+ OR: [
+ { ownerId: userId },
+ {
+ links: {
+ some: {
collection: {
- OR: [{ ownerId: userId }, { members: { some: { userId } } }],
+ members: {
+ some: { userId },
+ },
},
},
- { pinnedBy: { some: { id: userId } } },
- ],
+ },
},
- }),
- ]);
+ ],
+ };
+
+ const [dashboardSections, numberOfPinnedLinks, numberOfTags] =
+ await Promise.all([
+ prisma.dashboardSection.findMany({ where: { userId } }),
+ prisma.link.count({
+ where: {
+ AND: [
+ {
+ collection: {
+ OR: [{ ownerId: userId }, { members: { some: { userId } } }],
+ },
+ },
+ { pinnedBy: { some: { id: userId } } },
+ ],
+ },
+ }),
+ prisma.tag.count({
+ where: accessibleTagsWhere,
+ }),
+ ]);
const viewPinned = dashboardSections.some(
(section) => section.type === "PINNED_LINKS"
@@ -32,7 +52,7 @@ export default async function getDashboardData(userId: number) {
if (!viewRecent && !viewPinned && collectionSections.length === 0) {
return {
- data: { links: [], numberOfPinnedLinks },
+ data: { links: [], numberOfPinnedLinks, numberOfTags },
message: "Dashboard data fetched successfully.",
statusCode: 200,
success: true,
@@ -143,6 +163,7 @@ export default async function getDashboardData(userId: number) {
links: uniqueLinks,
collectionLinks,
numberOfPinnedLinks,
+ numberOfTags,
},
message: "Dashboard data fetched successfully.",
statusCode: 200,
diff --git a/apps/web/lib/api/controllers/tags/getTags.ts b/apps/web/lib/api/controllers/tags/getTags.ts
index 8e29379b..1b3ec2b0 100644
--- a/apps/web/lib/api/controllers/tags/getTags.ts
+++ b/apps/web/lib/api/controllers/tags/getTags.ts
@@ -1,14 +1,34 @@
import { prisma } from "@linkwarden/prisma";
+import { TagRequestQuery, TagSort } from "@linkwarden/types/global";
export default async function getTags({
userId,
collectionId,
+ query = {},
}: {
userId?: number;
collectionId?: number;
+ query?: TagRequestQuery;
}) {
+ const paginationTakeCount = Number(process.env.PAGINATION_TAKE_COUNT) || 50;
+
+ let orderBy: any[] = [{ id: "desc" }];
+
+ if (query.sort === TagSort.DateOldestFirst) orderBy = [{ id: "asc" }];
+ else if (query.sort === TagSort.NameAZ)
+ orderBy = [{ name: "asc" }, { id: "asc" }];
+ else if (query.sort === TagSort.NameZA)
+ orderBy = [{ name: "desc" }, { id: "desc" }];
+ else if (query.sort === TagSort.LinkCountHighLow)
+ orderBy = [{ links: { _count: "desc" } }, { id: "desc" }];
+ else if (query.sort === TagSort.LinkCountLowHigh)
+ orderBy = [{ links: { _count: "asc" } }, { id: "asc" }];
+
if (userId) {
const tags = await prisma.tag.findMany({
+ take: paginationTakeCount,
+ skip: query.cursor ? 1 : undefined,
+ cursor: query.cursor ? { id: query.cursor } : undefined,
where: {
OR: [
{ ownerId: userId }, // Tags owned by the user
@@ -32,14 +52,19 @@ export default async function getTags({
select: { links: true },
},
},
- // orderBy: {
- // links: {
- // _count: "desc",
- // },
- // },
+ orderBy,
});
- return { response: tags, status: 200 };
+ return {
+ data: {
+ tags,
+ nextCursor:
+ tags.length === paginationTakeCount ? tags[tags.length - 1].id : null,
+ },
+ statusCode: 200,
+ success: true,
+ message: "Success",
+ };
} else if (collectionId) {
const tags = await prisma.tag.findMany({
where: {
@@ -51,8 +76,30 @@ export default async function getTags({
},
},
},
+ include: {
+ _count: {
+ select: {
+ links: true,
+ },
+ },
+ },
+ orderBy: [{ name: "asc" }, { id: "asc" }],
});
- return { response: tags, status: 200 };
+ return {
+ data: {
+ tags,
+ },
+ statusCode: 200,
+ success: true,
+ message: "Success",
+ };
}
+
+ return {
+ data: { tags: [] },
+ statusCode: 400,
+ success: false,
+ message: "Please choose a valid user or collection.",
+ };
}
diff --git a/apps/web/lib/api/controllers/tags/tagId/getTagById.ts b/apps/web/lib/api/controllers/tags/tagId/getTagById.ts
new file mode 100644
index 00000000..0c501769
--- /dev/null
+++ b/apps/web/lib/api/controllers/tags/tagId/getTagById.ts
@@ -0,0 +1,39 @@
+import { prisma } from "@linkwarden/prisma";
+
+export default async function getTagById(userId: number, tagId: number) {
+ if (!tagId)
+ return { response: "Please choose a valid name for the tag.", status: 401 };
+
+ const tag = await prisma.tag.findFirst({
+ where: {
+ id: tagId,
+ OR: [
+ { ownerId: userId },
+ {
+ links: {
+ some: {
+ collection: {
+ members: {
+ some: {
+ userId,
+ },
+ },
+ },
+ },
+ },
+ },
+ ],
+ },
+ include: {
+ _count: {
+ select: {
+ links: true,
+ },
+ },
+ },
+ });
+
+ if (!tag) return { response: "Tag not found.", status: 404 };
+
+ return { response: tag, status: 200 };
+}
diff --git a/apps/web/lib/api/controllers/tags/tagId/updateTagById.ts b/apps/web/lib/api/controllers/tags/tagId/updateTagById.ts
index ae7fb101..a6043f9a 100644
--- a/apps/web/lib/api/controllers/tags/tagId/updateTagById.ts
+++ b/apps/web/lib/api/controllers/tags/tagId/updateTagById.ts
@@ -60,6 +60,11 @@ export default async function updateTagById(
id: true,
},
},
+ _count: {
+ select: {
+ links: true,
+ },
+ },
},
});
diff --git a/apps/web/pages/api/v1/public/collections/tags/index.ts b/apps/web/pages/api/v1/public/collections/tags/index.ts
index b1e85d0f..54e11213 100644
--- a/apps/web/pages/api/v1/public/collections/tags/index.ts
+++ b/apps/web/pages/api/v1/public/collections/tags/index.ts
@@ -37,6 +37,8 @@ export default async function collections(
collectionId: collection.id,
});
- return res.status(tags?.status || 500).json({ response: tags?.response });
+ const { statusCode, ...data } = tags;
+
+ return res.status(statusCode).json(data);
}
}
diff --git a/apps/web/pages/api/v1/tags/[id].ts b/apps/web/pages/api/v1/tags/[id].ts
index 6aa8194d..d398bce9 100644
--- a/apps/web/pages/api/v1/tags/[id].ts
+++ b/apps/web/pages/api/v1/tags/[id].ts
@@ -2,6 +2,7 @@ import type { NextApiRequest, NextApiResponse } from "next";
import updateTagById from "@/lib/api/controllers/tags/tagId/updateTagById";
import verifyUser from "@/lib/api/verifyUser";
import deleteTagById from "@/lib/api/controllers/tags/tagId/deleteTagById";
+import getTagById from "@/lib/api/controllers/tags/tagId/getTagById";
export default async function tags(req: NextApiRequest, res: NextApiResponse) {
const user = await verifyUser({ req, res });
@@ -14,7 +15,10 @@ export default async function tags(req: NextApiRequest, res: NextApiResponse) {
response: "Please choose a valid name for the tag.",
});
- if (req.method === "PUT") {
+ if (req.method === "GET") {
+ const tag = await getTagById(user.id, tagId);
+ return res.status(tag.status).json({ response: tag.response });
+ } else if (req.method === "PUT") {
if (process.env.NEXT_PUBLIC_DEMO === "true")
return res.status(400).json({
response:
diff --git a/apps/web/pages/api/v1/tags/index.ts b/apps/web/pages/api/v1/tags/index.ts
index 5d2d2574..20d13241 100644
--- a/apps/web/pages/api/v1/tags/index.ts
+++ b/apps/web/pages/api/v1/tags/index.ts
@@ -4,17 +4,26 @@ import verifyUser from "@/lib/api/verifyUser";
import { PostTagSchema } from "@linkwarden/lib/schemaValidation";
import createOrUpdateTags from "@/lib/api/controllers/tags/createOrUpdateTags";
import bulkTagDelete from "@/lib/api/controllers/tags/bulkTagDelete";
+import { TagRequestQuery } from "@linkwarden/types/global";
export default async function tags(req: NextApiRequest, res: NextApiResponse) {
const user = await verifyUser({ req, res });
if (!user) return;
if (req.method === "GET") {
+ const convertedData: TagRequestQuery = {
+ sort: req.query.sort ? Number(req.query.sort as string) : undefined,
+ cursor: req.query.cursor ? Number(req.query.cursor as string) : undefined,
+ };
+
const tags = await getTags({
userId: user.id,
+ query: convertedData,
});
- return res.status(tags?.status || 500).json({ response: tags?.response });
+ const { statusCode, ...data } = tags;
+
+ return res.status(statusCode).json(data);
}
if (req.method === "POST") {
diff --git a/apps/web/pages/dashboard.tsx b/apps/web/pages/dashboard.tsx
index ed5f6e40..fde40a89 100644
--- a/apps/web/pages/dashboard.tsx
+++ b/apps/web/pages/dashboard.tsx
@@ -9,7 +9,6 @@ import PageHeader from "@/components/PageHeader";
import getServerSideProps from "@/lib/client/getServerSideProps";
import { useTranslation } from "next-i18next";
import { useCollections } from "@linkwarden/router/collections";
-import { useTags } from "@linkwarden/router/tags";
import { useDashboardData } from "@linkwarden/router/dashboardData";
import { useUpdateUser, useUser } from "@linkwarden/router/user";
import SurveyModal from "@/components/ModalContent/SurveyModal";
@@ -32,13 +31,17 @@ const Page: NextPageWithLayout = () => {
const { t } = useTranslation();
const { data: collections = [] } = useCollections();
const {
- data: { links = [], numberOfPinnedLinks, collectionLinks = {} } = {
+ data: {
+ links = [],
+ numberOfPinnedLinks,
+ numberOfTags = 0,
+ collectionLinks = {},
+ } = {
links: [],
},
...dashboardData
} = useDashboardData();
- const { data: tags = [] } = useTags();
const { data: user } = useUser();
const [numberOfLinks, setNumberOfLinks] = useState(0);
@@ -159,7 +162,7 @@ const Page: NextPageWithLayout = () => {
: []
}
links={links}
- tags={tags}
+ numberOfTags={numberOfTags}
numberOfLinks={numberOfLinks}
collectionsLength={collections.length}
numberOfPinnedLinks={numberOfPinnedLinks}
@@ -215,7 +218,7 @@ type SectionProps = {
collection: any;
collectionsLength: number;
links: any[];
- tags: any[];
+ numberOfTags: number;
numberOfLinks: number;
numberOfPinnedLinks: number;
dashboardData: any;
@@ -228,7 +231,7 @@ const Section = ({
t,
collection,
links,
- tags,
+ numberOfTags,
numberOfLinks,
collectionsLength,
numberOfPinnedLinks,
@@ -253,8 +256,8 @@ const Section = ({
/>
<DashboardItem
- name={tags.length === 1 ? t("tag") : t("tags")}
- value={tags.length}
+ name={numberOfTags === 1 ? t("tag") : t("tags")}
+ value={numberOfTags}
icon={"bi-hash"}
/>
diff --git a/apps/web/pages/settings/preference.tsx b/apps/web/pages/settings/preference.tsx
index d784b1f5..4e42e1e5 100644
--- a/apps/web/pages/settings/preference.tsx
+++ b/apps/web/pages/settings/preference.tsx
@@ -5,6 +5,7 @@ import Checkbox from "@/components/Checkbox";
import useLocalSettingsStore from "@/store/localSettings";
import { useTranslation } from "next-i18next";
import getServerSideProps from "@/lib/client/getServerSideProps";
+import { TagSort } from "@linkwarden/types/global";
import { AiTaggingMethod, LinksRouteTo } from "@linkwarden/prisma/client";
import {
useUpdateUser,
@@ -31,7 +32,9 @@ const Page: NextPageWithLayout = () => {
const { settings, updateSettings } = useLocalSettingsStore();
const updateUserPreference = useUpdateUserPreference();
const { data: account } = useUser() as any;
- const { data: tags } = useTags();
+ const { data: tags } = useTags(undefined, {
+ sort: TagSort.NameAZ,
+ });
const upsertTags = useUpsertTags();
const {
ARCHIVAL_OPTIONS,
diff --git a/apps/web/pages/tags/[id].tsx b/apps/web/pages/tags/[id].tsx
index 42f8310a..1b5f1c7e 100644
--- a/apps/web/pages/tags/[id].tsx
+++ b/apps/web/pages/tags/[id].tsx
@@ -1,19 +1,14 @@
import { useRouter } from "next/router";
import { FormEvent, ReactElement, useEffect, useState } from "react";
import MainLayout from "@/layouts/MainLayout";
-import {
- LinkIncludingShortenedCollectionAndTags,
- Sort,
- TagIncludingLinkCount,
- ViewMode,
-} from "@linkwarden/types/global";
+import { Sort, ViewMode } from "@linkwarden/types/global";
import { useLinks } from "@linkwarden/router/links";
import BulkDeleteLinksModal from "@/components/ModalContent/BulkDeleteLinksModal";
import BulkEditLinksModal from "@/components/ModalContent/BulkEditLinksModal";
import { useTranslation } from "next-i18next";
import getServerSideProps from "@/lib/client/getServerSideProps";
import LinkListOptions from "@/components/LinkListOptions";
-import { useRemoveTag, useTags, useUpdateTag } from "@linkwarden/router/tags";
+import { useRemoveTag, useTag, useUpdateTag } from "@linkwarden/router/tags";
import Links from "@/components/LinkViews/Links";
import toast from "react-hot-toast";
import { Button } from "@/components/ui/button";
@@ -29,8 +24,15 @@ import { NextPageWithLayout } from "../_app";
const Page: NextPageWithLayout = () => {
const { t } = useTranslation();
const router = useRouter();
-
- const { data: tags = [] } = useTags();
+ const parsedTagId = Number(router.query.id);
+ const tagId =
+ Number.isFinite(parsedTagId) && parsedTagId > 0 ? parsedTagId : undefined;
+
+ const {
+ data: activeTag,
+ isLoading: isTagLoading,
+ isError: isTagError,
+ } = useTag(tagId);
const updateTag = useUpdateTag();
const removeTag = useRemoveTag();
@@ -41,13 +43,9 @@ const Page: NextPageWithLayout = () => {
const [renameTag, setRenameTag] = useState(false);
const [newTagName, setNewTagName] = useState<string>();
- const [activeTag, setActiveTag] = useState<TagIncludingLinkCount>();
-
const [bulkDeleteLinksModal, setBulkDeleteLinksModal] = useState(false);
const [bulkEditLinksModal, setBulkEditLinksModal] = useState(false);
const [editMode, setEditMode] = useState(false);
- const [activeLink, setActiveLink] =
- useState<LinkIncludingShortenedCollectionAndTags | null>(null);
useEffect(() => {
if (editMode) return setEditMode(false);
@@ -55,19 +53,13 @@ const Page: NextPageWithLayout = () => {
const { links, data } = useLinks({
sort: sortBy,
- tagId: Number(router.query.id),
+ tagId,
});
useEffect(() => {
- const tag = tags.find((e: any) => e.id === Number(router.query.id));
-
- if (tags.length > 0 && !tag?.id) {
- router.push("/dashboard");
- return;
- }
-
- setActiveTag(tag);
- }, [router, tags, Number(router.query.id), setActiveTag]);
+ if (!router.isReady || isTagLoading) return;
+ if (isTagError) router.push("/dashboard");
+ }, [router, router.isReady, isTagLoading, isTagError]);
useEffect(() => {
setNewTagName(activeTag?.name);
@@ -190,7 +182,7 @@ const Page: NextPageWithLayout = () => {
<DropdownMenuContent
sideOffset={4}
align={
- activeTag?.name.length && activeTag?.name.length > 8
+ activeTag?.name && activeTag.name.length > 8
? "end"
: "start"
}
diff --git a/apps/web/pages/tags/index.tsx b/apps/web/pages/tags/index.tsx
index c41e63cd..91a08e9a 100644
--- a/apps/web/pages/tags/index.tsx
+++ b/apps/web/pages/tags/index.tsx
@@ -12,7 +12,7 @@ import {
DropdownMenuRadioItem,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
-import { ReactElement, useMemo, useState } from "react";
+import { ReactElement, useEffect, useState } from "react";
import NewTagModal from "@/components/ModalContent/NewTagModal";
import {
Tooltip,
@@ -23,55 +23,38 @@ import {
import BulkDeleteTagsModal from "@/components/ModalContent/BulkDeleteTagsModal";
import MergeTagsModal from "@/components/ModalContent/MergeTagsModal";
import { NextPageWithLayout } from "../_app";
-
-enum TagSort {
- DateNewestFirst = 0,
- DateOldestFirst = 1,
- NameAZ = 2,
- NameZA = 3,
- LinkCountHighLow = 4,
- LinkCountLowHigh = 5,
-}
+import { TagSort } from "@linkwarden/types/global";
+import { useInView } from "react-intersection-observer";
const Page: NextPageWithLayout = () => {
const { t } = useTranslation();
- const { data: tags = [], isLoading } = useTags();
-
const [sortBy, setSortBy] = useState<TagSort>(TagSort.DateNewestFirst);
+ const { ref, inView } = useInView();
+ const {
+ data: tags = [],
+ isLoading,
+ hasNextPage,
+ isFetchingNextPage,
+ fetchNextPage,
+ } = useTags(undefined, {
+ sort: sortBy,
+ });
+
const [newTagModal, setNewTagModal] = useState(false);
const [bulkDeleteModal, setBulkDeleteModal] = useState(false);
const [mergeTagsModal, setMergeTagsModal] = useState(false);
- const tagTime = (tag: any) => {
- if (tag?.createdAt) return new Date(tag.createdAt as string).getTime();
- return typeof tag?.id === "number" ? tag.id : 0;
- };
- const linkCount = (tag: any) =>
- tag?.linkCount ?? tag?.linksCount ?? tag?._count?.links ?? 0;
-
- const compare = useMemo(() => {
- switch (sortBy) {
- case TagSort.NameAZ:
- return (a: any, b: any) => (a?.name ?? "").localeCompare(b?.name ?? "");
- case TagSort.NameZA:
- return (a: any, b: any) => (b?.name ?? "").localeCompare(a?.name ?? "");
- case TagSort.DateOldestFirst:
- return (a: any, b: any) => tagTime(a) - tagTime(b);
- case TagSort.LinkCountHighLow:
- return (a: any, b: any) => linkCount(b) - linkCount(a);
- case TagSort.LinkCountLowHigh:
- return (a: any, b: any) => linkCount(a) - linkCount(b);
- case TagSort.DateNewestFirst:
- default:
- return (a: any, b: any) => tagTime(b) - tagTime(a);
- }
- }, [sortBy]);
-
- const sortedTags = useMemo(() => tags.slice().sort(compare), [tags, compare]);
-
const [editMode, setEditMode] = useState(false);
const [selectedTags, setSelectedTags] = useState<number[]>([]);
+ useEffect(() => {
+ if (!inView) return;
+ if (!hasNextPage) return;
+ if (isFetchingNextPage) return;
+
+ fetchNextPage();
+ }, [inView, hasNextPage, isFetchingNextPage, fetchNextPage]);
+
return (
<div className="p-5 flex flex-col gap-5 w-full h-full">
<div className="flex justify-between items-center">
@@ -223,7 +206,7 @@ const Page: NextPageWithLayout = () => {
)}
<div className="grid 2xl:grid-cols-6 xl:grid-cols-5 sm:grid-cols-3 grid-cols-2 gap-5">
- {sortedTags.map((tag: any) => (
+ {tags.map((tag: any) => (
<TagCard
key={tag.id}
tag={tag}
@@ -237,8 +220,12 @@ const Page: NextPageWithLayout = () => {
}}
/>
))}
+ {isLoading && !tags.length && <TagCardSkeleton />}
+ {isFetchingNextPage && <TagCardSkeleton />}
</div>
+ {hasNextPage && <div ref={ref} className="h-1 w-full" />}
+
{!isLoading && tags && !tags[0] && (
<div
style={{ flex: "1 1 auto" }}
@@ -291,3 +278,16 @@ Page.getLayout = function getLayout(page: ReactElement<any>) {
export default Page;
export { getServerSideProps };
+
+const TagCardSkeleton = () => {
+ return (
+ <div className="rounded-xl p-2">
+ <div className="flex gap-3 flex-col">
+ <div className="skeleton h-5 w-3/4"></div>
+ <div className="flex justify-between items-center mt-auto">
+ <div className="skeleton h-4 w-24"></div>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/router/config.tsx b/packages/router/config.tsx
index dcc64c7c..4c32b86c 100644
--- a/packages/router/config.tsx
+++ b/packages/router/config.tsx
@@ -1,4 +1,5 @@
import { useQuery } from "@tanstack/react-query";
+import { MobileAuth } from "@linkwarden/types/global";
export type Config = {
DISABLE_REGISTRATION: boolean | null;
@@ -7,13 +8,59 @@ export type Config = {
EMAIL_PROVIDER: boolean | null;
MAX_FILE_BUFFER: number | null;
AI_ENABLED: boolean | null;
+ INSTANCE_VERSION: string | null;
};
-const useConfig = () => {
+const normalizeVersion = (version?: string | null) => {
+ if (!version) return null;
+
+ return version
+ .replace(/^v/i, "")
+ .split("-")[0]
+ .split(".")
+ .map((part) => Number(part.replace(/\D/g, "")) || 0);
+};
+
+const compareInstanceVersions = (a?: string | null, b?: string | null) => {
+ const normalizedA = normalizeVersion(a);
+ const normalizedB = normalizeVersion(b);
+
+ if (!normalizedA || !normalizedB) return -1;
+
+ const length = Math.max(normalizedA.length, normalizedB.length);
+
+ for (let index = 0; index < length; index++) {
+ const left = normalizedA[index] ?? 0;
+ const right = normalizedB[index] ?? 0;
+
+ if (left > right) return 1;
+ if (left < right) return -1;
+ }
+
+ return 0;
+};
+
+const isAtLeastInstanceVersion = (
+ version?: string | null,
+ minimumVersion?: string | null
+) => {
+ return compareInstanceVersions(version, minimumVersion) >= 0;
+};
+
+const useConfig = (auth?: MobileAuth) => {
return useQuery({
- queryKey: ["config"],
+ queryKey: ["config", auth?.instance ?? "web"],
queryFn: async () => {
- const response = await fetch("/api/v1/config");
+ const response = await fetch(
+ (auth?.instance ? auth.instance : "") + "/api/v1/config",
+ auth?.session
+ ? {
+ headers: {
+ Authorization: `Bearer ${auth.session}`,
+ },
+ }
+ : undefined
+ );
const data = await response.json();
return data.response as Config;
@@ -21,4 +68,4 @@ const useConfig = () => {
});
};
-export { useConfig };
+export { useConfig, compareInstanceVersions, isAtLeastInstanceVersion };
diff --git a/packages/router/links.tsx b/packages/router/links.tsx
index 32a86047..fe5c269c 100644
--- a/packages/router/links.tsx
+++ b/packages/router/links.tsx
@@ -11,6 +11,7 @@ import {
LinkIncludingShortenedCollectionAndTags,
LinkRequestQuery,
MobileAuth,
+ TagIncludingLinkCount,
} from "@linkwarden/types/global";
import { useSession } from "next-auth/react";
import {
@@ -115,6 +116,34 @@ const buildQueryString = (params: LinkRequestQuery) => {
.join("&");
};
+const extractTagsFromQueryData = (data: unknown): TagIncludingLinkCount[] => {
+ if (Array.isArray(data)) return data as TagIncludingLinkCount[];
+
+ if (
+ data &&
+ typeof data === "object" &&
+ "pages" in data &&
+ Array.isArray((data as any).pages)
+ ) {
+ return (data as any).pages.flatMap((page: any) => page?.tags ?? []);
+ }
+
+ return [];
+};
+
+const mergeTagsFromQueriesData = (queries: [QueryKey, unknown][]) => {
+ const tagsById = new Map<number, TagIncludingLinkCount>();
+
+ for (const [, data] of queries ?? []) {
+ for (const tag of extractTagsFromQueryData(data)) {
+ if (tag.id == null || tagsById.has(tag.id)) continue;
+ tagsById.set(tag.id, tag);
+ }
+ }
+
+ return Array.from(tagsById.values());
+};
+
const upsertLinkInList = (
links: LinkIncludingShortenedCollectionAndTags[] = [],
link: LinkIncludingShortenedCollectionAndTags,
@@ -406,7 +435,11 @@ const useAddLink = ({
const collections =
(queryClient.getQueryData(["collections"]) as any[]) ?? [];
- const tags = (queryClient.getQueryData(["tags"]) as any[]) ?? [];
+ const tags = mergeTagsFromQueriesData(
+ queryClient.getQueriesData({
+ queryKey: ["tags"],
+ })
+ );
const user = queryClient.getQueryData(["user"]) as any;
const collectionFromId =
diff --git a/packages/router/publicTags.tsx b/packages/router/publicTags.tsx
index d7936fbf..ac577fa9 100644
--- a/packages/router/publicTags.tsx
+++ b/packages/router/publicTags.tsx
@@ -6,20 +6,20 @@ type TagIncludingCount = Tag & { _count: { links: number } };
const usePublicTags = (): UseQueryResult<TagIncludingCount[]> => {
const router = useRouter();
+ const collectionId = Number(router.query.id);
return useQuery({
- queryKey: ["tags"],
+ queryKey: ["publicTags", collectionId],
queryFn: async () => {
const response = await fetch(
- "/api/v1/public/collections/tags" +
- "?collectionId=" +
- router.query.id || ""
+ `/api/v1/public/collections/tags?collectionId=${collectionId}`
);
if (!response.ok) throw new Error("Failed to fetch tags.");
const data = await response.json();
- return data.response;
+ return data.data.tags;
},
+ enabled: Number.isFinite(collectionId),
});
};
diff --git a/packages/router/tags.tsx b/packages/router/tags.tsx
index 53cdff65..8ce6652e 100644
--- a/packages/router/tags.tsx
+++ b/packages/router/tags.tsx
@@ -1,33 +1,258 @@
import {
- useQuery,
+ InfiniteData,
+ useInfiniteQuery,
useMutation,
+ useQuery,
useQueryClient,
- UseQueryResult,
} from "@tanstack/react-query";
-import { MobileAuth, TagIncludingLinkCount } from "@linkwarden/types/global";
+import { useMemo } from "react";
+import {
+ MobileAuth,
+ TagIncludingLinkCount,
+ TagRequestQuery,
+ TagSort,
+} from "@linkwarden/types/global";
import { useSession } from "next-auth/react";
-import { Tag } from "@linkwarden/prisma/client";
import { ArchivalTagOption } from "@linkwarden/types/inputSelect";
import {
MergeTagsSchemaType,
TagBulkDeletionSchemaType,
} from "@linkwarden/lib/schemaValidation";
+import { isAtLeastInstanceVersion, useConfig } from "./config";
-const useTags = (auth?: MobileAuth): UseQueryResult<Tag[], Error> => {
- let status: "loading" | "authenticated" | "unauthenticated";
+type TagsPage = {
+ tags: TagIncludingLinkCount[];
+ nextCursor: number | null;
+};
+
+type UseTagsOptions = {
+ sort?: TagSort;
+ enabled?: boolean;
+};
+const MIN_TAG_PAGINATION_VERSION = "2.13.5";
+
+const buildQueryString = (params: TagRequestQuery) => {
+ return Object.keys(params)
+ .filter((key) => params[key as keyof TagRequestQuery] !== undefined)
+ .map(
+ (key) =>
+ `${encodeURIComponent(key)}=${encodeURIComponent(
+ String(params[key as keyof TagRequestQuery])
+ )}`
+ )
+ .join("&");
+};
+
+const getAuthStatus = (auth?: MobileAuth) => {
if (!auth) {
const session = useSession();
- status = session.status;
- } else {
- status = auth?.status;
+ return session.status;
+ }
+
+ return auth.status;
+};
+
+const supportsTagPagination = (version?: string | null) => {
+ return isAtLeastInstanceVersion(version, MIN_TAG_PAGINATION_VERSION);
+};
+
+const sortTags = (tags: TagIncludingLinkCount[], sort?: TagSort) => {
+ const nextTags = [...tags];
+
+ return nextTags.sort((a, b) => {
+ switch (sort) {
+ case TagSort.DateOldestFirst:
+ return (
+ new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
+ );
+ case TagSort.NameAZ:
+ return a.name.localeCompare(b.name);
+ case TagSort.NameZA:
+ return b.name.localeCompare(a.name);
+ case TagSort.LinkCountHighLow:
+ return (b._count?.links ?? 0) - (a._count?.links ?? 0);
+ case TagSort.LinkCountLowHigh:
+ return (a._count?.links ?? 0) - (b._count?.links ?? 0);
+ case TagSort.DateNewestFirst:
+ default:
+ return (
+ new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
+ );
+ }
+ });
+};
+
+const extractTagsPayload = (data: any): TagsPage => {
+ if (Array.isArray(data?.response)) {
+ return {
+ tags: data.response as TagIncludingLinkCount[],
+ nextCursor: null,
+ };
+ }
+
+ if (Array.isArray(data?.response?.tags)) {
+ return {
+ tags: data.response.tags as TagIncludingLinkCount[],
+ nextCursor: data.response.nextCursor ?? null,
+ };
}
+ if (Array.isArray(data?.data?.tags)) {
+ return {
+ tags: data.data.tags as TagIncludingLinkCount[],
+ nextCursor: data.data.nextCursor ?? null,
+ };
+ }
+
+ return {
+ tags: [],
+ nextCursor: null,
+ };
+};
+
+const flattenTagPages = (
+ data?: InfiniteData<TagsPage, number> | TagIncludingLinkCount[] | null
+) => {
+ if (!data) return [];
+ if (Array.isArray(data)) return data;
+ return data.pages?.flatMap((page) => page.tags ?? []) ?? [];
+};
+
+const replaceTagInQueryData = (
+ oldData: InfiniteData<TagsPage, number> | TagIncludingLinkCount[] | undefined,
+ tag: TagIncludingLinkCount
+) => {
+ if (!oldData) return oldData;
+
+ if (Array.isArray(oldData)) {
+ return oldData.map((existing) =>
+ existing.id === tag.id ? { ...existing, ...tag } : existing
+ );
+ }
+
+ return {
+ ...oldData,
+ pages: oldData.pages.map((page) => ({
+ ...page,
+ tags: page.tags.map((existing) =>
+ existing.id === tag.id ? { ...existing, ...tag } : existing
+ ),
+ })),
+ };
+};
+
+const removeTagFromQueryData = (
+ oldData: InfiniteData<TagsPage, number> | TagIncludingLinkCount[] | undefined,
+ tagId: number
+) => {
+ if (!oldData) return oldData;
+
+ if (Array.isArray(oldData)) {
+ return oldData.filter((tag) => tag.id !== tagId);
+ }
+
+ return {
+ ...oldData,
+ pages: oldData.pages.map((page) => ({
+ ...page,
+ tags: page.tags.filter((tag) => tag.id !== tagId),
+ })),
+ };
+};
+
+const useTags = (auth?: MobileAuth, options: UseTagsOptions = {}) => {
+ const status = getAuthStatus(auth);
+ const config = useConfig(auth);
+
+ const params = useMemo(
+ () =>
+ buildQueryString({
+ sort: options.sort,
+ }),
+ [options.sort]
+ );
+
+ const shouldUsePaginatedSchema = supportsTagPagination(
+ config.data?.INSTANCE_VERSION
+ );
+
+ const query = useInfiniteQuery({
+ queryKey: [
+ "tags",
+ { params, shouldUsePaginatedSchema, auth: auth?.instance },
+ ],
+ queryFn: async ({ pageParam, queryKey }) => {
+ const supportsPagination = (queryKey[1] as any).shouldUsePaginatedSchema;
+ const url =
+ (auth?.instance ? auth.instance : "") +
+ "/api/v1/tags" +
+ (supportsPagination
+ ? `?cursor=${pageParam}${
+ (queryKey[1] as any).params
+ ? "&" + (queryKey[1] as any).params
+ : ""
+ }`
+ : "");
+
+ const response = await fetch(
+ url,
+ auth?.session
+ ? {
+ headers: {
+ Authorization: `Bearer ${auth.session}`,
+ },
+ }
+ : undefined
+ );
+
+ if (!response.ok) throw new Error("Failed to fetch tags.");
+
+ const data = await response.json();
+ const payload = extractTagsPayload(data);
+
+ return {
+ tags: supportsPagination
+ ? payload.tags
+ : sortTags(payload.tags, options.sort),
+ nextCursor: supportsPagination ? payload.nextCursor : null,
+ };
+ },
+ initialPageParam: 0,
+ refetchOnWindowFocus: false,
+ getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
+ enabled:
+ options.enabled !== false &&
+ status === "authenticated" &&
+ (config.isSuccess || config.isError),
+ });
+
+ const tags = useMemo(
+ () => flattenTagPages(query.data as InfiniteData<TagsPage, number>),
+ [query.data]
+ );
+
+ return {
+ ...query,
+ data: tags,
+ isLoading: config.isLoading || query.isLoading,
+ };
+};
+
+const useTag = (tagId?: number, auth?: MobileAuth) => {
+ const status = getAuthStatus(auth);
+ const config = useConfig(auth);
+
return useQuery({
- queryKey: ["tags"],
+ queryKey: ["tag", tagId, auth?.instance ?? "web"],
queryFn: async () => {
+ const shouldUsePaginatedSchema = supportsTagPagination(
+ config.data?.INSTANCE_VERSION
+ );
+
const response = await fetch(
- (auth?.instance ? auth?.instance : "") + "/api/v1/tags",
+ (auth?.instance ? auth.instance : "") +
+ (shouldUsePaginatedSchema ? `/api/v1/tags/${tagId}` : "/api/v1/tags"),
auth?.session
? {
headers: {
@@ -36,12 +261,26 @@ const useTags = (auth?: MobileAuth): UseQueryResult<Tag[], Error> => {
}
: undefined
);
- if (!response.ok) throw new Error("Failed to fetch tags.");
const data = await response.json();
- return data.response;
+ if (!response.ok) throw new Error(data.response);
+
+ if (shouldUsePaginatedSchema) {
+ return data.response as TagIncludingLinkCount;
+ }
+
+ const legacyTag = extractTagsPayload(data).tags.find(
+ (tag) => tag.id === tagId
+ );
+
+ if (!legacyTag) throw new Error("Tag not found.");
+
+ return legacyTag;
},
- enabled: status === "authenticated",
+ enabled:
+ status === "authenticated" &&
+ !!tagId &&
+ (config.isSuccess || config.isError),
});
};
@@ -61,14 +300,16 @@ const useUpdateTag = () => {
const data = await response.json();
if (!response.ok) throw new Error(data.response);
- return data.response;
+ return data.response as TagIncludingLinkCount;
},
onSuccess: (data) => {
- queryClient.setQueryData(["tags"], (oldData: any) =>
- oldData.map((tag: TagIncludingLinkCount) =>
- tag.id === data.id ? data : tag
- )
+ queryClient.setQueriesData({ queryKey: ["tags"] }, (oldData: any) =>
+ replaceTagInQueryData(oldData, data)
);
+ queryClient.setQueriesData({ queryKey: ["tag", data.id] }, () => data);
+ queryClient.invalidateQueries({ queryKey: ["tags"] });
+ queryClient.invalidateQueries({ queryKey: ["links"] });
+ queryClient.invalidateQueries({ queryKey: ["dashboardData"] });
},
});
};
@@ -89,24 +330,11 @@ const useUpsertTags = () => {
const data = await response.json();
if (!response.ok) throw new Error(data.response);
- return data.response;
+ return data.response as TagIncludingLinkCount[];
},
- onSuccess: (data: TagIncludingLinkCount[]) => {
- queryClient.setQueryData(
- ["tags"],
- (oldData: TagIncludingLinkCount[] = []) => {
- const updatedTags = oldData.map((tag) => {
- const updatedTag = data.find((t) => t.id === tag.id);
- return updatedTag ? { ...tag, ...updatedTag } : tag;
- });
-
- const newTags = data.filter(
- (t) => !oldData.some((tag) => tag.id === t.id)
- );
-
- return [...updatedTags, ...newTags];
- }
- );
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ["tags"] });
+ queryClient.invalidateQueries({ queryKey: ["dashboardData"] });
},
});
};
@@ -117,7 +345,7 @@ const useRemoveTag = (auth?: MobileAuth) => {
return useMutation({
mutationFn: async (tagId: number) => {
const response = await fetch(
- (auth?.instance ? auth?.instance : "") + `/api/v1/tags/${tagId}`,
+ (auth?.instance ? auth.instance : "") + `/api/v1/tags/${tagId}`,
{
method: "DELETE",
headers: {
@@ -133,10 +361,14 @@ const useRemoveTag = (auth?: MobileAuth) => {
return data.response;
},
- onSuccess: (data, variables) => {
- queryClient.setQueryData(["tags"], (oldData: any) =>
- oldData.filter((tag: TagIncludingLinkCount) => tag.id !== variables)
+ onSuccess: (_data, tagId) => {
+ queryClient.setQueriesData({ queryKey: ["tags"] }, (oldData: any) =>
+ removeTagFromQueryData(oldData, tagId)
);
+ queryClient.removeQueries({ queryKey: ["tag", tagId] });
+ queryClient.invalidateQueries({ queryKey: ["tags"] });
+ queryClient.invalidateQueries({ queryKey: ["links"] });
+ queryClient.invalidateQueries({ queryKey: ["dashboardData"] });
},
});
};
@@ -159,9 +391,11 @@ const useBulkTagDeletion = () => {
return responseData.response;
},
- onSuccess: (data) => {
+ onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["tags"] });
+ queryClient.invalidateQueries({ queryKey: ["tag"] });
queryClient.invalidateQueries({ queryKey: ["links"] });
+ queryClient.invalidateQueries({ queryKey: ["dashboardData"] });
},
});
};
@@ -184,18 +418,22 @@ const useMergeTags = () => {
return responseData.response;
},
- onSuccess: (data) => {
+ onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["tags"] });
+ queryClient.invalidateQueries({ queryKey: ["tag"] });
queryClient.invalidateQueries({ queryKey: ["links"] });
+ queryClient.invalidateQueries({ queryKey: ["dashboardData"] });
},
});
};
export {
+ useTag,
useTags,
useUpdateTag,
useUpsertTags,
useRemoveTag,
useBulkTagDeletion,
useMergeTags,
+ flattenTagPages,
};
diff --git a/packages/types/global.ts b/packages/types/global.ts
index 85a19aa8..9017a4e3 100644
--- a/packages/types/global.ts
+++ b/packages/types/global.ts
@@ -91,6 +91,15 @@ export enum Sort {
NameZA = 3,
}
+export enum TagSort {
+ DateNewestFirst = 0,
+ DateOldestFirst = 1,
+ NameAZ = 2,
+ NameZA = 3,
+ LinkCountHighLow = 4,
+ LinkCountLowHigh = 5,
+}
+
export type Order = { [key: string]: "asc" | "desc" };
export type LinkRequestQuery = {
@@ -102,6 +111,11 @@ export type LinkRequestQuery = {
searchQueryString?: string;
};
+export type TagRequestQuery = {
+ sort?: TagSort;
+ cursor?: number;
+};
+
export type PublicLinkRequestQuery = {
cursor?: number;
collectionId: number;