Skip to content

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

feat(mobile): add highlight sheet and delete highlight functionality

daniel31x13366f9e991149
diff --git a/apps/mobile/app/links/[id].tsx b/apps/mobile/app/links/[id].tsx
index 1842c17c..b3dc29dc 100644
--- a/apps/mobile/app/links/[id].tsx
+++ b/apps/mobile/app/links/[id].tsx
@@ -1,5 +1,11 @@
-import React, { useCallback, useEffect, useState } from "react";
-import { View, ActivityIndicator, Text, Platform } from "react-native";
+import React, { useCallback, useEffect, useRef, useState } from "react";
+import {
+ View,
+ ActivityIndicator,
+ Text,
+ Platform,
+ TouchableOpacity,
+} from "react-native";
import { WebView } from "react-native-webview";
import { useQueryClient } from "@tanstack/react-query";
import useAuthStore from "@/store/auth";
@@ -8,11 +14,17 @@ import { useUser } from "@linkwarden/router/user";
import { useGetLink } from "@linkwarden/router/links";
import useTmpStore from "@/store/tmp";
import { ArchivedFormat } from "@linkwarden/types/global";
-import ReadableFormat from "@/components/Formats/ReadableFormat";
+import ReadableFormat, {
+ ReadableFormatRef,
+} from "@/components/Formats/ReadableFormat";
import ImageFormat from "@/components/Formats/ImageFormat";
import PdfFormat from "@/components/Formats/PdfFormat";
import WebpageFormat from "@/components/Formats/WebpageFormat";
import { useSafeAreaInsets } from "react-native-safe-area-context";
+import { SheetManager } from "react-native-actions-sheet";
+import { Highlighter, List } from "lucide-react-native";
+import { useColorScheme } from "nativewind";
+import { rawTheme, ThemeName } from "@/lib/colors";
export default function LinkScreen() {
const { auth } = useAuthStore();
@@ -20,8 +32,13 @@ export default function LinkScreen() {
const queryClient = useQueryClient();
const { data: user } = useUser(auth);
const linkId = Number(id);
+ const archivedFormat = Number(format);
+ const isReadableFormat = archivedFormat === ArchivedFormat.readability;
const [url, setUrl] = useState<string>();
const [isLoading, setIsLoading] = useState(true);
+ const readableFormatRef = useRef<ReadableFormatRef>(null);
+ const { colorScheme } = useColorScheme();
+ const theme = rawTheme[colorScheme as ThemeName];
const { data: link, refetch: refetchLink } = useGetLink({
id: linkId,
@@ -72,24 +89,42 @@ export default function LinkScreen() {
const insets = useSafeAreaInsets();
+ const handleOpenHighlights = useCallback(async () => {
+ if (!link?.id || !isReadableFormat) return;
+
+ const highlightId = await SheetManager.show("readable-highlights-sheet", {
+ payload: {
+ linkId: link.id,
+ },
+ });
+
+ if (typeof highlightId === "number") {
+ readableFormatRef.current?.scrollToHighlight(highlightId);
+ }
+ }, [isReadableFormat, link?.id]);
+
return (
<View
className="flex-1"
style={{ paddingBottom: Platform.OS === "android" ? insets.bottom : 0 }}
>
- {link?.id && Number(format) === ArchivedFormat.readability ? (
- <ReadableFormat link={link as any} setIsLoading={setIsLoading} />
+ {link?.id && isReadableFormat ? (
+ <ReadableFormat
+ ref={readableFormatRef}
+ link={link as any}
+ setIsLoading={setIsLoading}
+ />
) : link?.id &&
- (Number(format) === ArchivedFormat.jpeg ||
- Number(format) === ArchivedFormat.png) ? (
+ (archivedFormat === ArchivedFormat.jpeg ||
+ archivedFormat === ArchivedFormat.png) ? (
<ImageFormat
link={link as any}
setIsLoading={setIsLoading}
- format={Number(format)}
+ format={archivedFormat}
/>
- ) : link?.id && Number(format) === ArchivedFormat.pdf ? (
+ ) : link?.id && archivedFormat === ArchivedFormat.pdf ? (
<PdfFormat link={link as any} setIsLoading={setIsLoading} />
- ) : link?.id && Number(format) === ArchivedFormat.monolith ? (
+ ) : link?.id && archivedFormat === ArchivedFormat.monolith ? (
<WebpageFormat link={link as any} setIsLoading={setIsLoading} />
) : url ? (
<WebView
@@ -115,6 +150,33 @@ export default function LinkScreen() {
</View>
)}
+ {link?.id && isReadableFormat ? (
+ <TouchableOpacity
+ activeOpacity={0.85}
+ onPress={() => {
+ void handleOpenHighlights();
+ }}
+ style={{
+ position: "absolute",
+ right: 20,
+ bottom: insets.bottom + 20,
+ width: 56,
+ height: 56,
+ borderRadius: 28,
+ alignItems: "center",
+ justifyContent: "center",
+ backgroundColor: theme.primary,
+ shadowColor: "#000",
+ shadowOffset: { width: 0, height: 4 },
+ shadowOpacity: 0.18,
+ shadowRadius: 8,
+ elevation: 5,
+ }}
+ >
+ <Highlighter size={22} color={theme["base-100"]} />
+ </TouchableOpacity>
+ ) : null}
+
{isLoading && (
<View className="absolute inset-0 flex-1 justify-center items-center bg-base-100 p-5">
<ActivityIndicator size="large" />
diff --git a/apps/mobile/components/ActionSheets/ReadableHighlightsSheet.tsx b/apps/mobile/components/ActionSheets/ReadableHighlightsSheet.tsx
new file mode 100644
index 00000000..8c5b9b56
--- /dev/null
+++ b/apps/mobile/components/ActionSheets/ReadableHighlightsSheet.tsx
@@ -0,0 +1,209 @@
+import { useMemo, useState } from "react";
+import {
+ ActivityIndicator,
+ Alert,
+ Text,
+ TouchableOpacity,
+ View,
+} from "react-native";
+import ActionSheet, {
+ FlatList,
+ SheetManager,
+ SheetProps,
+} from "react-native-actions-sheet";
+import { Trash2 } from "lucide-react-native";
+import { useColorScheme } from "nativewind";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+import { Highlight } from "@linkwarden/prisma/client";
+import {
+ useGetLinkHighlights,
+ useRemoveHighlight,
+} from "@linkwarden/router/highlights";
+import { rawTheme, ThemeName } from "@/lib/colors";
+import useAuthStore from "@/store/auth";
+import { Button } from "@/components/ui/Button";
+import { HIGHLIGHT_COLORS } from "./ReadableHighlightSheet";
+
+const highlightColorMap = Object.fromEntries(
+ HIGHLIGHT_COLORS.map((colorOption) => [colorOption.name, colorOption])
+);
+
+function getHighlightColors(color?: string | null) {
+ return (
+ highlightColorMap[color as keyof typeof highlightColorMap] ||
+ HIGHLIGHT_COLORS[0]
+ );
+}
+
+function formatHighlightDate(createdAt: Highlight["createdAt"]) {
+ return new Date(createdAt).toLocaleDateString("en-US", {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ });
+}
+
+export default function ReadableHighlightsSheet(
+ props: SheetProps<"readable-highlights-sheet">
+) {
+ const linkId = props.payload?.linkId ?? 0;
+ const { auth } = useAuthStore();
+ const { colorScheme } = useColorScheme();
+ const insets = useSafeAreaInsets();
+ const theme = rawTheme[colorScheme as ThemeName];
+ const { data, isLoading } = useGetLinkHighlights(linkId, auth);
+ const removeHighlight = useRemoveHighlight(linkId, auth);
+ const [deletingHighlightId, setDeletingHighlightId] = useState<number | null>(
+ null
+ );
+
+ const highlights = useMemo(
+ () =>
+ [...(data ?? [])].sort(
+ (left, right) => left.startOffset - right.startOffset
+ ),
+ [data]
+ );
+
+ const closeSheet = () => {
+ void SheetManager.hide(props.sheetId, {
+ payload: null,
+ });
+ };
+
+ const handleSelectHighlight = (highlightId: number) => {
+ void SheetManager.hide(props.sheetId, {
+ payload: highlightId,
+ });
+ };
+
+ const handleDeleteHighlight = (highlightId: number) => {
+ setDeletingHighlightId(highlightId);
+
+ removeHighlight.mutate(highlightId, {
+ onError: (error) => {
+ Alert.alert("Error", "There was an error removing the highlight.");
+ console.error("Failed to delete highlight", error);
+ },
+ onSettled: () => {
+ setDeletingHighlightId(null);
+ },
+ });
+ };
+
+ return (
+ <ActionSheet
+ gestureEnabled
+ indicatorStyle={{
+ display: "none",
+ }}
+ containerStyle={{
+ backgroundColor: theme["base-200"],
+ }}
+ safeAreaInsets={insets}
+ >
+ <View className="px-6 pt-5 pb-3">
+ <Text className="font-semibold text-lg text-center text-base-content">
+ Notes & Highlights
+ </Text>
+ <Text className="text-sm text-center text-neutral mt-1">
+ Tap a highlight to jump to it in the article.
+ </Text>
+ </View>
+
+ {isLoading ? (
+ <View className="px-6 py-10 items-center">
+ <ActivityIndicator />
+ </View>
+ ) : (
+ <FlatList
+ data={highlights}
+ keyExtractor={(item) => item.id.toString()}
+ contentContainerStyle={{
+ paddingHorizontal: 24,
+ paddingBottom: 16,
+ }}
+ style={{
+ maxHeight: 460,
+ }}
+ ItemSeparatorComponent={() => <View style={{ height: 12 }} />}
+ ListEmptyComponent={
+ <View className="py-10">
+ <Text className="text-center text-neutral">
+ No notes or highlights found for this link.
+ </Text>
+ </View>
+ }
+ renderItem={({ item }) => {
+ const colorOption = getHighlightColors(item.color);
+ const isDeleting =
+ deletingHighlightId === item.id && removeHighlight.isPending;
+
+ return (
+ <View
+ style={{
+ backgroundColor: theme["base-100"],
+ borderColor: theme["neutral-content"],
+ borderLeftColor: colorOption.borderColor,
+ borderLeftWidth: 3,
+ borderRadius: 14,
+ borderWidth: 1,
+ padding: 14,
+ }}
+ >
+ <View className="flex-row items-start">
+ <TouchableOpacity
+ activeOpacity={0.8}
+ className="flex-1"
+ onPress={() => handleSelectHighlight(item.id)}
+ >
+ <View
+ style={{
+ alignSelf: "flex-start",
+ backgroundColor: colorOption.backgroundColor,
+ borderRadius: 8,
+ paddingHorizontal: 8,
+ paddingVertical: 4,
+ }}
+ >
+ <Text className="text-base-content">{item.text}</Text>
+ </View>
+
+ {item.comment ? (
+ <Text className="text-base-content mt-3">
+ {item.comment}
+ </Text>
+ ) : null}
+
+ <Text className="text-xs text-neutral mt-3">
+ {formatHighlightDate(item.createdAt)}
+ </Text>
+ </TouchableOpacity>
+
+ <TouchableOpacity
+ activeOpacity={0.75}
+ className="ml-3 mt-1"
+ disabled={removeHighlight.isPending}
+ onPress={() => handleDeleteHighlight(item.id)}
+ >
+ {isDeleting ? (
+ <ActivityIndicator size="small" color={theme.error} />
+ ) : (
+ <Trash2 size={16} color={theme.error} />
+ )}
+ </TouchableOpacity>
+ </View>
+ </View>
+ );
+ }}
+ />
+ )}
+
+ <View className="px-6 pb-4">
+ <Button onPress={closeSheet} variant="outline">
+ <Text className="text-base-content">Close</Text>
+ </Button>
+ </View>
+ </ActionSheet>
+ );
+}
diff --git a/apps/mobile/components/ActionSheets/Sheets.tsx b/apps/mobile/components/ActionSheets/Sheets.tsx
index 7334493f..789d404f 100644
--- a/apps/mobile/components/ActionSheets/Sheets.tsx
+++ b/apps/mobile/components/ActionSheets/Sheets.tsx
@@ -10,6 +10,7 @@ import NewCollectionSheet from "./NewCollectionSheet";
import ReadableHighlightSheet, {
ReadableHighlightDraft,
} from "./ReadableHighlightSheet";
+import ReadableHighlightsSheet from "./ReadableHighlightsSheet";
import { LinkIncludingShortenedCollectionAndTags } from "@linkwarden/types/global";
registerSheet("support-sheet", SupportSheet);
@@ -17,6 +18,7 @@ registerSheet("add-link-sheet", AddLinkSheet);
registerSheet("edit-link-sheet", EditLinkSheet);
registerSheet("new-collection-sheet", NewCollectionSheet);
registerSheet("readable-highlight-sheet", ReadableHighlightSheet);
+registerSheet("readable-highlights-sheet", ReadableHighlightsSheet);
declare module "react-native-actions-sheet" {
interface Sheets {
@@ -44,6 +46,12 @@ declare module "react-native-actions-sheet" {
draft: ReadableHighlightDraft;
};
}>;
+ "readable-highlights-sheet": SheetDefinition<{
+ payload: {
+ linkId: number;
+ };
+ returnValue: number | null;
+ }>;
}
}
diff --git a/apps/mobile/components/Formats/ReadableFormat.tsx b/apps/mobile/components/Formats/ReadableFormat.tsx
index ce40afc3..497ddc0a 100644
--- a/apps/mobile/components/Formats/ReadableFormat.tsx
+++ b/apps/mobile/components/Formats/ReadableFormat.tsx
@@ -1,6 +1,8 @@
import React, {
+ forwardRef,
useCallback,
useEffect,
+ useImperativeHandle,
useMemo,
useRef,
useState,
@@ -34,6 +36,10 @@ type Props = {
setIsLoading: (state: boolean) => void;
};
+export type ReadableFormatRef = {
+ scrollToHighlight: (highlightId: number) => void;
+};
+
type SelectionInfo = {
linkId: number;
text: string;
@@ -163,10 +169,13 @@ function ReadableSkeleton({ theme }: { theme: (typeof rawTheme)["light"] }) {
);
}
-export default function ReadableFormat({
- link,
- setIsLoading,
-}: Props) {
+const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFormat(
+ {
+ link,
+ setIsLoading,
+ }: Props,
+ ref
+) {
const FORMAT = ArchivedFormat.readability;
const { auth } = useAuthStore();
@@ -176,6 +185,7 @@ export default function ReadableFormat({
const webViewRef = useRef<any>(null);
const latestSelectionRef = useRef<SelectionInfo | null>(null);
const pendingSelectionTextRef = useRef<string | null>(null);
+ const pendingHighlightScrollIdRef = useRef<number | null>(null);
const isWebViewReadyRef = useRef(false);
useEffect(() => {
@@ -344,6 +354,40 @@ export default function ReadableFormat({
`);
}, []);
+ const scrollToHighlightInWebView = useCallback((highlightId: number) => {
+ if (!isWebViewReadyRef.current) return;
+
+ webViewRef.current?.injectJavaScript(`
+ if (window.__READABLE_VIEW__?.scrollToHighlight) {
+ window.__READABLE_VIEW__.scrollToHighlight(${highlightId});
+ }
+ true;
+ `);
+ }, []);
+
+ const flushPendingHighlightScroll = useCallback(() => {
+ if (
+ !isWebViewReadyRef.current ||
+ pendingHighlightScrollIdRef.current === null
+ ) {
+ return;
+ }
+
+ scrollToHighlightInWebView(pendingHighlightScrollIdRef.current);
+ pendingHighlightScrollIdRef.current = null;
+ }, [scrollToHighlightInWebView]);
+
+ useImperativeHandle(
+ ref,
+ () => ({
+ scrollToHighlight: (highlightId: number) => {
+ pendingHighlightScrollIdRef.current = highlightId;
+ flushPendingHighlightScroll();
+ },
+ }),
+ [flushPendingHighlightScroll]
+ );
+
useEffect(() => {
syncHighlightsToWebView(linkHighlights);
}, [linkHighlights, syncHighlightsToWebView]);
@@ -355,6 +399,7 @@ export default function ReadableFormat({
useEffect(() => {
latestSelectionRef.current = null;
pendingSelectionTextRef.current = null;
+ pendingHighlightScrollIdRef.current = null;
setDisableHighlightMenu(false);
clearWebSelection();
void SheetManager.hide("readable-highlight-sheet");
@@ -435,6 +480,9 @@ export default function ReadableFormat({
background-color: ${HIGHLIGHT_COLORS[3].backgroundColor};
border-bottom-color: ${HIGHLIGHT_COLORS[3].borderColor};
}
+ .rv-highlight--focused {
+ box-shadow: 0 0 0 2px ${theme.primary};
+ }
${readerViewCSS}
</style>
</head>
@@ -696,6 +744,55 @@ export default function ReadableFormat({
});
}
+ function scrollToHighlight(highlightId, attempt) {
+ const container = getContainer();
+ if (!container) return false;
+
+ const highlightNodes = Array.from(
+ container.querySelectorAll(
+ 'span[data-highlight-id="' + String(highlightId) + '"]'
+ )
+ );
+
+ if (highlightNodes.length === 0) {
+ if ((attempt || 0) < 8) {
+ window.setTimeout(function () {
+ scrollToHighlight(highlightId, (attempt || 0) + 1);
+ }, 60);
+ }
+
+ return false;
+ }
+
+ container
+ .querySelectorAll("span.rv-highlight--focused")
+ .forEach((node) => {
+ node.classList.remove("rv-highlight--focused");
+ });
+
+ highlightNodes.forEach((node) => {
+ node.classList.add("rv-highlight--focused");
+ });
+
+ window.setTimeout(function () {
+ highlightNodes.forEach((node) => {
+ node.classList.remove("rv-highlight--focused");
+ });
+ }, 1800);
+
+ const firstNode = highlightNodes[0];
+
+ if (firstNode instanceof HTMLElement) {
+ firstNode.scrollIntoView({
+ behavior: "smooth",
+ block: "center",
+ inline: "nearest",
+ });
+ }
+
+ return true;
+ }
+
document.addEventListener("selectionchange", function () {
serializeSelection(true);
});
@@ -739,6 +836,7 @@ export default function ReadableFormat({
clearSelection: clearSelection,
getSelectionInfo: getSelectionInfo,
renderHighlights: renderHighlights,
+ scrollToHighlight: scrollToHighlight,
};
setContent();
@@ -819,6 +917,7 @@ export default function ReadableFormat({
if (message?.type === "ready") {
isWebViewReadyRef.current = true;
syncHighlightsToWebView(linkHighlights);
+ flushPendingHighlightScroll();
return;
}
@@ -883,4 +982,6 @@ export default function ReadableFormat({
originWhitelist={["*"]}
/>
);
-}
+});
+
+export default ReadableFormat;