⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.
TypeScript bookmarkbookmark-managercollaborationnextjsreact-nativeread-it-laterself-hostedtypescript
feat(mobile): added highlight and annotation functionality to the reader view
daniel31x138e8e6f92aad8
diff --git a/apps/mobile/app/(tabs)/dashboard/index.tsx b/apps/mobile/app/(tabs)/dashboard/index.tsxindex 5a06bc0b..c659f6e8 100644--- a/apps/mobile/app/(tabs)/dashboard/index.tsx+++ b/apps/mobile/app/(tabs)/dashboard/index.tsx@@ -7,6 +7,7 @@ import {View,} from "react-native";import React, { useEffect, useMemo, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";import { useDashboardData } from "@linkwarden/router/dashboardData";import { isAtLeastInstanceVersion, useConfig } from "@linkwarden/router/config";import useAuthStore from "@/store/auth";@@ -23,6 +24,7 @@ const DASHBOARD_TAG_COUNT_VERSION = "2.14.0";export default function DashboardScreen() {const { auth } = useAuthStore();+ const queryClient = useQueryClient();const {data: {links = [],@@ -89,6 +91,10 @@ export default function DashboardScreen() {dashboardData.refetch(),userData.refetch(),collectionsData.refetch(),+ queryClient.refetchQueries({+ queryKey: ["highlights"],+ type: "all",+ }),...(shouldUseLegacyTagsCount ? [legacyTags.refetch()] : []),]);} finally {diff --git a/apps/mobile/app/links/[id].tsx b/apps/mobile/app/links/[id].tsxindex 962c046c..1842c17c 100644--- a/apps/mobile/app/links/[id].tsx+++ b/apps/mobile/app/links/[id].tsx@@ -1,8 +1,9 @@-import React, { useEffect, useState } from "react";+import React, { useCallback, useEffect, useState } from "react";import { View, ActivityIndicator, Text, Platform } from "react-native";import { WebView } from "react-native-webview";+import { useQueryClient } from "@tanstack/react-query";import useAuthStore from "@/store/auth";-import { useLocalSearchParams } from "expo-router";+import { useFocusEffect, useLocalSearchParams } from "expo-router";import { useUser } from "@linkwarden/router/user";import { useGetLink } from "@linkwarden/router/links";import useTmpStore from "@/store/tmp";@@ -16,11 +17,17 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";export default function LinkScreen() {const { auth } = useAuthStore();const { id, format } = useLocalSearchParams();+ const queryClient = useQueryClient();const { data: user } = useUser(auth);+ const linkId = Number(id);const [url, setUrl] = useState<string>();const [isLoading, setIsLoading] = useState(true);- const { data: link } = useGetLink({ id: Number(id), auth, enabled: true });+ const { data: link, refetch: refetchLink } = useGetLink({+ id: linkId,+ auth,+ enabled: true,+ });const { updateTmp } = useTmpStore();@@ -49,6 +56,20 @@ export default function LinkScreen() {}}, [user, link]);+ useFocusEffect(+ useCallback(() => {+ if (!linkId) return;++ void Promise.all([+ refetchLink(),+ queryClient.invalidateQueries({+ queryKey: ["highlights", linkId],+ exact: true,+ }),+ ]);+ }, [linkId, queryClient, refetchLink])+ );+const insets = useSafeAreaInsets();return (diff --git a/apps/mobile/components/ActionSheets/ReadableHighlightSheet.tsx b/apps/mobile/components/ActionSheets/ReadableHighlightSheet.tsxnew file mode 100644index 00000000..e5464016--- /dev/null+++ b/apps/mobile/components/ActionSheets/ReadableHighlightSheet.tsx@@ -0,0 +1,300 @@+import { Alert, Text, TouchableOpacity, View } from "react-native";+import { useEffect, useState } from "react";+import ActionSheet, {+ SheetManager,+ SheetProps,+} from "react-native-actions-sheet";+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { Trash2 } from "lucide-react-native";+import { useColorScheme } from "nativewind";+import { Highlight } from "@linkwarden/prisma/client";+import { rawTheme, ThemeName } from "@/lib/colors";+import { useSafeAreaInsets } from "react-native-safe-area-context";+import useAuthStore from "@/store/auth";+import { Button } from "@/components/ui/Button";+import Input from "@/components/ui/Input";++export const HIGHLIGHT_COLORS = [+ {+ name: "yellow",+ previewColor: "#FDE047",+ backgroundColor: "rgba(234, 179, 8, 0.45)",+ borderColor: "rgba(202, 138, 4, 0.95)",+ },+ {+ name: "red",+ previewColor: "#EF4444",+ backgroundColor: "rgba(239, 68, 68, 0.3)",+ borderColor: "rgba(220, 38, 38, 0.95)",+ },+ {+ name: "blue",+ previewColor: "#3B82F6",+ backgroundColor: "rgba(59, 130, 246, 0.3)",+ borderColor: "rgba(37, 99, 235, 0.95)",+ },+ {+ name: "green",+ previewColor: "#22C55E",+ backgroundColor: "rgba(34, 197, 94, 0.3)",+ borderColor: "rgba(22, 163, 74, 0.95)",+ },+] as const;++export type HighlightColor = (typeof HIGHLIGHT_COLORS)[number]["name"];++export type ReadableHighlightDraft = {+ highlightId: number | null;+ linkId: number;+ text: string;+ startOffset: number;+ endOffset: number;+ color: HighlightColor;+ comment: string;+};++export const MAX_HIGHLIGHT_TEXT_LENGTH = 2048;++export default function ReadableHighlightSheet(+ props: SheetProps<"readable-highlight-sheet">+) {+ const { auth } = useAuthStore();+ const queryClient = useQueryClient();+ const [draft, setDraft] = useState<ReadableHighlightDraft | null>(null);+ const { colorScheme } = useColorScheme();+ const insets = useSafeAreaInsets();+ const theme = rawTheme[colorScheme as ThemeName];++ useEffect(() => {+ setDraft(props.payload?.draft ?? null);+ }, [props.payload?.draft]);++ const closeSheet = () => {+ void SheetManager.hide("readable-highlight-sheet");+ };++ const saveHighlight = useMutation({+ mutationFn: async (highlight: ReadableHighlightDraft) => {+ const response = await fetch(`${auth.instance}/api/v1/highlights`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${auth.session}`,+ },+ body: JSON.stringify({+ color: highlight.color,+ comment: highlight.comment,+ startOffset: highlight.startOffset,+ endOffset: highlight.endOffset,+ text: highlight.text,+ linkId: highlight.linkId,+ }),+ });++ const data = await response.json();++ if (!response.ok) throw new Error(data.response);++ return data.response as Highlight;+ },+ onSuccess: (highlight) => {+ queryClient.setQueryData(+ ["highlights", highlight.linkId],+ (existing: Highlight[] = []) => {+ const index = existing.findIndex((item) => item.id === highlight.id);++ if (index === -1) return [...existing, highlight];++ const next = [...existing];+ next[index] = highlight;+ return next;+ }+ );++ closeSheet();+ },+ onError: (error) => {+ Alert.alert("Error", "There was an error saving the highlight.");+ console.error("Failed to save highlight", error);+ },+ });++ const deleteHighlight = useMutation({+ mutationFn: async (payload: { highlightId: number; linkId: number }) => {+ const response = await fetch(+ `${auth.instance}/api/v1/highlights/${payload.highlightId}`,+ {+ method: "DELETE",+ headers: {+ Authorization: `Bearer ${auth.session}`,+ },+ }+ );++ const data = await response.json();++ if (!response.ok) throw new Error(data.response);++ return payload;+ },+ onSuccess: ({ highlightId, linkId }) => {+ queryClient.setQueryData(+ ["highlights", linkId],+ (existing: Highlight[] = []) =>+ existing.filter((highlight) => highlight.id !== highlightId)+ );++ closeSheet();+ },+ onError: (error) => {+ Alert.alert("Error", "There was an error removing the highlight.");+ console.error("Failed to delete highlight", error);+ },+ });++ const handleSave = () => {+ if (!draft) return;++ if (!draft.text.trim()) {+ Alert.alert("Highlight", "Please select some text to highlight.");+ return;+ }++ if (draft.text.length > MAX_HIGHLIGHT_TEXT_LENGTH) {+ Alert.alert(+ "Selection too long",+ "Please select a shorter passage before creating a highlight."+ );+ return;+ }++ saveHighlight.mutate(draft);+ };++ const handleDelete = () => {+ if (!draft?.highlightId) return;++ deleteHighlight.mutate({+ highlightId: draft.highlightId,+ linkId: draft.linkId,+ });+ };++ return (+ <ActionSheet+ gestureEnabled+ indicatorStyle={{+ display: "none",+ }}+ containerStyle={{+ backgroundColor: theme["base-200"],+ }}+ safeAreaInsets={insets}+ onClose={() => {+ setDraft(null);+ }}+ >+ <View className="px-8 py-5">+ <Text className="font-semibold text-lg mx-auto mb-5 text-base-content">+ Highlight+ </Text>++ <View className="flex-row items-center justify-center gap-4 mb-4">+ {HIGHLIGHT_COLORS.map((colorOption) => {+ const isSelected = draft?.color === colorOption.name;++ return (+ <TouchableOpacity+ key={colorOption.name}+ activeOpacity={0.8}+ onPress={() =>+ setDraft((current) =>+ current+ ? {+ ...current,+ color: colorOption.name,+ }+ : current+ )+ }+ style={{+ width: 36,+ height: 36,+ borderRadius: 999,+ backgroundColor: colorOption.previewColor,+ alignItems: "center",+ justifyContent: "center",+ }}+ >+ {isSelected ? (+ <View+ style={{+ width: 15,+ height: 15,+ borderRadius: 999,+ backgroundColor: theme["base-200"],+ }}+ />+ ) : null}+ </TouchableOpacity>+ );+ })}+ </View>++ <Input+ multiline+ maxLength={2048}+ textAlignVertical="top"+ placeholder="Notes, Thoughts, etc."+ className="mb-4 h-28 bg-base-100"+ value={draft?.comment ?? ""}+ onChangeText={(text) =>+ setDraft((current) =>+ current+ ? {+ ...current,+ comment: text,+ }+ : current+ )+ }+ />++ <Button+ onPress={handleSave}+ isLoading={saveHighlight.isPending}+ disabled={!draft || deleteHighlight.isPending}+ variant="accent"+ className="mb-2"+ >+ <Text className="text-white">Save</Text>+ </Button>++ {draft?.highlightId ? (+ <Button+ onPress={handleDelete}+ isLoading={deleteHighlight.isPending}+ disabled={saveHighlight.isPending}+ variant="outline"+ className="mb-2"+ >+ <View className="flex-row items-center justify-center gap-2">+ <Trash2 size={16} color={theme["error"]} />+ <Text+ style={{+ color: theme["error"],+ }}+ >+ Remove Highlight+ </Text>+ </View>+ </Button>+ ) : null}++ <Button onPress={closeSheet} variant="outline" className="mb-2">+ <Text className="text-base-content">Cancel</Text>+ </Button>+ </View>+ </ActionSheet>+ );+}diff --git a/apps/mobile/components/ActionSheets/Sheets.tsx b/apps/mobile/components/ActionSheets/Sheets.tsxindex e4a07cfa..7334493f 100644--- a/apps/mobile/components/ActionSheets/Sheets.tsx+++ b/apps/mobile/components/ActionSheets/Sheets.tsx@@ -7,12 +7,16 @@ import SupportSheet from "./SupportSheet";import AddLinkSheet from "./AddLinkSheet";import EditLinkSheet from "./EditLinkSheet";import NewCollectionSheet from "./NewCollectionSheet";+import ReadableHighlightSheet, {+ ReadableHighlightDraft,+} from "./ReadableHighlightSheet";import { LinkIncludingShortenedCollectionAndTags } from "@linkwarden/types/global";registerSheet("support-sheet", SupportSheet);registerSheet("add-link-sheet", AddLinkSheet);registerSheet("edit-link-sheet", EditLinkSheet);registerSheet("new-collection-sheet", NewCollectionSheet);+registerSheet("readable-highlight-sheet", ReadableHighlightSheet);declare module "react-native-actions-sheet" {interface Sheets {@@ -35,6 +39,11 @@ declare module "react-native-actions-sheet" {};}>;"new-collection-sheet": SheetDefinition;+ "readable-highlight-sheet": SheetDefinition<{+ payload: {+ draft: ReadableHighlightDraft;+ };+ }>;}}diff --git a/apps/mobile/components/Formats/ReadableFormat.tsx b/apps/mobile/components/Formats/ReadableFormat.tsxindex aa3aefbf..16d22712 100644--- a/apps/mobile/components/Formats/ReadableFormat.tsx+++ b/apps/mobile/components/Formats/ReadableFormat.tsx@@ -1,24 +1,111 @@-import React, { useEffect, useMemo, useState } from "react";-import { View, Linking } from "react-native";+import React, {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { Alert, Linking, View } from "react-native";+import { useQuery } from "@tanstack/react-query";import * as FileSystem from "expo-file-system/legacy";+import * as Clipboard from "expo-clipboard";import NetInfo from "@react-native-community/netinfo";import useAuthStore from "@/store/auth";import WebView from "react-native-webview";+import { SheetManager } from "react-native-actions-sheet";import { decode } from "html-entities";import { useColorScheme } from "nativewind";import { rawTheme, ThemeName } from "@/lib/colors";import { ArchivedFormat } from "@linkwarden/types/global";-import { Link as LinkType } from "@linkwarden/prisma/client";+import { Highlight, Link as LinkType } from "@linkwarden/prisma/client";import {readerViewCSS,readerViewThemeVars,} from "@linkwarden/lib/readerViewStyles";+import {+ HIGHLIGHT_COLORS,+ HighlightColor,+ MAX_HIGHLIGHT_TEXT_LENGTH,+ ReadableHighlightDraft,+} from "@/components/ActionSheets/ReadableHighlightSheet";type Props = {link: LinkType;setIsLoading: (state: boolean) => void;};+type SelectionInfo = {+ linkId: number;+ text: string;+ startOffset: number;+ endOffset: number;+};+const HIGHLIGHT_MENU_KEY = "highlight";+const COPY_MENU_KEY = "copy";+const SEARCH_WEB_MENU_KEY = "search-web";++function normalizeHighlightColor(color?: string | null): HighlightColor {+ if (color === "red" || color === "blue" || color === "green") return color;+ return "yellow";+}++function normalizeSelectedText(text?: string | null) {+ return (text || "").replace(/\s+/g, " ").trim();+}++function escapeForInlineScript(value: string) {+ return JSON.stringify(value)+ .replace(/</g, "\\u003c")+ .replace(/\u2028/g, "\\u2028")+ .replace(/\u2029/g, "\\u2029");+}++function escapeForInjectedScript(value: unknown) {+ return JSON.stringify(value)+ .replace(/</g, "\\u003c")+ .replace(/\u2028/g, "\\u2028")+ .replace(/\u2029/g, "\\u2029");+}++function isSelectionInfo(value: unknown): value is SelectionInfo {+ if (!value || typeof value !== "object") return false;++ const candidate = value as SelectionInfo;++ return (+ typeof candidate.linkId === "number" &&+ typeof candidate.text === "string" &&+ typeof candidate.startOffset === "number" &&+ typeof candidate.endOffset === "number"+ );+}++function isHighlight(value: unknown): value is Highlight {+ if (!value || typeof value !== "object") return false;++ const candidate = value as Highlight;++ return (+ typeof candidate.id === "number" &&+ typeof candidate.linkId === "number" &&+ typeof candidate.text === "string" &&+ typeof candidate.startOffset === "number" &&+ typeof candidate.endOffset === "number" &&+ typeof candidate.color === "string"+ );+}++function findMatchingHighlight(+ highlights: Highlight[],+ selection: SelectionInfo+) {+ return highlights.find(+ (highlight) =>+ highlight.startOffset === selection.startOffset &&+ highlight.endOffset === selection.endOffset+ );+}+function ReadableSkeleton({ theme }: { theme: (typeof rawTheme)["light"] }) {const barStyle = {backgroundColor: theme["neutral-content"],@@ -29,9 +116,13 @@ function ReadableSkeleton({ theme }: { theme: (typeof rawTheme)["light"] }) {return (<View style={{ flex: 1, padding: 16 }}>- <View style={{ ...barStyle, height: 22, width: "75%", marginBottom: 14 }} />+ <View+ style={{ ...barStyle, height: 22, width: "75%", marginBottom: 14 }}+ /><View style={{ ...barStyle, width: "50%", height: 12 }} />- <View style={{ ...barStyle, width: "40%", height: 12, marginBottom: 20 }} />+ <View+ style={{ ...barStyle, width: "40%", height: 12, marginBottom: 20 }}+ /><Viewstyle={{borderTopWidth: 1,@@ -51,12 +142,19 @@ function ReadableSkeleton({ theme }: { theme: (typeof rawTheme)["light"] }) {);}-export default function ReadableFormat({ link, setIsLoading }: Props) {+export default function ReadableFormat({+ link,+ setIsLoading,+}: Props) {const FORMAT = ArchivedFormat.readability;const { auth } = useAuthStore();const [content, setContent] = useState<string>("");const { colorScheme } = useColorScheme();+ const webViewRef = useRef<any>(null);+ const latestSelectionRef = useRef<SelectionInfo | null>(null);+ const pendingSelectionTextRef = useRef<string | null>(null);+ const isWebViewReadyRef = useRef(false);useEffect(() => {async function loadCacheOrFetch() {@@ -100,17 +198,170 @@ export default function ReadableFormat({ link, setIsLoading }: Props) {}loadCacheOrFetch();- }, [link]);+ }, [FORMAT, auth.instance, auth.session, link.id]);const theme = rawTheme[colorScheme as ThemeName];const isDark = colorScheme === "dark";const title = decode(link.name || link.description || link.url || "");- const dateStr = new Date(link?.importDate || link.createdAt).toLocaleDateString(- "en-US",- { year: "numeric", month: "short", day: "numeric" }+ const dateStr = new Date(+ link?.importDate || link.createdAt+ ).toLocaleDateString("en-US", {+ year: "numeric",+ month: "short",+ day: "numeric",+ });++ const { data: linkHighlights = [] } = useQuery({+ queryKey: ["highlights", link.id],+ queryFn: async () => {+ const response = await fetch(+ `${auth.instance}/api/v1/links/${link.id}/highlights`,+ {+ headers: {+ Authorization: `Bearer ${auth.session}`,+ },+ }+ );++ if (!response.ok) throw new Error("Failed to fetch highlights.");++ const data = await response.json();++ return data.response as Highlight[];+ },+ enabled: Boolean(+ link.id &&+ auth.instance &&+ auth.session &&+ auth.status === "authenticated"+ ),+ initialData: [] as Highlight[],+ });++ const clearWebSelection = useCallback(() => {+ pendingSelectionTextRef.current = null;++ webViewRef.current?.injectJavaScript(`+ if (window.__READABLE_VIEW__?.clearSelection) {+ window.__READABLE_VIEW__.clearSelection();+ }+ true;+ `);+ }, []);++ const showHighlightSheet = useCallback(+ async (draft: ReadableHighlightDraft) => {+ try {+ await SheetManager.show("readable-highlight-sheet", {+ payload: {+ draft,+ },+ });+ } finally {+ clearWebSelection();+ }+ },+ [clearWebSelection]);+ const openDraftFromSelection = useCallback(+ (selection: SelectionInfo) => {+ if (!selection.text.trim()) {+ clearWebSelection();+ return;+ }++ if (selection.text.length > MAX_HIGHLIGHT_TEXT_LENGTH) {+ Alert.alert(+ "Selection too long",+ "Please select a shorter passage before creating a highlight."+ );+ clearWebSelection();+ return;+ }++ const existingHighlight = findMatchingHighlight(+ linkHighlights,+ selection+ );+ pendingSelectionTextRef.current = null;++ void showHighlightSheet({+ highlightId: existingHighlight?.id ?? null,+ linkId: selection.linkId,+ text: selection.text,+ startOffset: selection.startOffset,+ endOffset: selection.endOffset,+ color: normalizeHighlightColor(existingHighlight?.color),+ comment: existingHighlight?.comment ?? "",+ });+ },+ [clearWebSelection, linkHighlights, showHighlightSheet]+ );++ const openDraftFromHighlight = useCallback(+ (highlight: Highlight) => {+ pendingSelectionTextRef.current = null;++ void showHighlightSheet({+ highlightId: highlight.id,+ linkId: highlight.linkId,+ text: highlight.text,+ startOffset: highlight.startOffset,+ endOffset: highlight.endOffset,+ color: normalizeHighlightColor(highlight.color),+ comment: highlight.comment ?? "",+ });+ },+ [showHighlightSheet]+ );++ const requestLatestSelection = useCallback(() => {+ webViewRef.current?.injectJavaScript(`+ (function () {+ const selection =+ window.__READABLE_VIEW__?.getSelectionInfo?.() ?? null;++ window.ReactNativeWebView?.postMessage(+ JSON.stringify({+ type: "selection",+ payload: selection,+ })+ );+ })();+ true;+ `);+ }, []);++ const syncHighlightsToWebView = useCallback((highlights: Highlight[]) => {+ if (!isWebViewReadyRef.current) return;++ webViewRef.current?.injectJavaScript(`+ if (window.__READABLE_VIEW__?.renderHighlights) {+ window.__READABLE_VIEW__.renderHighlights(${escapeForInjectedScript(+ highlights+ )});+ }+ true;+ `);+ }, []);++ useEffect(() => {+ syncHighlightsToWebView(linkHighlights);+ }, [linkHighlights, syncHighlightsToWebView]);++ useEffect(() => {+ isWebViewReadyRef.current = false;+ }, [content, colorScheme]);++ useEffect(() => {+ latestSelectionRef.current = null;+ pendingSelectionTextRef.current = null;+ clearWebSelection();+ void SheetManager.hide("readable-highlight-sheet");+ }, [clearWebSelection, link.id]);+const htmlDocument = useMemo(() => `<!DOCTYPE html>@@ -161,48 +412,449 @@ export default function ReadableFormat({ link, setIsLoading }: Props) {border-top: 1px solid ${theme["neutral-content"]};margin: 10px 0 20px 0;}+ .rv-highlight {+ border-radius: 5px;+ padding-left: 0.25rem;+ padding-right: 0.25rem;+ }+ .rv-highlight--commented {+ border-bottom-style: solid;+ border-bottom-width: 2px;+ }+ .rv-highlight--yellow {+ background-color: ${HIGHLIGHT_COLORS[0].backgroundColor};+ border-bottom-color: ${HIGHLIGHT_COLORS[0].borderColor};+ }+ .rv-highlight--red {+ background-color: ${HIGHLIGHT_COLORS[1].backgroundColor};+ border-bottom-color: ${HIGHLIGHT_COLORS[1].borderColor};+ }+ .rv-highlight--blue {+ background-color: ${HIGHLIGHT_COLORS[2].backgroundColor};+ border-bottom-color: ${HIGHLIGHT_COLORS[2].borderColor};+ }+ .rv-highlight--green {+ background-color: ${HIGHLIGHT_COLORS[3].backgroundColor};+ border-bottom-color: ${HIGHLIGHT_COLORS[3].borderColor};+ }${readerViewCSS}</style></head><body>- <div class="rv-header-title">${title.replace(/</g, "<").replace(/>/g, ">")}</div>+ <div class="rv-header-title">${title+ .replace(/</g, "<")+ .replace(/>/g, ">")}</div><div class="rv-header-meta">- <a href="${(link.url || "").replace(/"/g, """)}">${link.url || ""}</a>+ <a href="${(link.url || "").replace(/"/g, """)}">${+ link.url || ""+ }</a></div><div class="rv-header-meta">${dateStr}</div><hr class="rv-header-separator" />- <div class="reader-view read-only">- ${content}- </div>+ <div id="readable-view" class="reader-view read-only"></div>+ <script>+ (function () {+ const initialContent = ${escapeForInlineScript(content)};++ const state = {+ currentSelection: null,+ lastValidSelection: null,+ highlightsById: {},+ };++ function postMessage(type, payload) {+ window.ReactNativeWebView?.postMessage(+ JSON.stringify({ type: type, payload: payload })+ );+ }++ function getContainer() {+ return document.getElementById("readable-view");+ }++ function setContent() {+ const container = getContainer();+ if (!container) return;++ // Injecting via innerHTML keeps archived scripts inert while still+ // preserving the article markup we need to render.+ container.innerHTML = initialContent;+ }++ function clearSelection() {+ window.getSelection?.()?.removeAllRanges();+ state.currentSelection = null;+ state.lastValidSelection = null;+ }++ function getSelectionInfo() {+ return state.currentSelection || state.lastValidSelection;+ }++ function serializeSelection(shouldNotify) {+ const selection = window.getSelection?.();+ const container = getContainer();++ if (+ !selection ||+ selection.isCollapsed ||+ !container ||+ selection.rangeCount === 0+ ) {+ state.currentSelection = null;+ if (shouldNotify) postMessage("selection", null);+ return null;+ }++ const range = selection.getRangeAt(0);++ if (!container.contains(range.commonAncestorContainer)) {+ state.currentSelection = null;+ if (shouldNotify) postMessage("selection", null);+ return null;+ }++ let startOffset = -1;+ let endOffset = -1;+ let currentOffset = 0;++ const treeWalker = document.createTreeWalker(+ container,+ NodeFilter.SHOW_TEXT+ );++ while (treeWalker.nextNode()) {+ const node = treeWalker.currentNode;+ const nodeLength = node.textContent?.length ?? 0;++ if (node === range.startContainer) {+ startOffset = currentOffset + range.startOffset;+ }++ if (node === range.endContainer) {+ endOffset = currentOffset + range.endOffset;+ break;+ }++ currentOffset += nodeLength;+ }++ if (startOffset === -1 || endOffset === -1) {+ state.currentSelection = null;+ if (shouldNotify) postMessage("selection", null);+ return null;+ }++ const info = {+ linkId: ${link.id},+ text: range.toString(),+ startOffset: startOffset,+ endOffset: endOffset,+ };++ if (!info.text.trim()) {+ state.currentSelection = null;+ if (shouldNotify) postMessage("selection", null);+ return null;+ }++ state.currentSelection = info;+ state.lastValidSelection = info;++ if (shouldNotify) {+ postMessage("selection", info);+ }++ return info;+ }++ function unwrapHighlights() {+ const container = getContainer();+ if (!container) return;++ const wrappers = Array.from(+ container.querySelectorAll('span[data-rv-highlight="true"]')+ );++ wrappers.forEach((wrapper) => {+ const parent = wrapper.parentNode;+ if (!parent) return;++ while (wrapper.firstChild) {+ parent.insertBefore(wrapper.firstChild, wrapper);+ }++ parent.removeChild(wrapper);+ parent.normalize();+ });+ }++ function applyHighlight(highlight) {+ const container = getContainer();+ if (!container) return;++ let currentOffset = 0;+ const treeWalker = document.createTreeWalker(+ container,+ NodeFilter.SHOW_TEXT+ );++ const rangesToWrap = [];++ while (treeWalker.nextNode()) {+ const node = treeWalker.currentNode;+ const nodeLength = node.textContent?.length ?? 0;+ const nodeStart = currentOffset;+ const nodeEnd = nodeStart + nodeLength;++ if (+ nodeStart < highlight.endOffset &&+ nodeEnd > highlight.startOffset+ ) {+ rangesToWrap.push({+ node: node,+ start: Math.max(0, highlight.startOffset - nodeStart),+ end: Math.min(nodeLength, highlight.endOffset - nodeStart),+ });+ }++ currentOffset += nodeLength;+ }++ rangesToWrap.forEach((rangeToWrap) => {+ let textNode = rangeToWrap.node;+ let start = rangeToWrap.start;+ let end = rangeToWrap.end;++ if (!(textNode instanceof Text)) return;++ if (start > 0) {+ textNode.splitText(start);+ textNode = textNode.nextSibling;+ end -= start;+ }++ if (!(textNode instanceof Text)) return;++ if (end < textNode.length) {+ textNode.splitText(end);+ }++ const wrapper = document.createElement("span");++ wrapper.setAttribute("data-rv-highlight", "true");+ wrapper.setAttribute("data-highlight-id", String(highlight.id));+ wrapper.classList.add(+ "rv-highlight",+ "rv-highlight--" + highlight.color+ );++ if (highlight.comment) {+ wrapper.classList.add("rv-highlight--commented");+ }++ textNode.parentNode?.insertBefore(wrapper, textNode);+ wrapper.appendChild(textNode);+ });+ }++ function renderHighlights(highlights) {+ state.highlightsById = {};++ unwrapHighlights();++ if (!Array.isArray(highlights) || highlights.length === 0) {+ return;+ }++ const sortedHighlights = highlights+ .slice()+ .sort((a, b) => a.startOffset - b.startOffset);++ sortedHighlights.forEach((highlight) => {+ state.highlightsById[highlight.id] = highlight;+ applyHighlight(highlight);+ });+ }++ document.addEventListener("selectionchange", function () {+ serializeSelection(true);+ });++ document.addEventListener("mouseup", function () {+ serializeSelection(true);+ });++ document.addEventListener(+ "touchend",+ function () {+ window.setTimeout(function () {+ serializeSelection(true);+ }, 0);+ },+ { passive: true }+ );++ document.addEventListener("click", function (event) {+ const target = event.target;++ if (!(target instanceof Element)) return;++ const highlightEl = target.closest('span[data-rv-highlight="true"]');+ if (!highlightEl) return;++ const highlightId = Number(+ highlightEl.getAttribute("data-highlight-id")+ );+ const highlight = state.highlightsById[highlightId];++ if (!highlight) return;++ event.preventDefault();+ event.stopPropagation();+ clearSelection();+ postMessage("highlight-press", highlight);+ });++ window.__READABLE_VIEW__ = {+ clearSelection: clearSelection,+ getSelectionInfo: getSelectionInfo,+ renderHighlights: renderHighlights,+ };++ setContent();+ postMessage("ready", null);+ })();+ </script></body></html>`,- [content, colorScheme]+ [content, dateStr, isDark, link.id, link.url, theme, title]);if (!content) {return <ReadableSkeleton theme={theme} />;}+ const handleCustomMenuSelection = (event: {+ nativeEvent: {+ key: string;+ selectedText: string;+ };+ }) => {+ const selectedText = event.nativeEvent.selectedText || "";++ if (event.nativeEvent.key === COPY_MENU_KEY) {+ if (selectedText) {+ void Clipboard.setStringAsync(selectedText);+ }+ clearWebSelection();+ return;+ }++ if (event.nativeEvent.key === SEARCH_WEB_MENU_KEY) {+ const normalizedText = normalizeSelectedText(selectedText);++ if (normalizedText) {+ void Linking.openURL(+ `https://www.google.com/search?q=${encodeURIComponent(+ normalizedText+ )}`+ );+ }++ clearWebSelection();+ return;+ }++ if (event.nativeEvent.key !== HIGHLIGHT_MENU_KEY) return;++ const normalizedText = normalizeSelectedText(selectedText);+ if (!normalizedText) return;++ const selection = latestSelectionRef.current;++ if (selection && normalizeSelectedText(selection.text) === normalizedText) {+ openDraftFromSelection(selection);+ return;+ }++ pendingSelectionTextRef.current = normalizedText;+ requestLatestSelection();+ };++ const handleWebViewMessage = (event: { nativeEvent: { data: string } }) => {+ let message:+ | {+ type?: string;+ payload?: unknown;+ }+ | undefined;++ try {+ message = JSON.parse(event.nativeEvent.data);+ } catch {+ return;+ }++ if (message?.type === "ready") {+ isWebViewReadyRef.current = true;+ syncHighlightsToWebView(linkHighlights);+ return;+ }++ if (message?.type === "selection") {+ if (!isSelectionInfo(message.payload)) {+ latestSelectionRef.current = null;+ pendingSelectionTextRef.current = null;+ return;+ }++ latestSelectionRef.current = message.payload;++ if (+ pendingSelectionTextRef.current &&+ normalizeSelectedText(message.payload.text) ===+ pendingSelectionTextRef.current+ ) {+ pendingSelectionTextRef.current = null;+ openDraftFromSelection(message.payload);+ return;+ }++ pendingSelectionTextRef.current = null;+ return;+ }++ if (message?.type === "highlight-press" && isHighlight(message.payload)) {+ openDraftFromHighlight(message.payload);+ }+ };+return (<WebView+ ref={webViewRef}source={{ html: htmlDocument }}style={{flex: 1,backgroundColor: "transparent",}}onLoadEnd={() => setIsLoading(false)}+ onMessage={handleWebViewMessage}+ onCustomMenuSelection={handleCustomMenuSelection}onShouldStartLoadWithRequest={(request) => {- if (- request.url === "about:blank" ||- request.url.startsWith("data:")- ) {+ if (request.url === "about:blank" || request.url.startsWith("data:")) {return true;}Linking.openURL(request.url);return false;}}- javaScriptEnabled={false}+ javaScriptEnabled+ menuItems={[+ { label: "Highlight", key: HIGHLIGHT_MENU_KEY },+ { label: "Copy", key: COPY_MENU_KEY },+ { label: "Search Web", key: SEARCH_WEB_MENU_KEY },+ ]}originWhitelist={["*"]}/>);