Skip to content

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

feat(mobile): implement display settings functionality in the reader view

daniel31x13cd13a89fe2a4
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index e9c6bd1f..3266a827 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -17,6 +17,7 @@ import { rawTheme, ThemeName } from "@/lib/colors";
import { useShareIntent } from "expo-share-intent";
import useDataStore from "@/store/data";
import useAuthStore from "@/store/auth";
+import useReaderStore from "@/store/reader";
import { KeyboardProvider } from "react-native-keyboard-controller";
import { queryClient } from "@/lib/queryClient";
import { StatusBar } from "expo-status-bar";
@@ -32,6 +33,7 @@ export default Sentry.wrap(function RootLayout() {
const [isLoading, setIsLoading] = useState(true);
const { hasShareIntent, shareIntent, resetShareIntent } = useShareIntent();
const { updateData, setData, data } = useDataStore();
+ const { setReader } = useReaderStore();
const router = useRouter();
const pathname = usePathname();
@@ -42,6 +44,7 @@ export default Sentry.wrap(function RootLayout() {
useEffect(() => {
setAuth();
setData();
+ setReader();
}, []);
useEffect(() => {
diff --git a/apps/mobile/app/links/[id].tsx b/apps/mobile/app/links/[id].tsx
index 2b11e489..aa366720 100644
--- a/apps/mobile/app/links/[id].tsx
+++ b/apps/mobile/app/links/[id].tsx
@@ -205,6 +205,17 @@ export default function LinkScreen() {
</DropdownMenu.Item>
)}
+ {tmp.link && isReadableFormat && (
+ <DropdownMenu.Item
+ key="display-settings"
+ onSelect={() => {
+ void SheetManager.show("reader-settings-sheet");
+ }}
+ >
+ <DropdownMenu.ItemTitle>Display Settings</DropdownMenu.ItemTitle>
+ </DropdownMenu.Item>
+ )}
+
{tmp.link && (
<DropdownMenu.Item
key="edit-link"
diff --git a/apps/mobile/components/ActionSheets/ReadableHighlightsSheet.tsx b/apps/mobile/components/ActionSheets/ReadableHighlightsSheet.tsx
index 8c5b9b56..01cef933 100644
--- a/apps/mobile/components/ActionSheets/ReadableHighlightsSheet.tsx
+++ b/apps/mobile/components/ActionSheets/ReadableHighlightsSheet.tsx
@@ -106,9 +106,6 @@ export default function ReadableHighlightsSheet(
<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 ? (
diff --git a/apps/mobile/components/ActionSheets/ReaderSettingsSheet.tsx b/apps/mobile/components/ActionSheets/ReaderSettingsSheet.tsx
new file mode 100644
index 00000000..484f3a4a
--- /dev/null
+++ b/apps/mobile/components/ActionSheets/ReaderSettingsSheet.tsx
@@ -0,0 +1,281 @@
+import { Text, TouchableOpacity, View, ScrollView } from "react-native";
+import type { ReactNode } from "react";
+import ActionSheet, {
+ SheetManager,
+ SheetProps,
+} from "react-native-actions-sheet";
+import { ChevronDown, Minus, Plus } from "lucide-react-native";
+import { useColorScheme } from "nativewind";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+import { rawTheme, ThemeName } from "@/lib/colors";
+import { Button } from "@/components/ui/Button";
+import * as DropdownMenu from "zeego/dropdown-menu";
+import useReaderStore, {
+ READER_BACKGROUND_COLORS,
+ READER_DEFAULTS,
+ READER_FONT_FAMILIES,
+ READER_FONT_SIZES,
+ READER_LINE_HEIGHTS,
+} from "@/store/reader";
+
+const FONT_LABELS = {
+ "sans-serif": "Sans Serif",
+ serif: "Serif",
+ monospace: "Monospace",
+ cursive: "Cursive",
+ caveat: "Caveat",
+ bentham: "Bentham",
+} as const;
+
+const BACKGROUND_LABELS = {
+ system: "System",
+ light: "Light",
+ dark: "Dark",
+ sepia: "Sepia",
+} as const;
+
+function DropdownRow({
+ label,
+ value,
+ children,
+}: {
+ label: string;
+ value: string;
+ children: ReactNode;
+}) {
+ const { colorScheme } = useColorScheme();
+
+ return (
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger asChild>
+ <TouchableOpacity
+ activeOpacity={0.8}
+ className="bg-base-100 rounded-xl px-4 py-3 flex-row items-center justify-between"
+ >
+ <Text className="text-base-content text-base">{label}</Text>
+ <View className="flex-row items-center gap-1">
+ <Text className="text-neutral">{value}</Text>
+ <ChevronDown
+ size={16}
+ color={rawTheme[colorScheme as ThemeName].neutral}
+ />
+ </View>
+ </TouchableOpacity>
+ </DropdownMenu.Trigger>
+
+ <DropdownMenu.Content>{children}</DropdownMenu.Content>
+ </DropdownMenu.Root>
+ );
+}
+
+function StepperRow({
+ label,
+ value,
+ onDecrease,
+ onIncrease,
+}: {
+ label: string;
+ value: string;
+ onDecrease: () => void;
+ onIncrease: () => void;
+}) {
+ return (
+ <View className="bg-base-100 rounded-xl px-4 py-3 flex-row items-center justify-between">
+ <Text className="text-base-content text-base">{label}</Text>
+ <View className="flex-row items-center gap-2">
+ <TouchableOpacity
+ activeOpacity={0.8}
+ className="w-9 h-9 rounded-full items-center justify-center bg-base-200"
+ onPress={onDecrease}
+ >
+ <Minus size={16} color="#6B7280" />
+ </TouchableOpacity>
+ <Text className="text-base-content min-w-[64px] text-center">
+ {value}
+ </Text>
+ <TouchableOpacity
+ activeOpacity={0.8}
+ className="w-9 h-9 rounded-full items-center justify-center bg-base-200"
+ onPress={onIncrease}
+ >
+ <Plus size={16} color="#6B7280" />
+ </TouchableOpacity>
+ </View>
+ </View>
+ );
+}
+
+function moveInList<T extends string>(
+ values: readonly T[],
+ currentValue: T,
+ direction: -1 | 1
+) {
+ const currentIndex = values.indexOf(currentValue);
+ const nextIndex = currentIndex + direction;
+
+ if (nextIndex < 0 || nextIndex >= values.length) {
+ return currentValue;
+ }
+
+ return values[nextIndex];
+}
+
+export default function ReaderSettingsSheet(
+ props: SheetProps<"reader-settings-sheet">
+) {
+ const { colorScheme } = useColorScheme();
+ const insets = useSafeAreaInsets();
+ const theme = rawTheme[colorScheme as ThemeName];
+ const { reader, resetReader, updateReader } = useReaderStore();
+
+ const closeSheet = () => {
+ void SheetManager.hide(props.sheetId);
+ };
+
+ 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">
+ Display Settings
+ </Text>
+ </View>
+
+ <ScrollView
+ style={{
+ maxHeight: 540,
+ }}
+ contentContainerStyle={{
+ paddingHorizontal: 24,
+ paddingBottom: 12,
+ }}
+ showsVerticalScrollIndicator={false}
+ contentContainerClassName="flex flex-col gap-5"
+ >
+ <DropdownRow
+ label="Font Style"
+ value={
+ FONT_LABELS[reader.readableFontFamily as keyof typeof FONT_LABELS]
+ }
+ >
+ {READER_FONT_FAMILIES.map((option) => (
+ <DropdownMenu.CheckboxItem
+ key={option}
+ value={reader.readableFontFamily === option}
+ onValueChange={() => {
+ if (reader.readableFontFamily === option) return;
+
+ void updateReader({
+ readableFontFamily:
+ option as (typeof READER_FONT_FAMILIES)[number],
+ });
+ }}
+ >
+ <DropdownMenu.ItemTitle>
+ {FONT_LABELS[option as keyof typeof FONT_LABELS]}
+ </DropdownMenu.ItemTitle>
+ </DropdownMenu.CheckboxItem>
+ ))}
+ </DropdownRow>
+
+ <StepperRow
+ label="Font Size"
+ value={reader.readableFontSize}
+ onDecrease={() =>
+ void updateReader({
+ readableFontSize: moveInList(
+ READER_FONT_SIZES,
+ reader.readableFontSize,
+ -1
+ ),
+ })
+ }
+ onIncrease={() =>
+ void updateReader({
+ readableFontSize: moveInList(
+ READER_FONT_SIZES,
+ reader.readableFontSize,
+ 1
+ ),
+ })
+ }
+ />
+
+ <StepperRow
+ label="Line Height"
+ value={reader.readableLineHeight}
+ onDecrease={() =>
+ void updateReader({
+ readableLineHeight: moveInList(
+ READER_LINE_HEIGHTS,
+ reader.readableLineHeight,
+ -1
+ ),
+ })
+ }
+ onIncrease={() =>
+ void updateReader({
+ readableLineHeight: moveInList(
+ READER_LINE_HEIGHTS,
+ reader.readableLineHeight,
+ 1
+ ),
+ })
+ }
+ />
+
+ <DropdownRow
+ label="Background Color"
+ value={
+ BACKGROUND_LABELS[
+ reader.readableBackgroundColor as keyof typeof BACKGROUND_LABELS
+ ]
+ }
+ >
+ {READER_BACKGROUND_COLORS.map((option) => (
+ <DropdownMenu.CheckboxItem
+ key={option}
+ value={reader.readableBackgroundColor === option}
+ onValueChange={() => {
+ if (reader.readableBackgroundColor === option) return;
+
+ void updateReader({
+ readableBackgroundColor:
+ option as (typeof READER_BACKGROUND_COLORS)[number],
+ });
+ }}
+ >
+ <DropdownMenu.ItemTitle>
+ {BACKGROUND_LABELS[option as keyof typeof BACKGROUND_LABELS]}
+ </DropdownMenu.ItemTitle>
+ </DropdownMenu.CheckboxItem>
+ ))}
+ </DropdownRow>
+ </ScrollView>
+
+ <View className="px-6 pb-4 pt-2">
+ <Button
+ onPress={() => {
+ void resetReader();
+ }}
+ variant="outline"
+ className="mb-2"
+ disabled={JSON.stringify(reader) === JSON.stringify(READER_DEFAULTS)}
+ >
+ <Text className="text-base-content">Reset to Defaults</Text>
+ </Button>
+ <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 789d404f..b0b8b968 100644
--- a/apps/mobile/components/ActionSheets/Sheets.tsx
+++ b/apps/mobile/components/ActionSheets/Sheets.tsx
@@ -11,6 +11,7 @@ import ReadableHighlightSheet, {
ReadableHighlightDraft,
} from "./ReadableHighlightSheet";
import ReadableHighlightsSheet from "./ReadableHighlightsSheet";
+import ReaderSettingsSheet from "./ReaderSettingsSheet";
import { LinkIncludingShortenedCollectionAndTags } from "@linkwarden/types/global";
registerSheet("support-sheet", SupportSheet);
@@ -19,6 +20,7 @@ registerSheet("edit-link-sheet", EditLinkSheet);
registerSheet("new-collection-sheet", NewCollectionSheet);
registerSheet("readable-highlight-sheet", ReadableHighlightSheet);
registerSheet("readable-highlights-sheet", ReadableHighlightsSheet);
+registerSheet("reader-settings-sheet", ReaderSettingsSheet);
declare module "react-native-actions-sheet" {
interface Sheets {
@@ -52,6 +54,7 @@ declare module "react-native-actions-sheet" {
};
returnValue: number | null;
}>;
+ "reader-settings-sheet": SheetDefinition;
}
}
diff --git a/apps/mobile/components/Formats/ReadableFormat.tsx b/apps/mobile/components/Formats/ReadableFormat.tsx
index 497ddc0a..68cea070 100644
--- a/apps/mobile/components/Formats/ReadableFormat.tsx
+++ b/apps/mobile/components/Formats/ReadableFormat.tsx
@@ -20,8 +20,8 @@ import { rawTheme, ThemeName } from "@/lib/colors";
import { ArchivedFormat } from "@linkwarden/types/global";
import { Highlight, Link as LinkType } from "@linkwarden/prisma/client";
import {
+ READER_VIEW_DEFAULTS,
readerViewCSS,
- readerViewThemeVars,
} from "@linkwarden/lib/readerViewStyles";
import {
HIGHLIGHT_COLORS,
@@ -30,6 +30,10 @@ import {
ReadableHighlightDraft,
} from "@/components/ActionSheets/ReadableHighlightSheet";
import { useGetLinkHighlights } from "@linkwarden/router/highlights";
+import useReaderStore, {
+ getReadableFontFamily,
+ resolveReaderTheme,
+} from "@/store/reader";
type Props = {
link: LinkType;
@@ -51,6 +55,25 @@ type SelectionContext = {
disableHighlightMenu: boolean;
};
+type ReaderStyleConfig = {
+ bodyBackground: string;
+ bodyColor: string;
+ codeBackground: string;
+ fontFamily: string;
+ h1FontSize: string;
+ h2FontSize: string;
+ h3FontSize: string;
+ h4FontSize: string;
+ h5FontSize: string;
+ lineHeight: string;
+ linkColor: string;
+ markBackground: string;
+ markColor: string;
+ neutralColor: string;
+ neutralBorderColor: string;
+ paragraphFontSize: string;
+};
+
const HIGHLIGHT_MENU_KEY = "highlight";
const COPY_MENU_KEY = "copy";
const SEARCH_WEB_MENU_KEY = "search-web";
@@ -169,6 +192,41 @@ function ReadableSkeleton({ theme }: { theme: (typeof rawTheme)["light"] }) {
);
}
+function getReaderStyleConfig({
+ fontFamily,
+ fontSize,
+ lineHeight,
+ theme,
+ isDark,
+}: {
+ fontFamily: string;
+ fontSize: string;
+ lineHeight: string;
+ theme: (typeof rawTheme)["light"];
+ isDark: boolean;
+}): ReaderStyleConfig {
+ const ratio = parseInt(fontSize, 10) / READER_VIEW_DEFAULTS.fontSize;
+
+ return {
+ bodyBackground: theme["base-100"],
+ bodyColor: theme["base-content"],
+ codeBackground: isDark ? "rgb(49, 49, 49)" : "rgb(230, 230, 230)",
+ fontFamily,
+ h1FontSize: `${READER_VIEW_DEFAULTS.h1Size * ratio}px`,
+ h2FontSize: `${READER_VIEW_DEFAULTS.h2Size * ratio}px`,
+ h3FontSize: `${READER_VIEW_DEFAULTS.h3Size * ratio}px`,
+ h4FontSize: `${READER_VIEW_DEFAULTS.h4Size * ratio}px`,
+ h5FontSize: `${READER_VIEW_DEFAULTS.h5Size * ratio}px`,
+ lineHeight,
+ linkColor: theme.primary,
+ markBackground: `${theme.primary}80`,
+ markColor: theme["base-content"],
+ neutralColor: theme.neutral,
+ neutralBorderColor: theme["neutral-content"],
+ paragraphFontSize: fontSize,
+ };
+}
+
const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFormat(
{
link,
@@ -179,11 +237,14 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFor
const FORMAT = ArchivedFormat.readability;
const { auth } = useAuthStore();
+ const { reader } = useReaderStore();
const [content, setContent] = useState<string>("");
const [disableHighlightMenu, setDisableHighlightMenu] = useState(false);
+ const [webViewHtml, setWebViewHtml] = useState("");
const { colorScheme } = useColorScheme();
const webViewRef = useRef<any>(null);
const latestSelectionRef = useRef<SelectionInfo | null>(null);
+ const latestReaderStyleConfigRef = useRef<ReaderStyleConfig | null>(null);
const pendingSelectionTextRef = useRef<string | null>(null);
const pendingHighlightScrollIdRef = useRef<number | null>(null);
const isWebViewReadyRef = useRef(false);
@@ -232,8 +293,11 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFor
loadCacheOrFetch();
}, [FORMAT, auth.instance, auth.session, link.id]);
- const theme = rawTheme[colorScheme as ThemeName];
- const isDark = colorScheme === "dark";
+ const systemTheme: ThemeName = colorScheme === "dark" ? "dark" : "light";
+ const { theme, isDark } = resolveReaderTheme(
+ reader.readableBackgroundColor,
+ systemTheme as ThemeName
+ );
const title = decode(link.name || link.description || link.url || "");
const dateStr = new Date(
@@ -365,6 +429,44 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFor
`);
}, []);
+ const readerStyleConfig = useMemo(
+ () =>
+ getReaderStyleConfig({
+ fontFamily: getReadableFontFamily(reader.readableFontFamily),
+ fontSize: reader.readableFontSize,
+ lineHeight: reader.readableLineHeight,
+ theme,
+ isDark,
+ }),
+ [
+ isDark,
+ reader.readableFontFamily,
+ reader.readableFontSize,
+ reader.readableLineHeight,
+ theme,
+ ]
+ );
+
+ const syncReaderStylesToWebView = useCallback(
+ (styles: ReaderStyleConfig) => {
+ if (!isWebViewReadyRef.current) return;
+
+ webViewRef.current?.injectJavaScript(`
+ if (window.__READABLE_VIEW__?.applyReaderStyles) {
+ window.__READABLE_VIEW__.applyReaderStyles(
+ ${escapeForInjectedScript(styles)}
+ );
+ }
+ true;
+ `);
+ },
+ []
+ );
+
+ useEffect(() => {
+ latestReaderStyleConfigRef.current = readerStyleConfig;
+ }, [readerStyleConfig]);
+
const flushPendingHighlightScroll = useCallback(() => {
if (
!isWebViewReadyRef.current ||
@@ -393,37 +495,55 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFor
}, [linkHighlights, syncHighlightsToWebView]);
useEffect(() => {
- isWebViewReadyRef.current = false;
- }, [content, colorScheme]);
+ syncReaderStylesToWebView(readerStyleConfig);
+ }, [readerStyleConfig, syncReaderStylesToWebView]);
useEffect(() => {
- latestSelectionRef.current = null;
- pendingSelectionTextRef.current = null;
- pendingHighlightScrollIdRef.current = null;
- setDisableHighlightMenu(false);
- clearWebSelection();
- void SheetManager.hide("readable-highlight-sheet");
- }, [clearWebSelection, link.id]);
+ const currentReaderStyleConfig =
+ latestReaderStyleConfigRef.current ?? readerStyleConfig;
+ const initialStyles = escapeForInlineScript(
+ JSON.stringify(currentReaderStyleConfig)
+ );
- const htmlDocument = useMemo(
- () => `
+ setWebViewHtml(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<style>
- :root { ${readerViewThemeVars(theme, isDark)} }
+ :root {
+ --rv-body-bg: ${currentReaderStyleConfig.bodyBackground};
+ --rv-body-color: ${currentReaderStyleConfig.bodyColor};
+ --rv-code-bg: ${currentReaderStyleConfig.codeBackground};
+ --rv-font-family: ${currentReaderStyleConfig.fontFamily};
+ --rv-h1-font-size: ${currentReaderStyleConfig.h1FontSize};
+ --rv-h2-font-size: ${currentReaderStyleConfig.h2FontSize};
+ --rv-h3-font-size: ${currentReaderStyleConfig.h3FontSize};
+ --rv-h4-font-size: ${currentReaderStyleConfig.h4FontSize};
+ --rv-h5-font-size: ${currentReaderStyleConfig.h5FontSize};
+ --rv-link-color: ${currentReaderStyleConfig.linkColor};
+ --rv-mark-bg: ${currentReaderStyleConfig.markBackground};
+ --rv-mark-color: ${currentReaderStyleConfig.markColor};
+ --rv-neutral-border-color: ${currentReaderStyleConfig.neutralBorderColor};
+ --rv-neutral-color: ${currentReaderStyleConfig.neutralColor};
+ --rv-p-font-size: ${currentReaderStyleConfig.paragraphFontSize};
+ --rv-p-line-height: ${currentReaderStyleConfig.lineHeight};
+ }
* { box-sizing: border-box; }
body {
margin: 0;
padding: 16px;
- background-color: ${theme["base-100"]};
- color: ${theme["base-content"]};
- font-family: -apple-system, system-ui, sans-serif;
+ background-color: var(--rv-body-bg);
+ color: var(--rv-body-color);
+ font-family: var(--rv-font-family, -apple-system, system-ui, sans-serif);
-webkit-text-size-adjust: 100%;
}
- a { color: ${theme.primary}; }
+ a { color: var(--rv-link-color); }
img { max-width: 100%; height: auto; }
+ #readable-shell {
+ width: 100%;
+ margin: 0 auto;
+ }
.rv-header-title {
font-size: 24px;
font-weight: bold;
@@ -435,7 +555,7 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFor
}
.rv-header-meta {
font-size: 16px;
- color: ${theme.neutral};
+ color: var(--rv-neutral-color);
margin-bottom: 10px;
display: flex;
align-items: center;
@@ -443,7 +563,7 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFor
min-width: 0;
}
.rv-header-meta a {
- color: ${theme.neutral};
+ color: var(--rv-neutral-color);
text-decoration: none;
overflow: hidden;
text-overflow: ellipsis;
@@ -452,7 +572,7 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFor
}
.rv-header-separator {
border: none;
- border-top: 1px solid ${theme["neutral-content"]};
+ border-top: 1px solid var(--rv-neutral-border-color);
margin: 10px 0 20px 0;
}
.rv-highlight {
@@ -480,27 +600,27 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFor
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>
<body>
- <div class="rv-header-title">${title
- .replace(/</g, "&lt;")
- .replace(/>/g, "&gt;")}</div>
- <div class="rv-header-meta">
- <a href="${(link.url || "").replace(/"/g, "&quot;")}">${
- link.url || ""
- }</a>
+ <div id="readable-shell">
+ <div class="rv-header-title">${title
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;")}</div>
+ <div class="rv-header-meta">
+ <a href="${(link.url || "").replace(/"/g, "&quot;")}">${
+ link.url || ""
+ }</a>
+ </div>
+ <div class="rv-header-meta">${dateStr}</div>
+ <hr class="rv-header-separator" />
+ <div id="readable-view" class="reader-view read-only"></div>
</div>
- <div class="rv-header-meta">${dateStr}</div>
- <hr class="rv-header-separator" />
- <div id="readable-view" class="reader-view read-only"></div>
<script>
(function () {
const initialContent = ${escapeForInlineScript(content)};
+ const initialReaderStyles = JSON.parse(${initialStyles});
const state = {
currentSelection: null,
@@ -524,6 +644,37 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFor
return document.getElementById("readable-view");
}
+ function applyReaderStyles(styleConfig) {
+ const root = document.documentElement;
+ if (!root || !styleConfig) return;
+
+ root.style.setProperty("--rv-body-bg", styleConfig.bodyBackground);
+ root.style.setProperty("--rv-body-color", styleConfig.bodyColor);
+ root.style.setProperty("--rv-code-bg", styleConfig.codeBackground);
+ root.style.setProperty("--rv-font-family", styleConfig.fontFamily);
+ root.style.setProperty("--rv-h1-font-size", styleConfig.h1FontSize);
+ root.style.setProperty("--rv-h2-font-size", styleConfig.h2FontSize);
+ root.style.setProperty("--rv-h3-font-size", styleConfig.h3FontSize);
+ root.style.setProperty("--rv-h4-font-size", styleConfig.h4FontSize);
+ root.style.setProperty("--rv-h5-font-size", styleConfig.h5FontSize);
+ root.style.setProperty("--rv-link-color", styleConfig.linkColor);
+ root.style.setProperty("--rv-mark-bg", styleConfig.markBackground);
+ root.style.setProperty("--rv-mark-color", styleConfig.markColor);
+ root.style.setProperty(
+ "--rv-neutral-border-color",
+ styleConfig.neutralBorderColor
+ );
+ root.style.setProperty(
+ "--rv-neutral-color",
+ styleConfig.neutralColor
+ );
+ root.style.setProperty(
+ "--rv-p-font-size",
+ styleConfig.paragraphFontSize
+ );
+ root.style.setProperty("--rv-p-line-height", styleConfig.lineHeight);
+ }
+
function setContent() {
const container = getContainer();
if (!container) return;
@@ -764,22 +915,6 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFor
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) {
@@ -833,23 +968,40 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFor
});
window.__READABLE_VIEW__ = {
+ applyReaderStyles: applyReaderStyles,
clearSelection: clearSelection,
getSelectionInfo: getSelectionInfo,
renderHighlights: renderHighlights,
scrollToHighlight: scrollToHighlight,
};
+ applyReaderStyles(initialReaderStyles);
setContent();
postMessage("ready", null);
})();
</script>
</body>
</html>
- `,
- [content, dateStr, isDark, link.id, link.url, theme, title]
- );
+ `);
+ isWebViewReadyRef.current = false;
+ }, [
+ content,
+ dateStr,
+ link.id,
+ link.url,
+ title,
+ ]);
+
+ useEffect(() => {
+ latestSelectionRef.current = null;
+ pendingSelectionTextRef.current = null;
+ pendingHighlightScrollIdRef.current = null;
+ setDisableHighlightMenu(false);
+ clearWebSelection();
+ void SheetManager.hide("readable-highlight-sheet");
+ }, [clearWebSelection, link.id]);
- if (!content) {
+ if (!content || !webViewHtml) {
return <ReadableSkeleton theme={theme} />;
}
@@ -916,6 +1068,7 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFor
if (message?.type === "ready") {
isWebViewReadyRef.current = true;
+ syncReaderStylesToWebView(readerStyleConfig);
syncHighlightsToWebView(linkHighlights);
flushPendingHighlightScroll();
return;
@@ -960,7 +1113,7 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFor
return (
<WebView
ref={webViewRef}
- source={{ html: htmlDocument }}
+ source={{ html: webViewHtml }}
style={{
flex: 1,
backgroundColor: "transparent",
diff --git a/apps/mobile/store/reader.ts b/apps/mobile/store/reader.ts
new file mode 100644
index 00000000..fe007e02
--- /dev/null
+++ b/apps/mobile/store/reader.ts
@@ -0,0 +1,211 @@
+import AsyncStorage from "@react-native-async-storage/async-storage";
+import { Platform } from "react-native";
+import { create } from "zustand";
+import { READER_VIEW_DEFAULTS } from "@linkwarden/lib/readerViewStyles";
+import { rawTheme, ThemeName } from "@/lib/colors";
+
+export const READER_FONT_FAMILIES = [
+ "sans-serif",
+ "serif",
+ "monospace",
+ "cursive",
+ "caveat",
+ "bentham",
+] as const;
+
+export const READER_FONT_SIZES = [
+ "12px",
+ "14px",
+ "16px",
+ "18px",
+ "20px",
+ "22px",
+ "24px",
+ "26px",
+ "28px",
+ "30px",
+ "32px",
+ "34px",
+ "36px",
+ "38px",
+ "40px",
+ "42px",
+ "44px",
+ "46px",
+ "48px",
+ "50px",
+] as const;
+
+export const READER_LINE_HEIGHTS = [
+ "1",
+ "1.1",
+ "1.2",
+ "1.3",
+ "1.4",
+ "1.5",
+ "1.6",
+ "1.7",
+ "1.8",
+ "1.9",
+ "2",
+ "2.1",
+ "2.2",
+ "2.3",
+ "2.4",
+ "2.5",
+ "2.6",
+ "2.7",
+ "2.8",
+ "2.9",
+ "3",
+] as const;
+
+export const READER_BACKGROUND_COLORS = [
+ "system",
+ "light",
+ "dark",
+ "sepia",
+] as const;
+
+export type ReaderFontFamily = (typeof READER_FONT_FAMILIES)[number];
+export type ReaderFontSize = (typeof READER_FONT_SIZES)[number];
+export type ReaderLineHeight = (typeof READER_LINE_HEIGHTS)[number];
+export type ReaderBackgroundColor =
+ (typeof READER_BACKGROUND_COLORS)[number];
+
+export type ReaderSettings = {
+ readableFontFamily: ReaderFontFamily;
+ readableFontSize: ReaderFontSize;
+ readableLineHeight: ReaderLineHeight;
+ readableBackgroundColor: ReaderBackgroundColor;
+};
+
+export const READER_DEFAULTS: ReaderSettings = {
+ readableFontFamily: "sans-serif",
+ readableFontSize: `${READER_VIEW_DEFAULTS.fontSize}px`,
+ readableLineHeight: String(
+ READER_VIEW_DEFAULTS.lineHeight
+ ) as ReaderLineHeight,
+ readableBackgroundColor: "system",
+};
+
+const READER_SEPIA_THEME = {
+ primary: "#8C6239",
+ secondary: "#A47A52",
+ accent: "#8C6239",
+ neutral: "#8A7558",
+ "neutral-content": "#D5C8B1",
+ "base-100": "#F5ECD9",
+ "base-200": "#EBDDCA",
+ "base-content": "#433422",
+ info: "#C2D3E0",
+ success: "#5F8A5D",
+ warning: "#C9A227",
+ error: "#B45309",
+} as const;
+
+type ReaderStore = {
+ reader: ReaderSettings;
+ setReader: () => Promise<void>;
+ updateReader: (patch: Partial<ReaderSettings>) => Promise<void>;
+ resetReader: () => Promise<void>;
+};
+
+function parseStoredReaderSettings(value: string | null): Partial<ReaderSettings> {
+ if (!value) return {};
+
+ try {
+ const parsed = JSON.parse(value) as Partial<ReaderSettings>;
+
+ return {
+ readableBackgroundColor: parsed.readableBackgroundColor,
+ readableFontFamily: parsed.readableFontFamily,
+ readableFontSize: parsed.readableFontSize,
+ readableLineHeight: parsed.readableLineHeight,
+ };
+ } catch {
+ return {};
+ }
+}
+
+export function getReadableFontFamily(fontFamily: ReaderFontFamily) {
+ if (fontFamily === "caveat") {
+ if (Platform.OS === "android") {
+ return '"casual", "Comic Sans MS", cursive';
+ }
+
+ return '"Caveat", "Segoe Print", "Bradley Hand", "Comic Sans MS", cursive';
+ }
+
+ if (fontFamily === "bentham") {
+ return '"Bentham", "Palatino Linotype", "Book Antiqua", Georgia, serif';
+ }
+
+ if (fontFamily === "monospace") {
+ return '"Courier New", Courier, monospace';
+ }
+
+ return fontFamily;
+}
+
+export function resolveReaderTheme(
+ backgroundColor: ReaderBackgroundColor,
+ systemTheme: ThemeName
+) {
+ if (backgroundColor === "system") {
+ return {
+ theme: rawTheme[systemTheme],
+ isDark: systemTheme === "dark",
+ };
+ }
+
+ if (backgroundColor === "dark") {
+ return {
+ theme: rawTheme.dark,
+ isDark: true,
+ };
+ }
+
+ if (backgroundColor === "sepia") {
+ return {
+ theme: READER_SEPIA_THEME,
+ isDark: false,
+ };
+ }
+
+ return {
+ theme: rawTheme.light,
+ isDark: false,
+ };
+}
+
+const useReaderStore = create<ReaderStore>((set, get) => ({
+ reader: READER_DEFAULTS,
+ setReader: async () => {
+ const storedReader = parseStoredReaderSettings(
+ await AsyncStorage.getItem("reader")
+ );
+
+ set((state) => ({
+ reader: {
+ ...state.reader,
+ ...storedReader,
+ },
+ }));
+ },
+ updateReader: async (patch) => {
+ const merged = {
+ ...get().reader,
+ ...patch,
+ };
+
+ await AsyncStorage.setItem("reader", JSON.stringify(merged));
+ set({ reader: merged });
+ },
+ resetReader: async () => {
+ await AsyncStorage.setItem("reader", JSON.stringify(READER_DEFAULTS));
+ set({ reader: READER_DEFAULTS });
+ },
+}));
+
+export default useReaderStore;