Skip to content

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

feat(mobile): finished building the dashboard

daniel31x13de3ca46ef0db
diff --git a/apps/mobile/app/(tabs)/(dashboard)/_layout.tsx b/apps/mobile/app/(tabs)/(dashboard)/_layout.tsx
new file mode 100644
index 00000000..6f91c5cb
--- /dev/null
+++ b/apps/mobile/app/(tabs)/(dashboard)/_layout.tsx
@@ -0,0 +1,51 @@
+import { IconSymbol } from "@/components/ui/IconSymbol";
+import { Stack } from "expo-router";
+import { TouchableOpacity } from "react-native";
+import { SheetManager } from "react-native-actions-sheet";
+import * as DropdownMenu from "zeego/dropdown-menu";
+
+export default function RootLayout() {
+ return (
+ <Stack
+ screenOptions={{
+ headerTitle: "Dashboard",
+ headerLargeTitle: true,
+ headerTransparent: true,
+ headerBlurEffect: "systemUltraThinMaterial",
+ headerLargeStyle: {
+ backgroundColor: "#f2f2f2",
+ },
+ headerRight: () => (
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ <TouchableOpacity>
+ <IconSymbol size={20} name="plus" color={"#3478f6"} />
+ </TouchableOpacity>
+ </DropdownMenu.Trigger>
+
+ <DropdownMenu.Content>
+ <DropdownMenu.Item
+ key="new-link"
+ onSelect={() => SheetManager.show("add-link-sheet")}
+ >
+ <DropdownMenu.ItemTitle>New Link</DropdownMenu.ItemTitle>
+ </DropdownMenu.Item>
+ <DropdownMenu.Item
+ key="new-collection"
+ onSelect={() => alert("Item 2 selected")}
+ >
+ <DropdownMenu.ItemTitle>New Collection</DropdownMenu.ItemTitle>
+ </DropdownMenu.Item>
+ {/* <DropdownMenu.Item
+ key="upload-file"
+ onSelect={() => alert("Item 3 selected")}
+ >
+ <DropdownMenu.ItemTitle>Upload File</DropdownMenu.ItemTitle>
+ </DropdownMenu.Item> */}
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ ),
+ }}
+ />
+ );
+}
diff --git a/apps/mobile/app/(tabs)/(dashboard)/index.tsx b/apps/mobile/app/(tabs)/(dashboard)/index.tsx
new file mode 100644
index 00000000..79fa9211
--- /dev/null
+++ b/apps/mobile/app/(tabs)/(dashboard)/index.tsx
@@ -0,0 +1,340 @@
+import {
+ FlatList,
+ Platform,
+ RefreshControl,
+ ScrollView,
+ StyleSheet,
+ Text,
+ TouchableOpacity,
+ View,
+} from "react-native";
+import { IconSymbol } from "@/components/ui/IconSymbol";
+import { SafeAreaView } from "react-native-safe-area-context";
+import { useDashboardData } from "@linkwarden/router/dashboardData";
+import useAuthStore from "@/store/auth";
+import React, { useEffect, useMemo, useState } from "react";
+import { DashboardSection, DashboardSectionType } from "@prisma/client";
+import { useUser } from "@linkwarden/router/user";
+import { useCollections } from "@linkwarden/router/collections";
+import { useTags } from "@linkwarden/router/tags";
+import clsx from "clsx";
+import DashboardItem from "@/components/DashboardItem";
+import { LinkIncludingShortenedCollectionAndTags } from "@linkwarden/types";
+import LinkListing from "@/components/LinkListing";
+
+export default function DashboardScreen() {
+ const { auth } = useAuthStore();
+ const {
+ data: { links = [], numberOfPinnedLinks, collectionLinks = {} } = {
+ links: [],
+ },
+ ...dashboardData
+ } = useDashboardData(auth);
+ const { data: user } = useUser(auth);
+ const { data: collections = [] } = useCollections(auth);
+ const { data: tags = [] } = useTags(auth);
+
+ const [dashboardSections, setDashboardSections] = useState<
+ DashboardSection[]
+ >(user?.dashboardSections || []);
+
+ const [numberOfLinks, setNumberOfLinks] = useState(0);
+
+ useEffect(() => {
+ setDashboardSections(user?.dashboardSections || []);
+ }, [user?.dashboardSections]);
+
+ useEffect(() => {
+ setNumberOfLinks(
+ collections.reduce(
+ (accumulator, collection) =>
+ accumulator + (collection._count as any).links,
+ 0
+ )
+ );
+ }, [collections]);
+
+ const orderedSections = useMemo(() => {
+ return [...dashboardSections].sort((a, b) => {
+ const orderA = a.order ?? Number.MAX_SAFE_INTEGER;
+ const orderB = b.order ?? Number.MAX_SAFE_INTEGER;
+ return orderA - orderB;
+ });
+ }, [dashboardSections]);
+
+ return (
+ <SafeAreaView style={styles.container}>
+ <ScrollView
+ refreshControl={
+ <RefreshControl
+ refreshing={dashboardData.isLoading}
+ onRefresh={dashboardData.refetch}
+ />
+ }
+ contentContainerStyle={{
+ flexDirection: "column",
+ gap: 15,
+ paddingVertical: 20,
+ }}
+ contentInsetAdjustmentBehavior="automatic"
+ >
+ {orderedSections.map((sectionData) => {
+ const collection = collections.find(
+ (c) => c.id === sectionData.collectionId
+ );
+
+ return (
+ <Section
+ key={sectionData.id}
+ sectionData={sectionData}
+ collection={collection}
+ links={links}
+ tagsLength={tags.length}
+ numberOfLinks={numberOfLinks}
+ collectionsLength={collections.length}
+ numberOfPinnedLinks={numberOfPinnedLinks}
+ dashboardData={dashboardData}
+ collectionLinks={
+ sectionData.collectionId
+ ? collectionLinks[sectionData.collectionId]
+ : []
+ }
+ />
+ );
+ })}
+ </ScrollView>
+ </SafeAreaView>
+ );
+}
+
+interface SectionProps {
+ sectionData: { type: DashboardSectionType };
+ collection?: any;
+ links?: any[];
+ tagsLength: number;
+ numberOfLinks: number;
+ collectionsLength: number;
+ numberOfPinnedLinks: number;
+ dashboardData: { isLoading: boolean };
+ collectionLinks?: any[];
+}
+
+const Section: React.FC<SectionProps> = ({
+ sectionData,
+ collection,
+ links = [],
+ tagsLength,
+ numberOfLinks,
+ collectionsLength,
+ numberOfPinnedLinks,
+ dashboardData,
+ collectionLinks = [],
+}) => {
+ switch (sectionData.type) {
+ case DashboardSectionType.STATS:
+ return (
+ <View className="flex-col gap-4 max-w-full px-5">
+ <View className="flex-row gap-4">
+ <DashboardItem
+ name={numberOfLinks === 1 ? "Link" : "Links"}
+ value={numberOfLinks}
+ icon="link.circle.fill"
+ />
+ <DashboardItem
+ name={collectionsLength === 1 ? "Collection" : "Collections"}
+ value={collectionsLength}
+ icon="folder.circle.fill"
+ />
+ </View>
+ <View className="flex-row gap-4">
+ <DashboardItem
+ name={tagsLength === 1 ? "Tag" : "Tags"}
+ value={tagsLength}
+ icon="tag.circle.fill"
+ />
+ <DashboardItem
+ name={"Pinned Links"}
+ value={numberOfPinnedLinks}
+ icon="pin.circle.fill"
+ />
+ </View>
+ </View>
+ );
+
+ case DashboardSectionType.RECENT_LINKS:
+ return (
+ <>
+ <View className="flex-row justify-between items-center px-5">
+ <View className="flex-row gap-2 items-center">
+ <View className={"flex-row items-center gap-2"}>
+ <IconSymbol size={30} name="clock" color={""} />
+ <Text className="text-2xl capitalize">Recent Links</Text>
+ </View>
+ </View>
+ <TouchableOpacity
+ className="flex-row items-center text-sm gap-1"
+ // onPress={() => navigation.navigate('Links')}
+ >
+ <Text className="text-[#3478f6]">View All</Text>
+ <IconSymbol size={15} name="chevron.right" color={"#3478f6"} />
+ </TouchableOpacity>
+ </View>
+
+ {dashboardData.isLoading ||
+ (links.length > 0 && !dashboardData.isLoading) ? (
+ <FlatList
+ horizontal
+ showsHorizontalScrollIndicator={false}
+ directionalLockEnabled
+ data={links || []}
+ refreshing={dashboardData.isLoading}
+ initialNumToRender={2}
+ keyExtractor={(item) => item.id?.toString() || ""}
+ renderItem={({ item }) => (
+ <RenderItem item={item} key={item.id?.toString()} />
+ )}
+ ItemSeparatorComponent={() => <View style={{ width: 10 }} />}
+ contentContainerStyle={{
+ paddingHorizontal: 20,
+ }}
+ />
+ ) : (
+ <View className="flex-col gap-2 justify-center items-center h-40 p-10 rounded-xl bg-base-200 bg-white mx-5">
+ <IconSymbol size={40} name="clock" color={""} />
+ <Text className="text-center text-xl text-gray-500">
+ No Recent Links
+ </Text>
+
+ {/* <View className="text-center w-full mt-4 flex-row flex-wrap gap-4 justify-center">
+ <Button onPress={() => setNewLinkModal(true)} variant="accent">
+ <Icon name="bi-plus-lg" className="text-xl" />
+ <Text>{t("add_link")}</Text>
+ </Button>
+ <ImportDropdown />
+ </View> */}
+ </View>
+ )}
+ </>
+ );
+
+ case DashboardSectionType.PINNED_LINKS:
+ return (
+ <>
+ <View className="flex-row justify-between items-center px-5">
+ <View className="flex-row gap-2 items-center">
+ <View className={"flex-row items-center gap-2"}>
+ <IconSymbol size={30} name="pin" color={""} />
+ <Text className="text-2xl capitalize">Pinned Links</Text>
+ </View>
+ </View>
+ <TouchableOpacity
+ className="flex-row items-center text-sm gap-1"
+ // onPress={() => navigation.navigate("PinnedLinks")}
+ >
+ <Text className="text-[#3478f6]">View All</Text>
+ <IconSymbol size={15} name="chevron.right" color={"#3478f6"} />
+ </TouchableOpacity>
+ </View>
+
+ {dashboardData.isLoading ||
+ links?.some((e: any) => e.pinnedBy && e.pinnedBy[0]) ? (
+ <FlatList
+ horizontal
+ showsHorizontalScrollIndicator={false}
+ data={links.filter((e: any) => e.pinnedBy && e.pinnedBy[0]) || []}
+ // onRefresh={() => data.refetch()}
+ refreshing={dashboardData.isLoading}
+ initialNumToRender={2}
+ keyExtractor={(item) => item.id?.toString() || ""}
+ renderItem={({ item }) => (
+ <RenderItem item={item} key={item.id?.toString()} />
+ )}
+ ItemSeparatorComponent={() => <View style={{ width: 10 }} />}
+ contentContainerStyle={{
+ paddingHorizontal: 20,
+ }}
+ />
+ ) : (
+ <View className="flex-col gap-2 justify-center items-center h-40 p-10 rounded-xl bg-base-200 bg-white mx-5">
+ <IconSymbol size={40} name="pin" color={""} />
+ <Text className="text-center text-xl text-gray-500">
+ No Pinned Links
+ </Text>
+ </View>
+ )}
+ </>
+ );
+
+ case DashboardSectionType.COLLECTION:
+ return collection?.id ? (
+ <>
+ <View className="flex-row justify-between items-center px-5">
+ <View className="flex-row gap-2 items-center max-w-[60%]">
+ <View className={clsx("flex-row items-center gap-2")}>
+ <IconSymbol
+ size={30}
+ name="folder.fill"
+ color={collection.color || "#0ea5e9"}
+ />
+ <Text className="text-2xl capitalize w-full" numberOfLines={1}>
+ {collection.name}
+ </Text>
+ </View>
+ </View>
+ <TouchableOpacity
+ className="flex-row items-center text-sm gap-1 whitespace-nowrap"
+ // onPress={() =>
+ // navigation.navigate("Collection", { id: collection.id })
+ // }
+ >
+ <Text className="text-[#3478f6]">View All</Text>
+ <IconSymbol size={15} name="chevron.right" color={"#3478f6"} />
+ </TouchableOpacity>
+ </View>
+
+ {dashboardData.isLoading || collectionLinks.length > 0 ? (
+ <FlatList
+ horizontal
+ showsHorizontalScrollIndicator={false}
+ data={collectionLinks || []}
+ // onRefresh={() => data.refetch()}
+ refreshing={dashboardData.isLoading}
+ initialNumToRender={2}
+ keyExtractor={(item) => item.id?.toString() || ""}
+ renderItem={({ item }) => (
+ <RenderItem item={item} key={item.id?.toString()} />
+ )}
+ ItemSeparatorComponent={() => <View style={{ width: 10 }} />}
+ contentContainerStyle={{
+ paddingHorizontal: 20,
+ }}
+ />
+ ) : (
+ <View className="flex-col gap-2 justify-center items-center h-40 p-10 rounded-xl bg-base-200 bg-white mx-5">
+ <Text className="text-center text-xl text-gray-500">
+ Empty Collection
+ </Text>
+ </View>
+ )}
+ </>
+ ) : null;
+
+ default:
+ return null;
+ }
+};
+
+const RenderItem = React.memo(
+ ({ item }: { item: LinkIncludingShortenedCollectionAndTags }) => {
+ return <LinkListing link={item} dashboard />;
+ }
+);
+
+const styles = StyleSheet.create({
+ container: Platform.select({
+ ios: {
+ paddingBottom: 49,
+ },
+ default: {},
+ }),
+});
diff --git a/apps/mobile/app/(tabs)/_layout.tsx b/apps/mobile/app/(tabs)/_layout.tsx
index 52112d17..6651824a 100644
--- a/apps/mobile/app/(tabs)/_layout.tsx
+++ b/apps/mobile/app/(tabs)/_layout.tsx
@@ -26,7 +26,7 @@ export default function TabLayout() {
}}
>
<Tabs.Screen
- name="dashboard"
+ name="(dashboard)"
options={{
title: "Dashboard",
headerShown: false,
diff --git a/apps/mobile/app/(tabs)/dashboard.tsx b/apps/mobile/app/(tabs)/dashboard.tsx
deleted file mode 100644
index bd5bdf5e..00000000
--- a/apps/mobile/app/(tabs)/dashboard.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-import { Text, TouchableOpacity } from "react-native";
-import { IconSymbol } from "@/components/ui/IconSymbol";
-import * as DropdownMenu from "zeego/dropdown-menu";
-import { SafeAreaView } from "react-native-safe-area-context";
-import { SheetManager } from "react-native-actions-sheet";
-
-export default function DashboardScreen() {
- return (
- <SafeAreaView className="flex-1 justify-center items-center">
- <DropdownMenu.Root>
- <DropdownMenu.Trigger>
- <TouchableOpacity>
- <IconSymbol size={20} name="plus" color={""} />
- </TouchableOpacity>
- </DropdownMenu.Trigger>
-
- <DropdownMenu.Content>
- <DropdownMenu.Item
- key="new-link"
- onSelect={() => SheetManager.show("add-link-sheet")}
- >
- <DropdownMenu.ItemTitle>New Link</DropdownMenu.ItemTitle>
- </DropdownMenu.Item>
- <DropdownMenu.Item
- key="new-collection"
- onSelect={() => alert("Item 2 selected")}
- >
- <DropdownMenu.ItemTitle>New Collection</DropdownMenu.ItemTitle>
- </DropdownMenu.Item>
- <DropdownMenu.Item
- key="upload-file"
- onSelect={() => alert("Item 3 selected")}
- >
- <DropdownMenu.ItemTitle>Upload File</DropdownMenu.ItemTitle>
- </DropdownMenu.Item>
- </DropdownMenu.Content>
- </DropdownMenu.Root>
- <Text>Dashboard</Text>
- {/* <TouchableOpacity>
- <IconSymbol size={20} name="plus" color={""} />
- </TouchableOpacity> */}
- </SafeAreaView>
- );
-}
diff --git a/apps/mobile/app/index.tsx b/apps/mobile/app/index.tsx
index 156b36ef..6cf1324a 100644
--- a/apps/mobile/app/index.tsx
+++ b/apps/mobile/app/index.tsx
@@ -10,7 +10,7 @@ export default function HomeScreen() {
}, []);
if (auth.session) {
- return <Redirect href="/dashboard" />;
+ return <Redirect href="/(tabs)/(dashboard)" />;
} else {
return <Redirect href="/login" />;
}
diff --git a/apps/mobile/components/DashboardItem.tsx b/apps/mobile/components/DashboardItem.tsx
new file mode 100644
index 00000000..d81101d1
--- /dev/null
+++ b/apps/mobile/components/DashboardItem.tsx
@@ -0,0 +1,30 @@
+import { Text, View } from "react-native";
+import { IconSymbol } from "./ui/IconSymbol";
+import { SFSymbols6_0 } from "sf-symbols-typescript";
+
+export default function DashboardItem({
+ name,
+ value,
+ icon,
+}: {
+ name: string;
+ value: number;
+ icon: SFSymbols6_0;
+}) {
+ return (
+ <View className="flex-1 flex-col gap-2 rounded-xl bg-white p-3">
+ <View className="flex-row justify-between">
+ <View className="flex-col gap-2 items-start">
+ <IconSymbol name={icon} size={40} color={"#4169e1"} />
+ </View>
+ <Text
+ className="text-4xl text-primary mt-0.5 text-right max-w-[75%]"
+ numberOfLines={1}
+ >
+ {value || 0}
+ </Text>
+ </View>
+ <Text className="font-semibold text-gray-500">{name}</Text>
+ </View>
+ );
+}
diff --git a/apps/mobile/components/LinkListing.tsx b/apps/mobile/components/LinkListing.tsx
index f891e3ac..21ef6b1c 100644
--- a/apps/mobile/components/LinkListing.tsx
+++ b/apps/mobile/components/LinkListing.tsx
@@ -13,12 +13,14 @@ import * as ContextMenu from "zeego/context-menu";
import { useDeleteLink } from "@linkwarden/router/links";
import { SheetManager } from "react-native-actions-sheet";
import * as Clipboard from "expo-clipboard";
+import { cn } from "@linkwarden/lib/utils";
type Props = {
link: LinkIncludingShortenedCollectionAndTags;
+ dashboard?: boolean;
};
-const LinkListing = ({ link }: Props) => {
+const LinkListing = ({ link, dashboard }: Props) => {
const { auth } = useAuthStore();
const router = useRouter();
@@ -42,14 +44,23 @@ const LinkListing = ({ link }: Props) => {
>
<ContextMenu.Trigger asChild>
<Pressable
- className={`p-5 flex-row justify-between bg-white ${
- Platform.OS === "android" ? "active:bg-white" : "active:bg-gray-200"
- }`}
+ className={cn(
+ "p-5 flex-row justify-between bg-white",
+ Platform.OS === "android"
+ ? "active:bg-white"
+ : "active:bg-gray-200",
+ dashboard && "rounded-xl"
+ )}
onPress={() => router.push(`/links/${link.id}`)}
android_ripple={{ color: "#ddd", borderless: false }}
>
- <View className="flex-row justify-between w-full">
- <View className="w-[70%] flex-col justify-between">
+ <View
+ className={cn(
+ "flex-row justify-between",
+ dashboard ? "w-80" : "w-full"
+ )}
+ >
+ <View className="w-[65%] flex-col justify-between">
<Text numberOfLines={2} className="font-medium text-lg">
{decode(link.name || link.description || link.url)}
</Text>
diff --git a/apps/mobile/store/auth.ts b/apps/mobile/store/auth.ts
index fa03b7c5..ddc22390 100644
--- a/apps/mobile/store/auth.ts
+++ b/apps/mobile/store/auth.ts
@@ -3,10 +3,8 @@ import * as SecureStore from "expo-secure-store";
import { router } from "expo-router";
import { MobileAuth } from "@linkwarden/types";
-type Auth = MobileAuth;
-
type AuthStore = {
- auth: Auth;
+ auth: MobileAuth;
signIn: (username: string, password: string, instance?: string) => void;
signOut: () => void;
setAuth: () => void;
@@ -70,7 +68,7 @@ const useAuthStore = create<AuthStore>((set) => ({
},
});
- router.replace("/dashboard");
+ router.replace("/(tabs)/(dashboard)");
} else {
set({
auth: {
diff --git a/packages/router/dashboardData.tsx b/packages/router/dashboardData.tsx
index 96e03eb1..e185f3a5 100644
--- a/packages/router/dashboardData.tsx
+++ b/packages/router/dashboardData.tsx
@@ -1,14 +1,31 @@
import { UpdateDashboardLayoutSchemaType } from "@linkwarden/lib/schemaValidation";
+import { MobileAuth } from "@linkwarden/types";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useSession } from "next-auth/react";
-const useDashboardData = () => {
- const { status } = useSession();
+const useDashboardData = (auth?: MobileAuth) => {
+ let status: "loading" | "authenticated" | "unauthenticated";
+
+ if (!auth) {
+ const session = useSession();
+ status = session.status;
+ } else {
+ status = auth?.status;
+ }
return useQuery({
queryKey: ["dashboardData"],
queryFn: async () => {
- const response = await fetch("/api/v2/dashboard");
+ const response = await fetch(
+ (auth?.instance ? auth?.instance : "") + "/api/v2/dashboard",
+ auth?.session
+ ? {
+ headers: {
+ Authorization: `Bearer ${auth.session}`,
+ },
+ }
+ : undefined
+ );
const data = await response.json();
return data.data;
diff --git a/packages/router/tags.tsx b/packages/router/tags.tsx
index f49868b8..386c03f6 100644
--- a/packages/router/tags.tsx
+++ b/packages/router/tags.tsx
@@ -4,18 +4,34 @@ import {
useQueryClient,
UseQueryResult,
} from "@tanstack/react-query";
-import { TagIncludingLinkCount } from "@linkwarden/types";
+import { MobileAuth, TagIncludingLinkCount } from "@linkwarden/types";
import { useSession } from "next-auth/react";
import { Tag } from "@linkwarden/prisma/client";
import { ArchivalTagOption } from "@linkwarden/types/inputSelect";
-const useTags = (): UseQueryResult<Tag[], Error> => {
- const { status } = useSession();
+const useTags = (auth?: MobileAuth): UseQueryResult<Tag[], Error> => {
+ let status: "loading" | "authenticated" | "unauthenticated";
+
+ if (!auth) {
+ const session = useSession();
+ status = session.status;
+ } else {
+ status = auth?.status;
+ }
return useQuery({
queryKey: ["tags"],
queryFn: async () => {
- const response = await fetch("/api/v1/tags");
+ const response = await fetch(
+ (auth?.instance ? auth?.instance : "") + "/api/v1/tags",
+ auth?.session
+ ? {
+ headers: {
+ Authorization: `Bearer ${auth.session}`,
+ },
+ }
+ : undefined
+ );
if (!response.ok) throw new Error("Failed to fetch tags.");
const data = await response.json();