Skip to content

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

2.6 KB
Raw Blame
import React, { useEffect, useState } from "react";
import * as FileSystem from "expo-file-system/legacy";
import getPreservedFormatUrl from "@linkwarden/lib/getPreservedFormatUrl";
import { useConfig } from "@linkwarden/router/config";
import useAuthStore from "@/store/auth";
import { customHeadersFor } from "@/lib/customHeaders";
import { ArchivedFormat } from "@linkwarden/types/global";
import { Link as LinkType } from "@linkwarden/prisma/client";
import WebView from "react-native-webview";
import { loadCacheOrFetch } from "@/lib/cache";

type Props = {
  link: LinkType;
  setIsLoading: (state: boolean) => void;
};

export default function WebpageFormat({ link, setIsLoading }: Props) {
  const FORMAT = ArchivedFormat.monolith;

  const { auth } = useAuthStore();
  const { data: config, isLoading: isConfigLoading } = useConfig(auth);
  const [content, setContent] = useState<string>("");

  useEffect(() => {
    loadCacheOrFetch({
      filePath:
        FileSystem.documentDirectory + `archivedData/webpage/link_${link.id}.html`,
      setContent,
      shouldFetch: !isConfigLoading,
      updatedAt: link.updatedAt,
      fetchContent: async (filePath) => {
        const apiUrl = config?.USER_CONTENT_DOMAIN
          ? await getPreservedFormatUrl({
              tokenEndpoint: `${auth.instance}/api/v1/preserved/token`,
              linkId: link.id,
              format: FORMAT,
              headers: {
                Authorization: `Bearer ${auth.session}`,
              },
            })
          : `${auth.instance}/api/v1/archives/${link.id}?format=${FORMAT}`;

        const result = await FileSystem.downloadAsync(apiUrl, filePath, {
          ...(config?.USER_CONTENT_DOMAIN
            ? {}
            : {
                headers: {
                  ...customHeadersFor(apiUrl),
                  Authorization: `Bearer ${auth.session}`,
                },
              }),
        });

        return result.uri;
      },
    });
  }, [link, auth.instance, auth.session, config?.USER_CONTENT_DOMAIN, isConfigLoading]);

  return (
    content && (
      <WebView
        style={{
          flex: 1,
        }}
        source={{
          uri: content,
          baseUrl: FileSystem.documentDirectory,
        }}
        scalesPageToFit
        originWhitelist={[...(auth.instance ? [auth.instance] : []), "file://"]}
        javaScriptEnabled={false}
        allowFileAccess={true}
        onLoadEnd={() => setIsLoading(false)}
        contentInsetAdjustmentBehavior="automatic"
        automaticallyAdjustContentInsets
        automaticallyAdjustsScrollIndicatorInsets
      />
    )
  );
}