Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

35.5 KB
Raw Blame
import { scopedKey } from '@aliasvault/client/database/ItemRef';
import { CredentialSortOrder } from '@aliasvault/client/database/repositories/SettingsRepository';
import { canHaveSubfolders, getDescendantFolderIds, getFolderPath, isItemInFolder, isSharedFolder } from '@aliasvault/client/items/FolderUtils';
import { ItemFilter, applyTypeFilter, type ItemFilterType, parseItemFilterType } from '@aliasvault/client/items/ItemFilters';
import { multiManifestRendering } from '@aliasvault/client/sharing/MultiManifestRendering';
import { SharingService } from '@aliasvault/client/sharing/SharingService';
import { canAdministerGroup, sharingText, holdsManifestKey } from '@aliasvault/client/sharing/SharingView';
import { ItemTypes, type Item, type ItemType } from '@aliasvault/models/vault';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';

import DeleteFolderModal from '@/components/folders/DeleteFolderModal';
import FolderModal from '@/components/folders/FolderModal';
import FolderPill, { type FolderWithCount } from '@/components/items/FolderPill';
import ItemCard from '@/components/items/ItemCard';
import ItemFilterDropdown from '@/components/items/ItemFilterDropdown';
import { type ItemListEntry, toItemListEntry } from '@/components/items/ItemListEntry';
import ItemsTable from '@/components/items/ItemsTable';
import LoadingIndicator from '@/components/loading/LoadingIndicator';
import type { BreadcrumbItem } from '@/components/shared/Breadcrumb';
import Button from '@/components/shared/Button';
import FormLabel from '@/components/shared/FormLabel';
import Icon from '@/components/shared/Icon';
import LinkButton from '@/components/shared/LinkButton';
import PageContent from '@/components/shared/PageContent';
import PageHeader from '@/components/shared/PageHeader';
import RefreshButton from '@/components/shared/RefreshButton';
import Select from '@/components/shared/Select';
import type { SortDirection } from '@/components/shared/SortableTable';
import SharedFolderAccessModal from '@/components/sharing/SharedFolderAccessModal';
import SharedFolderInvitationModal from '@/components/sharing/SharedFolderInvitationModal';
import { useConfirmModal } from '@/context/ConfirmModalContext';
import { useDb } from '@/context/DbContext';
import { useNotifications } from '@/context/NotificationContext';
import { useQuickCreate } from '@/context/QuickCreateContext';
import { useWebApi } from '@/context/WebApiContext';
import { useClickOutside } from '@/hooks/useClickOutside';
import { usePageTitle } from '@/hooks/usePageTitle';
import { usePasswordConfirmedAction } from '@/hooks/usePasswordConfirmedAction';
import { useSharedFolders } from '@/hooks/useSharedFolders';
import { useVaultMutate, VaultPushFailedError } from '@/hooks/useVaultMutate';
import { useVaultRefresh } from '@/hooks/useVaultRefresh';
import { useVaultSync } from '@/hooks/useVaultSync';
import { folderRoute } from '@/utils/ItemRoute';
import { getLocalPreferenceJson, setLocalPreferenceJson } from '@/utils/LocalPreferences';
import { unwrapSharingResult } from '@/utils/SharingErrors';
import { LocalPreferenceKeys } from '@/utils/StorageKeys';
import { vaultStore } from '@/vault/VaultStore';

import type { Folder, FolderRef } from '@aliasvault/client/database/repositories/FolderRepository';

/** How many items render per infinite scroll batch (180 makes up for 30 equal rows in full width desktop view) */
const BATCH_SIZE = 180;

/** Grid or table. */
type ViewMode = 'grid' | 'table';

/**
 * The items URL for a folder and filter. The filter is always in the query string so it survives navigation.
 * @param folder - the folder, or null for the root
 * @param filter - the active filter
 */
const buildItemsUrl = (folder: FolderRef | null, filter: ItemFilterType): string => `${folder ? folderRoute(folder) : '/items'}?filter=${filter}`;

/**
 * Sort entries by the table column.
 */
const applyTableSort = (entries: ItemListEntry[], column: string, direction: SortDirection): ItemListEntry[] => {
  const sign = direction === 'asc' ? 1 : -1;
  /**
   * Compare two strings, nulls first.
   */
  const byString = (a: string | null, b: string | null): number => (a ?? '').localeCompare(b ?? '') * sign;
  switch (column) {
    case 'Service': return [...entries].sort((a, b) => byString(a.service, b.service));
    case 'Username': return [...entries].sort((a, b) => byString(a.username, b.username));
    case 'Email': return [...entries].sort((a, b) => byString(a.email, b.email));
    default: return [...entries].sort((a, b) => (a.createdAt.getTime() - b.createdAt.getTime()) * (column === 'CreatedAt' ? sign : 1));
  }
};

