Skip to content

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

Add items pages (#2413)

Leendert de Borst5304555d798a
diff --git a/apps/web/src/components/shared/Button.tsx b/apps/web/src/components/shared/Button.tsx
index 6a99fb337..d84dca77f 100644
--- a/apps/web/src/components/shared/Button.tsx
+++ b/apps/web/src/components/shared/Button.tsx
@@ -14,7 +14,8 @@ type ButtonProps = {
id?: string;
};
-const BASE_CLASSES = 'center items-center px-3 py-2 text-sm font-medium text-white rounded-lg focus:outline-none focus:ring-4';
+/** Base classes shared by every button-styled element. */
+export const BUTTON_BASE_CLASSES = 'center items-center px-3 py-2 text-sm font-medium text-white rounded-lg focus:outline-none focus:ring-4';
const DISABLED_CLASSES = 'bg-gray-400 cursor-not-allowed';
/**
@@ -38,7 +39,7 @@ export const getButtonColorClasses = (color: ButtonColor): string => {
* Generic button.
*/
const Button: React.FC<ButtonProps> = ({ children, onClick, isDisabled = false, type = 'button', color = 'primary', additionalClasses = '', display = 'inline', id }) => {
- const classes = `${display} ${BASE_CLASSES} ${getButtonColorClasses(color)} ${isDisabled ? DISABLED_CLASSES : ''} ${additionalClasses}`.trim();
+ const classes = `${display} ${BUTTON_BASE_CLASSES} ${getButtonColorClasses(color)} ${isDisabled ? DISABLED_CLASSES : ''} ${additionalClasses}`.trim();
return (
<button type={type} id={id} onClick={isDisabled ? undefined : onClick} disabled={isDisabled} className={classes}>
diff --git a/apps/web/src/components/shared/LinkButton.tsx b/apps/web/src/components/shared/LinkButton.tsx
index 55773a5b1..3cd0d53af 100644
--- a/apps/web/src/components/shared/LinkButton.tsx
+++ b/apps/web/src/components/shared/LinkButton.tsx
@@ -1,7 +1,7 @@
import React from 'react';
import { Link } from 'react-router-dom';
-import { type ButtonColor, getButtonColorClasses } from '@/components/shared/Button';
+import { BUTTON_BASE_CLASSES, type ButtonColor, getButtonColorClasses } from '@/components/shared/Button';
type LinkButtonProps = {
href: string;
@@ -12,14 +12,11 @@ type LinkButtonProps = {
additionalClasses?: string;
};
-/** Base classes. */
-const BASE_CLASSES = 'inline center items-center px-3 py-2 text-sm font-medium text-white rounded-lg focus:outline-none focus:ring-4';
-
/**
* A link styled as a button.
*/
const LinkButton: React.FC<LinkButtonProps> = ({ href, text, smallText = '', color = 'primary', additionalClasses = '' }) => (
- <Link to={href} className={`${BASE_CLASSES} ${getButtonColorClasses(color)} ${additionalClasses}`.trim()}>
+ <Link to={href} className={`inline ${BUTTON_BASE_CLASSES} ${getButtonColorClasses(color)} ${additionalClasses}`.trim()}>
{smallText.length > 0 ? (
<>
<span className="md:hidden">{smallText}</span>
diff --git a/apps/web/src/pages/auth/Unlock.tsx b/apps/web/src/pages/auth/Unlock.tsx
index 189aa44e1..f8690d7b3 100644
--- a/apps/web/src/pages/auth/Unlock.tsx
+++ b/apps/web/src/pages/auth/Unlock.tsx
@@ -127,8 +127,7 @@ const Unlock: React.FC = () => {
}, [isLoading, isWebAuthnLoading, showWebAuthnButton]);
/**
- * Derive the KEK from the password and open the vault key chain: online through the server, offline through the
- * cached key material.
+ * Derive the KEK from the password and open the vault key chain.
*/
const unlockSubmit = async (e: React.FormEvent): Promise<void> => {
e.preventDefault();
diff --git a/apps/web/src/pages/items/AddEdit.tsx b/apps/web/src/pages/items/AddEdit.tsx
new file mode 100644
index 000000000..e540caeba
--- /dev/null
+++ b/apps/web/src/pages/items/AddEdit.tsx
@@ -0,0 +1,711 @@
+import { fieldAppliesToType, FieldKey, getFieldConfigForType, getOptionalFieldsForItemType, getSystemField, getSystemFieldsForItemType, type ItemType, ItemTypes, SystemFieldRegistry } from '@aliasvault/models/vault';
+import React, { useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useLocation, useNavigate, useParams } from 'react-router-dom';
+
+import AttachmentUploader from '@/components/attachments/AttachmentUploader';
+import DraggableCustomFieldsList from '@/components/forms/DraggableCustomFieldsList';
+import EditFormRow from '@/components/forms/EditFormRow';
+import EditPasswordFormRow from '@/components/forms/EditPasswordFormRow';
+import EditUsernameFormRow from '@/components/forms/EditUsernameFormRow';
+import EmailDomainField from '@/components/forms/EmailDomainField';
+import MultiValueFormRow from '@/components/forms/MultiValueFormRow';
+import RemovableSection from '@/components/forms/RemovableSection';
+import AddFieldMenu from '@/components/items/AddFieldMenu';
+import { buildFolderBreadcrumbs } from '@/components/items/FolderBreadcrumbs';
+import FolderSelector from '@/components/items/FolderSelector';
+import ItemTypeSelector from '@/components/items/ItemTypeSelector';
+import LoadingIndicator from '@/components/loading/LoadingIndicator';
+import type { BreadcrumbItem } from '@/components/shared/Breadcrumb';
+import Button from '@/components/shared/Button';
+import PageContent from '@/components/shared/PageContent';
+import PageHeader from '@/components/shared/PageHeader';
+import StickyActionBar from '@/components/shared/StickyActionBar';
+import TotpCodes from '@/components/totp/TotpCodes';
+import { useDb } from '@/context/DbContext';
+import { useLoading } from '@/context/LoadingContext';
+import { useNotifications } from '@/context/NotificationContext';
+import { useWebApi } from '@/context/WebApiContext';
+import { usePageTitle } from '@/hooks/usePageTitle';
+import { useSaveItem } from '@/hooks/useSaveItem';
+import {
+ addCustomField, createNewItemEdit, DEFAULT_SERVICE_URL, getCustomFields, getFieldValue, getFieldValues, hasAliasValues, hasFieldValue,
+ type ItemEdit, itemEditFromItem, removeCustomField, reorderCustomFields, setFieldValue, setFieldValues, setFolder, updateCustomField,
+} from '@/models/ItemEdit';
+import { generateAliasEmail, generateIdentity, generateRandomEmail, generateUsername, type GeneratedAliasData } from '@/utils/IdentityGenerator';
+import { itemRoute } from '@/utils/ItemRoute';
+
+const MIN_SAVE_INDICATOR_MS = 250;
+
+/**
+ * A card section on the form.
+ */
+const Section: React.FC<{ title?: React.ReactNode; children: React.ReactNode; className?: string }> = ({ title, children, className = '' }) => (
+ <div className={`p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm 2xl:col-span-2 dark:border-gray-700 sm:p-6 dark:bg-gray-800 ${className}`}>
+ {title && <h3 className="mb-4 text-xl font-semibold dark:text-white flex items-center gap-2">{title}</h3>}
+ <div className="grid gap-6">
+ {children}
+ </div>
+ </div>
+);
+
+/**
+ * The passkey key icon.
+ */
+const PasskeyIcon: React.FC<{ className: string }> = ({ className }) => (
+ <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
+ <path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4" />
+ </svg>
+);
+
+/**
+ * The item create and edit page.
+ */
+const ItemAddEdit: React.FC = () => {
+ const { manifestId, id } = useParams<{ manifestId: string; id: string }>();
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const location = useLocation();
+ const dbContext = useDb();
+ const notifications = useNotifications();
+ const { showLoading, hideLoading } = useLoading();
+ const { saveItem } = useSaveItem();
+ const webApi = useWebApi();
+ const editMode = id !== undefined;
+ const tk = 'pages.main.items.addEdit';
+ usePageTitle(editMode ? t(`${tk}.EditItemTitle`) : t(`${tk}.AddItemTitle`));
+
+ const [loading, setLoading] = useState(true);
+ const [edit, setEdit] = useState<ItemEdit>(() => ({ Id: '', ManifestId: '', ItemType: ItemTypes.Login, ServiceName: '', FolderId: null, CreatedAt: '', Fields: [], Attachments: [], TotpCodes: [], Passkeys: [] }));
+ const [isPasswordVisible, setIsPasswordVisible] = useState(false);
+ const [passkeyMarkedForDeletion, setPasskeyMarkedForDeletion] = useState(false);
+ const [showTypeDropdown, setShowTypeDropdown] = useState(false);
+ const [show2FA, setShow2FA] = useState(false);
+ const [showAttachments, setShowAttachments] = useState(false);
+ const [manuallyAddedFields, setManuallyAddedFields] = useState<Set<string>>(new Set());
+ const [initiallyVisibleFields, setInitiallyVisibleFields] = useState<Set<string>>(new Set());
+ const [breadcrumbItems, setBreadcrumbItems] = useState<BreadcrumbItem[]>([]);
+ const [nameError, setNameError] = useState('');
+ const [isSaving, setIsSaving] = useState(false);
+ const originalTotpCodeIds = useRef<string[]>([]);
+ const originalAttachmentIds = useRef<string[]>([]);
+ const lastGenerated = useRef<GeneratedAliasData | null>(null);
+
+ /**
+ * Apply a change to the form.
+ */
+ const update = useCallback((updater: (current: ItemEdit) => ItemEdit): void => setEdit(current => updater(current)), []);
+
+ /**
+ * Fill the alias fields with a random identity. Username, password and email are only replaced when empty or
+ * still the last generated value, so manual entries survive a regenerate.
+ */
+ const generateRandomAlias = useCallback(async (current: ItemEdit): Promise<ItemEdit> => {
+ const client = dbContext.sqliteClient;
+ const generated = client ? await generateIdentity(client, webApi) : null;
+ if (!generated) {
+ return current;
+ }
+ const currentUsername = getFieldValue(current, FieldKey.LoginUsername);
+ const currentPassword = getFieldValue(current, FieldKey.LoginPassword);
+ const currentEmail = getFieldValue(current, FieldKey.LoginEmail);
+ const previous = lastGenerated.current;
+ lastGenerated.current = generated;
+
+ let next = current;
+ next = setFieldValue(next, FieldKey.AliasFirstName, generated.firstName);
+ next = setFieldValue(next, FieldKey.AliasLastName, generated.lastName);
+ next = setFieldValue(next, FieldKey.AliasGender, generated.gender);
+ next = setFieldValue(next, FieldKey.AliasBirthdate, generated.birthdate);
+ if (currentUsername.trim().length === 0 || currentUsername === previous?.username) {
+ next = setFieldValue(next, FieldKey.LoginUsername, generated.username);
+ }
+ if (currentPassword.trim().length === 0 || currentPassword === previous?.password) {
+ next = setFieldValue(next, FieldKey.LoginPassword, generated.password);
+ setIsPasswordVisible(true);
+ }
+ if (currentEmail.trim().length === 0 || currentEmail === previous?.email || currentEmail.startsWith('@')) {
+ next = setFieldValue(next, FieldKey.LoginEmail, generated.email);
+ }
+ return next;
+ }, [dbContext.sqliteClient, webApi]);
+
+ /**
+ * Switch the item type, dropping the fields that do not apply to the new type.
+ */
+ const handleItemTypeChange = useCallback(async (current: ItemEdit, newType: ItemType): Promise<ItemEdit> => {
+ if (current.ItemType === newType) {
+ return current;
+ }
+ let next: ItemEdit = { ...current, ItemType: newType };
+ for (const definition of Object.values(SystemFieldRegistry)) {
+ if (!fieldAppliesToType(definition, newType)) {
+ next = setFieldValue(next, definition.FieldKey, '');
+ }
+ }
+ /**
+ * Whether a field key applies to the new type.
+ */
+ const applies = (fieldKey: string): boolean => {
+ const definition = getSystemField(fieldKey);
+ return !definition || fieldAppliesToType(definition, newType);
+ };
+ setManuallyAddedFields(prev => new Set([...prev].filter(applies)));
+ setInitiallyVisibleFields(prev => new Set([...prev].filter(applies)));
+
+ if (newType === ItemTypes.Alias && !editMode && !hasAliasValues(next)) {
+ next = await generateRandomAlias(next);
+ }
+ return next;
+ }, [editMode, generateRandomAlias]);
+
+ // Load the item (edit) or prefill the form from the quick create widget's query (create).
+ useEffect(() => {
+ const client = dbContext.sqliteClient;
+ if (!client) {
+ return;
+ }
+ let cancelled = false;
+
+ /**
+ * Set up the form.
+ */
+ const initialize = async (): Promise<void> => {
+ setLoading(true);
+ setManuallyAddedFields(new Set());
+ setInitiallyVisibleFields(new Set());
+ setPasskeyMarkedForDeletion(false);
+ setNameError('');
+ const allFolders = client.folders.getAll();
+
+ if (editMode) {
+ if (!manifestId) {
+ return;
+ }
+ const ref = { Id: id, ManifestId: manifestId };
+ const item = client.items.getById(ref);
+ if (!item) {
+ notifications.addErrorMessage(t(`${tk}.ItemNotExistError`));
+ navigate('/items', { replace: true });
+ return;
+ }
+ const totpCodes = client.items.getTotpCodesForItem(ref);
+ const attachments = client.items.getAttachmentsForItem(ref);
+ const passkeys = client.passkeys.getByItemId(ref);
+ let loaded = itemEditFromItem(item, totpCodes, attachments, passkeys);
+ originalTotpCodeIds.current = loaded.TotpCodes.map(c => c.Id);
+ originalAttachmentIds.current = loaded.Attachments.map(a => a.Id);
+ setInitiallyVisibleFields(new Set(getSystemFieldsForItemType(loaded.ItemType).filter(f => hasFieldValue(loaded, f.FieldKey)).map(f => f.FieldKey)));
+ setShow2FA(loaded.TotpCodes.length > 0);
+ setShowAttachments(loaded.Attachments.length > 0);
+ if (!hasFieldValue(loaded, FieldKey.LoginUrl)) {
+ loaded = setFieldValue(loaded, FieldKey.LoginUrl, DEFAULT_SERVICE_URL);
+ }
+ const crumbs = loaded.FolderId ? buildFolderBreadcrumbs({ Id: loaded.FolderId, ManifestId: loaded.ManifestId }, allFolders) : [];
+ crumbs.push({ displayName: t(`${tk}.ViewItemBreadcrumb`), url: itemRoute(ref) });
+ crumbs.push({ displayName: t(`${tk}.EditItemBreadcrumb`) });
+ if (!cancelled) {
+ setEdit(loaded);
+ setBreadcrumbItems(crumbs);
+ setLoading(false);
+ }
+ return;
+ }
+
+ const params = new URLSearchParams(location.search);
+ const folderId = params.get('folderId');
+ const folderManifestId = params.get('folderManifestId');
+ const folder = folderId && folderManifestId ? allFolders.find(f => f.Id === folderId && f.ManifestId === folderManifestId) ?? null : null;
+ let created = createNewItemEdit(folder, client.getPersonalManifestId());
+ const name = params.get('name');
+ const url = params.get('url');
+ const type = params.get('type');
+ if (name) {
+ created = { ...created, ServiceName: name };
+ }
+ if (url) {
+ created = setFieldValue(created, FieldKey.LoginUrl, url);
+ }
+ if (type && Object.values(ItemTypes).includes(type as ItemType)) {
+ created = await handleItemTypeChange(created, type as ItemType);
+ }
+ originalTotpCodeIds.current = [];
+ originalAttachmentIds.current = [];
+ setShow2FA(false);
+ setShowAttachments(false);
+ const crumbs = folder ? buildFolderBreadcrumbs(folder, allFolders) : [];
+ crumbs.push({ displayName: t(`${tk}.AddNewItemBreadcrumb`) });
+ if (!cancelled) {
+ setEdit(created);
+ setBreadcrumbItems(crumbs);
+ setLoading(false);
+ setTimeout(() => document.getElementById('service-name')?.focus(), 50);
+ }
+ };
+
+ void initialize();
+ return (): void => {
+ cancelled = true;
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dbContext.sqliteClient, editMode, manifestId, id, location.search]);
+
+ const hasLoginFields = edit.ItemType === ItemTypes.Login || edit.ItemType === ItemTypes.Alias;
+
+ /**
+ * Whether a system field is on the form: it applies to the type and was added, was there on load, has a value or
+ * shows by default.
+ */
+ const shouldShowField = (fieldKey: string): boolean => {
+ const definition = getSystemField(fieldKey);
+ if (!definition || !fieldAppliesToType(definition, edit.ItemType)) {
+ return false;
+ }
+ if (manuallyAddedFields.has(fieldKey) || initiallyVisibleFields.has(fieldKey) || hasFieldValue(edit, fieldKey)) {
+ return true;
+ }
+ return getFieldConfigForType(definition, edit.ItemType)?.ShowByDefault ?? false;
+ };
+
+ /**
+ * Whether a field is optional for the type and can be removed.
+ */
+ const canRemoveField = (fieldKey: string): boolean => {
+ const definition = getSystemField(fieldKey);
+ const config = definition ? getFieldConfigForType(definition, edit.ItemType) : undefined;
+ return config !== undefined && !config.ShowByDefault;
+ };
+
+ const visibleFieldKeys = new Set(getSystemFieldsForItemType(edit.ItemType).filter(f => shouldShowField(f.FieldKey)).map(f => f.FieldKey));
+
+ /**
+ * Show an optional field.
+ */
+ const addOptionalField = (fieldKey: string): void => setManuallyAddedFields(prev => new Set([...prev, fieldKey]));
+
+ /**
+ * Hide an optional field and clear it.
+ */
+ const removeOptionalField = (fieldKey: string): void => {
+ setManuallyAddedFields(prev => new Set([...prev].filter(k => k !== fieldKey)));
+ setInitiallyVisibleFields(prev => new Set([...prev].filter(k => k !== fieldKey)));
+ update(current => setFieldValue(current, fieldKey, ''));
+ };
+
+ /**
+ * Show the 2FA section, restoring codes removed with it.
+ */
+ const add2FASection = (): void => {
+ setShow2FA(true);
+ update(current => ({ ...current, TotpCodes: current.TotpCodes.map(c => c.IsDeleted ? { ...c, IsDeleted: false } : c) }));
+ };
+
+ /**
+ * Hide the 2FA section: existing codes are soft deleted, new ones dropped.
+ */
+ const remove2FASection = (): void => {
+ setShow2FA(false);
+ update(current => ({ ...current, TotpCodes: current.TotpCodes.filter(c => originalTotpCodeIds.current.includes(c.Id)).map(c => ({ ...c, IsDeleted: true })) }));
+ };
+
+ /**
+ * Show the attachments section, restoring attachments removed with it.
+ */
+ const addAttachmentsSection = (): void => {
+ setShowAttachments(true);
+ update(current => ({ ...current, Attachments: current.Attachments.map(a => a.IsDeleted ? { ...a, IsDeleted: false } : a) }));
+ };
+
+ /**
+ * Hide the attachments section: existing attachments are soft deleted, new ones dropped.
+ */
+ const removeAttachmentsSection = (): void => {
+ setShowAttachments(false);
+ update(current => ({ ...current, Attachments: current.Attachments.filter(a => originalAttachmentIds.current.includes(a.Id)).map(a => ({ ...a, IsDeleted: true })) }));
+ };
+
+ /**
+ * Put the cursor after the URL placeholder when the field still holds it.
+ */
+ const onFocusUrlInput = (index: number, event: React.FocusEvent<HTMLInputElement>): void => {
+ if (getFieldValues(edit, FieldKey.LoginUrl)[index] !== DEFAULT_SERVICE_URL) {
+ return;
+ }
+ const input = event.target;
+ setTimeout(() => input.setSelectionRange(DEFAULT_SERVICE_URL.length, DEFAULT_SERVICE_URL.length), 1);
+ };
+
+ /**
+ * Regenerate the alias identity.
+ */
+ const onGenerateRandomAlias = async (): Promise<void> => setEdit(await generateRandomAlias(edit));
+
+ /**
+ * Regenerate the username.
+ */
+ const onGenerateUsername = async (): Promise<void> => {
+ if (!dbContext.sqliteClient) {
+ return;
+ }
+ const username = await generateUsername(dbContext.sqliteClient, edit);
+ update(current => setFieldValue(current, FieldKey.LoginUsername, username));
+ };
+
+ /**
+ * Regenerate the email address, from the identity for an alias and at random for a login.
+ */
+ const onGenerateEmail = async (): Promise<void> => {
+ if (!dbContext.sqliteClient) {
+ return;
+ }
+ const email = edit.ItemType === ItemTypes.Alias ? await generateAliasEmail(dbContext.sqliteClient, edit) : await generateRandomEmail(dbContext.sqliteClient);
+ update(current => setFieldValue(current, FieldKey.LoginEmail, email));
+ };
+
+ /**
+ * Save the item and go to its page.
+ */
+ const save = async (): Promise<void> => {
+ if (isSaving) {
+ return;
+ }
+ if (edit.ServiceName.trim().length === 0) {
+ setNameError(t('validationMessages.ServiceNameRequired'));
+ return;
+ }
+ setNameError('');
+ setIsSaving(true);
+ showLoading(t(`${tk}.SavingVaultMessage`));
+ const startedAt = Date.now();
+ try {
+ const saved = await saveItem(edit, { original: editMode && manifestId ? { Id: edit.Id, ManifestId: manifestId } : undefined, originalAttachmentIds: originalAttachmentIds.current, originalTotpCodeIds: originalTotpCodeIds.current, deletePasskeys: passkeyMarkedForDeletion });
+ // Keep the saving indicator up for a moment: a save that completes instantly reads as a flicker.
+ await new Promise(resolve => setTimeout(resolve, Math.max(0, MIN_SAVE_INDICATOR_MS - (Date.now() - startedAt))));
+ notifications.addSuccessMessage(editMode ? t(`${tk}.ItemUpdatedSuccess`) : t(`${tk}.ItemCreatedSuccess`));
+ navigate(itemRoute(saved));
+ } catch (error) {
+ console.error('Error saving item:', error);
+ notifications.addErrorMessage(t(`${tk}.ErrorSavingItem`), true);
+ } finally {
+ hideLoading();
+ setIsSaving(false);
+ }
+ };
+
+ /**
+ * Leave without saving.
+ */
+ const cancel = (): void => {
+ navigate(editMode && manifestId ? itemRoute({ Id: id, ManifestId: manifestId }) : '/items/');
+ };
+
+ const customFields = getCustomFields(edit);
+ const passkey = editMode ? edit.Passkeys[0] : undefined;
+ const optionalSystemFields = getOptionalFieldsForItemType(edit.ItemType);
+
+ const addFieldMenu = (
+ <AddFieldMenu
+ optionalSystemFields={optionalSystemFields}
+ visibleFieldKeys={visibleFieldKeys}
+ show2FA={show2FA}
+ showAttachments={showAttachments}
+ hasLoginFields={hasLoginFields}
+ customFieldCount={customFields.length}
+ onAddSystemField={addOptionalField}
+ onAddCustomField={(label, fieldType) => update(current => addCustomField(current, label, fieldType))}
+ onAdd2FA={add2FASection}
+ onAddAttachments={addAttachmentsSection}
+ />
+ );
+
+ const emailField = (
+ <EmailDomainField
+ id="email"
+ value={getFieldValue(edit, FieldKey.LoginEmail)}
+ onChange={value => update(current => setFieldValue(current, FieldKey.LoginEmail, value))}
+ defaultToEmailMode={edit.ItemType === ItemTypes.Login}
+ onRemove={!passkey && canRemoveField(FieldKey.LoginEmail) ? (): void => removeOptionalField(FieldKey.LoginEmail) : undefined}
+ onGenerateAlias={() => void onGenerateEmail()}
+ />
+ );
+
+ const usernameField = (
+ <EditUsernameFormRow id="username" label={t(`${tk}.UsernameLabel`)} value={getFieldValue(edit, FieldKey.LoginUsername)} onChange={value => update(current => setFieldValue(current, FieldKey.LoginUsername, value))} onGenerateNewUsername={() => void onGenerateUsername()} />
+ );
+
+ const passwordField = (
+ <EditPasswordFormRow id="password" label={t(`${tk}.PasswordLabel`)} value={getFieldValue(edit, FieldKey.LoginPassword)} onChange={value => update(current => setFieldValue(current, FieldKey.LoginPassword, value))} showPassword={isPasswordVisible} />
+ );
+
+ /**
+ * A plain text field bound to a system field.
+ */
+ const textField = (fieldKey: string, inputId: string, label: string, placeholder: string = ''): React.ReactNode => (
+ <EditFormRow id={inputId} label={label} placeholder={placeholder} value={getFieldValue(edit, fieldKey)} onChange={value => update(current => setFieldValue(current, fieldKey, value))} />
+ );
+
+ /**
+ * A masked field bound to a system field.
+ */
+ const secretField = (fieldKey: string, inputId: string, label: string): React.ReactNode => (
+ <EditPasswordFormRow id={inputId} label={label} value={getFieldValue(edit, fieldKey)} onChange={value => update(current => setFieldValue(current, fieldKey, value))} showPassword={false} showGenerateButtons={false} />
+ );
+
+ return (
+ <>
+ <PageHeader
+ breadcrumbItems={breadcrumbItems}
+ title={editMode ? t(`${tk}.EditItemTitle`) : t(`${tk}.AddItemTitle`)}
+ description={editMode ? t(`${tk}.EditItemDescription`) : t(`${tk}.AddItemDescription`)}
+ customActions={(
+ <>
+ <Button color="success" onClick={() => void save()}>{t(`${tk}.SaveItemButton`)}</Button>
+ <Button color="danger" onClick={cancel}>{t('sharedResources.Cancel')}</Button>
+ </>
+ )}
+ />
+
+ {loading ? <LoadingIndicator /> : (
+ <PageContent>
+ <form onSubmit={(e) => {
+ e.preventDefault();
+ void save();
+ }}>
+ <div className="grid grid-cols-1 px-4 pt-6 md:grid-cols-2 lg:grid-cols-3 md:gap-4 dark:bg-gray-900">
+ <div className="col-span-1 md:col-span-1 lg:col-span-1">
+ <ItemTypeSelector selectedType={edit.ItemType} onSelectedTypeChange={(type) => {
+ void handleItemTypeChange(edit, type).then(setEdit);
+ }} showDropdown={showTypeDropdown} onShowDropdownChange={setShowTypeDropdown} />
+
+ <div className="p-4 mb-4 bg-white border-2 border-primary-600 rounded-lg shadow-sm 2xl:col-span-2 dark:border-gray-700 sm:p-6 dark:bg-gray-800">
+ <h3 className="mb-4 text-xl font-semibold dark:text-white">{t(`${tk}.ServiceSectionHeader`)}</h3>
+ <div className="grid gap-6">
+ <div className="col-span-6 sm:col-span-3">
+ <EditFormRow id="service-name" label={t(`${tk}.ServiceNameLabel`)} placeholder={t(`${tk}.ServiceNamePlaceholder`)} value={edit.ServiceName} onChange={(value) => {
+ setNameError('');
+ update(current => ({ ...current, ServiceName: value }));
+ }} />
+ {nameError.length > 0 && <div className="validation-message text-red-600 dark:text-red-400 text-sm mt-1">{nameError}</div>}
+ <FolderSelector selectedFolder={edit.FolderId ? { Id: edit.FolderId, ManifestId: edit.ManifestId } : null} onSelectedFolderChange={folder => update(current => setFolder(current, folder, dbContext.sqliteClient?.getPersonalManifestId() ?? null))} />
+ </div>
+ {shouldShowField(FieldKey.LoginUrl) && (
+ <div className="col-span-6 sm:col-span-3">
+ <MultiValueFormRow id="service-url" label={t(`${tk}.ServiceUrlLabel`)} values={getFieldValues(edit, FieldKey.LoginUrl)} onChange={values => update(current => setFieldValues(current, FieldKey.LoginUrl, values))} onFocus={onFocusUrlInput} />
+ </div>
+ )}
+ </div>
+ </div>
+
+ {show2FA && hasLoginFields && (
+ <div className="col-span-1 md:col-span-1 lg:col-span-1">
+ <TotpCodes
+ totpCodes={edit.TotpCodes}
+ onTotpCodesChange={totpCodes => update(current => ({ ...current, TotpCodes: totpCodes }))}
+ canRemove={!edit.TotpCodes.some(c => !c.IsDeleted)}
+ onRemove={remove2FASection}
+ itemDisplayName={edit.ServiceName}
+ itemUsername={getFieldValue(edit, FieldKey.LoginUsername) || getFieldValue(edit, FieldKey.LoginEmail)}
+ />
+ </div>
+ )}
+
+ {shouldShowField(FieldKey.NotesContent) && edit.ItemType !== ItemTypes.Note && (
+ <div className="col-span-1 md:col-span-1 lg:col-span-1">
+ <RemovableSection canRemove={canRemoveField(FieldKey.NotesContent)} onRemove={() => removeOptionalField(FieldKey.NotesContent)}>
+ <div className="col-span-6 sm:col-span-3">
+ <EditFormRow type="textarea" id="notes" label={t(`${tk}.NotesLabel`)} labelStyle="header" value={getFieldValue(edit, FieldKey.NotesContent)} onChange={value => update(current => setFieldValue(current, FieldKey.NotesContent, value))} />
+ </div>
+ </RemovableSection>
+ </div>
+ )}
+
+ {showAttachments && (
+ <div className="col-span-1 md:col-span-1 lg:col-span-1">
+ <RemovableSection title={t(`${tk}.AttachmentsSectionHeader`)} canRemove onRemove={removeAttachmentsSection}>
+ <div className="col-span-6 sm:col-span-3">
+ <AttachmentUploader attachments={edit.Attachments} onAttachmentsChange={attachments => update(current => ({ ...current, Attachments: attachments }))} />
+ </div>
+ </RemovableSection>
+ </div>
+ )}
+
+ <div className="hidden lg:block mb-4">{addFieldMenu}</div>
+ </div>
+
+ <div className="col-span-1 md:col-span-1 lg:col-span-2">
+ {hasLoginFields && (
+ <Section className="overflow-visible" title={(
+ <>
+ <span>{t(`${tk}.LoginDetailsSectionHeader`)}</span>
+ {edit.ItemType === ItemTypes.Login && !shouldShowField(FieldKey.LoginEmail) && (
+ <button type="button" onClick={() => addOptionalField(FieldKey.LoginEmail)} className="inline-flex items-center gap-1 px-2 py-0.5 text-xs rounded-full transition-colors focus:outline-none text-gray-500 dark:text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 border border-dashed border-gray-300 dark:border-gray-600 hover:border-primary-400 dark:hover:border-primary-500">
+ <svg className="w-2.5 h-2.5 -ml-0.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
+ <line x1="12" y1="5" x2="12" y2="19" />
+ <line x1="5" y1="12" x2="19" y2="12" />
+ </svg>
+ <span>{t('sharedResources.Email')}</span>
+ </button>
+ )}
+ </>
+ )}>
+ {passkey ? (
+ <>
+ <div className="col-span-6">{usernameField}</div>
+ {!passkeyMarkedForDeletion ? (
+ <div className="col-span-6">
+ <div className="p-3 rounded-lg bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700">
+ <div className="flex items-start gap-3">
+ <PasskeyIcon className="w-5 h-5 text-gray-600 dark:text-gray-400 mt-0.5 flex-shrink-0" />
+ <div className="flex-1">
+ <div className="mb-1 flex items-center justify-between">
+ <span className="text-sm font-semibold text-gray-900 dark:text-white">{t(`${tk}.PasskeyLabel`)}</span>
+ <button type="button" onClick={() => setPasskeyMarkedForDeletion(true)} className="text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300" title={t(`${tk}.DeletePasskeyButton`)}>
+ <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
+ <polyline points="3 6 5 6 21 6" />
+ <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
+ <line x1="10" y1="11" x2="10" y2="17" />
+ <line x1="14" y1="11" x2="14" y2="17" />
+ </svg>
+ </button>
+ </div>
+ <div className="space-y-1 mb-2">
+ {passkey.RpId.trim().length > 0 && (
+ <div>
+ <span className="text-xs text-gray-500 dark:text-gray-400">{t(`${tk}.PasskeySiteLabel`)}: </span>
+ <span className="text-sm text-gray-900 dark:text-white">{passkey.RpId}</span>
+ </div>
+ )}
+ {(passkey.DisplayName ?? '').trim().length > 0 && (
+ <div>
+ <span className="text-xs text-gray-500 dark:text-gray-400">{t(`${tk}.PasskeyDisplayNameLabel`)}: </span>
+ <span className="text-sm text-gray-900 dark:text-white">{passkey.DisplayName}</span>
+ </div>
+ )}
+ </div>
+ <p className="text-xs text-gray-600 dark:text-gray-400">{t(`${tk}.PasskeyHelpText`)}</p>
+ </div>
+ </div>
+ </div>
+ </div>
+ ) : (
+ <div className="col-span-6">
+ <div className="p-3 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800">
+ <div className="flex items-start gap-3">
+ <PasskeyIcon className="w-5 h-5 text-red-600 dark:text-red-400 mt-0.5 flex-shrink-0" />
+ <div className="flex-1">
+ <div className="mb-1 flex items-center justify-between">
+ <span className="text-sm font-semibold text-red-900 dark:text-red-100">{t(`${tk}.PasskeyMarkedForDeletion`)}</span>
+ <button type="button" onClick={() => setPasskeyMarkedForDeletion(false)} className="text-gray-600 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300" title={t(`${tk}.UndoButton`)}>
+ <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
+ <path d="M3 7v6h6" />
+ <path d="M21 17a9 9 0 00-9-9 9 9 0 00-6 2.3L3 13" />
+ </svg>
+ </button>
+ </div>
+ <p className="text-xs text-red-800 dark:text-red-200">{t(`${tk}.PasskeyWillBeDeleted`)}</p>
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+ <div className="col-span-6">{emailField}</div>
+ <div className="col-span-6">{passwordField}</div>
+ </>
+ ) : (
+ <>
+ {shouldShowField(FieldKey.LoginEmail) && <div className="col-span-6">{emailField}</div>}
+ <div className="col-span-6">{usernameField}</div>
+ <div className="col-span-6">{passwordField}</div>
+ </>
+ )}
+ </Section>
+ )}
+
+ {edit.ItemType === ItemTypes.Alias && (
+ <div className="col-span-1 md:col-span-1 lg:col-span-2">
+ <div className="p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm 2xl:col-span-2 dark:border-gray-700 sm:p-6 dark:bg-gray-800">
+ <h3 className="mb-4 text-xl font-semibold dark:text-white flex items-center justify-between gap-2">
+ <span>{t(`${tk}.AliasSectionHeader`)}</span>
+ <button type="button" id="generate-random-alias" onClick={() => void onGenerateRandomAlias()} className="p-1.5 text-gray-400 hover:text-primary-500 transition-colors focus:outline-none" title={t('sharedResources.Generate')}>
+ <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
+ <path d="M23 4v6h-6" />
+ <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10" />
+ </svg>
+ </button>
+ </h3>
+ <div className="grid gap-6">
+ <div className="col-span-6 sm:col-span-3">{textField(FieldKey.AliasFirstName, 'first-name', t(`${tk}.FirstNameLabel`))}</div>
+ <div className="col-span-6 sm:col-span-3">{textField(FieldKey.AliasLastName, 'last-name', t(`${tk}.LastNameLabel`))}</div>
+ <div className="col-span-6 sm:col-span-3">{textField(FieldKey.AliasGender, 'gender', t(`${tk}.GenderLabel`))}</div>
+ <div className="col-span-6 sm:col-span-3">{textField(FieldKey.AliasBirthdate, 'birthdate', t(`${tk}.BirthDateLabel`))}</div>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {edit.ItemType === ItemTypes.CreditCard && (
+ <div className="col-span-1 md:col-span-1 lg:col-span-2">
+ <Section title={t(`${tk}.CardDetailsSectionHeader`)}>
+ <div className="col-span-6">{textField(FieldKey.CardCardholderName, 'cardholder-name', t(`${tk}.CardholderNameLabel`))}</div>
+ <div className="col-span-6">{secretField(FieldKey.CardNumber, 'card-number', t(`${tk}.CardNumberLabel`))}</div>
+ <div className="col-span-3">{textField(FieldKey.CardExpiryMonth, 'expiry-month', t(`${tk}.ExpiryMonthLabel`), 'MM')}</div>
+ <div className="col-span-3">{textField(FieldKey.CardExpiryYear, 'expiry-year', t(`${tk}.ExpiryYearLabel`), 'YYYY')}</div>
+ <div className="col-span-6 sm:col-span-3">{secretField(FieldKey.CardCvv, 'cvv', t(`${tk}.CardCvvLabel`))}</div>
+ {shouldShowField(FieldKey.CardPin) && (
+ <div className="col-span-6 sm:col-span-3 relative">
+ {secretField(FieldKey.CardPin, 'pin', t(`${tk}.CardPinLabel`))}
+ {canRemoveField(FieldKey.CardPin) && (
+ <button type="button" onClick={() => removeOptionalField(FieldKey.CardPin)} className="absolute top-0 right-0 text-gray-400 hover:text-red-500 transition-colors" title={t(`${tk}.RemoveField`)}>
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
+ </svg>
+ </button>
+ )}
+ </div>
+ )}
+ </Section>
+ </div>
+ )}
+
+ {edit.ItemType === ItemTypes.Note && (
+ <div className="col-span-1 md:col-span-1 lg:col-span-2">
+ <Section title={t(`${tk}.NotesLabel`)}>
+ <div className="col-span-6">
+ <EditFormRow type="textarea" id="notes" label="" value={getFieldValue(edit, FieldKey.NotesContent)} onChange={value => update(current => setFieldValue(current, FieldKey.NotesContent, value))} />
+ </div>
+ </Section>
+ </div>
+ )}
+
+ {customFields.length > 0 && (
+ <div className="col-span-1 md:col-span-1 lg:col-span-2">
+ <div className="p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm 2xl:col-span-2 dark:border-gray-700 sm:p-6 dark:bg-gray-800">
+ <h3 className="mb-4 text-xl font-semibold dark:text-white">{t(`${tk}.CustomFieldsSectionHeader`)}</h3>
+ <DraggableCustomFieldsList
+ customFields={customFields}
+ onReorder={reordered => update(current => reorderCustomFields(current, reordered))}
+ onValueChange={(fieldKey, value) => update(current => ({ ...current, Fields: current.Fields.map(f => f.FieldKey === fieldKey ? { ...f, Value: value } : f) }))}
+ onFieldUpdate={(fieldKey, label, fieldType) => update(current => updateCustomField(current, fieldKey, label, fieldType))}
+ onDelete={fieldKey => update(current => removeCustomField(current, fieldKey))}
+ />
+ </div>
+ </div>
+ )}
+
+ <div className="col-span-1 md:col-span-1 lg:col-span-2 mb-4">{addFieldMenu}</div>
+ </div>
+ </div>
+ <button type="submit" className="hidden">{t(`${tk}.SaveItemButton`)}</button>
+ </form>
+
+ <StickyActionBar>
+ <Button color="success" onClick={() => void save()}>{t(`${tk}.SaveItemButton`)}</Button>
+ <Button color="danger" onClick={cancel}>{t('sharedResources.Cancel')}</Button>
+ </StickyActionBar>
+ </PageContent>
+ )}
+ </>
+ );
+};
+
+export default ItemAddEdit;
diff --git a/apps/web/src/pages/items/Home.tsx b/apps/web/src/pages/items/Home.tsx
new file mode 100644
index 000000000..8422359a4
--- /dev/null
+++ b/apps/web/src/pages/items/Home.tsx
@@ -0,0 +1,608 @@
+import { scopedKey } from '@aliasvault/client/database/ItemRef';
+import { CredentialSortOrder } from '@aliasvault/client/database/repositories/SettingsRepository';
+import { canHaveSubfolders, getDescendantFolderIds, getFolderPath, isItemInFolder } from '@aliasvault/client/items/FolderUtils';
+import { ItemFilter, applyTypeFilter, type ItemFilterType, parseItemFilterType } from '@aliasvault/client/items/ItemFilters';
+import { multiManifestRendering } from '@aliasvault/client/sharing/MultiManifestRendering';
+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Link, 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 PageContent from '@/components/shared/PageContent';
+import PageHeader from '@/components/shared/PageHeader';
+import RefreshButton from '@/components/shared/RefreshButton';
+import type { SortDirection } from '@/components/shared/SortableTable';
+import { useDb } from '@/context/DbContext';
+import { useNotifications } from '@/context/NotificationContext';
+import { useClickOutside } from '@/hooks/useClickOutside';
+import { usePageTitle } from '@/hooks/usePageTitle';
+import { useVaultMutate } from '@/hooks/useVaultMutate';
+import { useVaultSync } from '@/hooks/useVaultSync';
+import { folderRoute } from '@/utils/ItemRoute';
+import { getLocalPreferenceJson, setLocalPreferenceJson } from '@/utils/LocalPreferences';
+import { LocalPreferenceKeys } from '@/utils/StorageKeys';
+
+import type { Folder, FolderRef } from '@aliasvault/client/database/repositories/FolderRepository';
+import type { Item } from '@aliasvault/models/vault';
+
+/** 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 navigate = useNavigate();
+ const { manifestId: manifestIdParam, folderId: folderIdParam } = useParams<{ manifestId?: string; folderId?: string }>();
+ const [searchParams] = useSearchParams();
+ const dbContext = useDb();
+ const notifications = useNotifications();
+ const { syncVault } = useVaultSync();
+ const { executeVaultMutationAsync } = 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);
+ 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();
+ 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('pages.main.items.home.FailedToLoadItemsMessage'), true);
+ } finally {
+ setIsLoading(false);
+ }
+ }, [dbContext.sqliteClient, 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 executeVaultMutationAsync(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 executeVaultMutationAsync(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 not editable or deletable here.
+ const currentFolderIsVirtual = currentFolder !== null && multiManifestRendering.isVirtualFolder(currentFolder);
+
+ /**
+ * 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);
+
+ /**
+ * Folders at the current level with their (recursive) filtered item counts.
+ */
+ const currentLevelFolders = useMemo((): FolderWithCount[] => {
+ 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,
+ };
+ });
+ }, [allFolders, folderRef, items, filterType]);
+
+ 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('pages.main.items.home.FilterPasskeysOption');
+ case ItemFilter.Attachments: return t('pages.main.items.home.FilterAttachmentsOption');
+ case ItemFilter.Totp: return t('pages.main.items.home.FilterTotpOption');
+ case ItemFilter.Login: return t('components.main.items.itemTypeSelector.TypeLogin');
+ case ItemFilter.Alias: return t('components.main.items.itemTypeSelector.TypeAlias');
+ case ItemFilter.CreditCard: return t('components.main.items.itemTypeSelector.TypeCreditCard');
+ case ItemFilter.Note: return t('components.main.items.itemTypeSelector.TypeNote');
+ default:
+ return isInFolder && currentFolderName ? currentFolderName : t('pages.main.items.home.PageTitle');
+ }
+ };
+
+ /**
+ * 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-orange-600 dark:hover:text-orange-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-orange-400 dark:hover:border-orange-500 hover:text-orange-600 dark:hover:text-orange-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);
+ };
+
+ /**
+ * Pull the latest vault from the server, then reload the list.
+ */
+ const refreshVault = async (): Promise<void> => {
+ await syncVault({ onSuccess: 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);
+ notifications.addErrorMessage(t('pages.main.items.home.FailedToCreateFolder'), true);
+ }
+ };
+
+ /**
+ * Rename the current folder.
+ */
+ const editFolder = async (name: string): Promise<void> => {
+ const client = dbContext.sqliteClient;
+ if (!client || !folderRef) {
+ return;
+ }
+ try {
+ await executeVaultMutationAsync(async () => {
+ await client.folders.update(folderRef, name);
+ });
+ setAllFolders(client.folders.getAll());
+ } catch (error) {
+ console.error('Failed to rename folder:', error);
+ notifications.addErrorMessage(t('sharedResources.ErrorGeneric'), true);
+ }
+ };
+
+ /**
+ * 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);
+ notifications.addErrorMessage(t('pages.main.items.home.FailedToDeleteFolder'), true);
+ }
+ };
+
+ const selectClass = 'bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500';
+
+ return (
+ <>
+ <PageHeader
+ breadcrumbItems={breadcrumbItems}
+ title={getFilterTitle()}
+ description={t('pages.main.items.home.PageDescription')}
+ titleActions={(
+ <ItemFilterDropdown
+ title={getFilterTitle()}
+ count={totalFilteredItems}
+ activeFilter={filterType}
+ recentlyDeletedCount={recentlyDeletedCount}
+ showFoldersToggle={!isInFolder}
+ showFolders={showFolders}
+ onSelectFilter={setFilter}
+ onSelectRecentlyDeleted={() => navigate('/items/recently-deleted')}
+ onToggleShowFolders={toggleShowFolders}
+ titleActions={isInFolder && !currentFolderIsVirtual ? (
+ <>
+ <button onClick={() => setShowEditFolderModal(true)} title={t('pages.main.items.home.EditFolder')} className="p-1.5 text-gray-400 hover:text-orange-500 dark:text-gray-500 dark:hover:text-orange-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors">
+ <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
+ </svg>
+ </button>
+ <button onClick={() => setShowDeleteFolderModal(true)} title={t('pages.main.items.home.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">
+ <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <polyline points="3 6 5 6 21 6" />
+ <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
+ </svg>
+ </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">
+ <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
+ <path fillRule="evenodd" d="M11.49 3.17c-.38-1.56-2.6-1.56-2.98 0a1.532 1.532 0 01-2.286.948c-1.372-.836-2.942.734-2.106 2.106.54.886.061 2.042-.947 2.287-1.561.379-1.561 2.6 0 2.978a1.532 1.532 0 01.947 2.287c-.836 1.372.734 2.942 2.106 2.106a1.532 1.532 0 012.287.947c.379 1.561 2.6 1.561 2.978 0a1.533 1.533 0 012.287-.947c1.372.836 2.942-.734 2.106-2.106a1.533 1.533 0 01.947-2.287c1.561-.379 1.561-2.6 0-2.978a1.532 1.532 0 01-.947-2.287c.836-1.372-.734-2.942-2.106-2.106a1.532 1.532 0 01-2.287-.947zM10 13a3 3 0 100-6 3 3 0 000 6z" clipRule="evenodd"></path>
+ </svg>
+ </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">
+ <label className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">{t('pages.main.items.home.ViewModeLabel')}</label>
+ <select value={viewMode} onChange={(e) => {
+ setViewMode(e.target.value as ViewMode); closeSettingsPopup();
+ }} className={selectClass}>
+ <option value="grid">{t('pages.main.items.home.GridViewOption')}</option>
+ <option value="table">{t('pages.main.items.home.TableViewOption')}</option>
+ </select>
+ </div>
+ <div className="mb-4">
+ <label className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">{t('pages.main.items.home.SortOrderLabel')}</label>
+ <select value={sortOrder} onChange={(e) => {
+ setSortOrder(e.target.value as CredentialSortOrder); closeSettingsPopup();
+ }} className={selectClass}>
+ <option value={CredentialSortOrder.OldestFirst}>{t('pages.main.items.home.OldestFirstOption')}</option>
+ <option value={CredentialSortOrder.NewestFirst}>{t('pages.main.items.home.NewestFirstOption')}</option>
+ <option value={CredentialSortOrder.Alphabetical}>{t('pages.main.items.home.AlphabeticalOption')}</option>
+ </select>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ <RefreshButton onClick={refreshVault} buttonText={t('sharedResources.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('pages.main.items.home.FilteringBy')}</span>
+ <button onClick={() => setFilter(ItemFilter.All)} className="inline-flex items-center gap-1 px-3 py-1.5 text-sm bg-orange-100 dark:bg-orange-900/30 hover:bg-orange-200 dark:hover:bg-orange-900/50 text-orange-700 dark:text-orange-300 rounded-lg transition-colors">
+ <span>{getFilterTitle()}</span>
+ <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
+ <line x1="18" y1="6" x2="6" y2="18" />
+ <line x1="6" y1="6" x2="18" y2="18" />
+ </svg>
+ </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));
+ }} />
+ ))}
+ {canCreateSubfolder && (
+ <button onClick={() => setShowFolderModal(true)} className={getAddFolderButtonClass()}>
+ <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
+ <path strokeLinecap="round" strokeLinejoin="round" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
+ </svg>
+ <svg className="w-3.5 h-3.5 -ml-0.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
+ <line x1="12" y1="5" x2="12" y2="19" />
+ <line x1="5" y1="12" x2="19" y2="12" />
+ </svg>
+ {currentLevelFolders.length === 0 && <span>{t('pages.main.items.home.NewFolder')}</span>}
+ </button>
+ )}
+ </div>
+ )}
+
+ {viewMode === 'table' ? (
+ <ItemsTable entries={filteredAndSortedItems} sortColumn={tableSortColumn} sortDirection={tableSortDirection} onTableSortChanged={handleTableSortChanged} onMutated={loadItems} />
+ ) : (
+ <div className="grid gap-4 md:grid-cols-4 xl:grid-cols-6">
+ {items.length === 0 && !isInFolder ? (
+ <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('pages.main.items.home.NoItemsTitle')}</p>
+ <div className="max-w-md mx-auto">
+ <div className="mb-6">
+ <p className="text-sm mb-2">{t('pages.main.items.home.CreateFirstItemText')} <span className="hidden md:inline">{t('pages.main.items.home.NewAliasButtonText')}</span><span className="md:hidden">{t('pages.main.items.home.NewAliasButtonTextMobile')}</span> {t('pages.main.items.home.ButtonLocationText')}</p>
+ </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('pages.main.items.home.OrText')}</span>
+ <div className="flex-1 h-px bg-gray-300 dark:bg-gray-600"></div>
+ </div>
+ <div>
+ <p className="text-sm mb-2">{t('pages.main.items.home.ImportItemsText')}</p>
+ <Link to="/settings/import-export" className="inline-block text-sm px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors dark:bg-primary-700 dark:hover:bg-primary-600">
+ {t('pages.main.items.home.ImportButtonText')}
+ </Link>
+ </div>
+ </div>
+ </div>
+ </div>
+ ) : 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-gray-700 dark:text-gray-200 rounded text-center">
+ {filterType !== ItemFilter.All ? (
+ <p>{t('pages.main.items.home.NoItemsFound')}</p>
+ ) : isInFolder ? (
+ <p>{t('pages.main.items.home.EmptyFolderMessage')}</p>
+ ) : hasItemsInFoldersOnly ? (
+ <p>{t('pages.main.items.home.AllItemsInFoldersMessage')}</p>
+ ) : (
+ <p>{t('pages.main.items.home.NoItemsFound')}</p>
+ )}
+ </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">
+ <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
+ <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
+ <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
+ </svg>
+ <span>{t('pages.main.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)} />
+ </>
+ );
+};
+
+export default ItemsHome;
diff --git a/apps/web/src/pages/items/View.tsx b/apps/web/src/pages/items/View.tsx
new file mode 100644
index 000000000..aba1d0800
--- /dev/null
+++ b/apps/web/src/pages/items/View.tsx
@@ -0,0 +1,331 @@
+import { FieldCategories, FieldKey, ItemTypes, TRASH_RETENTION_DEFAULT_DAYS, getFieldValue, type Attachment, type Item, type Passkey, type TotpCode } from '@aliasvault/models/vault';
+import React, { useCallback, useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Link, useNavigate, useParams } from 'react-router-dom';
+
+import AttachmentViewer from '@/components/attachments/AttachmentViewer';
+import RecentEmails from '@/components/email/RecentEmails';
+import CopyPasteFormRow from '@/components/forms/CopyPasteFormRow';
+import { type DisplayField, getUrlValues, groupDisplayFields, shouldBeFullWidth } from '@/components/items/DisplayField';
+import FieldBlock from '@/components/items/FieldBlock';
+import { buildFolderBreadcrumbs } from '@/components/items/FolderBreadcrumbs';
+import ItemIcon from '@/components/items/ItemIcon';
+import LoadingIndicator from '@/components/loading/LoadingIndicator';
+import type { BreadcrumbItem } from '@/components/shared/Breadcrumb';
+import Button from '@/components/shared/Button';
+import FormModal from '@/components/shared/FormModal';
+import LinkButton from '@/components/shared/LinkButton';
+import PageContent from '@/components/shared/PageContent';
+import PageHeader from '@/components/shared/PageHeader';
+import TotpViewer from '@/components/totp/TotpViewer';
+import { useDb } from '@/context/DbContext';
+import { useNotifications } from '@/context/NotificationContext';
+import { useEmailDomains } from '@/hooks/useEmailDomains';
+import { useKeyboardShortcut } from '@/hooks/useKeyboardShortcut';
+import { usePageTitle } from '@/hooks/usePageTitle';
+import { useVaultMutate } from '@/hooks/useVaultMutate';
+import { folderRoute, itemRoute } from '@/utils/ItemRoute';
+
+import type { ItemRef } from '@aliasvault/client/database/ItemRef';
+import type { Folder } from '@aliasvault/client/database/repositories/FolderRepository';
+
+/**
+ * A card section on the item page.
+ */
+const Section: React.FC<{ title?: string; children: React.ReactNode }> = ({ title, children }) => (
+ <div className="p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm 2xl:col-span-2 dark:border-gray-700 sm:p-6 dark:bg-gray-800">
+ {title && <h3 className="mb-4 text-xl font-semibold dark:text-white">{title}</h3>}
+ {children}
+ </div>
+);
+
+/**
+ * The fields of a section in the six column grid.
+ */
+const FieldGrid: React.FC<{ fields: DisplayField[]; item: ItemRef; fullWidth?: (field: DisplayField) => boolean; hideLabel?: boolean; withForm?: boolean }> = ({ fields, item, fullWidth, hideLabel = false, withForm = true }) => {
+ const grid = (
+ <div className="grid grid-cols-6 gap-6">
+ {fields.map((field, index) => (
+ <FieldBlock key={`${field.FieldKey}-${index}`} field={field} item={item} fullWidth={fullWidth ? fullWidth(field) : false} hideLabel={hideLabel} />
+ ))}
+ </div>
+ );
+ return withForm ? <form action="#">{grid}</form> : grid;
+};
+
+/**
+ * The item details page.
+ */
+const ItemView: React.FC = () => {
+ const { manifestId, id } = useParams<{ manifestId: string; id: string }>();
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const dbContext = useDb();
+ const notifications = useNotifications();
+ const domains = useEmailDomains();
+ const { executeVaultMutationAsync } = useVaultMutate();
+ usePageTitle(t('pages.main.items.view.ViewItemPageTitle'));
+
+ const [isLoading, setIsLoading] = useState(true);
+ const [item, setItem] = useState<Item | null>(null);
+ const [folder, setFolder] = useState<Folder | null>(null);
+ const [totpCodes, setTotpCodes] = useState<TotpCode[]>([]);
+ const [attachments, setAttachments] = useState<Attachment[]>([]);
+ const [passkeys, setPasskeys] = useState<Passkey[]>([]);
+ const [breadcrumbItems, setBreadcrumbItems] = useState<BreadcrumbItem[]>([]);
+ const [showDeleteModal, setShowDeleteModal] = useState(false);
+ const [isDeleting, setIsDeleting] = useState(false);
+
+ /**
+ * Load the item and everything shown with it.
+ */
+ const loadEntry = useCallback((): void => {
+ const client = dbContext.sqliteClient;
+ if (!client || !manifestId || !id) {
+ return;
+ }
+ setIsLoading(true);
+
+ const ref = { Id: id, ManifestId: manifestId };
+ const loaded = client.items.getById(ref);
+ if (!loaded) {
+ notifications.addErrorMessage(t('pages.main.items.view.ItemNotFoundError'));
+ navigate('/items', { replace: true });
+ return;
+ }
+
+ const allFolders = client.folders.getAll();
+ const folderRef = loaded.FolderId ? { Id: loaded.FolderId, ManifestId: loaded.ManifestId } : null;
+ const itemFolder = folderRef ? allFolders.find(f => f.Id === folderRef.Id && f.ManifestId === folderRef.ManifestId) ?? null : null;
+ const crumbs = folderRef ? buildFolderBreadcrumbs(folderRef, allFolders) : [];
+ crumbs.push({ displayName: t('pages.main.items.view.ViewItemBreadcrumb') });
+
+ setItem(loaded);
+ setFolder(itemFolder);
+ setBreadcrumbItems(crumbs);
+ setTotpCodes(client.items.getTotpCodesForItem(ref));
+ setAttachments(client.items.getAttachmentsForItem(ref));
+ setPasskeys(client.passkeys.getByItemId(ref));
+ setIsLoading(false);
+ }, [dbContext.sqliteClient, manifestId, id, navigate, notifications, t]);
+
+ // Reload when the vault is (re)loaded, so changes synced from other devices show without a refresh.
+ useEffect(() => loadEntry(), [loadEntry]);
+
+ useKeyboardShortcut('ge', () => {
+ if (item) {
+ navigate(itemRoute(item, true));
+ }
+ });
+ useKeyboardShortcut('gd', () => setShowDeleteModal(true));
+
+ const groupedFields = useMemo(() => item ? groupDisplayFields(item) : null, [item]);
+ const urlValues = useMemo(() => item ? getUrlValues(item) : [], [item]);
+ const emailAddress = item ? getFieldValue(item, FieldKey.LoginEmail) ?? '' : '';
+
+ /**
+ * Delete the item (move it to the trash / recently deleted items) and go back to the list.
+ */
+ const confirmDelete = async (): Promise<void> => {
+ if (isDeleting) {
+ return;
+ }
+ if (!item) {
+ notifications.addErrorMessage(t('pages.main.items.delete.DeleteItemNotFoundError'), true);
+ setShowDeleteModal(false);
+ return;
+ }
+
+ setIsDeleting(true);
+ try {
+ await executeVaultMutationAsync(async () => {
+ await dbContext.sqliteClient?.items.trash(item);
+ });
+ notifications.addSuccessMessage(t('pages.main.items.delete.DeleteSuccessMessage'));
+ navigate('/items');
+ } finally {
+ setIsDeleting(false);
+ setShowDeleteModal(false);
+ }
+ };
+
+ if (isLoading || !item || !groupedFields) {
+ return <LoadingIndicator />;
+ }
+
+ const isLoginLike = item.ItemType === ItemTypes.Login || item.ItemType === ItemTypes.Alias;
+ const loginFields = groupedFields[FieldCategories.Login];
+ const aliasFields = groupedFields[FieldCategories.Alias];
+ const cardFields = groupedFields[FieldCategories.Card];
+ const notesFields = groupedFields[FieldCategories.Notes];
+ const customFields = groupedFields[FieldCategories.Custom];
+ const firstName = aliasFields.find(f => f.FieldKey === FieldKey.AliasFirstName)?.Value ?? '';
+ const lastName = aliasFields.find(f => f.FieldKey === FieldKey.AliasLastName)?.Value ?? '';
+ const passkey = passkeys[0];
+
+ return (
+ <>
+ <PageHeader
+ breadcrumbItems={breadcrumbItems}
+ title={t('pages.main.items.view.ViewItemTitle')}
+ customActions={(
+ <>
+ <LinkButton smallText={t('pages.main.items.view.EditButtonMobile')} text={t('pages.main.items.view.EditButtonDesktop')} href={itemRoute(item, true)} color="primary" />
+ <Button color="danger" onClick={() => setShowDeleteModal(true)}>
+ <span className="md:hidden">{t('pages.main.items.view.DeleteButtonMobile')}</span>
+ <span className="hidden md:inline">{t('pages.main.items.view.DeleteButtonDesktop')}</span>
+ </Button>
+ </>
+ )}
+ />
+
+ <PageContent>
+ <div className="grid grid-cols-1 px-4 md:grid-cols-2 lg:grid-cols-3 lg:gap-4 dark:bg-gray-900">
+ <div className="col-span-1 md:col-span-2 lg:col-span-1">
+ <Section>
+ <div className="items-center flex space-x-4">
+ <ItemIcon item={item} altText={item.Name ?? 'Item'} sizeClass="w-14 h-14" />
+ <div className="flex-1 min-w-0">
+ <h3 className="mb-1 text-xl font-bold text-gray-900 dark:text-white truncate">{item.Name ?? t('pages.main.items.view.Untitled')}</h3>
+ {urlValues.map((url) => (
+ <div key={url} className="text-sm truncate">
+ {/^https?:\/\//i.test(url)
+ ? <a href={url} target="_blank" rel="noopener noreferrer" className="text-primary-600 break-all dark:text-primary-400 hover:underline">{url}</a>
+ : <span className="text-gray-700 break-all dark:text-gray-300">{url}</span>}
+ </div>
+ ))}
+ {folder && (
+ <Link to={folderRoute(folder)} className="inline-flex items-center gap-2 mt-2 px-3 py-1.5 text-sm font-medium text-gray-600 dark:text-gray-400 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors">
+ <svg className="w-4 h-4 text-orange-500" viewBox="0 0 24 24" fill="currentColor">
+ <path d="M10 4H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2z" />
+ </svg>
+ <span>{folder.Name}</span>
+ </Link>
+ )}
+ </div>
+ </div>
+ </Section>
+
+ {isLoginLike && emailAddress.length > 0 && <RecentEmails emailAddress={emailAddress} />}
+
+ {totpCodes.length > 0 && <TotpViewer totpCodes={totpCodes} />}
+
+ {item.ItemType !== ItemTypes.Note && notesFields.length > 0 && (
+ <Section title={t('pages.main.items.view.NotesSection')}>
+ <FieldGrid fields={notesFields} item={item} hideLabel withForm={false} />
+ </Section>
+ )}
+
+ {attachments.some(a => !a.IsDeleted) && <AttachmentViewer attachments={attachments} />}
+ </div>
+
+ <div className="col-span-1 md:col-span-2 lg:col-span-2">
+ {isLoginLike && loginFields.length > 0 && (
+ <div className="p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm 2xl:col-span-2 dark:border-gray-700 sm:p-6 dark:bg-gray-800">
+ <h3 className="mb-2 text-xl font-semibold dark:text-white">{t('pages.main.items.view.LoginDetailsSection')}</h3>
+ <p className="mb-4 text-sm text-gray-600 dark:text-gray-400">
+ <span>{domains.isAliasVaultSupportedDomain(emailAddress) ? t('pages.main.items.view.GeneratedItemDescription') : t('pages.main.items.view.StoredItemDescription')}</span>
+ </p>
+
+ {passkey && (
+ <div className="mb-6 p-3 rounded-lg bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700">
+ <div className="flex items-start gap-3">
+ <svg className="w-5 h-5 text-gray-600 dark:text-gray-400 mt-0.5 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
+ <path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4" />
+ </svg>
+ <div className="flex-1">
+ <div className="mb-1">
+ <span className="text-sm font-semibold text-gray-900 dark:text-white">{t('pages.main.items.view.PasskeyLabel')}</span>
+ </div>
+ <div className="space-y-1 mb-2">
+ {passkey.RpId.trim().length > 0 && (
+ <div>
+ <span className="text-xs text-gray-500 dark:text-gray-400">{t('pages.main.items.view.PasskeySiteLabel')}: </span>
+ <span className="text-sm text-gray-900 dark:text-white">{passkey.RpId}</span>
+ </div>
+ )}
+ {(passkey.DisplayName ?? '').trim().length > 0 && (
+ <div>
+ <span className="text-xs text-gray-500 dark:text-gray-400">{t('pages.main.items.view.PasskeyDisplayNameLabel')}: </span>
+ <span className="text-sm text-gray-900 dark:text-white">{passkey.DisplayName}</span>
+ </div>
+ )}
+ </div>
+ <p className="text-xs text-gray-600 dark:text-gray-400">{t('pages.main.items.view.PasskeyHelpText')}</p>
+ </div>
+ </div>
+ </div>
+ )}
+
+ <FieldGrid fields={loginFields} item={item} fullWidth={f => shouldBeFullWidth(f, loginFields)} />
+ </div>
+ )}
+
+ {item.ItemType === ItemTypes.Alias && aliasFields.length > 0 && (
+ <Section title={t('pages.main.items.view.AliasSection')}>
+ <form action="#">
+ <div className="grid grid-cols-6 gap-6">
+ {firstName.trim().length > 0 && lastName.trim().length > 0 && (
+ <div className="col-span-6">
+ <CopyPasteFormRow id="alias-full-name" label={t('pages.main.items.view.FullNameLabel')} value={`${firstName} ${lastName}`} />
+ </div>
+ )}
+ {aliasFields.map((field, index) => (
+ <FieldBlock key={`${field.FieldKey}-${index}`} field={field} item={item} fullWidth={shouldBeFullWidth(field, aliasFields)} />
+ ))}
+ </div>
+ </form>
+ </Section>
+ )}
+
+ {item.ItemType === ItemTypes.CreditCard && cardFields.length > 0 && (
+ <Section title={t('pages.main.items.view.CardSection')}>
+ <FieldGrid fields={cardFields} item={item} fullWidth={f => shouldBeFullWidth(f, cardFields)} />
+ </Section>
+ )}
+
+ {item.ItemType === ItemTypes.Note && notesFields.length > 0 && (
+ <Section title={t('pages.main.items.view.NotesSection')}>
+ <FieldGrid fields={notesFields} item={item} hideLabel withForm={false} />
+ </Section>
+ )}
+
+ {customFields.length > 0 && (
+ <Section>
+ <FieldGrid fields={customFields} item={item} fullWidth={() => true} />
+ </Section>
+ )}
+ </div>
+ </div>
+ </PageContent>
+
+ <FormModal
+ isOpen={showDeleteModal}
+ title={t('pages.main.items.delete.DeleteItemTitle')}
+ iconBackgroundClass="bg-red-100 dark:bg-red-900/30"
+ confirmText={t('pages.main.items.delete.YesImSureButton')}
+ cancelText={t('pages.main.items.delete.NoCancelButton')}
+ confirmButtonClass="bg-red-600 hover:bg-red-700"
+ isLoading={isDeleting}
+ onConfirm={() => void confirmDelete()}
+ onClose={() => {
+ if (!isDeleting) {
+ setShowDeleteModal(false);
+ }
+ }}
+ icon={(
+ <svg className="h-6 w-6 text-red-600 dark:text-red-400" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
+ <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
+ </svg>
+ )}
+ >
+ <p className="text-sm text-gray-500 dark:text-gray-400 mb-3">{t('pages.main.items.delete.DeleteItemDescription', { 0: TRASH_RETENTION_DEFAULT_DAYS })}</p>
+ <div className="bg-gray-50 dark:bg-gray-700/50 rounded-md p-3">
+ <p className="text-sm font-medium text-gray-900 dark:text-white break-all">{item.Name ?? ''}</p>
+ </div>
+ </FormModal>
+ </>
+ );
+};
+
+export default ItemView;