Skip to content

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

8.1 KB
Raw Blame
import {
  ArchivedFormat,
  CollectionIncludingMembersAndLinkCount,
  LinkIncludingShortenedCollectionAndTags,
} from "@linkwarden/types/global";
import React, { useEffect, useState } from "react";
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { useTranslation } from "next-i18next";
import Link from "next/link";
import { useRouter } from "next/router";
import { useConfig } from "@linkwarden/router/config";
import getPreservedFormatUrl from "@linkwarden/lib/getPreservedFormatUrl";
import {
  atLeastOneFormatAvailable,
  formatAvailable,
} from "@linkwarden/lib/formatStats";
import LinkActions from "../LinkViews/LinkComponents/LinkActions";
import { useCollections } from "@linkwarden/router/collections";
import clsx from "clsx";
import ToggleDarkMode from "../ToggleDarkMode";
import TextStyleDropdown from "../TextStyleDropdown";
import HighlightDrawer from "../HighlightDrawer";

type Props = {
  link: LinkIncludingShortenedCollectionAndTags;
  format?: ArchivedFormat;
  className?: string;
};

const PreservationNavbar = ({ link, format, className }: Props) => {
  const { data: collections = [] } = useCollections();
  const { data: config, isLoading: isConfigLoading } = useConfig();

  const [collection, setCollection] =
    useState<CollectionIncludingMembersAndLinkCount>(
      collections.find(
        (e) => e.id === link.collection.id
      ) as CollectionIncludingMembersAndLinkCount
    );

  const [linkModal, setLinkModal] = useState(false);
  const [highlightDrawer, setHighlightDrawer] = useState(false);

  useEffect(() => {
    setCollection(
      collections.find(
        (e) => e.id === link.collection.id
      ) as CollectionIncludingMembersAndLinkCount
    );
  }, [collections]);

  const { t } = useTranslation();
  const router = useRouter();
  const isMonolithConfigPending =
    format === ArchivedFormat.monolith && isConfigLoading && !config;

  const handleDownload = async () => {
    if (
      typeof link.id !== "number" ||
      format === undefined ||
      isMonolithConfigPending
    ) {
      return;
    }

    try {
      const isCrossOriginMonolith =
        format === ArchivedFormat.monolith && config?.USER_CONTENT_DOMAIN;
      const path = isCrossOriginMonolith
        ? await getPreservedFormatUrl({
            tokenEndpoint: "/api/v1/preserved/token",
            linkId: link.id,
            format,
            download: true,
            requestInit: {
              cache: "no-store",
            },
          })
        : `/api/v1/archives/${link?.id}?format=${format}`;

      if (!isCrossOriginMonolith) {
        const response = await fetch(path);
        if (!response.ok) {
          throw new Error("Failed to download file");
        }
      }

      const anchorElement = document.createElement("a");
      anchorElement.href = path;
      anchorElement.download =
        format === ArchivedFormat.monolith
          ? "Webpage"
          : format === ArchivedFormat.pdf
            ? "PDF"
            : "Screenshot";
      anchorElement.click();
    } catch (error) {
      console.error("Error:", error);
    }
  };

  return (
    <>
      <div
        className={clsx(
          "p-2 z-10 bg-base-100 flex gap-2 justify-between fixed top-0 left-0 right-0",
          className
        )}
      >
        <div className="flex items-center gap-2">
          <Button variant="ghost" size="icon" asChild>
            <Link href={`/dashboard`}>
              <i className="bi-chevron-left text-lg text-neutral" />
            </Link>
          </Button>
          {format === ArchivedFormat.readability ? (
            <TextStyleDropdown />
          ) : (
            <Button
              variant="ghost"
              size="icon"
              onClick={handleDownload}
              disabled={isMonolithConfigPending}
            >
              <i className="bi-cloud-arrow-down text-xl text-neutral" />
            </Button>
          )}
          {format === ArchivedFormat.readability && (
            <Button
              variant="ghost"
              size="icon"
              onClick={() => setHighlightDrawer(true)}
            >
              <i className="bi-highlighter text-xl text-neutral" />
            </Button>
          )}
        </div>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="ghost"
              className="h-8 text-neutral"
              disabled={!atLeastOneFormatAvailable(link) || false}
            >
              {format === ArchivedFormat.readability
                ? t("readable")
                : format === ArchivedFormat.monolith
                  ? t("webpage")
                  : format === ArchivedFormat.pdf
                    ? t("pdf")
                    : t("screenshot")}
              <i className="bi-chevron-down" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent>
            {formatAvailable(link, "readable") && (
              <DropdownMenuCheckboxItem
                onSelect={() =>
                  router.push(
                    {
                      query: {
                        ...router.query,
                        format: ArchivedFormat.readability,
                      },
                    },
                    undefined,
                    { shallow: true }
                  )
                }
                checked={format === ArchivedFormat.readability}
              >
                {t("readable")}
              </DropdownMenuCheckboxItem>
            )}
            {formatAvailable(link, "monolith") && (
              <DropdownMenuCheckboxItem
                onSelect={() =>
                  router.push(
                    {
                      query: {
                        ...router.query,
                        format: ArchivedFormat.monolith,
                      },
                    },
                    undefined,
                    { shallow: true }
                  )
                }
                checked={format === ArchivedFormat.monolith}
              >
                {t("webpage")}
              </DropdownMenuCheckboxItem>
            )}
            {formatAvailable(link, "image") && (
              <DropdownMenuCheckboxItem
                onSelect={() =>
                  router.push(
                    {
                      query: {
                        ...router.query,
                        format: link?.image?.endsWith(".png")
                          ? ArchivedFormat.png
                          : ArchivedFormat.jpeg,
                      },
                    },
                    undefined,
                    { shallow: true }
                  )
                }
                checked={
                  format === ArchivedFormat.png ||
                  format === ArchivedFormat.jpeg
                }
              >
                {t("screenshot")}
              </DropdownMenuCheckboxItem>
            )}
            {formatAvailable(link, "pdf") && (
              <DropdownMenuCheckboxItem
                onSelect={() =>
                  router.push(
                    {
                      query: {
                        ...router.query,
                        format: ArchivedFormat.pdf,
                      },
                    },
                    undefined,
                    { shallow: true }
                  )
                }
                checked={format === ArchivedFormat.pdf}
              >
                {t("pdf")}
              </DropdownMenuCheckboxItem>
            )}
          </DropdownMenuContent>
        </DropdownMenu>

        <div className="flex gap-2 items-center text-neutral">
          <ToggleDarkMode />
          <LinkActions
            link={link}
            t={t}
            linkModal={linkModal}
            setLinkModal={(e) => setLinkModal(e)}
            ghost
          />
        </div>
      </div>
      {highlightDrawer && (
        <HighlightDrawer onClose={() => setHighlightDrawer(false)} />
      )}
    </>
  );
};

export default PreservationNavbar;