/**
 * The vault dashboard showing all items.
 */
const ItemsHome: React.FC = () => {
  const { t } = useTranslation();
  const { openQuickCreate } = useQuickCreate();
  const navigate = useNavigate();
  const { manifestId: manifestIdParam, folderId: folderIdParam } = useParams<{ manifestId?: string; folderId?: string }>();
  const [searchParams] = useSearchParams();
  const dbContext = useDb();
  const notifications = useNotifications();
  const { executeVaultMutationAsync, executeVaultMutationInBackground } = useVaultMutate();
  usePageTitle('Home');

  const folderRef = useMemo((): FolderRef | null => (folderIdParam && manifestIdParam ? { Id: folderIdParam, ManifestId: manifestIdParam } : null), [folderIdParam, manifestIdParam]);
  const isInFolder = folderRef !== null;
  const filterType = parseItemFilterType(searchParams.get('filter'));

  const [isLoading, setIsLoading] = useState(true);
  const [items, setItems] = useState<ItemListEntry[]>([]);
  const [allFolders, setAllFolders] = useState<Folder[]>([]);
  const [recentlyDeletedCount, setRecentlyDeletedCount] = useState(0);
  const [showSettingsDropdown, setShowSettingsDropdown] = useState(false);
  const [showFolderModal, setShowFolderModal] = useState(false);
  const [showEditFolderModal, setShowEditFolderModal] = useState(false);
  const [showDeleteFolderModal, setShowDeleteFolderModal] = useState(false);
  /** The folder whose people dialog is open; kept while the folder turns into a shared one and the page moves to it. */
  const [peopleFolder, setPeopleFolder] = useState<{ folder: Folder; isShared: boolean } | null>(null);
  const [openInvitationId, setOpenInvitationId] = useState<string | null>(null);
  const shared = useSharedFolders();
  const webApi = useWebApi();
  const { syncVault } = useVaultSync();
  const { showConfirmation } = useConfirmModal();
  const { askPassword, passwordModal } = usePasswordConfirmedAction();
  const [showFolders, setShowFolders] = useState<boolean>(() => getLocalPreferenceJson<boolean>(LocalPreferenceKeys.ITEMS_SHOW_FOLDERS) ?? true);
  const [viewMode, setViewModeState] = useState<ViewMode>('grid');
  const [sortOrder, setSortOrderState] = useState<CredentialSortOrder>(CredentialSortOrder.NewestFirst);
  const [tableSortColumn, setTableSortColumn] = useState('CreatedAt');
  const [tableSortDirection, setTableSortDirection] = useState<SortDirection>('desc');
  const [visibleItemCount, setVisibleItemCount] = useState(BATCH_SIZE);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const settingsButtonRef = useRef<HTMLButtonElement>(null);
  const settingsDropdownRef = useRef<HTMLDivElement>(null);
  const sentinelRef = useRef<HTMLDivElement>(null);

  /**
   * Close the settings dropdown.
   */
  const closeSettingsPopup = useCallback((): void => setShowSettingsDropdown(false), []);
  useClickOutside([settingsButtonRef, settingsDropdownRef], closeSettingsPopup, showSettingsDropdown);

  /**
   * Table sort follows the sort order setting.
   */
  const syncTableSortWithSortOrder = useCallback((order: CredentialSortOrder): void => {
    switch (order) {
      case CredentialSortOrder.NewestFirst:
        setTableSortColumn('CreatedAt');
        setTableSortDirection('desc');
        break;
      case CredentialSortOrder.Alphabetical:
        setTableSortColumn('Service');
        setTableSortDirection('asc');
        break;
      default:
        setTableSortColumn('CreatedAt');
        setTableSortDirection('asc');
    }
  }, []);

  /**
   * Load the items, folders and settings from the vault.
   */
  const loadItems = useCallback((): void => {
    const client = dbContext.sqliteClient;
    if (!client) {
      return;
    }
    setIsLoading(true);
    setVisibleItemCount(BATCH_SIZE);
    try {
      const vaultItems: Item[] = client.items.getAll();
      if (vaultItems.length === 0 && !folderRef && client.settings.getSetting('TutorialDone', 'False').toLowerCase() !== 'true') {
        navigate('/welcome');
        return;
      }
      setItems(vaultItems.map(toItemListEntry));
      setAllFolders(client.folders.getAll());
      setRecentlyDeletedCount(client.items.getRecentlyDeletedCount());
      const mode = client.settings.getSetting('CredentialsViewMode', 'grid');
      setViewModeState(mode === 'table' ? 'table' : 'grid');
      const order = client.settings.getCredentialsSortOrder();
      setSortOrderState(order);
      syncTableSortWithSortOrder(order);
    } catch (error) {
      console.error('Failed to load items:', error);
      notifications.addErrorMessage(t('items.home.failedToLoadItemsMessage'), true);
    } finally {
      setIsLoading(false);
    }
  }, [dbContext.sqliteClient, folderRef, navigate, notifications, syncTableSortWithSortOrder, t]);

  useEffect(() => {
    loadItems();
  }, [loadItems]);

  /**
   * Persist the view mode in the vault settings.
   */
  const setViewMode = (mode: ViewMode): void => {
    setViewModeState(mode);
    const client = dbContext.sqliteClient;
    if (client) {
      void executeVaultMutationInBackground(async () => {
        client.settings.updateSetting('CredentialsViewMode', mode);
      });
    }
  };

  /**
   * Persist the sort order in the vault settings.
   */
  const setSortOrder = (order: CredentialSortOrder): void => {
    setSortOrderState(order);
    syncTableSortWithSortOrder(order);
    setVisibleItemCount(BATCH_SIZE);
    const client = dbContext.sqliteClient;
    if (client) {
      void executeVaultMutationInBackground(async () => {
        client.settings.setCredentialsSortOrder(order);
      });
    }
  };

  const currentFolder = useMemo(() => folderRef ? allFolders.find(f => f.Id === folderRef.Id && f.ManifestId === folderRef.ManifestId) ?? null : null, [allFolders, folderRef]);
  const currentFolderName = currentFolder?.Name ?? '';
  // A virtual folder (a shared manifest) is renamed and deleted through its shared folder, not as a stored folder.
  const currentFolderIsVirtual = currentFolder !== null && multiManifestRendering.isVirtualFolder(currentFolder);
  const currentShared = currentFolderIsVirtual ? shared.folders.find(folder => folder.manifest.manifestId.toLowerCase() === currentFolder.ManifestId.toLowerCase()) ?? null : null;
  const canManageShared = currentShared !== null && canAdministerGroup(currentShared.group);
  // A top-level personal folder can be shared; a subfolder cannot, as a shared folder is always a top-level one.
  const canShareCurrent = shared.isEnabled && currentFolder !== null && (currentFolderIsVirtual || (currentFolder.ParentFolderId ?? null) === null);

  /**
   * Items after the folder and type filters.
   */
  const allFilteredAndSortedItems = useMemo((): ItemListEntry[] => {
    let filtered = items;
    if (folderRef) {
      filtered = filtered.filter(x => isItemInFolder(x.item, folderRef));
    } else if (showFolders) {
      filtered = filtered.filter(x => x.folderId === null);
    }

    const filteredItems = new Set(applyTypeFilter(filtered.map(e => e.item), filterType).map(i => scopedKey(i.ManifestId, i.Id)));
    filtered = filtered.filter(e => filteredItems.has(scopedKey(e.manifestId, e.id)));

    if (viewMode === 'table') {
      return applyTableSort(filtered, tableSortColumn, tableSortDirection);
    }
    switch (sortOrder) {
      case CredentialSortOrder.NewestFirst: return [...filtered].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
      case CredentialSortOrder.Alphabetical: return [...filtered].sort((a, b) => (a.service ?? '').localeCompare(b.service ?? ''));
      default: return [...filtered].sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
    }
  }, [items, folderRef, showFolders, filterType, viewMode, tableSortColumn, tableSortDirection, sortOrder]);

  const totalFilteredItems = allFilteredAndSortedItems.length;
  const hasMoreItems = visibleItemCount < totalFilteredItems;
  const filteredAndSortedItems = allFilteredAndSortedItems.slice(0, visibleItemCount);
  const hasItemsInFoldersOnly = items.length > 0 && items.every(x => x.folderId !== null);
  const isEmptyVault = items.length === 0 && !isInFolder;

  /**
   * Open the quick create dialog, with the type of the active type filter preselected.
   */
  const createItem = (): void => {
    const typeFilters: string[] = [ItemTypes.Login, ItemTypes.Alias, ItemTypes.CreditCard, ItemTypes.Note];
    openQuickCreate(typeFilters.includes(filterType) ? filterType as ItemType : undefined);
  };

  /**
   * Folders at the current level with their (recursive) filtered item counts.
   */
  const currentLevelFolders = useMemo((): FolderWithCount[] => {
    const personalManifestId = dbContext.sqliteClient?.getPersonalManifestId() ?? null;
    const typeFiltered = new Set(applyTypeFilter(items.map(e => e.item), filterType).map(i => scopedKey(i.ManifestId, i.Id)));
    // At the root the top-level folders of every manifest show; inside a folder its children, which share its manifest.
    return allFolders
      .filter(f => folderRef ? f.ParentFolderId === folderRef.Id && f.ManifestId === folderRef.ManifestId : (f.ParentFolderId ?? null) === null)
      .map(f => {
        const folderIds = new Set([f.Id, ...getDescendantFolderIds(f, allFolders)]);
        return {
          id: f.Id,
          manifestId: f.ManifestId,
          name: f.Name,
          parentFolderId: f.ParentFolderId ?? null,
          itemCount: items.filter(e => e.manifestId === f.ManifestId && e.folderId !== null && folderIds.has(e.folderId) && typeFiltered.has(scopedKey(e.manifestId, e.id))).length,
          isShared: isSharedFolder(f, personalManifestId),
        };
      });
  }, [allFolders, folderRef, items, filterType, dbContext.sqliteClient]);

  const canCreateSubfolder = !folderRef || (allFolders.length > 0 && canHaveSubfolders(folderRef, allFolders));

  /**
   * Items in the current folder tree, for the delete folder modal.
   */
  const currentFolderItemCount = useMemo((): number => {
    if (!folderRef) {
      return filteredAndSortedItems.length;
    }
    const folderIds = new Set([folderRef.Id, ...getDescendantFolderIds(folderRef, allFolders)]);
    return items.filter(e => e.manifestId === folderRef.ManifestId && e.folderId !== null && folderIds.has(e.folderId)).length;
  }, [folderRef, allFolders, items, filteredAndSortedItems.length]);

  /**
   * Breadcrumbs for the folder hierarchy (the last folder is the current page).
   */
  const breadcrumbItems = useMemo((): BreadcrumbItem[] => {
    if (!folderRef) {
      return [];
    }
    const names = getFolderPath(folderRef, allFolders);
    const manifestFolders = allFolders.filter(f => f.ManifestId === folderRef.ManifestId);
    const path: BreadcrumbItem[] = [];
    let current: Folder | undefined = manifestFolders.find(f => f.Id === folderRef.Id);
    const chain: Folder[] = [];
    while (current) {
      chain.unshift(current);
      const parentId: string | null | undefined = current.ParentFolderId;
      current = parentId ? manifestFolders.find(f => f.Id === parentId) : undefined;
    }
    chain.forEach((folder, index) => {
      path.push({ displayName: names[index] ?? folder.Name, url: index === chain.length - 1 ? undefined : buildItemsUrl(folder, filterType) });
    });
    return path;
  }, [folderRef, allFolders, filterType]);

  /**
   * The title for the active filter and folder.
   */
  const getFilterTitle = (): string => {
    switch (filterType) {
      case ItemFilter.Passkeys: return t('common.passkeys');
      case ItemFilter.Attachments: return t('common.attachments');
      case ItemFilter.Totp: return t('items.filters.totp');
      case ItemFilter.Login: return t('itemTypes.login.title');
      case ItemFilter.Alias: return t('itemTypes.alias.title');
      case ItemFilter.CreditCard: return t('itemTypes.creditCard.title');
      case ItemFilter.Note: return t('itemTypes.secureNote');
      default:
        return isInFolder && currentFolderName ? currentFolderName : t('navigation.vault');
    }
  };

  /**
   * The class of the add folder button: dashed when there are no folders yet.
   */
  const getAddFolderButtonClass = (): string => allFolders.length > 0
    ? 'inline-flex items-center gap-1.5 px-5 py-2.5 text-sm rounded-lg transition-colors focus:outline-none text-gray-500 dark:text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 hover:bg-gray-100 dark:hover:bg-gray-700/50'
    : 'inline-flex items-center gap-1.5 px-5 py-2.5 text-sm rounded-lg transition-colors focus:outline-none text-gray-400 dark:text-gray-500 border border-dashed border-gray-300 dark:border-gray-600 hover:border-primary-400 dark:hover:border-primary-500 hover:text-primary-600 dark:hover:text-primary-400';

  /**
   * Pick a filter.
   */
  const setFilter = (filter: ItemFilterType): void => {
    setVisibleItemCount(BATCH_SIZE);
    navigate(buildItemsUrl(folderRef, filter), { replace: true });
  };

  /**
   * Toggle folder grouping.
   */
  const toggleShowFolders = (): void => {
    const next = !showFolders;
    setShowFolders(next);
    setVisibleItemCount(BATCH_SIZE);
    setLocalPreferenceJson(LocalPreferenceKeys.ITEMS_SHOW_FOLDERS, next);
  };

  /**
   * Table header sort.
   */
  const handleTableSortChanged = (column: string, direction: SortDirection): void => {
    setTableSortColumn(column);
    setTableSortDirection(direction);
    setVisibleItemCount(BATCH_SIZE);
  };

  const refreshVault = useVaultRefresh(loadItems);

  /**
   * Infinite scroll: load the next batch when the sentinel comes into view.
   */
  useEffect(() => {
    const sentinel = sentinelRef.current;
    if (!sentinel || !hasMoreItems || isLoading) {
      return;
    }
    const observer = new IntersectionObserver((entries) => {
      if (entries.some(entry => entry.isIntersecting) && !isLoadingMore) {
        setIsLoadingMore(true);
        setTimeout(() => {
          setVisibleItemCount(count => count + BATCH_SIZE);
          setIsLoadingMore(false);
        }, 300);
      }
    });
    observer.observe(sentinel);
    return (): void => observer.disconnect();
  }, [hasMoreItems, isLoading, isLoadingMore]);

  /**
   * Create a folder at the current level.
   */
  const createFolder = async (name: string): Promise<void> => {
    const client = dbContext.sqliteClient;
    if (!client) {
      return;
    }
    try {
      await executeVaultMutationAsync(async () => {
        await client.folders.create(name, folderRef);
      });
      setAllFolders(client.folders.getAll());
    } catch (error) {
      console.error('Failed to create folder:', error);
      // Failed push (e.g. server not reachable).
      if (!(error instanceof VaultPushFailedError)) {
        notifications.addErrorMessage(t('items.home.failedToCreateFolder'), true);
      }
    }
  };

  /**
   * Rename the current folder.
   */
  const editFolder = async (name: string): Promise<void> => {
    const client = dbContext.sqliteClient;
    if (!client || !folderRef) {
      return;
    }
    try {
      if (currentShared) {
        // A shared folder's name is encrypted with its key and kept on the server for every member.
        unwrapSharingResult(await vaultStore.updateSharedManifest(currentShared.group.groupId, currentShared.manifest.manifestId, { name }), t('common.errorGeneric'), t);
        await syncVault();
        setAllFolders((await dbContext.loadStoredDatabase())?.folders.getAll() ?? client.folders.getAll());
        return;
      }
      await executeVaultMutationAsync(async () => {
        await client.folders.update(folderRef, name);
      });
      setAllFolders(client.folders.getAll());
    } catch (error) {
      console.error('Failed to rename folder:', error);
      if (!(error instanceof VaultPushFailedError)) {
        notifications.addErrorMessage(t('common.errorGeneric'), true);
      }
    }
  };

  /**
   * Delete the current shared folder for everyone, after a confirmation and the master password.
   */
  const deleteSharedFolder = async (): Promise<void> => {
    if (!currentShared || !await showConfirmation(sharingText.deleteVault, sharingText.deleteVaultConfirm(currentFolderName), t('common.delete'), t('common.cancel'))) {
      return;
    }

    askPassword({
      title: sharingText.deleteVault,
      description: sharingText.deleteVaultPasswordPrompt(currentFolderName),
      failureMessage: sharingText.errors.deleteVaultFailed,
      /**
       * Run the deletion with the password proof.
       * @param answerChallenge - answers the SRP challenge.
       */
      perform: answerChallenge => SharingService.deleteSharedManifest(webApi, currentShared.group.groupId, currentShared.manifest.manifestId, answerChallenge),
      /**
       * Sync the deletion in and go to the vault's top level.
       */
      onDone: async () => {
        await syncVault();
        await dbContext.loadStoredDatabase();
        await shared.reload();
        notifications.addSuccessMessage(sharingText.vaultDeleted);
        navigate(buildItemsUrl(null, filterType));
      },
    });
  };

  /**
   * Finish an answered invitation: an accepted one is synced in and opened.
   * @param invitationId - the invitation.
   * @param manifestId - the shared folder it was for.
   * @param accepted - whether it was accepted.
   */
  const finishInvitation = async (invitationId: string, manifestId: string, accepted: boolean): Promise<void> => {
    setOpenInvitationId(null);
    if (accepted) {
      await syncVault();
      const client = await dbContext.loadStoredDatabase();
      if (client) {
        setAllFolders(client.folders.getAll());
      }
      navigate(buildItemsUrl({ Id: manifestId.toLowerCase(), ManifestId: manifestId.toLowerCase() }, filterType));
    }
    await shared.reload();
  };

  /**
   * Delete the current folder, keeping or trashing its contents, and go to its parent.
   */
  const deleteFolder = async (withContents: boolean): Promise<void> => {
    const client = dbContext.sqliteClient;
    if (!client || !folderRef) {
      return;
    }
    const parentFolderId = currentFolder?.ParentFolderId ?? null;
    try {
      await executeVaultMutationAsync(async () => {
        if (withContents) {
          await client.folders.deleteWithContents(folderRef);
        } else {
          await client.folders.delete(folderRef);
        }
      });
      navigate(buildItemsUrl(parentFolderId ? { Id: parentFolderId, ManifestId: folderRef.ManifestId } : null, filterType));
    } catch (error) {
      console.error('Failed to delete folder:', error);
      if (!(error instanceof VaultPushFailedError)) {
        notifications.addErrorMessage(t('items.home.failedToDeleteFolder'), true);
      }
    }
  };

  /** The empty vault message: importing first, creating an item by hand as the alternative. */
  const welcomeCard = (
    <div className="credential-card col-span-full p-4 space-y-2 bg-amber-50 border border-primary-500 rounded-lg shadow-sm dark:border-primary-700 dark:bg-gray-800">
      <div className="px-4 py-6 text-gray-700 dark:text-gray-200 rounded text-center flex flex-col items-center">
        <p className="mb-2 text-lg font-semibold text-primary-700 dark:text-primary-400">{t('items.home.noItemsTitle')}</p>
        <div className="max-w-md mx-auto">
          <div>
            <p className="text-sm mb-3">{t('items.home.importItemsText')}</p>
            <LinkButton href="/settings/import-export" text={t('items.home.importButtonText')} />
          </div>
          <div className="flex items-center my-6">
            <div className="flex-1 h-px bg-gray-300 dark:bg-gray-600"></div>
            <span className="px-4 text-sm text-gray-500 dark:text-gray-400">{t('common.or')}</span>
            <div className="flex-1 h-px bg-gray-300 dark:bg-gray-600"></div>
          </div>
          <div>
            <p className="text-sm mb-3">{t('items.home.createFirstItemManuallyText')}</p>
            <Button id="quickIdentityButton" color="outline" onClick={createItem}><Icon name="plus" className="inline w-4 h-4 mr-1.5 -mt-0.5" strokeWidth={2.25} />{t('items.addNewItem')}</Button>
          </div>
        </div>
      </div>
    </div>
  );

  return (
    <>
      <PageHeader
        breadcrumbItems={breadcrumbItems}
        title={getFilterTitle()}
        description={t('items.home.pageDescription')}
        titleActions={(
          <ItemFilterDropdown
            title={getFilterTitle()}
            count={totalFilteredItems}
            titleFolder={filterType === ItemFilter.All && currentFolder && currentFolderName ? { isShared: isSharedFolder(currentFolder, dbContext.sqliteClient?.getPersonalManifestId()) } : undefined}
            activeFilter={filterType}
            recentlyDeletedCount={recentlyDeletedCount}
            showFoldersToggle={!isInFolder}
            showFolders={showFolders}
            onSelectFilter={setFilter}
            onSelectRecentlyDeleted={() => navigate('/items/recently-deleted')}
            onToggleShowFolders={toggleShowFolders}
            titleActions={isInFolder ? (
              <>
                {canShareCurrent && (
                  <button id="folder-people" onClick={() => setPeopleFolder({ folder: currentFolder, isShared: currentFolderIsVirtual })} title={sharingText.peopleTitle} className="p-1.5 text-gray-400 hover:text-primary-500 dark:text-gray-500 dark:hover:text-primary-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors">
                    <Icon name="users" className="w-5 h-5" />
                  </button>
                )}
                {(!currentFolderIsVirtual || (canManageShared && holdsManifestKey(currentShared.manifest, shared.myUserId))) && (
                  <button onClick={() => setShowEditFolderModal(true)} title={t('items.folders.editFolder')} className="p-1.5 text-gray-400 hover:text-primary-500 dark:text-gray-500 dark:hover:text-primary-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors">
                    <Icon name="pencil-alt" className="w-5 h-5" />
                  </button>
                )}
                {(!currentFolderIsVirtual || canManageShared) && (
                  <button onClick={() => (currentFolderIsVirtual ? void deleteSharedFolder() : setShowDeleteFolderModal(true))} title={t('items.folders.deleteFolder')} className="p-1.5 text-gray-400 hover:text-red-500 dark:text-gray-500 dark:hover:text-red-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors">
                    <Icon name="trash" className="w-5 h-5" strokeWidth={1} />
                  </button>
                )}
              </>
            ) : undefined} />
        )}
        customActions={(
          <>
            <div className="relative">
              <button ref={settingsButtonRef} onClick={() => setShowSettingsDropdown(!showSettingsDropdown)} id="settingsButton" className="p-2 text-gray-500 rounded-lg hover:text-gray-900 hover:bg-gray-100 dark:text-gray-400 dark:hover:text-white dark:hover:bg-gray-700">
                <Icon name="cog" className="w-5 h-5" />
              </button>

              {showSettingsDropdown && (
                <div ref={settingsDropdownRef} id="settingsDropdown" className="absolute right-0 z-10 mt-2 min-w-[220px] origin-top-right rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none dark:bg-gray-700">
                  <div className="p-4">
                    <div className="mb-4">
                      <FormLabel>{t('items.home.viewModeLabel')}</FormLabel>
                      <Select value={viewMode} onChange={(e) => {
                        setViewMode(e.target.value as ViewMode); closeSettingsPopup(); 
                      }}>
                        <option value="grid">{t('items.home.gridViewOption')}</option>
                        <option value="table">{t('items.home.tableViewOption')}</option>
                      </Select>
                    </div>
                    <div className="mb-4">
                      <FormLabel>{t('items.home.sortOrderLabel')}</FormLabel>
                      <Select value={sortOrder} onChange={(e) => {
                        setSortOrder(e.target.value as CredentialSortOrder); closeSettingsPopup(); 
                      }}>
                        <option value={CredentialSortOrder.OldestFirst}>{t('items.sort.oldestFirst')}</option>
                        <option value={CredentialSortOrder.NewestFirst}>{t('items.sort.newestFirst')}</option>
                        <option value={CredentialSortOrder.Alphabetical}>{t('items.home.alphabeticalOption')}</option>
                      </Select>
                    </div>
                  </div>
                </div>
              )}
            </div>
            <RefreshButton onClick={refreshVault} buttonText={t('common.refresh')} />
          </>
        )} />

      {isLoading ? (
        <LoadingIndicator />
      ) : (
        <PageContent className="px-4 mb-4">
          {filterType !== ItemFilter.All && (
            <div className="flex flex-wrap items-center gap-2 mb-4">
              <span className="text-sm text-gray-500 dark:text-gray-400">{t('items.home.filteringBy')}</span>
              <button onClick={() => setFilter(ItemFilter.All)} className="inline-flex items-center gap-1 px-3 py-1.5 text-sm bg-primary-100 dark:bg-primary-900/30 hover:bg-primary-200 dark:hover:bg-primary-900/50 text-primary-700 dark:text-primary-300 rounded-lg transition-colors">
                <span>{getFilterTitle()}</span>
                <Icon name="x" className="w-4 h-4" />
              </button>
            </div>
          )}

          {showFolders && (
            <div className="flex flex-wrap items-center gap-2 mb-4">
              {currentLevelFolders.map(folder => (
                <FolderPill key={scopedKey(folder.manifestId, folder.id)} folder={folder} onClick={() => {
                  setVisibleItemCount(BATCH_SIZE); navigate(buildItemsUrl({ Id: folder.id, ManifestId: folder.manifestId }, filterType)); 
                }} />
              ))}
              {/* Invitations to shared folders wait in the folder list until they are answered. */}
              {!isInFolder && shared.invitations.map(invitation => (
                <button
                  key={invitation.id}
                  data-invitation={invitation.id}
                  onClick={() => setOpenInvitationId(invitation.id)}
                  className="inline-flex items-center gap-2 px-5 py-2.5 text-sm rounded-lg border border-dashed border-primary-400 bg-primary-50/50 text-gray-500 hover:bg-primary-50 dark:border-primary-600 dark:bg-primary-900/10 dark:text-gray-400 dark:hover:bg-primary-900/20 transition-colors"
                >
                  <Icon name="mail" className="w-4 h-4 text-primary-500" />
                  <span className="truncate max-w-[150px]">{shared.invitationNames[invitation.id] ?? sharingText.sharedVault}</span>
                  <span className="text-xs text-primary-600 dark:text-primary-400">{sharingText.invitationPending}</span>
                </button>
              ))}
              {canCreateSubfolder && (
                <button id="new-folder-button" onClick={() => setShowFolderModal(true)} className={getAddFolderButtonClass()}>
                  <Icon name="folder" className="w-4 h-4" />
                  <Icon name="plus" className="w-3.5 h-3.5 -ml-0.5" strokeWidth={2.5} />
                  {currentLevelFolders.length === 0 && <span>{t('items.folders.newFolder')}</span>}
                </button>
              )}
            </div>
          )}

          {isEmptyVault ? welcomeCard : viewMode === 'table' ? (
            <ItemsTable entries={filteredAndSortedItems} sortColumn={tableSortColumn} sortDirection={tableSortDirection} onTableSortChanged={handleTableSortChanged} onMutated={loadItems} />
          ) : (
            <div className="grid gap-2 md:gap-4 md:grid-cols-4 xl:grid-cols-6">
              {filteredAndSortedItems.length === 0 && (
                <div className="credential-card col-span-full p-4 space-y-2 bg-amber-50 border border-primary-500 rounded-lg shadow-sm dark:border-primary-700 dark:bg-gray-800">
                  <div className="px-4 py-6 text-sm text-gray-700 dark:text-gray-200 rounded text-center flex flex-col items-center gap-4">
                    {filterType !== ItemFilter.All ? (
                      <p>{t('items.noMatchingItems')}</p>
                    ) : isInFolder ? (
                      <p>{t('items.home.emptyFolderMessage')}</p>
                    ) : hasItemsInFoldersOnly ? (
                      <p>{t('items.allItemsInFoldersClick')}</p>
                    ) : (
                      <p>{t('items.noMatchingItems')}</p>
                    )}
                    <Button onClick={createItem}><Icon name="plus" className="inline w-4 h-4 mr-1.5 -mt-0.5" strokeWidth={2.25} />{t('items.addNewItem')}</Button>
                  </div>
                </div>
              )}
              {filteredAndSortedItems.map(entry => (
                <ItemCard key={scopedKey(entry.manifestId, entry.id)} entry={entry} onMutated={loadItems} />
              ))}
            </div>
          )}

          {hasMoreItems && (
            <div ref={sentinelRef} className="flex justify-center py-4 min-h-[40px]">
              {isLoadingMore && (
                <div className="flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400">
                  <Icon name="spinner" className="w-4 h-4 animate-spin" />
                  <span>{t('items.home.loadingMore')}</span>
                </div>
              )}
            </div>
          )}
        </PageContent>
      )}

      <FolderModal isOpen={showFolderModal} mode="create" onClose={() => setShowFolderModal(false)} onSave={createFolder} />
      <FolderModal isOpen={showEditFolderModal} mode="edit" initialName={currentFolderName} onClose={() => setShowEditFolderModal(false)} onSave={editFolder} />
      <DeleteFolderModal
        isOpen={showDeleteFolderModal}
        folderName={currentFolderName}
        itemCount={currentFolderItemCount}
        onClose={() => setShowDeleteFolderModal(false)}
        onDeleteFolderOnly={() => deleteFolder(false)}
        onDeleteFolderAndContents={() => deleteFolder(true)} />
      {peopleFolder && (
        <SharedFolderAccessModal
          isOpen
          folder={peopleFolder.folder}
          isShared={peopleFolder.isShared}
          shared={shared}
          onMoved={(ref, isShared) => {
            setPeopleFolder(open => (open ? { folder: { ...open.folder, Id: ref.Id, ManifestId: ref.ManifestId, ParentFolderId: null }, isShared } : null));
            navigate(buildItemsUrl(ref, filterType));
          }}
          onLeft={() => {
            setPeopleFolder(null);
            navigate(buildItemsUrl(null, filterType));
          }}
          onClose={() => setPeopleFolder(null)}
        />
      )}
      {((): React.ReactNode => {
        const invitation = shared.invitations.find(candidate => candidate.id === openInvitationId) ?? null;
        return (
          <SharedFolderInvitationModal
            invitation={invitation}
            folderName={invitation ? shared.invitationNames[invitation.id] ?? sharingText.sharedVault : ''}
            onDone={accepted => (invitation ? finishInvitation(invitation.id, invitation.manifestId, accepted) : Promise.resolve())}
            onClose={() => setOpenInvitationId(null)}
          />
        );
      })()}
      {passwordModal}
    </>
  );
};

export default ItemsHome;