Skip to content

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

feat(link): implement link submission with optimistic UI updates and toast notifications

daniel31x13b9fd802288e5
diff --git a/apps/web/components/MobileNavigation.tsx b/apps/web/components/MobileNavigation.tsx
index 9575ec13..af7b084a 100644
--- a/apps/web/components/MobileNavigation.tsx
+++ b/apps/web/components/MobileNavigation.tsx
@@ -13,6 +13,8 @@ import {
DropdownMenuItem,
} from "@/components/ui/dropdown-menu";
import { Button } from "./ui/button";
+import { useAddLink } from "@linkwarden/router/links";
+import toast from "react-hot-toast";
type Props = {};
@@ -22,6 +24,20 @@ export default function MobileNavigation({}: Props) {
const [newCollectionModal, setNewCollectionModal] = useState(false);
const [uploadFileModal, setUploadFileModal] = useState(false);
+ const addLink = useAddLink();
+
+ const submitLink = (link: any) => {
+ addLink.mutateAsync(link, {
+ onSettled: (data, error) => {
+ if (error) {
+ toast.error(t(error.message));
+ } else {
+ toast.success(t("link_created"));
+ }
+ },
+ });
+ };
+
return (
<>
<div
@@ -66,7 +82,14 @@ export default function MobileNavigation({}: Props) {
<MobileNavigationButton href={`/collections`} icon={"bi-folder"} />
</div>
</div>
- {newLinkModal && <NewLinkModal onClose={() => setNewLinkModal(false)} />}
+ {newLinkModal && (
+ <NewLinkModal
+ onClose={() => {
+ setNewLinkModal(false);
+ }}
+ onSubmit={submitLink}
+ />
+ )}
{newCollectionModal && (
<NewCollectionModal onClose={() => setNewCollectionModal(false)} />
)}
diff --git a/apps/web/components/ModalContent/NewLinkModal.tsx b/apps/web/components/ModalContent/NewLinkModal.tsx
index 6310614d..8114e546 100644
--- a/apps/web/components/ModalContent/NewLinkModal.tsx
+++ b/apps/web/components/ModalContent/NewLinkModal.tsx
@@ -7,17 +7,20 @@ import { useRouter } from "next/router";
import Modal from "../Modal";
import { useTranslation } from "next-i18next";
import { useCollections } from "@linkwarden/router/collections";
-import { useAddLink } from "@linkwarden/router/links";
import toast from "react-hot-toast";
-import { PostLinkSchemaType } from "@linkwarden/lib/schemaValidation";
+import {
+ PostLinkSchema,
+ PostLinkSchemaType,
+} from "@linkwarden/lib/schemaValidation";
import { Button } from "@/components/ui/button";
import { Separator } from "../ui/separator";
type Props = {
- onClose: Function;
+ onClose: () => void;
+ onSubmit: Function;
};
-export default function NewLinkModal({ onClose }: Props) {
+export default function NewLinkModal({ onClose, onSubmit }: Props) {
const { t } = useTranslation();
const initial = {
name: "",
@@ -33,8 +36,6 @@ export default function NewLinkModal({ onClose }: Props) {
const inputRef = useRef<HTMLInputElement>(null);
const [link, setLink] = useState<PostLinkSchemaType>(initial);
- const addLink = useAddLink();
- const [submitLoader, setSubmitLoader] = useState(false);
const [optionsExpanded, setOptionsExpanded] = useState(false);
const router = useRouter();
const { data: collections = [] } = useCollections();
@@ -80,22 +81,17 @@ export default function NewLinkModal({ onClose }: Props) {
}, []);
const submit = async () => {
- if (!submitLoader) {
- setSubmitLoader(true);
- const load = toast.loading(t("creating_link"));
- await addLink.mutateAsync(link, {
- onSettled: (data, error) => {
- setSubmitLoader(false);
- toast.dismiss(load);
- if (error) {
- toast.error(t(error.message));
- } else {
- onClose();
- toast.success(t("link_created"));
- }
- },
- });
- }
+ const dataValidation = PostLinkSchema.safeParse(link);
+
+ if (!dataValidation.success)
+ return toast.error(
+ `Error: ${
+ dataValidation.error.issues[0].message
+ } [${dataValidation.error.issues[0].path.join(", ")}]`
+ );
+
+ onSubmit(link);
+ onClose();
};
return (
diff --git a/apps/web/components/Navbar.tsx b/apps/web/components/Navbar.tsx
index c18896bb..e7999bd3 100644
--- a/apps/web/components/Navbar.tsx
+++ b/apps/web/components/Navbar.tsx
@@ -28,6 +28,8 @@ import { useUser } from "@linkwarden/router/user";
import Link from "next/link";
import SettingsSidebar from "@/components/SettingsSidebar";
import AdminSidebar from "@/components/AdminSidebar";
+import { useAddLink } from "@linkwarden/router/links";
+import toast from "react-hot-toast";
const STRIPE_ENABLED = process.env.NEXT_PUBLIC_STRIPE === "true";
const TRIAL_PERIOD_DAYS =
@@ -87,6 +89,20 @@ export default function Navbar({
setIsTrialing(Boolean(isTrialing));
}, [user, daysLeft]);
+ const addLink = useAddLink();
+
+ const submitLink = (link: any) => {
+ addLink.mutateAsync(link, {
+ onSettled: (data, error) => {
+ if (error) {
+ toast.error(t(error.message));
+ } else {
+ toast.success(t("link_created"));
+ }
+ },
+ });
+ };
+
return (
<>
{STRIPE_ENABLED && isTrialing && (
@@ -182,7 +198,12 @@ export default function Navbar({
</div>
)}
{newLinkModal && (
- <NewLinkModal onClose={() => setNewLinkModal(false)} />
+ <NewLinkModal
+ onClose={() => {
+ setNewLinkModal(false);
+ }}
+ onSubmit={submitLink}
+ />
)}
{newCollectionModal && (
<NewCollectionModal onClose={() => setNewCollectionModal(false)} />
diff --git a/apps/web/components/NoLinksFound.tsx b/apps/web/components/NoLinksFound.tsx
index e3dd500d..ff6dced7 100644
--- a/apps/web/components/NoLinksFound.tsx
+++ b/apps/web/components/NoLinksFound.tsx
@@ -2,6 +2,8 @@ import React, { useState } from "react";
import NewLinkModal from "./ModalContent/NewLinkModal";
import { useTranslation } from "next-i18next";
import { Button } from "./ui/button";
+import { useAddLink } from "@linkwarden/router/links";
+import toast from "react-hot-toast";
type Props = {
text?: string;
@@ -11,6 +13,20 @@ export default function NoLinksFound({ text }: Props) {
const { t } = useTranslation();
const [newLinkModal, setNewLinkModal] = useState(false);
+ const addLink = useAddLink();
+
+ const submitLink = (link: any) => {
+ addLink.mutateAsync(link, {
+ onSettled: (data, error) => {
+ if (error) {
+ toast.error(t(error.message));
+ } else {
+ toast.success(t("link_created"));
+ }
+ },
+ });
+ };
+
return (
<div className="w-full h-full flex flex-col justify-center p-3">
<svg
@@ -40,7 +56,14 @@ export default function NoLinksFound({ text }: Props) {
</span>
</Button>
</div>
- {newLinkModal && <NewLinkModal onClose={() => setNewLinkModal(false)} />}
+ {newLinkModal && (
+ <NewLinkModal
+ onClose={() => {
+ setNewLinkModal(false);
+ }}
+ onSubmit={submitLink}
+ />
+ )}
</div>
);
}
diff --git a/apps/web/pages/admin/background-jobs.tsx b/apps/web/pages/admin/background-jobs.tsx
index 558fe01c..78c6ef0c 100644
--- a/apps/web/pages/admin/background-jobs.tsx
+++ b/apps/web/pages/admin/background-jobs.tsx
@@ -158,7 +158,7 @@ const Page: NextPageWithLayout = () => {
<ul className="px-5 list-disc">
<Trans
i18nKey="regenerate_broken_preserved_content_desc"
- components={[<li />]}
+ components={[<li key={0} />]}
values={{
count: workerStats.data?.link.failed,
}}
@@ -181,7 +181,7 @@ const Page: NextPageWithLayout = () => {
<ul className="px-5 list-disc">
<Trans
i18nKey="delete_all_preserved_content_and_regenerate_desc"
- components={[<li />]}
+ components={[<li key={0} />]}
/>
</ul>
<div role="alert" className="alert alert-warning mt-3">
diff --git a/apps/web/pages/dashboard.tsx b/apps/web/pages/dashboard.tsx
index 8eb190c8..39f8c4df 100644
--- a/apps/web/pages/dashboard.tsx
+++ b/apps/web/pages/dashboard.tsx
@@ -26,7 +26,7 @@ import ViewDropdown from "@/components/ViewDropdown";
import clsx from "clsx";
import Icon from "@/components/Icon";
import Droppable from "@/components/Droppable";
-import { useUpdateLink } from "@linkwarden/router/links";
+import { useAddLink, useUpdateLink } from "@linkwarden/router/links";
import { NextPageWithLayout } from "./_app";
const Page: NextPageWithLayout = () => {
@@ -129,6 +129,20 @@ const Page: NextPageWithLayout = () => {
);
};
+ const addLink = useAddLink();
+
+ const submitLink = (link: any) => {
+ addLink.mutateAsync(link, {
+ onSettled: (data, error) => {
+ if (error) {
+ toast.error(t(error.message));
+ } else {
+ toast.success(t("link_created"));
+ }
+ },
+ });
+ };
+
return (
<>
<div className="p-5 flex flex-col gap-4">
@@ -192,7 +206,14 @@ const Page: NextPageWithLayout = () => {
}}
/>
)}
- {newLinkModal && <NewLinkModal onClose={() => setNewLinkModal(false)} />}
+ {newLinkModal && (
+ <NewLinkModal
+ onClose={() => {
+ setNewLinkModal(false);
+ }}
+ onSubmit={submitLink}
+ />
+ )}
</>
);
};
diff --git a/packages/router/links.tsx b/packages/router/links.tsx
index d7aa051a..6c9c2320 100644
--- a/packages/router/links.tsx
+++ b/packages/router/links.tsx
@@ -3,6 +3,7 @@ import {
useQueryClient,
useMutation,
useQuery,
+ QueryKey,
} from "@tanstack/react-query";
import { useMemo } from "react";
import {
@@ -111,6 +112,84 @@ const buildQueryString = (params: LinkRequestQuery) => {
.join("&");
};
+const upsertLinkInList = (
+ links: LinkIncludingShortenedCollectionAndTags[] = [],
+ link: LinkIncludingShortenedCollectionAndTags,
+ optimisticId?: number
+) => {
+ const existingIndex = links.findIndex(
+ (item) => item.id === optimisticId || item.id === link.id
+ );
+
+ if (existingIndex === -1) return [link, ...links];
+
+ const nextLinks = [...links];
+ nextLinks[existingIndex] = link;
+ return nextLinks;
+};
+
+const upsertLinkInInfiniteData = (
+ oldData: any,
+ link: LinkIncludingShortenedCollectionAndTags,
+ optimisticId?: number
+) => {
+ if (!oldData?.pages?.length) return oldData;
+
+ let replaced = false;
+ const pages = oldData.pages.map((page: any) => {
+ const links = page?.links?.map((item: any) => {
+ if (item.id === optimisticId || item.id === link.id) {
+ replaced = true;
+ return link;
+ }
+ return item;
+ });
+
+ return { ...page, links };
+ });
+
+ if (!replaced) {
+ const firstPage = pages[0];
+ pages[0] = {
+ ...firstPage,
+ links: upsertLinkInList(firstPage?.links ?? [], link, optimisticId),
+ };
+ }
+
+ return { ...oldData, pages };
+};
+
+const upsertLinkInDashboardData = (
+ oldData: any,
+ link: LinkIncludingShortenedCollectionAndTags,
+ optimisticId?: number
+) => {
+ if (!oldData) return oldData;
+
+ const updatedLinks = upsertLinkInList(
+ oldData.links ?? [],
+ link,
+ optimisticId
+ ).slice(0, 16);
+
+ const collectionLinks = { ...(oldData.collectionLinks ?? {}) };
+ const collectionId = link.collection?.id;
+
+ if (collectionId != null && collectionLinks[collectionId]) {
+ collectionLinks[collectionId] = upsertLinkInList(
+ collectionLinks[collectionId],
+ link,
+ optimisticId
+ ).slice(0, 16);
+ }
+
+ return {
+ ...oldData,
+ links: updatedLinks,
+ collectionLinks,
+ };
+};
+
const useAddLink = (auth?: MobileAuth) => {
const queryClient = useQueryClient();
@@ -144,21 +223,115 @@ const useAddLink = (auth?: MobileAuth) => {
return data.response;
},
- onSuccess: (data: LinkIncludingShortenedCollectionAndTags[]) => {
- queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
- if (!oldData) return undefined;
- return {
- pages: [
- {
- links: [data, ...oldData?.pages?.[0]?.links],
- nextCursor: oldData?.pages?.[0]?.nextCursor,
- },
- ...oldData?.pages?.slice(1),
- ],
- pageParams: oldData?.pageParams,
- };
+ onMutate: async (link) => {
+ await queryClient.cancelQueries({ queryKey: ["links"] });
+ await queryClient.cancelQueries({ queryKey: ["dashboardData"] });
+
+ const previousLinks = queryClient.getQueriesData({
+ queryKey: ["links"],
+ });
+ const previousDashboard = queryClient.getQueryData(["dashboardData"]);
+
+ const collections =
+ (queryClient.getQueryData(["collections"]) as any[]) ?? [];
+ const tags = (queryClient.getQueryData(["tags"]) as any[]) ?? [];
+ const user = queryClient.getQueryData(["user"]) as any;
+
+ const collectionFromId =
+ link.collection?.id != null
+ ? collections.find(
+ (collection) => collection.id === link.collection?.id
+ )
+ : undefined;
+ const collectionFromName =
+ !collectionFromId && link.collection?.name
+ ? collections.find(
+ (collection) => collection.name === link.collection?.name
+ )
+ : undefined;
+ const resolvedCollection = collectionFromId ?? collectionFromName;
+
+ const tempId = -Date.now();
+ const tempCollectionId = tempId - 1;
+ const collectionId =
+ resolvedCollection?.id ?? link.collection?.id ?? tempCollectionId;
+ const collectionName =
+ resolvedCollection?.name ?? link.collection?.name ?? "Unorganized";
+
+ const resolvedTags =
+ link.tags?.map((tag, index) => {
+ if (tag.id != null) {
+ return (
+ tags.find((existing) => existing.id === tag.id) ?? {
+ id: tag.id,
+ name: tag.name,
+ }
+ );
+ }
+
+ const existingTag = tags.find(
+ (existing) => existing.name === tag.name
+ );
+ return (
+ existingTag ?? {
+ id: tempId - 2 - index,
+ name: tag.name,
+ }
+ );
+ }) ?? [];
+
+ const optimisticLink = {
+ id: tempId,
+ name: link.name?.trim() || link.url || "",
+ url: link.url || "",
+ description: link.description || "",
+ type: link.type || "url",
+ preview: "",
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ collectionId,
+ collection:
+ resolvedCollection ??
+ ({
+ id: collectionId,
+ name: collectionName,
+ ownerId: user?.id ?? 0,
+ } as any),
+ tags: resolvedTags,
+ } as LinkIncludingShortenedCollectionAndTags;
+
+ queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) =>
+ upsertLinkInInfiniteData(oldData, optimisticLink, tempId)
+ );
+
+ queryClient.setQueryData(["dashboardData"], (oldData: any) =>
+ upsertLinkInDashboardData(oldData, optimisticLink, tempId)
+ );
+
+ return {
+ previousLinks,
+ previousDashboard,
+ optimisticId: tempId,
+ };
+ },
+ onError: (_error, _variables, context) => {
+ if (!context) return;
+
+ context.previousLinks?.forEach(([queryKey, data]: [unknown, unknown]) => {
+ queryClient.setQueryData(queryKey as QueryKey, data);
});
+ queryClient.setQueryData(["dashboardData"], context.previousDashboard);
+ },
+ onSuccess: (
+ data: LinkIncludingShortenedCollectionAndTags,
+ _link,
+ context
+ ) => {
+ queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) =>
+ upsertLinkInInfiniteData(oldData, data, context?.optimisticId)
+ );
+
queryClient.invalidateQueries({ queryKey: ["dashboardData"] });
queryClient.invalidateQueries({ queryKey: ["collections"] });
queryClient.invalidateQueries({ queryKey: ["tags"] });