Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add components (#2413)
Leendert de Borst0b4f13c4dd52
diff --git a/apps/web/src/components/items/AddFieldMenu.tsx b/apps/web/src/components/items/AddFieldMenu.tsxnew file mode 100644index 000000000..602d28f17--- /dev/null+++ b/apps/web/src/components/items/AddFieldMenu.tsx@@ -0,0 +1,139 @@+import { FieldCategories, FieldKey, type SystemFieldDefinition } from '@aliasvault/models/vault';+import React, { useState } from 'react';+import { useTranslation } from 'react-i18next';++import CustomFieldModal from '@/components/forms/CustomFieldModal';++type AddFieldMenuProps = {+ optionalSystemFields: SystemFieldDefinition[];+ visibleFieldKeys: Set<string>;+ show2FA: boolean;+ showAttachments: boolean;+ hasLoginFields: boolean;+ customFieldCount: number;+ onAddSystemField: (fieldKey: string) => void;+ onAddCustomField: (label: string, fieldType: string) => void;+ onAdd2FA: () => void;+ onAddAttachments: () => void;+};++/** Translation keys of the optional system field names. */+const FIELD_LABEL_KEYS: Record<string, string> = {+ [FieldKey.LoginUsername]: 'FieldLoginUsername',+ [FieldKey.LoginPassword]: 'FieldLoginPassword',+ [FieldKey.LoginEmail]: 'FieldLoginEmail',+ [FieldKey.LoginUrl]: 'FieldLoginUrl',+ [FieldKey.AliasFirstName]: 'FieldAliasFirstName',+ [FieldKey.AliasLastName]: 'FieldAliasLastName',+ [FieldKey.AliasGender]: 'FieldAliasGender',+ [FieldKey.AliasBirthdate]: 'FieldAliasBirthdate',+ [FieldKey.CardNumber]: 'FieldCardNumber',+ [FieldKey.CardCardholderName]: 'FieldCardCardholderName',+ [FieldKey.CardExpiryMonth]: 'FieldCardExpiryMonth',+ [FieldKey.CardExpiryYear]: 'FieldCardExpiryYear',+ [FieldKey.CardCvv]: 'FieldCardCvv',+ [FieldKey.CardPin]: 'FieldCardPin',+ [FieldKey.NotesContent]: 'FieldNotesContent',+};++/**+ * The icon of a field category.+ */+const FieldIcon: React.FC<{ category: string }> = ({ category }) => {+ switch (category) {+ case FieldCategories.Notes:+ return <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" /></svg>;+ case FieldCategories.Card:+ return <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" /></svg>;+ default:+ return <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" /></svg>;+ }+};++const MENU_ITEM_CLASSES = 'w-full px-4 py-3 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 border-b border-gray-100 dark:border-gray-700 last:border-b-0 text-gray-700 dark:text-gray-300';++/**+ * The "+" menu that adds optional fields and sections to the item form.+ */+const AddFieldMenu: React.FC<AddFieldMenuProps> = ({ optionalSystemFields, visibleFieldKeys, show2FA, showAttachments, hasLoginFields, customFieldCount, onAddSystemField, onAddCustomField, onAdd2FA, onAddAttachments }) => {+ const { t } = useTranslation();+ const [isOpen, setIsOpen] = useState(false);+ const [showCustomFieldModal, setShowCustomFieldModal] = useState(false);+ const [customFieldLabel, setCustomFieldLabel] = useState('');+ const tk = 'components.main.items.addFieldMenu';++ return (+ <div className="relative">+ <button type="button" onClick={() => setIsOpen(v => !v)} className="w-full px-4 py-2 border-2 border-dashed border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-400 rounded-md hover:border-primary-500 hover:text-primary-600 dark:hover:text-primary-400 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 transition-colors flex items-center justify-center gap-2">+ <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />+ </svg>+ </button>++ {isOpen && (+ <>+ <div className="fixed inset-0 z-40 bg-black bg-opacity-50" onClick={() => setIsOpen(false)}></div>+ <div className="absolute bottom-full left-0 right-0 mb-1 z-50 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg overflow-hidden max-h-64 overflow-y-auto">+ {optionalSystemFields.filter(f => !visibleFieldKeys.has(f.FieldKey)).map(field => (+ <button key={field.FieldKey} type="button" onClick={() => {+ onAddSystemField(field.FieldKey);+ setIsOpen(false);+ }} className={MENU_ITEM_CLASSES}>+ <span className="text-gray-500 dark:text-gray-400"><FieldIcon category={field.Category} /></span>+ <span>{FIELD_LABEL_KEYS[field.FieldKey] ? t(`${tk}.${FIELD_LABEL_KEYS[field.FieldKey]}`) : field.FieldKey}</span>+ </button>+ ))}++ {!show2FA && hasLoginFields && (+ <button type="button" onClick={() => {+ onAdd2FA();+ setIsOpen(false);+ }} className={MENU_ITEM_CLASSES}>+ <span className="text-gray-500 dark:text-gray-400">+ <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />+ </svg>+ </span>+ <span>{t(`${tk}.TwoFactorAuthentication`)}</span>+ </button>+ )}++ {!showAttachments && (+ <button type="button" onClick={() => {+ onAddAttachments();+ setIsOpen(false);+ }} className={MENU_ITEM_CLASSES}>+ <span className="text-gray-500 dark:text-gray-400">+ <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />+ </svg>+ </span>+ <span>{t(`${tk}.Attachments`)}</span>+ </button>+ )}++ <button type="button" onClick={() => {+ setCustomFieldLabel(t(`${tk}.DefaultFieldLabel`, { 0: customFieldCount + 1 }));+ setShowCustomFieldModal(true);+ setIsOpen(false);+ }} className={MENU_ITEM_CLASSES}>+ <span className="text-gray-500 dark:text-gray-400">+ <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />+ </svg>+ </span>+ <span>{t(`${tk}.AddCustomField`)}</span>+ </button>+ </div>+ </>+ )}++ <CustomFieldModal isOpen={showCustomFieldModal} initialLabel={customFieldLabel} onClose={() => {+ setShowCustomFieldModal(false);+ setCustomFieldLabel('');+ }} onSubmit={onAddCustomField} />+ </div>+ );+};++export default AddFieldMenu;diff --git a/apps/web/src/components/items/FieldBlock.tsx b/apps/web/src/components/items/FieldBlock.tsxnew file mode 100644index 000000000..f0c7bc4ea--- /dev/null+++ b/apps/web/src/components/items/FieldBlock.tsx@@ -0,0 +1,158 @@+import { FieldTypes } from '@aliasvault/models/vault';+import React, { useEffect, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import CopyPasteFormRow from '@/components/forms/CopyPasteFormRow';+import CopyPastePasswordFormRow from '@/components/forms/CopyPastePasswordFormRow';+import type { DisplayField } from '@/components/items/DisplayField';+import FieldHistoryModal from '@/components/items/FieldHistoryModal';+import { useDb } from '@/context/DbContext';++import type { ItemRef } from '@aliasvault/client/database/ItemRef';++type FieldBlockProps = {+ field: DisplayField;+ item: ItemRef;+ fullWidth?: boolean;+ /** Hide the label when the section header already names the field. */+ hideLabel?: boolean;+};++/**+ * snake_case to Title Case.+ */+const formatFieldName = (fieldName: string): string => fieldName.split('_').map(w => w.length > 0 ? w[0].toUpperCase() + w.slice(1) : '').join(' ');++/**+ * The label of a field: the custom label, the localized system label, or the key made readable.+ */+export function useFieldLabel(field: DisplayField): string {+ const { t } = useTranslation();+ return useMemo(() => {+ if (field.IsCustomField) {+ return field.Label.length > 0 ? field.Label : formatFieldName(field.FieldKey);+ }+ if (field.FieldKey.length > 0) {+ const key = `components.fields.fieldBlock.FieldLabel_${field.FieldKey.replace(/\./g, '_')}`;+ const localized = t(key, { defaultValue: '' });+ if (localized.length > 0) {+ return localized;+ }+ const parts = field.FieldKey.split('.');+ if (parts.length > 1) {+ return formatFieldName(parts[1]);+ }+ }+ return formatFieldName(field.FieldKey);+ }, [field.FieldKey, field.IsCustomField, field.Label, t]);+}++/**+ * Text with http(s) links made clickable.+ */+const TextWithLinks: React.FC<{ text: string }> = ({ text }) => {+ const parts = text.split(/(https?:\/\/[^\s<>"]+)/g);+ return (+ <>+ {parts.map((part, index) => /^https?:\/\//.test(part)+ ? <a key={index} href={part} target="_blank" rel="noopener noreferrer" className="text-blue-600 dark:text-blue-400 hover:underline">{part}</a>+ : <React.Fragment key={index}>{part}</React.Fragment>)}+ </>+ );+};++/**+ * Renders a single item field by its type.+ */+const FieldBlock: React.FC<FieldBlockProps> = ({ field, item, fullWidth = false, hideLabel = false }) => {+ const { t } = useTranslation();+ const dbContext = useDb();+ const label = useFieldLabel(field);+ const [showHistoryModal, setShowHistoryModal] = useState(false);+ const [historyCount, setHistoryCount] = useState(0);+ const fieldId = field.FieldKey.length > 0 ? field.FieldKey.replace(/\./g, '-') : field.Label;+ const widthClass = fullWidth ? 'col-span-6' : 'col-span-6 sm:col-span-3';++ /*+ * The history icon only shows when there is history that differs from the current value: a single record equal+ * to the current value is the snapshot taken on the last save, not a change.+ */+ useEffect(() => {+ if (!field.EnableHistory || !dbContext.sqliteClient || field.FieldKey.length === 0 || showHistoryModal) {+ return;+ }+ const records = dbContext.sqliteClient.items.getFieldHistory({ Id: item.Id, ManifestId: item.ManifestId }, field.FieldKey);+ if (records.length > 1) {+ setHistoryCount(records.length);+ } else if (records.length === 1) {+ setHistoryCount(records[0].ValueSnapshot !== JSON.stringify([field.Value].filter(v => v.trim().length > 0)) ? 1 : 0);+ } else {+ setHistoryCount(0);+ }+ }, [dbContext.sqliteClient, field.EnableHistory, field.FieldKey, field.Value, item.Id, item.ManifestId, showHistoryModal]);++ const labelElement = (+ <label htmlFor={fieldId} className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">+ {label}+ {field.EnableHistory && historyCount > 0 && (+ <button type="button" className="ml-2 inline-flex items-center text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 focus:outline-none" title={t('components.fields.fieldBlock.ViewHistory')} onClick={() => setShowHistoryModal(true)}>+ <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">+ <path strokeLinecap="round" strokeLinejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />+ </svg>+ </button>+ )}+ </label>+ );++ /**+ * The field body by type.+ */+ const renderField = (): React.ReactNode => {+ switch (field.FieldType) {+ case FieldTypes.Password:+ case FieldTypes.Hidden:+ return (+ <div className={widthClass}>+ {labelElement}+ <CopyPastePasswordFormRow id={fieldId} label="" value={field.Value} />+ </div>+ );+ case FieldTypes.TextArea:+ return (+ <div className="col-span-6">+ {!hideLabel && labelElement}+ <div className="p-3 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white whitespace-pre-wrap text-sm">+ <TextWithLinks text={field.Value} />+ </div>+ </div>+ );+ case FieldTypes.URL:+ return (+ <div className="col-span-6">+ {labelElement}+ {field.Value.length > 0 && (/^https?:\/\//i.test(field.Value)+ ? <a href={field.Value} target="_blank" rel="noopener noreferrer" className="text-blue-600 dark:text-blue-400 hover:underline break-all">{field.Value}</a>+ : <span className="text-gray-700 dark:text-gray-300 break-all">{field.Value}</span>)}+ </div>+ );+ default:+ return (+ <div className={widthClass}>+ {labelElement}+ <CopyPasteFormRow id={fieldId} label="" value={field.Value} />+ </div>+ );+ }+ };++ return (+ <>+ {renderField()}+ {showHistoryModal && (+ <FieldHistoryModal item={item} fieldKey={field.FieldKey} fieldLabel={label} isHidden={field.FieldType === FieldTypes.Password || field.FieldType === FieldTypes.Hidden} onClose={() => setShowHistoryModal(false)} />+ )}+ </>+ );+};++export default FieldBlock;diff --git a/apps/web/src/components/layout/SearchWidget.tsx b/apps/web/src/components/layout/SearchWidget.tsxnew file mode 100644index 000000000..e29a5e0c2--- /dev/null+++ b/apps/web/src/components/layout/SearchWidget.tsx@@ -0,0 +1,218 @@+import { scopedKey } from '@aliasvault/client/database/ItemRef';+import { getFolderPath, truncateFolderPath } from '@aliasvault/client/items/FolderUtils';+import { applySearchFilter } from '@aliasvault/client/items/ItemFilters';+import { FieldKey, type Item } from '@aliasvault/models/vault';+import React, { useCallback, useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useLocation, useNavigate } from 'react-router-dom';++import ItemIcon from '@/components/items/ItemIcon';+import { getFieldValue } from '@/components/items/ItemListEntry';+import { useDb } from '@/context/DbContext';+import { useClickOutside } from '@/hooks/useClickOutside';+import { useKeyboardShortcut } from '@/hooks/useKeyboardShortcut';+import { itemRoute } from '@/utils/ItemRoute';++const SEARCH_DEBOUNCE_MS = 100;+const MAX_RESULTS = 10;++/**+ * A search result with its folder path.+ */+type SearchResult = {+ item: Item;+ folderPath: string[];+};++/**+ * The vault search box in the top bar.+ */+const SearchWidget: React.FC = () => {+ const { t } = useTranslation();+ const navigate = useNavigate();+ const location = useLocation();+ const dbContext = useDb();+ const [searchTerm, setSearchTerm] = useState('');+ const [results, setResults] = useState<SearchResult[]>([]);+ const [showPopup, setShowPopup] = useState(false);+ const [selectedIndex, setSelectedIndex] = useState(-1);+ const [isLoading, setIsLoading] = useState(false);+ const containerRef = useRef<HTMLDivElement>(null);+ const inputRef = useRef<HTMLInputElement>(null);+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ /**+ * Close the popup.+ */+ const close = useCallback((): void => setShowPopup(false), []);+ useClickOutside([containerRef], close, showPopup);++ /**+ * Focus the search field (g+s / g+f).+ */+ const focusSearchField = useCallback((): void => inputRef.current?.focus(), []);+ useKeyboardShortcut('gs', focusSearchField);+ useKeyboardShortcut('gf', focusSearchField);++ /**+ * Reset the field on navigation.+ */+ useEffect(() => {+ setSearchTerm('');+ setResults([]);+ setSelectedIndex(-1);+ setShowPopup(false);+ setIsLoading(false);+ }, [location.pathname]);++ /**+ * Run the search after the debounce.+ */+ const performSearch = useCallback((term: string): void => {+ const sqliteClient = dbContext.sqliteClient;+ if (!sqliteClient || term.length < 2) {+ setResults([]);+ setSelectedIndex(-1);+ setIsLoading(false);+ return;+ }++ const allFolders = sqliteClient.folders.getAll();+ const matches = applySearchFilter(sqliteClient.items.getAll(), term).slice(0, MAX_RESULTS);+ setResults(matches.map(item => ({ item, folderPath: item.FolderId ? getFolderPath({ Id: item.FolderId, ManifestId: item.ManifestId }, allFolders) : [] })));+ setSelectedIndex(matches.length > 0 ? 0 : -1);+ setIsLoading(false);+ }, [dbContext.sqliteClient]);++ /**+ * Handle typing: debounce the search.+ */+ const onSearchTermChanged = (value: string): void => {+ setSearchTerm(value);+ if (timerRef.current) {+ clearTimeout(timerRef.current);+ }+ if (value.length < 2) {+ setResults([]);+ setSelectedIndex(-1);+ setIsLoading(false);+ return;+ }+ setIsLoading(true);+ timerRef.current = setTimeout(() => performSearch(value), SEARCH_DEBOUNCE_MS);+ };++ /**+ * Open an item.+ */+ const selectResult = (item: Item): void => {+ inputRef.current?.blur();+ navigate(itemRoute(item));+ };++ /**+ * Keyboard navigation through the results.+ */+ const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>): void => {+ switch (e.key) {+ case 'ArrowDown':+ setSelectedIndex(Math.min(selectedIndex + 1, results.length - 1));+ break;+ case 'ArrowUp':+ setSelectedIndex(Math.max(selectedIndex - 1, -1));+ break;+ case 'Enter':+ if (selectedIndex >= 0 && selectedIndex < results.length) {+ selectResult(results[selectedIndex].item);+ }+ break;+ }+ };++ /**+ * "First > ... > Last" for long paths.+ */+ const formatFolderPath = (path: string[]): string => truncateFolderPath(path, 3).join(' > ');++ const popupClass = 'absolute z-10 w-screen left-0 sm:left-auto sm:w-full mt-1 bg-white rounded-md shadow-lg dark:bg-gray-800 text-sm text-gray-600 dark:text-gray-400';++ return (+ <div className="relative" id="searchWidgetContainer" ref={containerRef}>+ <input+ ref={inputRef}+ id="searchWidget"+ type="text"+ placeholder={t('components.main.widgets.searchWidget.SearchVaultPlaceholder')}+ autoComplete="off"+ className="w-full px-4 py-2 text-gray-700 bg-white border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 dark:bg-gray-800 dark:text-gray-300 dark:border-gray-600 dark:focus:ring-primary-500"+ value={searchTerm}+ onChange={(e) => onSearchTermChanged(e.target.value)}+ onFocus={() => setShowPopup(true)}+ onClick={() => setShowPopup(true)}+ onKeyDown={handleKeyDown} />++ {showPopup && (+ <>+ <div className="absolute z-10 w-full mt-1 bg-white rounded-md shadow-lg dark:bg-gray-800 p-2 text-sm text-gray-600 dark:text-gray-400">+ {searchTerm.length === 0 ? (+ <p>{t('components.main.widgets.searchWidget.SearchHelpText')}</p>+ ) : searchTerm.length === 1 ? (+ <p>{t('components.main.widgets.searchWidget.SearchTooShortMessage')}</p>+ ) : (+ <p>{t('components.main.widgets.searchWidget.SearchingForMessage', { 0: searchTerm })}</p>+ )}+ </div>++ {searchTerm.length >= 2 && (+ isLoading ? (+ <div className={popupClass}>+ <div className="px-4 py-2 flex items-center">+ <svg className="animate-spin -ml-1 mr-3 h-4 w-4 text-gray-500" xmlns="http://www.w3.org/2000/svg" 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>+ {t('components.main.widgets.searchWidget.SearchingMessage')}+ </div>+ </div>+ ) : results.length > 0 ? (+ <div className={popupClass}>+ {results.map((result, index) => {+ const email = getFieldValue(result.item, FieldKey.LoginEmail);+ const username = getFieldValue(result.item, FieldKey.LoginUsername);+ return (+ <div key={scopedKey(result.item.ManifestId, result.item.Id)} className={`search-result ${index === selectedIndex ? 'bg-gray-100 dark:bg-gray-700' : ''} px-4 py-2 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center`} onClick={() => selectResult(result.item)}>+ <ItemIcon item={result.item} altText={result.item.Name ?? ''} sizeClass="w-6 h-6" />+ <div className="ml-2">+ <div className="font-medium text-gray-900 dark:text-white">+ {result.folderPath.length > 0 && (+ <span className="text-gray-500 dark:text-gray-400 text-sm font-normal" title={result.folderPath.join(' > ')}>+ {formatFolderPath(result.folderPath)} >{' '}+ </span>+ )}+ {result.item.Name}+ </div>+ {email ? (+ <span className="text-gray-500">({email})</span>+ ) : username ? (+ <span className="text-gray-500">({username})</span>+ ) : null}+ </div>+ </div>+ );+ })}+ </div>+ ) : (+ <div className={popupClass}>+ <div className="px-4 py-2 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700">+ {t('components.main.widgets.searchWidget.NoResultsFoundMessage')}+ </div>+ </div>+ )+ )}+ </>+ )}+ </div>+ );+};++export default SearchWidget;diff --git a/apps/web/src/components/layout/TopMenu.tsx b/apps/web/src/components/layout/TopMenu.tsxnew file mode 100644index 000000000..d6c8b4242--- /dev/null+++ b/apps/web/src/components/layout/TopMenu.tsx@@ -0,0 +1,152 @@+import React, { useCallback, useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { NavLink, useLocation } from 'react-router-dom';++import CreateNewIdentityWidget from '@/components/layout/CreateNewIdentityWidget';+import DbLockButton from '@/components/layout/DbLockButton';+import DbStatusIndicator from '@/components/layout/DbStatusIndicator';+import SearchWidget from '@/components/layout/SearchWidget';+import { useApp } from '@/context/AppContext';+import { useTheme } from '@/context/ThemeContext';+import { useClickOutside } from '@/hooks/useClickOutside';++/**+ * Class of a menu link, highlighting the active route.+ * @param isActive - whether the route is active+ * @param base - the base classes+ */+const navLinkClass = (isActive: boolean, base: string): string => `${base} ${isActive ? 'text-primary-700 dark:text-primary-500' : ''}`;++const DESKTOP_LINK = 'block text-gray-700 hover:text-primary-700 dark:text-gray-400 dark:hover:text-white';+const DROPDOWN_LINK = 'block py-2 px-4 text-sm hover:bg-gray-100 dark:hover:bg-gray-600 dark:text-gray-400 dark:hover:text-white';++/**+ * The fixed top bar with navigation, search, quick create and user menu.+ */+const TopMenu: React.FC = () => {+ const { t } = useTranslation();+ const location = useLocation();+ const { username } = useApp();+ const { isDarkMode, toggleTheme } = useTheme();+ const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);+ const menuRef = useRef<HTMLDivElement>(null);+ const toggleRef = useRef<HTMLButtonElement>(null);++ /**+ * Close the menu.+ */+ const closeMenu = useCallback((): void => setIsMobileMenuOpen(false), []);+ useClickOutside([menuRef, toggleRef], closeMenu, isMobileMenuOpen);++ useEffect(() => {+ setIsMobileMenuOpen(false);+ }, [location.pathname]);++ return (+ <header>+ <nav className="fixed z-30 w-full bg-white border-b border-gray-200 dark:bg-gray-800 dark:border-gray-700 py-3 px-4">+ <div className="flex justify-between items-center max-w-screen-2xl mx-auto relative">+ <div className="flex flex-shrink-0 justify-start items-center relative">+ <NavLink to="/" className="flex mr-0 sm:mr-4 lg:mr-8">+ <img src="/img/icon-nopadding.png" className="mr-3 h-8 w-10" alt="AliasVault Logo" />+ <span className="self-center hidden sm:flex text-2xl font-semibold content-start align-top whitespace-nowrap dark:text-white">+ AliasVault+ <span className="text-primary-500 text-[10px] ml-1 font-normal hidden sm:inline-block">{t('layout.topMenu.BetaLabel')}</span>+ </span>+ </NavLink>++ <div className="hidden justify-between items-center w-full lg:flex lg:w-auto lg:order-1">+ <ul className="flex flex-col mt-4 space-x-6 text-sm font-medium lg:flex-row xl:space-x-8 lg:mt-0">+ <NavLink to="/items" end className={({ isActive }) => navLinkClass(isActive, DESKTOP_LINK)}>+ {t('layout.topMenu.VaultNav')}+ </NavLink>+ <NavLink to="/emails" end className={({ isActive }) => navLinkClass(isActive, DESKTOP_LINK)}>+ {t('layout.topMenu.EmailsNav')}+ </NavLink>+ </ul>+ </div>+ </div>++ <div className="flex-grow min-w-0 mr-4 ms-0 lg:ms-4">+ <SearchWidget />+ </div>++ <div className="flex justify-end items-center lg:order-2">+ <CreateNewIdentityWidget />+ <DbLockButton />+ <DbStatusIndicator />+ <button ref={toggleRef} onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)} type="button" id="toggleMobileMenuButton" className="items-center p-2 text-gray-500 rounded-lg md:ml-2 hover:text-gray-900 hover:bg-gray-100 dark:text-gray-400 dark:hover:text-white dark:hover:bg-gray-700 focus:ring-4 focus:ring-gray-300 dark:focus:ring-gray-600" aria-expanded={isMobileMenuOpen}>+ <span className="sr-only">{t('layout.topMenu.OpenMenuLabel')}</span>+ <svg className="w-6 h-6" aria-hidden="true" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fillRule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 15a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clipRule="evenodd"></path></svg>+ </button>+ </div>++ <div ref={menuRef} className={`absolute w-full md:w-64 top-[40px] md:top-[39px] right-0 z-50 my-4 text-base list-none bg-white rounded-b-lg divide-y divide-gray-100 shadow dark:bg-gray-700 dark:divide-gray-600 ${isMobileMenuOpen ? 'block' : 'hidden'}`} id="mobileMenuDropdown">+ <ul className="lg:hidden py-1 text-gray-700 dark:text-gray-400">+ <li>+ <NavLink to="/items" className={({ isActive }) => navLinkClass(isActive, DROPDOWN_LINK)}>+ {t('layout.topMenu.VaultNav')}+ </NavLink>+ </li>+ <li>+ <NavLink to="/emails" end className={({ isActive }) => navLinkClass(isActive, DROPDOWN_LINK)}>+ {t('layout.topMenu.EmailsNav')}+ </NavLink>+ </li>+ </ul>+ <div className="py-3 px-4">+ <span className="block text-sm font-semibold text-gray-900 dark:text-white">{username}</span>+ </div>+ <ul className="py-1 text-gray-700 dark:text-gray-400">+ <li>+ <NavLink to="/settings/general" end className={({ isActive }) => navLinkClass(isActive, DROPDOWN_LINK)}>+ {t('layout.topMenu.GeneralSettingsNav')}+ </NavLink>+ </li>+ <li>+ <NavLink to="/settings/security" end className={({ isActive }) => navLinkClass(isActive, DROPDOWN_LINK)}>+ {t('layout.topMenu.SecuritySettingsNav')}+ </NavLink>+ </li>+ <li>+ <NavLink to="/settings/storage-insights" end className={({ isActive }) => navLinkClass(isActive, DROPDOWN_LINK)}>+ {t('layout.topMenu.StorageInsightsNav')}+ </NavLink>+ </li>+ <li>+ <NavLink to="/settings/import-export" end className={({ isActive }) => navLinkClass(isActive, DROPDOWN_LINK)}>+ {t('layout.topMenu.ImportExportNav')}+ </NavLink>+ </li>+ <li className="border-t border-b border-gray-100 dark:border-gray-600">+ <NavLink to="/settings/apps" end className={({ isActive }) => navLinkClass(isActive, DROPDOWN_LINK)}>+ {t('layout.topMenu.ExtensionsAppsNav')}+ <span className="ml-2 inline-flex items-center justify-center px-2 py-0.5 text-xs font-medium rounded bg-primary-100 text-primary-800 dark:bg-primary-900 dark:text-primary-200">+ {t('layout.topMenu.NewLabel')}+ </span>+ </NavLink>+ </li>+ <li>+ <button id="theme-toggle" type="button" onClick={toggleTheme} className="w-full text-start py-2 px-4 text-sm hover:bg-gray-100 dark:hover:bg-gray-600 dark:text-gray-400 dark:hover:text-white">+ {isDarkMode ? t('layout.topMenu.EnableLightMode') : t('layout.topMenu.EnableDarkMode')}+ {isDarkMode ? (+ <svg id="theme-toggle-light-icon" className="w-5 h-5 align-middle inline-block" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M10 2a1 1 0 011 1v1a1 1 0 11-2 0V3a1 1 0 011-1zm4 8a4 4 0 11-8 0 4 4 0 018 0zm-.464 4.95l.707.707a1 1 0 001.414-1.414l-.707-.707a1 1 0 00-1.414 1.414zm2.12-10.607a1 1 0 010 1.414l-.706.707a1 1 0 11-1.414-1.414l.707-.707a1 1 0 011.414 0zM17 11a1 1 0 100-2h-1a1 1 0 100 2h1zm-7 4a1 1 0 011 1v1a1 1 0 11-2 0v-1a1 1 0 011-1zM5.05 6.464A1 1 0 106.465 5.05l-.708-.707a1 1 0 00-1.414 1.414l.707.707zm1.414 8.486l-.707.707a1 1 0 01-1.414-1.414l.707-.707a1 1 0 011.414 1.414zM4 11a1 1 0 100-2H3a1 1 0 000 2h1z" fillRule="evenodd" clipRule="evenodd"></path></svg>+ ) : (+ <svg id="theme-toggle-dark-icon" className="w-5 h-5 align-middle inline-block" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M17.293 13.293A8 8 0 016.707 2.707a8.001 8.001 0 1010.586 10.586z"></path></svg>+ )}+ </button>+ </li>+ <li>+ <NavLink to="/user/logout" className={({ isActive }) => `block py-2 px-4 font-bold text-sm text-primary-700 hover:bg-gray-100 dark:hover:bg-gray-600 dark:text-primary-200 dark:hover:text-white ${isActive ? 'text-primary-700 dark:text-primary-500' : ''}`}>+ {t('layout.topMenu.LogOut')}+ </NavLink>+ </li>+ </ul>+ </div>+ </div>+ </nav>+ </header>+ );+};++export default TopMenu;diff --git a/apps/web/src/components/settings/PasswordSettingsPopup.tsx b/apps/web/src/components/settings/PasswordSettingsPopup.tsxnew file mode 100644index 000000000..3014f9cd9--- /dev/null+++ b/apps/web/src/components/settings/PasswordSettingsPopup.tsx@@ -0,0 +1,231 @@+import { getLanguageInfo, MAX_WORD_COUNT, MIN_WORD_COUNT, resolveDefaultLanguage } from '@aliasvault/models/defaults';+import React, { useEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import CopyPasteFormRow from '@/components/forms/CopyPasteFormRow';+import { useDb } from '@/context/DbContext';+import { useLoading } from '@/context/LoadingContext';+import { useNotifications } from '@/context/NotificationContext';+import { useClickOutside } from '@/hooks/useClickOutside';+import { usePasswordConfig } from '@/hooks/usePasswordConfig';+import { useVaultMutate } from '@/hooks/useVaultMutate';+import { lengthToSlider, SLIDER_MAX, SLIDER_MIN, sliderToLength } from '@/utils/PasswordLengthSlider';++import type { PasswordSettings } from '@aliasvault/models/vault';++type PasswordSettingsPopupProps = {+ passwordSettings: PasswordSettings;+ /** Offer "use just once" next to the global save. */+ isTemporary: boolean;+ onSaveSettings: (settings: PasswordSettings, generatedPassword: string) => void;+ onClose: () => void;+};++const DEFAULT_CAPITALIZATION = 'Lowercase';+const DEFAULT_SEPARATOR = 'Dash';+const DEFAULT_SALT = 'None';+const CAPITALIZATION_OPTIONS = ['Lowercase', 'TitleCase', 'Uppercase'];+const SEPARATOR_OPTIONS = ['Dash', 'Space', 'Underscore', 'Dot', 'None'];+const SALT_OPTIONS = ['None', 'Prefix', 'Sprinkle', 'Suffix'];++/**+ * The next option in a cycle.+ */+const cycle = (options: string[], current: string | undefined): string => options[(options.indexOf(current ?? '') + 1) % options.length];++/**+ * Classes of a character class toggle.+ */+const toggleClasses = (enabled: boolean): string => {+ const base = 'flex items-center justify-center px-3 py-2 rounded-md text-sm font-medium transition-colors';+ return enabled ? `${base} bg-primary-600 text-white hover:bg-primary-700` : `${base} bg-gray-200 text-gray-700 hover:bg-gray-300 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600`;+};++/**+ * Classes of a passphrase option button.+ */+const optionClasses = (customized: boolean): string => {+ const base = 'flex items-center justify-center px-2 py-2 rounded-md transition-colors';+ return customized ? `${base} bg-primary-600 text-white hover:bg-primary-700` : `${base} bg-gray-200 text-gray-700 hover:bg-gray-300 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600`;+};++/**+ * Glyph of a capitalization option.+ */+const capitalizationGlyph = (value: string | undefined): string => value === 'Uppercase' ? 'ABC' : value === 'TitleCase' ? 'Abc' : 'abc';++/**+ * Glyph of a separator option.+ */+const separatorGlyph = (value: string | undefined): string => ({ Dash: '-', Space: '␣', Underscore: '_', Dot: '.' } as Record<string, string>)[value ?? ''] ?? '∅';++/**+ * Glyph of a salt option.+ */+const saltGlyph = (value: string | undefined): string => ({ Prefix: '#ab', Sprinkle: 'a#b', Suffix: 'ab#' } as Record<string, string>)[value ?? ''] ?? 'ab';++/**+ * Popup to change the password generator settings, with a live preview.+ */+const PasswordSettingsPopup: React.FC<PasswordSettingsPopupProps> = ({ passwordSettings, isTemporary, onSaveSettings, onClose }) => {+ const { t, i18n } = useTranslation();+ const dbContext = useDb();+ const { showLoading, hideLoading } = useLoading();+ const notifications = useNotifications();+ const { executeVaultMutationAsync } = useVaultMutate();+ const { settings, previewPassword, dicewareLanguages, handleSettingChange, handleRefreshPreview } = usePasswordConfig({ ...passwordSettings });+ const [sliderValue, setSliderValue] = useState(lengthToSlider(passwordSettings.Length));+ const panelRef = useRef<HTMLDivElement>(null);+ const isDiceware = settings.Type === 'diceware';+ const tk = 'components.main.settings.passwordSettingsPopup';++ useClickOutside([panelRef], onClose, true);++ // The "auto" language shown when the user has not picked one explicitly, resolved like the Rust core does.+ const effectiveLanguage = useMemo(() => resolveDefaultLanguage(i18n.language, dicewareLanguages), [dicewareLanguages, i18n.language]);+ const selectedLanguage = settings.Language && settings.Language.length > 0 ? settings.Language : effectiveLanguage;++ /**+ * Save the settings to the vault and hand the preview password back.+ */+ const onSaveGlobal = async (): Promise<void> => {+ showLoading();+ await executeVaultMutationAsync(async () => {+ dbContext.sqliteClient?.settings.setPasswordSettings(settings);+ });+ hideLoading();+ notifications.addSuccessMessage(t(`${tk}.SettingsUpdatedMessage`), true);+ onSaveSettings(settings, previewPassword);+ onClose();+ };++ /**+ * Hand the settings and the preview password back without saving.+ */+ const onSaveTemporary = (): void => {+ onSaveSettings(settings, previewPassword);+ onClose();+ };++ useEffect(() => {+ /**+ * Enter saves, Escape closes.+ */+ const onKeyDown = (event: KeyboardEvent): void => {+ if (event.key === 'Escape') {+ onClose();+ } else if (event.key === 'Enter') {+ if (isTemporary) {+ onSaveTemporary();+ } else {+ void onSaveGlobal();+ }+ }+ };+ document.addEventListener('keydown', onKeyDown);+ return (): void => document.removeEventListener('keydown', onKeyDown);+ });++ /**+ * Classes of a generator type tab.+ */+ const tabClasses = (type: string): string => {+ const active = (settings.Type && settings.Type.length > 0 ? settings.Type : 'basic') === type;+ const base = '-mb-px flex-1 border-b-2 px-3 py-3 text-sm font-medium transition-colors';+ return active ? `${base} border-primary-600 text-primary-600 dark:border-primary-500 dark:text-primary-500` : `${base} border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200`;+ };++ return (+ <div className="modal-dialog fixed inset-0 z-50 overflow-auto bg-gray-500 bg-opacity-75 flex items-center justify-center">+ <div ref={panelRef} id="passwordSettingsModal" className="relative top-20 mx-auto p-5 pt-0 shadow-lg rounded-md bg-white dark:bg-gray-800 border-2 border-gray-300 dark:border-gray-400 w-96 max-w-[90vw]">+ <div className="m-2">+ <div className="flex border-b border-gray-200 dark:border-gray-700">+ <button type="button" onClick={() => handleSettingChange('Type', 'basic')} className={tabClasses('basic')}>{t(`${tk}.PasswordTypeBasic`)}</button>+ <button type="button" onClick={() => handleSettingChange('Type', 'diceware')} className={tabClasses('diceware')}>{t(`${tk}.PasswordTypeDiceware`)}</button>+ </div>++ <div className="mt-4 space-y-4">+ <div>+ <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">{t(`${tk}.PreviewLabel`)}</label>+ <div className="mt-1 flex">+ <div className="flex-grow"><CopyPasteFormRow id="preview-password" value={previewPassword} /></div>+ <button type="button" className="ml-2 px-3 py-2 text-sm text-gray-500 dark:text-white bg-gray-200 hover:bg-gray-300 focus:ring-4 focus:outline-none focus:ring-gray-300 font-medium rounded-md dark:bg-gray-600 dark:hover:bg-gray-700 dark:focus:ring-gray-800" onClick={handleRefreshPreview}>+ <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>+ </svg>+ </button>+ </div>+ </div>++ {!isDiceware ? (+ <>+ <div>+ <label htmlFor="password-length" className="block text-sm font-medium text-gray-700 dark:text-gray-300">{t(`${tk}.PasswordLengthLabel`, { 0: settings.Length })}</label>+ <input type="range" id="password-length" min={SLIDER_MIN} max={SLIDER_MAX} step="0.1" className="mt-1 w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer dark:bg-gray-700 av-range-slider" value={sliderValue} onChange={(e) => {+ const value = Number.parseFloat(e.target.value);+ setSliderValue(value);+ handleSettingChange('Length', sliderToLength(value));+ }} />+ </div>++ <div className="grid grid-cols-2 gap-2">+ <button type="button" className={toggleClasses(settings.UseLowercase)} title={t(`${tk}.IncludeLowercaseLabel`)} onClick={() => handleSettingChange('UseLowercase', !settings.UseLowercase)}><span className="font-mono text-base">a-z</span></button>+ <button type="button" className={toggleClasses(settings.UseUppercase)} title={t(`${tk}.IncludeUppercaseLabel`)} onClick={() => handleSettingChange('UseUppercase', !settings.UseUppercase)}><span className="font-mono text-base">A-Z</span></button>+ <button type="button" className={toggleClasses(settings.UseNumbers)} title={t(`${tk}.IncludeNumbersLabel`)} onClick={() => handleSettingChange('UseNumbers', !settings.UseNumbers)}><span className="font-mono text-base">0-9</span></button>+ <button type="button" className={toggleClasses(settings.UseSpecialChars)} title={t(`${tk}.IncludeSpecialCharsLabel`)} onClick={() => handleSettingChange('UseSpecialChars', !settings.UseSpecialChars)}><span className="font-mono text-base">!@#</span></button>+ </div>++ <div className="flex items-center">+ <input id="use-non-ambiguous" type="checkbox" className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded dark:bg-gray-700 dark:border-gray-600" checked={settings.UseNonAmbiguousChars} onChange={e => handleSettingChange('UseNonAmbiguousChars', e.target.checked)} />+ <label htmlFor="use-non-ambiguous" className="ml-2 block text-sm text-gray-700 dark:text-gray-300">{t(`${tk}.AvoidAmbiguousCharsLabel`)}</label>+ </div>+ </>+ ) : (+ <>+ <div>+ <div className="flex items-center justify-between mb-2">+ <label htmlFor="diceware-word-count" className="text-sm font-medium text-gray-700 dark:text-gray-300">{t(`${tk}.WordCountLabel`)}</label>+ <span className="text-sm text-gray-600 dark:text-gray-400 font-mono">{settings.WordCount}</span>+ </div>+ <input type="range" id="diceware-word-count" min={MIN_WORD_COUNT} max={MAX_WORD_COUNT} step="1" className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer dark:bg-gray-700 av-range-slider" value={settings.WordCount} onChange={e => handleSettingChange('WordCount', Number.parseInt(e.target.value, 10))} />+ </div>++ <div className="grid grid-cols-3 gap-2">+ <button type="button" className={optionClasses(settings.Capitalization !== DEFAULT_CAPITALIZATION)} title={t(`${tk}.Capitalization${settings.Capitalization ?? DEFAULT_CAPITALIZATION}`)} onClick={() => handleSettingChange('Capitalization', cycle(CAPITALIZATION_OPTIONS, settings.Capitalization))}>+ <span className="font-mono text-base">{capitalizationGlyph(settings.Capitalization)}</span>+ </button>+ <button type="button" className={optionClasses(settings.Separator !== DEFAULT_SEPARATOR)} title={`${t(`${tk}.SeparatorLabel`)}: ${t(`${tk}.Separator${settings.Separator ?? DEFAULT_SEPARATOR}`)}`} onClick={() => handleSettingChange('Separator', cycle(SEPARATOR_OPTIONS, settings.Separator))}>+ <span className="font-mono text-base">{separatorGlyph(settings.Separator)}</span>+ </button>+ <button type="button" className={optionClasses(settings.Salt !== DEFAULT_SALT)} title={`${t(`${tk}.SaltLabel`)}: ${t(`${tk}.Salt${settings.Salt ?? DEFAULT_SALT}`)}`} onClick={() => handleSettingChange('Salt', cycle(SALT_OPTIONS, settings.Salt))}>+ <span className="font-mono text-base">{saltGlyph(settings.Salt)}</span>+ </button>+ </div>++ <div>+ <label htmlFor="diceware-language" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{t(`${tk}.LanguageLabel`)}</label>+ <select id="diceware-language" className="w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md text-gray-900 dark:text-white focus:ring-primary-500 focus:border-primary-500" value={selectedLanguage} onChange={e => handleSettingChange('Language', e.target.value)}>+ {dicewareLanguages.map(language => <option key={language} value={language}>{getLanguageInfo(language).label}</option>)}+ </select>+ </div>+ </>+ )}++ <div className="flex justify-end pt-4 gap-2">+ {isTemporary && (+ <button type="button" className="px-4 py-2 bg-gray-200 text-gray-800 dark:bg-gray-700 dark:text-white rounded-md hover:bg-gray-300 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-500" onClick={onSaveTemporary}>+ {t(`${tk}.UseJustOnceButton`)}+ </button>+ )}+ <button type="button" id="save-button" className="px-4 py-2 bg-primary-600 text-white rounded-md hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-primary-500 dark:bg-primary-700 dark:hover:bg-primary-600" onClick={() => void onSaveGlobal()}>+ {t(`${tk}.SaveGloballyButton`)}+ </button>+ </div>+ </div>+ </div>+ </div>+ </div>+ );+};++export default PasswordSettingsPopup;