Skip to content

High performance self-hosted photo and video management solution.

2.1 KB
Raw Blame
import { useWindowSize } from '@docusaurus/theme-common';
import DropdownNavbarItem from '@theme/NavbarItem/DropdownNavbarItem';
import React, { useEffect, useState } from 'react';

const ARCHIVED_VERSIONS_URL = 'https://version.immich.cloud/v1/docs/versions';

export default function VersionSwitcher(): JSX.Element {
  const [versions, setVersions] = useState([]);
  const [activeLabel, setLabel] = useState('Versions');

  const windowSize = useWindowSize();

  useEffect(() => {
    async function getVersions() {
      try {
        const response = await fetch(ARCHIVED_VERSIONS_URL);

        const archiveVersions = await response.json();

        const allVersions = [
          { label: 'Next', url: 'https://docs.main.preview.immich.app' },
          { label: 'Latest', url: 'https://docs.immich.app' },
          ...archiveVersions,
        ].map(({ label, url, rootPath }) => ({
          label,
          url: new URL(url),
          rootPath,
        }));
        setVersions(allVersions);

        const activeVersion = allVersions.find((version) => version.url.origin === window.location.origin);
        if (activeVersion) {
          setLabel(activeVersion.label);
        }
      } catch (error) {
        console.error('Failed to fetch versions', error);
      }
    }

    if (versions.length === 0) {
      getVersions();
    }
  }, []);

  return (
    versions.length > 0 && (
      <DropdownNavbarItem
        className="version-switcher-34ab39"
        label={activeLabel}
        mobile={windowSize === 'mobile'}
        items={versions.map(({ label, url, rootPath }) => {
          let path = location.pathname + location.search + location.hash;
          if (rootPath && !path.startsWith(rootPath)) {
            path = rootPath + path;
          }
          return {
            label,
            to: new URL(path, url).href,
            target: '_self',
            className: label === activeLabel ? 'dropdown__link--active menu__link--active' : '', // workaround because React Router `<NavLink>` only supports using URL path for checking if active: https://v5.reactrouter.com/web/api/NavLink/isactive-func
          };
        })}
      />
    )
  );
}