Skip to content

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

refactor: remove unnecessary void operator from async function calls

daniel31x1343789c0e2b41
diff --git a/apps/mobile/app/index.tsx b/apps/mobile/app/index.tsx
index 3645095a..1d1a0625 100644
--- a/apps/mobile/app/index.tsx
+++ b/apps/mobile/app/index.tsx
@@ -1,15 +1,12 @@
import { Button } from "@/components/ui/Button";
import { rawTheme, ThemeName } from "@/lib/colors";
import useAuthStore from "@/store/auth";
-import {
- isAtLeastInstanceVersion,
- type Config,
-} from "@linkwarden/router/config";
+import { isAtLeastInstanceVersion } from "@linkwarden/router/config";
import { FontAwesome } from "@expo/vector-icons";
import { Redirect } from "expo-router";
import { ChevronDown, CircleHelp } from "lucide-react-native";
import { useColorScheme } from "nativewind";
-import { useEffect, useState } from "react";
+import { useEffect } from "react";
import {
Dimensions,
Image,
@@ -31,35 +28,53 @@ const displayInstance = (instance: string | null | undefined) =>
(instance || cloudInstance).replace(/^https?:\/\//, "").replace(/\/+$/, "");
export default function HomeScreen() {
- const { auth, setInstance, signInWithApple, signInWithGoogle } =
- useAuthStore();
+ const {
+ auth,
+ instanceInfo,
+ setInstance,
+ fetchInstanceInfo,
+ signInWithApple,
+ signInWithGoogle,
+ } = useAuthStore();
const { colorScheme } = useColorScheme();
const theme = rawTheme[colorScheme as ThemeName];
const serverName = displayInstance(auth.instance);
const instance = (auth.instance || cloudInstance).trim().replace(/\/+$/, "");
- const [appleEnabled, setAppleEnabled] = useState(
- Platform.OS === "ios" && instance === cloudInstance
- );
- const [googleEnabled, setGoogleEnabled] = useState(
- instance === cloudInstance
- );
- const [isCheckingOAuth, setIsCheckingOAuth] = useState(false);
+ const currentInstanceInfo =
+ instanceInfo.instance === instance ? instanceInfo : null;
+ const buttonAuths = currentInstanceInfo?.logins?.buttonAuths;
+ const versionOk = currentInstanceInfo?.config
+ ? isAtLeastInstanceVersion(
+ currentInstanceInfo.config.INSTANCE_VERSION,
+ "v2.15.0"
+ )
+ : instance === cloudInstance;
+ const hasApple = buttonAuths
+ ? buttonAuths.some((button) => button.method === "apple")
+ : instance === cloudInstance;
+ const hasGoogle = buttonAuths
+ ? buttonAuths.some((button) => button.method === "google")
+ : instance === cloudInstance;
+ const appleEnabled = Platform.OS === "ios" && hasApple && versionOk;
+ const googleEnabled = hasGoogle && versionOk;
+ const isCheckingOAuth =
+ currentInstanceInfo?.status === "loading" && !buttonAuths;
const openLoginSheet = () => {
- void SheetManager.show("login-sheet");
+ SheetManager.show("login-sheet");
};
const openSignUpSheet = () => {
- void SheetManager.show("sign-up-sheet");
+ SheetManager.show("sign-up-sheet");
};
const setCloudServer = () => {
- void setInstance(cloudInstance);
+ setInstance(cloudInstance);
};
const openSelfHostedSheet = () => {
requestAnimationFrame(() => {
- void SheetManager.show("self-hosted-server-sheet");
+ SheetManager.show("self-hosted-server-sheet");
});
};
@@ -86,57 +101,8 @@ export default function HomeScreen() {
: "Google";
useEffect(() => {
- if (!instance) {
- setAppleEnabled(false);
- setGoogleEnabled(false);
- setIsCheckingOAuth(false);
- return;
- }
-
- setAppleEnabled(Platform.OS === "ios" && instance === cloudInstance);
- setGoogleEnabled(instance === cloudInstance);
- setIsCheckingOAuth(true);
- let active = true;
- const timer = setTimeout(async () => {
- try {
- const [configRes, loginsRes] = await Promise.all([
- fetch(`${instance}/api/v1/config`),
- fetch(`${instance}/api/v1/logins`),
- ]);
-
- if (!active || !configRes.ok || !loginsRes.ok) return;
-
- const config = ((await configRes.json())?.response ??
- null) as Config | null;
- const logins = await loginsRes.json().catch(() => null);
- const versionOk = isAtLeastInstanceVersion(
- config?.INSTANCE_VERSION,
- "v2.15.0"
- );
- const hasApple =
- logins?.buttonAuths?.some(
- (b: { method?: string }) => b.method === "apple"
- ) === true;
- const hasGoogle =
- logins?.buttonAuths?.some(
- (b: { method?: string }) => b.method === "google"
- ) === true;
-
- if (active) {
- setAppleEnabled(Platform.OS === "ios" && hasApple && versionOk);
- setGoogleEnabled(hasGoogle && versionOk);
- }
- } catch {
- } finally {
- if (active) setIsCheckingOAuth(false);
- }
- }, 400);
-
- return () => {
- active = false;
- clearTimeout(timer);
- };
- }, [instance]);
+ fetchInstanceInfo(instance);
+ }, [fetchInstanceInfo, instance]);
if (auth.session) {
return <Redirect href="/dashboard" />;
@@ -229,7 +195,7 @@ export default function HomeScreen() {
disabled={isCheckingOAuth}
onPress={() => {
if (isCheckingOAuth) return;
- void signInWithApple(instance);
+ signInWithApple(instance);
}}
>
<FontAwesome
@@ -248,7 +214,7 @@ export default function HomeScreen() {
disabled={isCheckingOAuth}
onPress={() => {
if (isCheckingOAuth) return;
- void signInWithGoogle(instance);
+ signInWithGoogle(instance);
}}
>
<FontAwesome
diff --git a/apps/mobile/app/links/[id].tsx b/apps/mobile/app/links/[id].tsx
index aa366720..9110bb2f 100644
--- a/apps/mobile/app/links/[id].tsx
+++ b/apps/mobile/app/links/[id].tsx
@@ -19,7 +19,11 @@ import {
useRouter,
} from "expo-router";
import { useUser } from "@linkwarden/router/user";
-import { useDeleteLink, useGetLink, useUpdateLink } from "@linkwarden/router/links";
+import {
+ useDeleteLink,
+ useGetLink,
+ useUpdateLink,
+} from "@linkwarden/router/links";
import useTmpStore from "@/store/tmp";
import {
ArchivedFormat,
@@ -98,7 +102,7 @@ export default function LinkScreen() {
useCallback(() => {
if (!linkId) return;
- void Promise.all([
+ Promise.all([
refetchLink(),
queryClient.invalidateQueries({
queryKey: ["highlights", linkId],
@@ -154,7 +158,7 @@ export default function LinkScreen() {
{isReadableFormat ? (
<TouchableOpacity
onPress={() => {
- void handleOpenHighlights();
+ handleOpenHighlights();
}}
>
<Highlighter size={21} color={theme["base-content"]} />
@@ -209,10 +213,12 @@ export default function LinkScreen() {
<DropdownMenu.Item
key="display-settings"
onSelect={() => {
- void SheetManager.show("reader-settings-sheet");
+ SheetManager.show("reader-settings-sheet");
}}
>
- <DropdownMenu.ItemTitle>Display Settings</DropdownMenu.ItemTitle>
+ <DropdownMenu.ItemTitle>
+ Display Settings
+ </DropdownMenu.ItemTitle>
</DropdownMenu.Item>
)}
@@ -220,7 +226,7 @@ export default function LinkScreen() {
<DropdownMenu.Item
key="edit-link"
onSelect={() => {
- void SheetManager.show("edit-link-sheet", {
+ SheetManager.show("edit-link-sheet", {
payload: {
link: tmp.link as LinkIncludingShortenedCollectionAndTags,
},
diff --git a/apps/mobile/components/ActionSheets/EditLinkSheet.tsx b/apps/mobile/components/ActionSheets/EditLinkSheet.tsx
index 1168b32a..3f736258 100644
--- a/apps/mobile/components/ActionSheets/EditLinkSheet.tsx
+++ b/apps/mobile/components/ActionSheets/EditLinkSheet.tsx
@@ -61,7 +61,7 @@ const Main = (props: SheetProps<"edit-link-sheet">) => {
<SheetHeader
title="Edit Link"
onClose={() => {
- void SheetManager.hide("edit-link-sheet");
+ SheetManager.hide("edit-link-sheet");
}}
/>
@@ -226,7 +226,7 @@ const Collections = () => {
<SheetHeader
title="Collection"
onClose={() => {
- void SheetManager.hide("edit-link-sheet");
+ SheetManager.hide("edit-link-sheet");
}}
leftSlot={
<TouchableOpacity
@@ -379,7 +379,7 @@ const Tags = () => {
<SheetHeader
title="Tags"
onClose={() => {
- void SheetManager.hide("edit-link-sheet");
+ SheetManager.hide("edit-link-sheet");
}}
leftSlot={
<TouchableOpacity
diff --git a/apps/mobile/components/ActionSheets/LinkDetailsSheet.tsx b/apps/mobile/components/ActionSheets/LinkDetailsSheet.tsx
index 22fde5c8..7f7697ea 100644
--- a/apps/mobile/components/ActionSheets/LinkDetailsSheet.tsx
+++ b/apps/mobile/components/ActionSheets/LinkDetailsSheet.tsx
@@ -159,7 +159,7 @@ export default function LinkDetailsSheet(
}
};
- void fetchOwner();
+ fetchOwner();
return () => {
cancelled = true;
@@ -167,7 +167,7 @@ export default function LinkDetailsSheet(
}, [auth.instance, auth.session, link?.collection.ownerId, user]);
const closeSheet = () => {
- void SheetManager.hide("link-details-sheet");
+ SheetManager.hide("link-details-sheet");
};
const handleOpenOriginal = () => {
@@ -186,7 +186,7 @@ export default function LinkDetailsSheet(
return;
}
- void Linking.openURL(
+ Linking.openURL(
format !== null
? `${auth.instance}/preserved/${link.id}?format=${format}`
: (link.url as string)
@@ -218,7 +218,7 @@ export default function LinkDetailsSheet(
if (!link?.url) return;
closeSheet();
- void Linking.openURL(
+ Linking.openURL(
`https://web.archive.org/web/${link.url.replace(/(^\w+:|^)\/\//, "")}`
);
};
diff --git a/apps/mobile/components/ActionSheets/LoginSheet.tsx b/apps/mobile/components/ActionSheets/LoginSheet.tsx
index 5cf00fb2..beb5813b 100644
--- a/apps/mobile/components/ActionSheets/LoginSheet.tsx
+++ b/apps/mobile/components/ActionSheets/LoginSheet.tsx
@@ -54,7 +54,7 @@ export default function LoginSheet() {
}, [method]);
const closeSheet = () => {
- void SheetManager.hide("login-sheet");
+ SheetManager.hide("login-sheet");
};
const handleLogin = async () => {
diff --git a/apps/mobile/components/ActionSheets/ReadableHighlightSheet.tsx b/apps/mobile/components/ActionSheets/ReadableHighlightSheet.tsx
index ae2e2a51..9944a8c0 100644
--- a/apps/mobile/components/ActionSheets/ReadableHighlightSheet.tsx
+++ b/apps/mobile/components/ActionSheets/ReadableHighlightSheet.tsx
@@ -72,7 +72,7 @@ export default function ReadableHighlightSheet(
}, [props.payload?.draft]);
const closeSheet = () => {
- void SheetManager.hide("readable-highlight-sheet");
+ SheetManager.hide("readable-highlight-sheet");
};
const saveHighlight = usePostHighlight(draft?.linkId || 0, auth);
diff --git a/apps/mobile/components/ActionSheets/ReadableHighlightsSheet.tsx b/apps/mobile/components/ActionSheets/ReadableHighlightsSheet.tsx
index 79f03fa4..45756b4b 100644
--- a/apps/mobile/components/ActionSheets/ReadableHighlightsSheet.tsx
+++ b/apps/mobile/components/ActionSheets/ReadableHighlightsSheet.tsx
@@ -66,13 +66,13 @@ export default function ReadableHighlightsSheet(
);
const closeSheet = () => {
- void SheetManager.hide(props.sheetId, {
+ SheetManager.hide(props.sheetId, {
payload: null,
});
};
const handleSelectHighlight = (highlightId: number) => {
- void SheetManager.hide(props.sheetId, {
+ SheetManager.hide(props.sheetId, {
payload: highlightId,
});
};
diff --git a/apps/mobile/components/ActionSheets/ReaderSettingsSheet.tsx b/apps/mobile/components/ActionSheets/ReaderSettingsSheet.tsx
index 881acded..226f0270 100644
--- a/apps/mobile/components/ActionSheets/ReaderSettingsSheet.tsx
+++ b/apps/mobile/components/ActionSheets/ReaderSettingsSheet.tsx
@@ -130,7 +130,7 @@ export default function ReaderSettingsSheet(
const { reader, resetReader, updateReader } = useReaderStore();
const closeSheet = () => {
- void SheetManager.hide(props.sheetId);
+ SheetManager.hide(props.sheetId);
};
return (
@@ -170,7 +170,7 @@ export default function ReaderSettingsSheet(
onValueChange={() => {
if (reader.readableFontFamily === option) return;
- void updateReader({
+ updateReader({
readableFontFamily:
option as (typeof READER_FONT_FAMILIES)[number],
});
@@ -187,7 +187,7 @@ export default function ReaderSettingsSheet(
label="Font Size"
value={reader.readableFontSize}
onDecrease={() =>
- void updateReader({
+ updateReader({
readableFontSize: moveInList(
READER_FONT_SIZES,
reader.readableFontSize,
@@ -196,7 +196,7 @@ export default function ReaderSettingsSheet(
})
}
onIncrease={() =>
- void updateReader({
+ updateReader({
readableFontSize: moveInList(
READER_FONT_SIZES,
reader.readableFontSize,
@@ -210,7 +210,7 @@ export default function ReaderSettingsSheet(
label="Line Height"
value={reader.readableLineHeight}
onDecrease={() =>
- void updateReader({
+ updateReader({
readableLineHeight: moveInList(
READER_LINE_HEIGHTS,
reader.readableLineHeight,
@@ -219,7 +219,7 @@ export default function ReaderSettingsSheet(
})
}
onIncrease={() =>
- void updateReader({
+ updateReader({
readableLineHeight: moveInList(
READER_LINE_HEIGHTS,
reader.readableLineHeight,
@@ -244,7 +244,7 @@ export default function ReaderSettingsSheet(
onValueChange={() => {
if (reader.readableBackgroundColor === option) return;
- void updateReader({
+ updateReader({
readableBackgroundColor:
option as (typeof READER_BACKGROUND_COLORS)[number],
});
@@ -261,7 +261,7 @@ export default function ReaderSettingsSheet(
<View className="px-6 pb-4 pt-2">
<Button
onPress={() => {
- void resetReader();
+ resetReader();
}}
variant="outline"
disabled={JSON.stringify(reader) === JSON.stringify(READER_DEFAULTS)}
diff --git a/apps/mobile/components/ActionSheets/SelfHostedServerSheet.tsx b/apps/mobile/components/ActionSheets/SelfHostedServerSheet.tsx
index 365230a1..6155d8c2 100644
--- a/apps/mobile/components/ActionSheets/SelfHostedServerSheet.tsx
+++ b/apps/mobile/components/ActionSheets/SelfHostedServerSheet.tsx
@@ -7,6 +7,7 @@ import { Button } from "@/components/ui/Button";
import Input from "@/components/ui/Input";
import { rawTheme, ThemeName } from "@/lib/colors";
import useAuthStore from "@/store/auth";
+import type { Config } from "@linkwarden/router/config";
import SheetHeader from "./SheetHeader";
const cloudInstance = "https://cloud.linkwarden.app";
@@ -44,7 +45,7 @@ export default function SelfHostedServerSheet() {
}, [auth.instance]);
const closeSheet = () => {
- void SheetManager.hide("self-hosted-server-sheet");
+ SheetManager.hide("self-hosted-server-sheet");
};
const setSelfHostedServer = async () => {
@@ -60,12 +61,13 @@ export default function SelfHostedServerSheet() {
fetch(`${instance}/api/v1/config`),
timeout(),
]);
+ const data = await res.json().catch(() => null);
- if (!res.ok) {
+ if (!res.ok || !data?.response) {
return Alert.alert("Error", "Could not verify this server.");
}
- await setInstance(instance);
+ await setInstance(instance, data.response as Config);
closeSheet();
} catch (err: any) {
Alert.alert(
diff --git a/apps/mobile/components/ActionSheets/SignUpSheet.tsx b/apps/mobile/components/ActionSheets/SignUpSheet.tsx
index e1eaec09..f0656200 100644
--- a/apps/mobile/components/ActionSheets/SignUpSheet.tsx
+++ b/apps/mobile/components/ActionSheets/SignUpSheet.tsx
@@ -1,15 +1,17 @@
import { useEffect, useState } from "react";
import {
- ActivityIndicator,
Alert,
Dimensions,
+ Linking,
ScrollView,
Text,
+ TouchableOpacity,
View,
} from "react-native";
import ActionSheet, { SheetManager } from "react-native-actions-sheet";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useColorScheme } from "nativewind";
+import { Check } from "lucide-react-native";
import {
isAtLeastInstanceVersion,
type Config,
@@ -38,22 +40,14 @@ const cloudConfig: Config = {
const cleanInstance = (instance: string) => instance.trim().replace(/\/+$/, "");
-const timeout = () =>
- new Promise<Response>((_, reject) =>
- setTimeout(() => reject(new Error("TIMEOUT")), 30000)
- );
-
export default function SignUpSheet() {
- const { auth, signUp, requestVerificationEmail, setInstance } =
+ const { auth, instanceInfo, signUp, requestVerificationEmail } =
useAuthStore();
const { colorScheme } = useColorScheme();
const insets = useSafeAreaInsets();
const theme = rawTheme[colorScheme as ThemeName];
const [isLoading, setIsLoading] = useState(false);
- const [isConfigLoading, setIsConfigLoading] = useState(false);
- const [config, setConfig] = useState<Config | null>(null);
- const [configInstance, setConfigInstance] = useState("");
- const [configError, setConfigError] = useState("");
+ const [acceptPromotionalEmails, setAcceptPromotionalEmails] = useState(false);
const [sentTo, setSentTo] = useState<{
email: string;
instance: string;
@@ -68,18 +62,19 @@ export default function SignUpSheet() {
});
const instance = cleanInstance(form.instance);
+ const currentInstanceInfo =
+ instanceInfo.instance === instance ? instanceInfo : null;
const currentConfig =
instance === cloudInstance
- ? cloudConfig
- : configInstance === instance
- ? config
- : null;
+ ? currentInstanceInfo?.config || cloudConfig
+ : currentInstanceInfo?.config || null;
+ const isConfigLoading =
+ currentInstanceInfo?.status === "loading" && !currentConfig;
+ const configError = currentInstanceInfo?.error || "";
const emailSignUp = currentConfig?.EMAIL_PROVIDER === true;
const supportsMobileSignup =
instance === cloudInstance ||
isAtLeastInstanceVersion(currentConfig?.INSTANCE_VERSION, "v2.15.0");
- const instanceName =
- instance === cloudInstance ? "cloud.linkwarden.app" : instance;
useEffect(() => {
setForm((prev) => ({
@@ -88,78 +83,8 @@ export default function SignUpSheet() {
}));
}, [auth.instance]);
- useEffect(() => {
- let active = true;
-
- if (!instance) {
- setConfig(null);
- setConfigInstance("");
- setConfigError("");
- setIsConfigLoading(false);
- return;
- }
-
- if (instance === cloudInstance) {
- setConfig(null);
- setConfigInstance("");
- setConfigError("");
- setIsConfigLoading(false);
- return;
- }
-
- setConfig(null);
- setConfigError("");
- setIsConfigLoading(true);
-
- const timer = setTimeout(async () => {
- try {
- const res = await Promise.race([
- fetch(`${instance}/api/v1/config`),
- timeout(),
- ]);
- const data = await res.json().catch(() => null);
-
- if (!active) return;
-
- if (res.ok) {
- const nextConfig = data.response as Config;
-
- if (
- nextConfig.EMAIL_PROVIDER === true &&
- !isAtLeastInstanceVersion(nextConfig.INSTANCE_VERSION, "v2.15.0")
- ) {
- const reset = () => {
- void setInstance(cloudInstance);
- };
-
- Alert.alert(
- "Sign up through the web",
- "This instance needs to be updated to support mobile sign-up. You can sign up through the web, then come back here to log in.",
- [{ text: "OK", onPress: reset }],
- { onDismiss: reset }
- );
- }
-
- setConfig(nextConfig);
- setConfigInstance(instance);
- } else {
- setConfigError("Could not load this instance.");
- }
- } catch {
- if (active) setConfigError("Could not reach this instance.");
- } finally {
- if (active) setIsConfigLoading(false);
- }
- }, 400);
-
- return () => {
- active = false;
- clearTimeout(timer);
- };
- }, [instance]);
-
const closeSheet = () => {
- void SheetManager.hide("sign-up-sheet");
+ SheetManager.hide("sign-up-sheet");
};
const register = async () => {
@@ -195,6 +120,7 @@ export default function SignUpSheet() {
username: emailSignUp ? undefined : username,
password: form.password,
instance,
+ acceptPromotionalEmails,
});
setIsLoading(false);
@@ -317,6 +243,32 @@ export default function SignUpSheet() {
setForm({ ...form, passwordConfirmation: text })
}
/>
+ <TouchableOpacity
+ activeOpacity={0.75}
+ accessibilityRole="checkbox"
+ accessibilityState={{ checked: acceptPromotionalEmails }}
+ className="flex-row items-center gap-3 py-1"
+ onPress={() => setAcceptPromotionalEmails((checked) => !checked)}
+ >
+ <View
+ className="h-5 w-5 items-center justify-center rounded border"
+ style={{
+ backgroundColor: acceptPromotionalEmails
+ ? theme.accent
+ : "transparent",
+ borderColor: acceptPromotionalEmails
+ ? theme.accent
+ : theme.neutral,
+ }}
+ >
+ {acceptPromotionalEmails && (
+ <Check size={14} color="#FFFFFF" strokeWidth={3} />
+ )}
+ </View>
+ <Text className="text-neutral flex-1 text-sm">
+ Get notified about new features and offers via email.
+ </Text>
+ </TouchableOpacity>
<Button
variant="accent"
size="lg"
@@ -326,6 +278,25 @@ export default function SignUpSheet() {
>
<Text className="text-white text-xl">Sign Up</Text>
</Button>
+ <Text className="text-neutral text-center text-xs px-2">
+ By signing up, you agree to our{" "}
+ <Text
+ className="font-semibold"
+ onPress={() => Linking.openURL("https://linkwarden.app/tos")}
+ >
+ Terms of Service
+ </Text>{" "}
+ and{" "}
+ <Text
+ className="font-semibold"
+ onPress={() =>
+ Linking.openURL("https://linkwarden.app/privacy-policy")
+ }
+ >
+ Privacy Policy
+ </Text>
+ .
+ </Text>
</>
)}
</ScrollView>
diff --git a/apps/mobile/components/ActionSheets/SupportSheet.tsx b/apps/mobile/components/ActionSheets/SupportSheet.tsx
index cae8d0d3..3ffb93f1 100644
--- a/apps/mobile/components/ActionSheets/SupportSheet.tsx
+++ b/apps/mobile/components/ActionSheets/SupportSheet.tsx
@@ -21,7 +21,7 @@ export default function SupportSheet() {
const insets = useSafeAreaInsets();
const closeSheet = () => {
- void SheetManager.hide("support-sheet");
+ SheetManager.hide("support-sheet");
};
return (
diff --git a/apps/mobile/components/Formats/ReadableFormat.tsx b/apps/mobile/components/Formats/ReadableFormat.tsx
index 09a002ec..5a1755ff 100644
--- a/apps/mobile/components/Formats/ReadableFormat.tsx
+++ b/apps/mobile/components/Formats/ReadableFormat.tsx
@@ -227,149 +227,145 @@ function getReaderStyleConfig({
};
}
-const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFormat(
- {
- link,
- setIsLoading,
- }: Props,
- ref
-) {
- 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);
-
- useEffect(() => {
- loadCacheOrFetch({
- filePath:
- FileSystem.documentDirectory + `archivedData/readable/link_${link.id}.html`,
- setContent,
- getCachedContent: (filePath) => FileSystem.readAsStringAsync(filePath),
- fetchContent: async (filePath) => {
- const apiUrl = `${auth.instance}/api/v1/archives/${link.id}?format=${FORMAT}`;
-
- const response = await fetch(apiUrl, {
- headers: { Authorization: `Bearer ${auth.session}` },
- });
+const ReadableFormat = forwardRef<ReadableFormatRef, Props>(
+ function ReadableFormat({ link, setIsLoading }: Props, ref) {
+ 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);
+
+ useEffect(() => {
+ loadCacheOrFetch({
+ filePath:
+ FileSystem.documentDirectory +
+ `archivedData/readable/link_${link.id}.html`,
+ setContent,
+ getCachedContent: (filePath) => FileSystem.readAsStringAsync(filePath),
+ fetchContent: async (filePath) => {
+ const apiUrl = `${auth.instance}/api/v1/archives/${link.id}?format=${FORMAT}`;
+
+ const response = await fetch(apiUrl, {
+ headers: { Authorization: `Bearer ${auth.session}` },
+ });
- const data = (await response.json()).content;
+ const data = (await response.json()).content;
- await FileSystem.writeAsStringAsync(filePath, data, {
- encoding: FileSystem.EncodingType.UTF8,
- });
+ await FileSystem.writeAsStringAsync(filePath, data, {
+ encoding: FileSystem.EncodingType.UTF8,
+ });
- return data;
- },
- });
- }, [FORMAT, auth.instance, auth.session, link.id]);
+ return data;
+ },
+ });
+ }, [FORMAT, auth.instance, auth.session, link.id]);
- const systemTheme: ThemeName = colorScheme === "dark" ? "dark" : "light";
- const { theme, isDark } = resolveReaderTheme(
- reader.readableBackgroundColor,
- systemTheme as ThemeName
- );
+ 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(
- link?.importDate || link.createdAt
- ).toLocaleDateString("en-US", {
- year: "numeric",
- month: "short",
- day: "numeric",
- });
+ 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 { data: linkHighlights = [] } = useGetLinkHighlights(link.id, auth);
+ const { data: linkHighlights = [] } = useGetLinkHighlights(link.id, auth);
- const clearWebSelection = useCallback(() => {
- pendingSelectionTextRef.current = null;
+ const clearWebSelection = useCallback(() => {
+ pendingSelectionTextRef.current = null;
- webViewRef.current?.injectJavaScript(`
+ 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 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;
+ }
- 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;
+ }
- if (selection.text.length > MAX_HIGHLIGHT_TEXT_LENGTH) {
- Alert.alert(
- "Selection too long",
- "Please select a shorter passage before creating a highlight."
+ const existingHighlight = findMatchingHighlight(
+ linkHighlights,
+ selection
);
- clearWebSelection();
- return;
- }
-
- const existingHighlight = findMatchingHighlight(
- linkHighlights,
- selection
- );
- pendingSelectionTextRef.current = null;
+ 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]
- );
+ 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;
+ 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]
- );
+ 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(`
+ const requestLatestSelection = useCallback(() => {
+ webViewRef.current?.injectJavaScript(`
(function () {
const selection =
window.__READABLE_VIEW__?.getSelectionInfo?.() ?? null;
@@ -383,12 +379,12 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFor
})();
true;
`);
- }, []);
+ }, []);
- const syncHighlightsToWebView = useCallback((highlights: Highlight[]) => {
- if (!isWebViewReadyRef.current) return;
+ const syncHighlightsToWebView = useCallback((highlights: Highlight[]) => {
+ if (!isWebViewReadyRef.current) return;
- webViewRef.current?.injectJavaScript(`
+ webViewRef.current?.injectJavaScript(`
if (window.__READABLE_VIEW__?.renderHighlights) {
window.__READABLE_VIEW__.renderHighlights(${escapeForInjectedScript(
highlights
@@ -396,42 +392,42 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFor
}
true;
`);
- }, []);
+ }, []);
- const scrollToHighlightInWebView = useCallback((highlightId: number) => {
- if (!isWebViewReadyRef.current) return;
+ const scrollToHighlightInWebView = useCallback((highlightId: number) => {
+ if (!isWebViewReadyRef.current) return;
- webViewRef.current?.injectJavaScript(`
+ webViewRef.current?.injectJavaScript(`
if (window.__READABLE_VIEW__?.scrollToHighlight) {
window.__READABLE_VIEW__.scrollToHighlight(${highlightId});
}
true;
`);
- }, []);
-
- const readerStyleConfig = useMemo(
- () =>
- getReaderStyleConfig({
- fontFamily: getReadableFontFamily(reader.readableFontFamily),
- fontSize: reader.readableFontSize,
- lineHeight: reader.readableLineHeight,
- theme,
+ }, []);
+
+ const readerStyleConfig = useMemo(
+ () =>
+ getReaderStyleConfig({
+ fontFamily: getReadableFontFamily(reader.readableFontFamily),
+ fontSize: reader.readableFontSize,
+ lineHeight: reader.readableLineHeight,
+ theme,
+ isDark,
+ }),
+ [
isDark,
- }),
- [
- isDark,
- reader.readableFontFamily,
- reader.readableFontSize,
- reader.readableLineHeight,
- theme,
- ]
- );
+ reader.readableFontFamily,
+ reader.readableFontSize,
+ reader.readableLineHeight,
+ theme,
+ ]
+ );
- const syncReaderStylesToWebView = useCallback(
- (styles: ReaderStyleConfig) => {
- if (!isWebViewReadyRef.current) return;
+ const syncReaderStylesToWebView = useCallback(
+ (styles: ReaderStyleConfig) => {
+ if (!isWebViewReadyRef.current) return;
- webViewRef.current?.injectJavaScript(`
+ webViewRef.current?.injectJavaScript(`
if (window.__READABLE_VIEW__?.applyReaderStyles) {
window.__READABLE_VIEW__.applyReaderStyles(
${escapeForInjectedScript(styles)}
@@ -439,53 +435,53 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFor
}
true;
`);
- },
- []
- );
-
- useEffect(() => {
- latestReaderStyleConfigRef.current = readerStyleConfig;
- }, [readerStyleConfig]);
+ },
+ []
+ );
- const flushPendingHighlightScroll = useCallback(() => {
- if (
- !isWebViewReadyRef.current ||
- pendingHighlightScrollIdRef.current === null
- ) {
- return;
- }
+ useEffect(() => {
+ latestReaderStyleConfigRef.current = readerStyleConfig;
+ }, [readerStyleConfig]);
- scrollToHighlightInWebView(pendingHighlightScrollIdRef.current);
- pendingHighlightScrollIdRef.current = null;
- }, [scrollToHighlightInWebView]);
+ const flushPendingHighlightScroll = useCallback(() => {
+ if (
+ !isWebViewReadyRef.current ||
+ pendingHighlightScrollIdRef.current === null
+ ) {
+ return;
+ }
- useImperativeHandle(
- ref,
- () => ({
- scrollToHighlight: (highlightId: number) => {
- pendingHighlightScrollIdRef.current = highlightId;
- flushPendingHighlightScroll();
- },
- }),
- [flushPendingHighlightScroll]
- );
+ scrollToHighlightInWebView(pendingHighlightScrollIdRef.current);
+ pendingHighlightScrollIdRef.current = null;
+ }, [scrollToHighlightInWebView]);
+
+ useImperativeHandle(
+ ref,
+ () => ({
+ scrollToHighlight: (highlightId: number) => {
+ pendingHighlightScrollIdRef.current = highlightId;
+ flushPendingHighlightScroll();
+ },
+ }),
+ [flushPendingHighlightScroll]
+ );
- useEffect(() => {
- syncHighlightsToWebView(linkHighlights);
- }, [linkHighlights, syncHighlightsToWebView]);
+ useEffect(() => {
+ syncHighlightsToWebView(linkHighlights);
+ }, [linkHighlights, syncHighlightsToWebView]);
- useEffect(() => {
- syncReaderStylesToWebView(readerStyleConfig);
- }, [readerStyleConfig, syncReaderStylesToWebView]);
+ useEffect(() => {
+ syncReaderStylesToWebView(readerStyleConfig);
+ }, [readerStyleConfig, syncReaderStylesToWebView]);
- useEffect(() => {
- const currentReaderStyleConfig =
- latestReaderStyleConfigRef.current ?? readerStyleConfig;
- const initialStyles = escapeForInlineScript(
- JSON.stringify(currentReaderStyleConfig)
- );
+ useEffect(() => {
+ const currentReaderStyleConfig =
+ latestReaderStyleConfigRef.current ?? readerStyleConfig;
+ const initialStyles = escapeForInlineScript(
+ JSON.stringify(currentReaderStyleConfig)
+ );
- setWebViewHtml(`
+ setWebViewHtml(`
<!DOCTYPE html>
<html lang="en">
<head>
@@ -504,7 +500,9 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFor
--rv-link-color: ${currentReaderStyleConfig.linkColor};
--rv-mark-bg: ${currentReaderStyleConfig.markBackground};
--rv-mark-color: ${currentReaderStyleConfig.markColor};
- --rv-neutral-border-color: ${currentReaderStyleConfig.neutralBorderColor};
+ --rv-neutral-border-color: ${
+ currentReaderStyleConfig.neutralBorderColor
+ };
--rv-neutral-color: ${currentReaderStyleConfig.neutralColor};
--rv-p-font-size: ${currentReaderStyleConfig.paragraphFontSize};
--rv-p-line-height: ${currentReaderStyleConfig.lineHeight};
@@ -963,158 +961,159 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(function ReadableFor
</body>
</html>
`);
- 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 || !webViewHtml) {
- return <ReadableSkeleton theme={theme} />;
- }
-
- const handleCustomMenuSelection = (event: {
- nativeEvent: {
- key: string;
- selectedText: string;
- };
- }) => {
- const selectedText = event.nativeEvent.selectedText || "";
+ isWebViewReadyRef.current = false;
+ }, [content, dateStr, link.id, link.url, title]);
- if (event.nativeEvent.key === COPY_MENU_KEY) {
- if (selectedText) {
- void Clipboard.setStringAsync(selectedText);
- }
+ useEffect(() => {
+ latestSelectionRef.current = null;
+ pendingSelectionTextRef.current = null;
+ pendingHighlightScrollIdRef.current = null;
+ setDisableHighlightMenu(false);
clearWebSelection();
- return;
- }
+ SheetManager.hide("readable-highlight-sheet");
+ }, [clearWebSelection, link.id]);
- if (event.nativeEvent.key === SEARCH_WEB_MENU_KEY) {
- const normalizedText = normalizeSelectedText(selectedText);
+ if (!content || !webViewHtml) {
+ return <ReadableSkeleton theme={theme} />;
+ }
- if (normalizedText) {
- void Linking.openURL(
- `https://www.google.com/search?q=${encodeURIComponent(
- normalizedText
- )}`
- );
+ const handleCustomMenuSelection = (event: {
+ nativeEvent: {
+ key: string;
+ selectedText: string;
+ };
+ }) => {
+ const selectedText = event.nativeEvent.selectedText || "";
+
+ if (event.nativeEvent.key === COPY_MENU_KEY) {
+ if (selectedText) {
+ Clipboard.setStringAsync(selectedText);
+ }
+ clearWebSelection();
+ return;
}
- clearWebSelection();
- return;
- }
+ if (event.nativeEvent.key === SEARCH_WEB_MENU_KEY) {
+ const normalizedText = normalizeSelectedText(selectedText);
- if (event.nativeEvent.key !== HIGHLIGHT_MENU_KEY) return;
-
- const normalizedText = normalizeSelectedText(selectedText);
- if (!normalizedText) return;
+ if (normalizedText) {
+ Linking.openURL(
+ `https://www.google.com/search?q=${encodeURIComponent(
+ normalizedText
+ )}`
+ );
+ }
- const selection = latestSelectionRef.current;
+ clearWebSelection();
+ return;
+ }
- if (selection && normalizeSelectedText(selection.text) === normalizedText) {
- openDraftFromSelection(selection);
- return;
- }
+ if (event.nativeEvent.key !== HIGHLIGHT_MENU_KEY) return;
- pendingSelectionTextRef.current = normalizedText;
- requestLatestSelection();
- };
+ const normalizedText = normalizeSelectedText(selectedText);
+ if (!normalizedText) return;
- const handleWebViewMessage = (event: { nativeEvent: { data: string } }) => {
- let message:
- | {
- type?: string;
- payload?: unknown;
- }
- | undefined;
+ const selection = latestSelectionRef.current;
- try {
- message = JSON.parse(event.nativeEvent.data);
- } catch {
- return;
- }
+ if (
+ selection &&
+ normalizeSelectedText(selection.text) === normalizedText
+ ) {
+ openDraftFromSelection(selection);
+ return;
+ }
- if (message?.type === "ready") {
- isWebViewReadyRef.current = true;
- syncReaderStylesToWebView(readerStyleConfig);
- syncHighlightsToWebView(linkHighlights);
- flushPendingHighlightScroll();
- return;
- }
+ pendingSelectionTextRef.current = normalizedText;
+ requestLatestSelection();
+ };
- if (
- message?.type === "selection-context" &&
- isSelectionContext(message.payload)
- ) {
- setDisableHighlightMenu(message.payload.disableHighlightMenu);
- return;
- }
+ const handleWebViewMessage = (event: { nativeEvent: { data: string } }) => {
+ let message:
+ | {
+ type?: string;
+ payload?: unknown;
+ }
+ | undefined;
- if (message?.type === "selection") {
- if (!isSelectionInfo(message.payload)) {
- latestSelectionRef.current = null;
- pendingSelectionTextRef.current = null;
+ try {
+ message = JSON.parse(event.nativeEvent.data);
+ } catch {
return;
}
- latestSelectionRef.current = message.payload;
+ if (message?.type === "ready") {
+ isWebViewReadyRef.current = true;
+ syncReaderStylesToWebView(readerStyleConfig);
+ syncHighlightsToWebView(linkHighlights);
+ flushPendingHighlightScroll();
+ return;
+ }
if (
- pendingSelectionTextRef.current &&
- normalizeSelectedText(message.payload.text) ===
- pendingSelectionTextRef.current
+ message?.type === "selection-context" &&
+ isSelectionContext(message.payload)
) {
- pendingSelectionTextRef.current = null;
- openDraftFromSelection(message.payload);
+ setDisableHighlightMenu(message.payload.disableHighlightMenu);
return;
}
- pendingSelectionTextRef.current = null;
- return;
- }
+ if (message?.type === "selection") {
+ if (!isSelectionInfo(message.payload)) {
+ latestSelectionRef.current = null;
+ pendingSelectionTextRef.current = null;
+ return;
+ }
- if (message?.type === "highlight-press" && isHighlight(message.payload)) {
- openDraftFromHighlight(message.payload);
- }
- };
+ latestSelectionRef.current = message.payload;
- return (
- <WebView
- ref={webViewRef}
- source={{ html: webViewHtml }}
- style={{
- flex: 1,
- backgroundColor: "transparent",
- }}
- onLoadEnd={() => setIsLoading(false)}
- onMessage={handleWebViewMessage}
- onCustomMenuSelection={handleCustomMenuSelection}
- onShouldStartLoadWithRequest={(request) => {
- if (request.url === "about:blank" || request.url.startsWith("data:")) {
- return true;
+ if (
+ pendingSelectionTextRef.current &&
+ normalizeSelectedText(message.payload.text) ===
+ pendingSelectionTextRef.current
+ ) {
+ pendingSelectionTextRef.current = null;
+ openDraftFromSelection(message.payload);
+ return;
}
- Linking.openURL(request.url);
- return false;
- }}
- javaScriptEnabled
- menuItems={
- disableHighlightMenu ? NON_HIGHLIGHT_MENU_ITEMS : DEFAULT_MENU_ITEMS
+
+ pendingSelectionTextRef.current = null;
+ return;
}
- originWhitelist={["*"]}
- />
- );
-});
+
+ if (message?.type === "highlight-press" && isHighlight(message.payload)) {
+ openDraftFromHighlight(message.payload);
+ }
+ };
+
+ return (
+ <WebView
+ ref={webViewRef}
+ source={{ html: webViewHtml }}
+ style={{
+ flex: 1,
+ backgroundColor: "transparent",
+ }}
+ onLoadEnd={() => setIsLoading(false)}
+ onMessage={handleWebViewMessage}
+ onCustomMenuSelection={handleCustomMenuSelection}
+ onShouldStartLoadWithRequest={(request) => {
+ if (
+ request.url === "about:blank" ||
+ request.url.startsWith("data:")
+ ) {
+ return true;
+ }
+ Linking.openURL(request.url);
+ return false;
+ }}
+ javaScriptEnabled
+ menuItems={
+ disableHighlightMenu ? NON_HIGHLIGHT_MENU_ITEMS : DEFAULT_MENU_ITEMS
+ }
+ originWhitelist={["*"]}
+ />
+ );
+ }
+);
export default ReadableFormat;
diff --git a/apps/mobile/components/LinkListing.tsx b/apps/mobile/components/LinkListing.tsx
index b1327b12..8f717d72 100644
--- a/apps/mobile/components/LinkListing.tsx
+++ b/apps/mobile/components/LinkListing.tsx
@@ -64,7 +64,8 @@ const LinkListing = ({ link, dashboard }: Props) => {
useEffect(() => {
loadCacheOrFetch({
filePath:
- FileSystem.documentDirectory + `archivedData/previews/link_${link.id}.jpg`,
+ FileSystem.documentDirectory +
+ `archivedData/previews/link_${link.id}.jpg`,
setContent: setPreview,
shouldFetch: formatAvailable(link, "preview"),
onStart: () => setPreview(""),
@@ -95,7 +96,7 @@ const LinkListing = ({ link, dashboard }: Props) => {
onPress={() => {
if (user) {
if (user.linksRouteTo === "DETAILS") {
- void SheetManager.show("link-details-sheet", {
+ SheetManager.show("link-details-sheet", {
payload: { link },
});
diff --git a/apps/mobile/store/auth.ts b/apps/mobile/store/auth.ts
index 55a9bc5f..d5c514c2 100644
--- a/apps/mobile/store/auth.ts
+++ b/apps/mobile/store/auth.ts
@@ -17,6 +17,19 @@ import { useOfflineSyncStore } from "@/lib/offlineSync";
import { hasInactiveSubscription } from "@/lib/subscription";
const cloudInstance = "https://cloud.linkwarden.app";
+const cloudConfig: Config = {
+ DISABLE_REGISTRATION: null,
+ ADMIN: null,
+ RSS_POLLING_INTERVAL_MINUTES: null,
+ EMAIL_PROVIDER: true,
+ MAX_FILE_BUFFER: null,
+ USER_CONTENT_DOMAIN: null,
+ AI_ENABLED: null,
+ INSTANCE_VERSION: null,
+ STRIPE_ENABLED: null,
+ TRIAL_PERIOD_DAYS: null,
+ REQUIRE_CC: null,
+};
const googleWebClientId =
process.env.EXPO_PUBLIC_GOOGLE_WEB_CLIENT_ID ??
"1097450926817-fb426eh4dkq46gmhiuoa00k6rv196g1s.apps.googleusercontent.com";
@@ -35,10 +48,26 @@ type SignUpForm = {
email?: string;
password: string;
instance: string;
+ acceptPromotionalEmails?: boolean;
+};
+
+type InstanceLogins = {
+ buttonAuths?: {
+ method?: string;
+ }[];
+};
+
+type InstanceInfo = {
+ instance: string;
+ config: Config | null;
+ logins: InstanceLogins | null;
+ status: "idle" | "loading" | "success" | "error";
+ error: string;
};
type AuthStore = {
auth: MobileAuth;
+ instanceInfo: InstanceInfo;
signIn: (
username: string,
password: string,
@@ -52,16 +81,47 @@ type AuthStore = {
email: string,
instance: string
) => Promise<boolean>;
- setInstance: (instance: string) => Promise<void>;
+ setInstance: (instance: string, config?: Config) => Promise<void>;
+ fetchInstanceInfo: (instance?: string, config?: Config) => Promise<void>;
signOut: () => Promise<void>;
setAuth: () => Promise<void>;
};
+const cleanInstance = (instance?: string | null) =>
+ (instance || cloudInstance).trim().replace(/\/+$/, "");
+
+const getFallbackConfig = (instance: string) =>
+ instance === cloudInstance ? cloudConfig : null;
+
const timeout = () =>
new Promise<Response>((_, reject) =>
setTimeout(() => reject(new Error("TIMEOUT")), 30000)
);
+const fetchInstanceConfig = async (instance: string) => {
+ const res = await Promise.race([
+ fetch(`${instance}/api/v1/config`),
+ timeout(),
+ ]);
+ const data = await res.json().catch(() => null);
+
+ if (!res.ok || !data?.response) throw new Error("CONFIG");
+
+ return data.response as Config;
+};
+
+const fetchInstanceLogins = async (instance: string) => {
+ const res = await Promise.race([
+ fetch(`${instance}/api/v1/logins`),
+ timeout(),
+ ]);
+ const data = await res.json().catch(() => null);
+
+ if (!res.ok) throw new Error("LOGINS");
+
+ return data as InstanceLogins;
+};
+
const getPostAuthRoute = async (instance: string, session: string) => {
try {
const headers = { Authorization: `Bearer ${session}` };
@@ -118,20 +178,28 @@ const requestVerificationEmail = async (email: string, instance: string) => {
}
};
-const useAuthStore = create<AuthStore>((set) => ({
+const useAuthStore = create<AuthStore>((set, get) => ({
auth: {
instance: "",
session: null,
status: "loading" as const,
},
+ instanceInfo: {
+ instance: "",
+ config: null,
+ logins: null,
+ status: "idle",
+ error: "",
+ },
setAuth: async () => {
const session = await SecureStore.getItemAsync("TOKEN");
const instance = await SecureStore.getItemAsync("INSTANCE");
+ const nextInstance = cleanInstance(instance);
if (session) {
set({
auth: {
- instance,
+ instance: nextInstance,
session,
status: "authenticated",
},
@@ -139,24 +207,87 @@ const useAuthStore = create<AuthStore>((set) => ({
} else {
set({
auth: {
- instance: instance || cloudInstance,
+ instance: nextInstance,
session: null,
status: "unauthenticated",
},
});
}
+
+ get().fetchInstanceInfo(nextInstance);
},
requestVerificationEmail,
- setInstance: async (instance) => {
- await SecureStore.setItemAsync("INSTANCE", instance);
+ setInstance: async (instance, config) => {
+ const nextInstance = cleanInstance(instance);
+
+ await SecureStore.setItemAsync("INSTANCE", nextInstance);
set((state) => ({
auth: {
...state.auth,
- instance,
+ instance: nextInstance,
},
}));
+
+ get().fetchInstanceInfo(nextInstance, config);
+ },
+ fetchInstanceInfo: async (nextInstance, config) => {
+ const instance = cleanInstance(nextInstance || get().auth.instance);
+ const current = get().instanceInfo;
+ const currentConfig =
+ config ??
+ (current.instance === instance
+ ? current.config
+ : getFallbackConfig(instance));
+ const currentLogins = current.instance === instance ? current.logins : null;
+
+ if (
+ !config &&
+ current.instance === instance &&
+ (current.status === "loading" || current.status === "success")
+ ) {
+ return;
+ }
+
+ set({
+ instanceInfo: {
+ instance,
+ config: currentConfig,
+ logins: currentLogins,
+ status: "loading",
+ error: "",
+ },
+ });
+
+ const [configResult, loginsResult] = await Promise.allSettled([
+ config ? Promise.resolve(config) : fetchInstanceConfig(instance),
+ fetchInstanceLogins(instance),
+ ]);
+
+ if (get().instanceInfo.instance !== instance) return;
+
+ const nextConfig =
+ configResult.status === "fulfilled" ? configResult.value : currentConfig;
+ const nextLogins =
+ loginsResult.status === "fulfilled" ? loginsResult.value : currentLogins;
+
+ set({
+ instanceInfo: {
+ instance,
+ config: nextConfig,
+ logins: nextLogins,
+ status: nextConfig ? "success" : "error",
+ error: nextConfig ? "" : "Could not load this instance.",
+ },
+ });
},
- signUp: async ({ name, username, email, password, instance }) => {
+ signUp: async ({
+ name,
+ username,
+ email,
+ password,
+ instance,
+ acceptPromotionalEmails = false,
+ }) => {
try {
const res = await Promise.race([
fetch(`${instance}/api/v1/users`, {
@@ -166,7 +297,7 @@ const useAuthStore = create<AuthStore>((set) => ({
username,
email,
password,
- acceptPromotionalEmails: false,
+ acceptPromotionalEmails,
}),
headers: { "Content-Type": "application/json" },
}),
@@ -412,6 +543,7 @@ const useAuthStore = create<AuthStore>((set) => ({
},
signOut: async () => {
const instance = await SecureStore.getItemAsync("INSTANCE");
+ const nextInstance = cleanInstance(instance);
await SecureStore.deleteItemAsync("TOKEN");
@@ -426,12 +558,14 @@ const useAuthStore = create<AuthStore>((set) => ({
set({
auth: {
- instance: instance || cloudInstance,
+ instance: nextInstance,
session: null,
status: "unauthenticated",
},
});
+ get().fetchInstanceInfo(nextInstance);
+
router.replace("/");
},
}));
diff --git a/packages/lib/safeFetch.ts b/packages/lib/safeFetch.ts
index f546b22a..61baa50a 100644
--- a/packages/lib/safeFetch.ts
+++ b/packages/lib/safeFetch.ts
@@ -34,7 +34,7 @@ function createSafeLookup() {
? 6
: normalizedOptions.family;
- void resolveHostnameForServerSideFetch(hostname, defaultHostnameLookup)
+ resolveHostnameForServerSideFetch(hostname, defaultHostnameLookup)
.then((resolved) => {
if (normalizedOptions.all) {
callback(null, resolved);