Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add item logo picker to web app (#2413)
Leendert de Borst7a0c8c2dbda0
diff --git a/apps/web/src/components/items/FolderSelector.tsx b/apps/web/src/components/items/FolderSelector.tsxindex 2453ee0c4..e3954df34 100644--- a/apps/web/src/components/items/FolderSelector.tsx+++ b/apps/web/src/components/items/FolderSelector.tsx@@ -138,14 +138,28 @@ const FolderSelector: React.FC<FolderSelectorProps> = ({ selectedFolder, onSelecreturn (<>- <div className="flex items-center gap-2 mt-2">- <svg className="w-4 h-4 text-gray-400 dark:text-gray-500 flex-shrink-0" 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" />+ <button+ type="button"+ id="folder-selector"+ onClick={() => setShowFolderModal(true)}+ className={`flex w-full items-center gap-2 mt-2.5 px-3 py-1 text-sm font-medium rounded-lg transition-colors ${selectedFolder+ ? 'text-gray-600 dark:text-gray-400 bg-gray-100 dark:bg-gray-700 border border-transparent hover:bg-gray-200 dark:hover:bg-gray-600'+ : 'text-gray-500 dark:text-gray-400 border border-dashed border-gray-300 dark:border-gray-600 hover:text-primary-600 dark:hover:text-primary-400 hover:border-primary-400 dark:hover:border-primary-500'}`}+ >+ {selectedFolder ? (+ <svg className="w-4 h-4 text-orange-500 flex-shrink-0" 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>+ ) : (+ <svg className="w-4 h-4 flex-shrink-0" 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>+ )}+ <span className="truncate">{selectedFolder ? selectedFolderRow?.Name : t(`${tk}.NoFolder`)}</span>+ <svg className="w-3.5 h-3.5 ml-auto flex-shrink-0 opacity-70" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2">+ <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" /></svg>- <button type="button" onClick={() => setShowFolderModal(true)} className="text-sm text-gray-500 dark:text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 transition-colors">- {selectedFolder ? <span className="text-primary-600 dark:text-primary-400">{selectedFolderRow?.Name}</span> : <span>{t(`${tk}.NoFolder`)}</span>}- </button>- </div>+ </button><FormModalisOpen={showFolderModal}diff --git a/apps/web/src/components/items/ItemLogoPicker.tsx b/apps/web/src/components/items/ItemLogoPicker.tsxnew file mode 100644index 000000000..0987465d9--- /dev/null+++ b/apps/web/src/components/items/ItemLogoPicker.tsx@@ -0,0 +1,65 @@+import { effectiveItemLogo, logoSourceTranslationKey } from '@aliasvault/client/items/ItemLogoView';+import React, { useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import ItemIcon from '@/components/items/ItemIcon';+import LogoPickerModal from '@/components/items/LogoPickerModal';++import type { Item, LogoSelection } from '@aliasvault/models/vault';++type ItemLogoPickerProps = {+ item: Item;+ pendingSelection?: LogoSelection;+ faviconSource?: string | null;+ websiteSource?: string | null;+ isFetching?: boolean;+ onSelect: (selection: LogoSelection) => void;+ onFetchFromWebsite: () => void;+};++/**+ * The item's icon on the edit page.+ */+const ItemLogoPicker: React.FC<ItemLogoPickerProps> = ({ item, pendingSelection, faviconSource, websiteSource, isFetching = false, onSelect, onFetchFromWebsite }) => {+ const { t } = useTranslation();+ const [isPickerOpen, setIsPickerOpen] = useState(false);+ const closePicker = useCallback((): void => setIsPickerOpen(false), []);++ const effectiveLogo = effectiveItemLogo(item.LogoInfo, pendingSelection, faviconSource);+ const source = t(logoSourceTranslationKey(effectiveLogo), { domain: effectiveLogo?.Source });++ return (+ <>+ <button+ type="button"+ id="item-logo-picker"+ onClick={() => setIsPickerOpen(true)}+ title={`${t('items.logo.chooseLogo')}: ${source}`}+ aria-label={t('items.logo.chooseLogo')}+ className="flex items-center justify-center w-20 h-20 flex-shrink-0 cursor-pointer rounded-lg bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 hover:bg-primary-50 dark:hover:bg-primary-900/30 hover:border-primary-500 dark:hover:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors"+ >+ {isFetching ? (+ <svg className="animate-spin w-7 h-7 text-gray-500 dark:text-gray-300" 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>+ ) : (+ <ItemIcon item={{ ...item, LogoInfo: effectiveLogo }} sizeClass="w-12 h-12" />+ )}+ </button>++ {isPickerOpen && (+ <LogoPickerModal+ item={item}+ currentLogo={effectiveLogo}+ websiteSource={websiteSource}+ onSelect={onSelect}+ onFetchFromWebsite={onFetchFromWebsite}+ onClose={closePicker}+ />+ )}+ </>+ );+};++export default ItemLogoPicker;diff --git a/apps/web/src/components/items/LogoPickerModal.tsx b/apps/web/src/components/items/LogoPickerModal.tsxnew file mode 100644index 000000000..0aad9fe6b--- /dev/null+++ b/apps/web/src/components/items/LogoPickerModal.tsx@@ -0,0 +1,124 @@+import { logoSourceTranslationKey } from '@aliasvault/client/items/ItemLogoView';+import { AppIconSvgs, getAllAppIconKeys } from '@aliasvault/models/icons';+import { LogoKinds } from '@aliasvault/models/vault';+import React, { useCallback, useEffect } from 'react';+import { useTranslation } from 'react-i18next';++import ItemIcon from '@/components/items/ItemIcon';+import Modal from '@/components/shared/Modal';++import type { Item, ItemLogo, LogoSelection } from '@aliasvault/models/vault';++type LogoPickerModalProps = {+ item: Item;+ currentLogo?: ItemLogo;+ websiteSource?: string | null;+ onSelect: (selection: LogoSelection) => void;+ onFetchFromWebsite: () => void;+ onClose: () => void;+};++/**+ * Lets the user change an item's icon.+ */+const LogoPickerModal: React.FC<LogoPickerModalProps> = ({ item, currentLogo, websiteSource, onSelect, onFetchFromWebsite, onClose }) => {+ const { t } = useTranslation();++ useEffect(() => {+ /**+ * Escape closes the modal.+ */+ const onKeyDown = (event: KeyboardEvent): void => {+ if (event.key === 'Escape') {+ onClose();+ }+ };+ document.addEventListener('keydown', onKeyDown);+ return (): void => document.removeEventListener('keydown', onKeyDown);+ }, [onClose]);++ /**+ * Apply a choice and close: the item's save is what actually writes it.+ */+ const choose = useCallback((selection: LogoSelection): void => {+ if (selection.Kind === LogoKinds.Favicon) {+ onFetchFromWebsite();+ } else {+ onSelect(selection);+ }+ onClose();+ }, [onFetchFromWebsite, onSelect, onClose]);++ /**+ * Describe a logo: a library icon by its name, any other by where it comes from.+ */+ const describe = (logo: ItemLogo | undefined): string => {+ return logo?.Kind === LogoKinds.Builtin ? t(`items.logo.builtin.${logo.Source}`) : t(logoSourceTranslationKey(logo), { domain: logo?.Source });+ };++ return (+ <Modal id="logoPickerModal" onBackdropClick={onClose} panelClassName="w-full max-w-md flex flex-col max-h-[90vh]">+ <div className="p-4 border-b border-gray-200 dark:border-gray-700">+ <div className="flex items-center justify-between">+ <h2 className="text-xl font-bold text-gray-900 dark:text-white">{t('items.logo.chooseLogo')}</h2>+ <button type="button" onClick={onClose} className="text-gray-400 hover:text-gray-500 dark:hover:text-gray-300" title={t('sharedResources.Close')} aria-label={t('sharedResources.Close')}>+ <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />+ </svg>+ </button>+ </div>+ </div>++ <div className="flex-1 overflow-y-auto p-4 space-y-4">+ <div className="flex items-center gap-3 px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600">+ <div className="flex items-center justify-center w-10 h-10 flex-shrink-0 rounded-md bg-gray-100 dark:bg-gray-700">+ <ItemIcon item={{ ...item, LogoInfo: currentLogo }} sizeClass="w-7 h-7" />+ </div>+ <div className="min-w-0">+ <div className="text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">{t('items.logo.currentLogo')}</div>+ <div className="text-sm text-gray-900 dark:text-white truncate">{describe(currentLogo)}</div>+ </div>+ </div>++ <div>+ <h3 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">{t('items.logo.builtinLogos')}</h3>+ <div className="grid grid-cols-5 gap-2">+ {getAllAppIconKeys().map(key => (+ <button+ key={key}+ type="button"+ title={t(`items.logo.builtin.${key}`)}+ aria-label={t(`items.logo.builtin.${key}`)}+ onClick={() => choose({ Kind: LogoKinds.Builtin, Source: key })}+ className="flex items-center justify-center p-2 rounded-lg border border-gray-200 dark:border-gray-600 transition-colors hover:bg-primary-50 dark:hover:bg-primary-900/30 hover:border-primary-500 dark:hover:border-primary-500"+ >+ <span className="w-8 h-8 inline-block [&>svg]:w-full [&>svg]:h-full" dangerouslySetInnerHTML={{ __html: AppIconSvgs[key] }} />+ </button>+ ))}+ </div>+ </div>++ {/* Only offered when the URL field contains a (valid) URL. */}+ {websiteSource && (+ <button+ type="button"+ onClick={() => choose({ Kind: LogoKinds.Favicon })}+ className="w-full flex items-center gap-3 px-3 py-2 text-left rounded-lg border border-gray-200 dark:border-gray-600 transition-colors hover:bg-primary-50 dark:hover:bg-primary-900/30 hover:border-primary-500 dark:hover:border-primary-500"+ >+ <svg className="w-5 h-5 flex-shrink-0 text-primary-600 dark:text-primary-400" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M12 21a9 9 0 100-18 9 9 0 000 18zm0 0a8.95 8.95 0 003.2-9 8.95 8.95 0 00-3.2-9m0 18a8.95 8.95 0 01-3.2-9A8.95 8.95 0 0112 3m-8.7 6h17.4M3.3 15h17.4" /></svg>+ <span className="min-w-0">+ <span className="block text-sm text-gray-900 dark:text-white">+ {currentLogo?.Kind === LogoKinds.Favicon ? t('items.logo.refetchFromWebsite') : t('items.logo.fetchFromWebsite')}+ </span>+ <span className="block text-xs text-gray-500 dark:text-gray-400 truncate">+ {t('items.logo.sourceFavicon', { domain: websiteSource })}+ </span>+ </span>+ </button>+ )}+ </div>+ </Modal>+ );+};++export default LogoPickerModal;diff --git a/apps/web/src/hooks/useItemLogo.ts b/apps/web/src/hooks/useItemLogo.tsnew file mode 100644index 000000000..1f40be91b--- /dev/null+++ b/apps/web/src/hooks/useItemLogo.ts@@ -0,0 +1,199 @@+import { FaviconService } from '@aliasvault/client/items/FaviconService';+import { usesWebsiteLogo } from '@aliasvault/client/items/ItemLogoView';+import { LogoKinds } from '@aliasvault/models/vault';+import { useCallback, useEffect, useRef, useState } from 'react';++import { useDb } from '@/context/DbContext';+import { useWebApi } from '@/context/WebApiContext';++import type { LogoKind, LogoSelection } from '@aliasvault/models/vault';++/**+ * Debounce time for the URL field after typing before its favicon is looked up.+ */+const URL_SETTLE_MS = 600;++type UseItemLogoOptions = {+ url: string | string[] | undefined;+ currentLogoKind?: LogoKind;+ isReady: boolean;+ isExistingItem: boolean;+ onLogoBytesChange: (data?: Uint8Array) => void;+};++type UseItemLogoResult = {+ logoSelection: LogoSelection | undefined;+ isFetchingLogo: boolean;+ resolvedFaviconSource: string | null;+ websiteSource: string | null;+ selectLogo: (selection: LogoSelection) => void;+ fetchLogoFromWebsite: () => Promise<void>;+};++/**+ * Owns the icon shown while adding or editing an item.+ *+ * @param options The URL to follow, the item's current logo, and where to hand resolved icon bytes+ * @returns The icon choice, its loading state, and the actions the picker triggers+ */+const useItemLogo = ({ url, currentLogoKind, isReady, isExistingItem, onLogoBytesChange }: UseItemLogoOptions): UseItemLogoResult => {+ const dbContext = useDb();+ const webApi = useWebApi();++ const [logoSelection, setLogoSelection] = useState<LogoSelection | undefined>(undefined);+ const [isFetchingLogo, setIsFetchingLogo] = useState(false);+ const [isResolvePending, setIsResolvePending] = useState(!isExistingItem);+ const [resolvedFaviconSource, setResolvedFaviconSource] = useState<string | null>(null);+ const [websiteSource, setWebsiteSource] = useState<string | null>(null);++ const resolvedSourceRef = useRef<string | null>(null);+ const requestIdRef = useRef(0);+ const hasInitialisedRef = useRef(false);+ const fetchedRef = useRef(new Map<string, Uint8Array | null>());+ const fetchInFlightRef = useRef<Promise<unknown> | null>(null);+ const usesWebsiteIcon = logoSelection ? usesWebsiteLogo(logoSelection) : (currentLogoKind ?? LogoKinds.Favicon) === LogoKinds.Favicon;++ /**+ * Resolve the favicon for the URL the item currently has.+ * @param force Fetch from the server even when the vault already holds this domain's icon+ */+ const resolveFromWebsite = useCallback(async (force: boolean): Promise<void> => {+ const sqliteClient = dbContext.sqliteClient;+ if (!sqliteClient) {+ return;+ }++ const requestId = ++requestIdRef.current;+ setIsFetchingLogo(true);+ try {+ const target = await FaviconService.resolveTarget(url);+ if (requestId !== requestIdRef.current) {+ return;+ }++ const source = target?.source ?? null;+ resolvedSourceRef.current = source;+ setResolvedFaviconSource(source);+ setLogoSelection({ Kind: LogoKinds.Favicon });++ if (!target) {+ onLogoBytesChange(undefined);+ return;+ }++ const stored = await FaviconService.getStoredFavicon(target, sqliteClient.logos);+ if (requestId !== requestIdRef.current) {+ return;+ }+ onLogoBytesChange(stored ?? undefined);+ if (stored && !force) {+ return;+ }++ while (fetchInFlightRef.current) {+ await fetchInFlightRef.current;+ if (requestId !== requestIdRef.current) {+ return;+ }+ }++ if (!force && fetchedRef.current.has(target.source)) {+ const cached = fetchedRef.current.get(target.source);+ if (cached) {+ onLogoBytesChange(cached);+ }+ return;+ }++ const request = FaviconService.fetchFavicon(target, sqliteClient.logos, webApi, { ignoreStored: true });+ fetchInFlightRef.current = request;+ const result = await request.finally(() => {+ if (fetchInFlightRef.current === request) {+ fetchInFlightRef.current = null;+ }+ });+ fetchedRef.current.set(target.source, result.success && result.imageData ? result.imageData : null);+ if (requestId !== requestIdRef.current) {+ return;+ }++ if (result.success && result.imageData) {+ onLogoBytesChange(result.imageData);+ setLogoSelection(force ? { Kind: LogoKinds.Favicon, Data: result.imageData } : { Kind: LogoKinds.Favicon });+ }+ } finally {+ if (requestId === requestIdRef.current) {+ setIsFetchingLogo(false);+ }+ }+ }, [dbContext.sqliteClient, onLogoBytesChange, url, webApi]);++ /**+ * Follow the URL field: once it settles on a different domain, that domain's favicon is resolved.+ */+ useEffect(() => {+ if (!isReady) {+ return;+ }++ let cancelled = false;+ let timer: ReturnType<typeof setTimeout> | undefined;++ (async (): Promise<void> => {+ const source = (await FaviconService.resolveTarget(url))?.source ?? null;+ if (cancelled) {+ return;+ }+ setWebsiteSource(source);++ const isFirstRun = !hasInitialisedRef.current;+ hasInitialisedRef.current = true;+ if (isFirstRun && isExistingItem) {+ resolvedSourceRef.current = source;+ setIsResolvePending(false);+ return;+ }++ if (!usesWebsiteIcon || resolvedSourceRef.current === source) {+ setIsResolvePending(false);+ return;+ }++ if (isFirstRun) {+ void resolveFromWebsite(false);+ setIsResolvePending(false);+ return;+ }++ setIsResolvePending(true);+ timer = setTimeout(() => {+ void resolveFromWebsite(false);+ setIsResolvePending(false);+ }, URL_SETTLE_MS);+ })();++ return (): void => {+ cancelled = true;+ clearTimeout(timer);+ };+ }, [isExistingItem, isReady, resolveFromWebsite, url, usesWebsiteIcon]);++ /**+ * Apply a favicon the user picked from the built-in catalog.+ */+ const selectLogo = useCallback((selection: LogoSelection): void => {+ requestIdRef.current++;+ setIsFetchingLogo(false);+ setIsResolvePending(false);+ setLogoSelection(selection);+ }, []);++ /**+ * Fetch the website's favicon on request, replacing a favicon that has gone stale.+ */+ const fetchLogoFromWebsite = useCallback((): Promise<void> => resolveFromWebsite(true), [resolveFromWebsite]);++ return { logoSelection, isFetchingLogo: isFetchingLogo || isResolvePending, resolvedFaviconSource, websiteSource, selectLogo, fetchLogoFromWebsite };+};++export default useItemLogo;diff --git a/apps/web/src/hooks/useSaveItem.ts b/apps/web/src/hooks/useSaveItem.tsindex df809675a..82a334e52 100644--- a/apps/web/src/hooks/useSaveItem.ts+++ b/apps/web/src/hooks/useSaveItem.ts@@ -1,4 +1,5 @@import { FaviconService } from '@aliasvault/client/items/FaviconService';+import { usesWebsiteLogo } from '@aliasvault/client/items/ItemLogoView';import { FieldKey } from '@aliasvault/models/vault';import { useCallback } from 'react';@@ -8,6 +9,7 @@ import { useVaultMutate } from '@/hooks/useVaultMutate';import { type ItemEdit, itemEditToItem } from '@/models/ItemEdit';import type { ItemRef } from '@aliasvault/client/database/ItemRef';+import type { Item, LogoSelection } from '@aliasvault/models/vault';/*** How an item form is saved.@@ -17,6 +19,9 @@ export type SaveItemOptions = {originalAttachmentIds?: string[];originalTotpCodeIds?: string[];deletePasskeys?: boolean;+ logoSelection?: LogoSelection;+ resolvedFaviconSource?: string | null;+ resolvedFaviconBytes?: Item['Logo'];};/**@@ -35,7 +40,12 @@ export function useSaveItem(): { saveItem: (edit: ItemEdit, options?: SaveItemOplet item = itemEditToItem(edit);const urlValue = item.Fields.find(f => f.FieldKey === FieldKey.LoginUrl)?.Value;- if (urlValue && urlValue.length > 0) {+ // The form's preview already fetched this domain's icon: save exactly what it shows instead of fetching again.+ const usesAutomaticLogo = usesWebsiteLogo(options.logoSelection);+ const isLogoResolved = usesAutomaticLogo && !!options.resolvedFaviconSource && options.resolvedFaviconSource === (await FaviconService.resolveTarget(urlValue))?.source;+ if (isLogoResolved) {+ item.Logo = options.resolvedFaviconBytes;+ } else if (usesAutomaticLogo && urlValue && urlValue.length > 0) {item = await FaviconService.fetchAndAttachFavicon(item, urlValue, client.logos, webApi);} else {item.Logo = undefined;@@ -46,14 +56,14 @@ export function useSaveItem(): { saveItem: (edit: ItemEdit, options?: SaveItemOpconst original = options.original;if (original) {// A folder change can move the item to another manifest; the update reports where it ended up.- saved = await client.items.update(original, item, options.originalAttachmentIds ?? [], edit.Attachments, options.originalTotpCodeIds ?? [], edit.TotpCodes) ?? original;+ saved = await client.items.update(original, item, options.originalAttachmentIds ?? [], edit.Attachments, options.originalTotpCodeIds ?? [], edit.TotpCodes, options.logoSelection) ?? original;if (options.deletePasskeys) {for (const passkey of edit.Passkeys) {await client.passkeys.deleteById(passkey.Id, saved.ManifestId);}}} else {- saved = await client.items.create(item, edit.Attachments.filter(a => !a.IsDeleted), edit.TotpCodes.filter(c => !c.IsDeleted));+ saved = await client.items.create(item, edit.Attachments.filter(a => !a.IsDeleted), edit.TotpCodes.filter(c => !c.IsDeleted), options.logoSelection);}});diff --git a/apps/web/src/i18n/locales/en.json b/apps/web/src/i18n/locales/en.jsonindex 7ace40220..84360566e 100644--- a/apps/web/src/i18n/locales/en.json+++ b/apps/web/src/i18n/locales/en.json@@ -675,6 +675,31 @@"content": {"vaultUpgradeRequired": "Vault upgrade required."},+ "items": {+ "logo": {+ "builtin": {+ "Bank": "Banking",+ "Dev": "Development",+ "Game": "Games",+ "Health": "Health",+ "Mail": "Mail",+ "Media": "Media",+ "Shopping": "Shopping",+ "Social": "Social",+ "Travel": "Travel",+ "Work": "Work"+ },+ "builtinLogos": "Icon library",+ "chooseLogo": "Choose icon",+ "currentLogo": "Current icon",+ "fetchFromWebsite": "Fetch icon from website",+ "refetchFromWebsite": "(Re)fetch icon from website",+ "sourceBuiltin": "Built-in icon",+ "sourceCustom": "Custom icon",+ "sourceFavicon": "From {{domain}}",+ "sourceNone": "No icon"+ }+ },"layout": {"footer": {"CopyrightText": "All rights reserved.",diff --git a/apps/web/src/pages/items/AddEdit.tsx b/apps/web/src/pages/items/AddEdit.tsxindex ca45c1ba9..b83b6070b 100644--- a/apps/web/src/pages/items/AddEdit.tsx+++ b/apps/web/src/pages/items/AddEdit.tsx@@ -1,11 +1,11 @@-import { fieldAppliesToType, FieldKey, getFieldConfigForType, getOptionalFieldsForItemType, getSystemField, getSystemFieldsForItemType, type ItemType, ItemTypes, SystemFieldRegistry } from '@aliasvault/models/vault';-import React, { useCallback, useEffect, useRef, useState } from 'react';+import { fieldAppliesToType, FieldKey, getFieldConfigForType, getOptionalFieldsForItemType, getSystemField, getSystemFieldsForItemType, type Item, type ItemLogo, type ItemType, ItemTypes, SystemFieldRegistry } from '@aliasvault/models/vault';+import React, { useCallback, useEffect, useMemo, 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 EditFormRow, { EDIT_INPUT_CLASSES } from '@/components/forms/EditFormRow';import EditPasswordFormRow from '@/components/forms/EditPasswordFormRow';import EditUsernameFormRow from '@/components/forms/EditUsernameFormRow';import EmailDomainField from '@/components/forms/EmailDomainField';@@ -14,11 +14,13 @@ 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 ItemLogoPicker from '@/components/items/ItemLogoPicker';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 Card from '@/components/shared/Card';+import FormLabel from '@/components/shared/FormLabel';import PageContent from '@/components/shared/PageContent';import PageHeader from '@/components/shared/PageHeader';import StickyActionBar from '@/components/shared/StickyActionBar';@@ -27,12 +29,13 @@ import { useDb } from '@/context/DbContext';import { useLoading } from '@/context/LoadingContext';import { useNotifications } from '@/context/NotificationContext';import { useWebApi } from '@/context/WebApiContext';+import useItemLogo from '@/hooks/useItemLogo';import { usePageTitle } from '@/hooks/usePageTitle';import { useSaveItem } from '@/hooks/useSaveItem';import { VaultPushFailedError } from '@/hooks/useVaultMutate';import {addCustomField, createNewItemEdit, DEFAULT_SERVICE_URL, getCustomFields, getFieldValue, getFieldValues, hasAliasValues, hasFieldValue,- type ItemEdit, itemEditFromItem, removeCustomField, reorderCustomFields, setFieldValue, setFieldValues, setFolder, updateCustomField,+ type ItemEdit, itemEditFromItem, itemEditToItem, removeCustomField, reorderCustomFields, setFieldValue, setFieldValues, setFolder, updateCustomField,} from '@/models/ItemEdit';import { waitForMinimumDuration } from '@/utils/Delay';import { generateAliasEmail, generateIdentity, generateRandomEmail, generateUsername, type GeneratedAliasData } from '@/utils/IdentityGenerator';@@ -62,9 +65,9 @@ const PasskeyIcon: React.FC<{ className: string }> = ({ className }) => ();/**- * The item create and edit page.+ * The item create and edit form.*/-const ItemAddEdit: React.FC = () => {+const ItemAddEditForm: React.FC = () => {const { manifestId, id } = useParams<{ manifestId: string; id: string }>();const { t } = useTranslation();const navigate = useNavigate();@@ -94,6 +97,13 @@ const ItemAddEdit: React.FC = () => {const originalTotpCodeIds = useRef<string[]>([]);const originalAttachmentIds = useRef<string[]>([]);const lastGenerated = useRef<GeneratedAliasData | null>(null);+ const [storedLogo, setStoredLogo] = useState<ItemLogo | undefined>(undefined);+ const [logoBytes, setLogoBytes] = useState<Item['Logo']>(undefined);++ /**+ * Keep the icon bytes the form previews, so saving stores exactly what is shown.+ */+ const handleLogoBytesChange = useCallback((data?: Uint8Array): void => setLogoBytes(current => current === data ? current : data), []);/*** Apply a change to the form.@@ -197,6 +207,8 @@ const ItemAddEdit: React.FC = () => {const totpCodes = client.items.getTotpCodesForItem(ref);const attachments = client.items.getAttachmentsForItem(ref);const passkeys = client.passkeys.getByItemId(ref);+ setStoredLogo(item.LogoInfo);+ setLogoBytes(item.Logo);let loaded = itemEditFromItem(item, totpCodes, attachments, passkeys);originalTotpCodeIds.current = loaded.TotpCodes.map(c => c.Id);originalAttachmentIds.current = loaded.Attachments.map(a => a.Id);@@ -258,6 +270,18 @@ const ItemAddEdit: React.FC = () => {}, [dbContext.sqliteClient, editMode, manifestId, id, location.search]);const hasLoginFields = edit.ItemType === ItemTypes.Login || edit.ItemType === ItemTypes.Alias;+ const urlKey = getFieldValues(edit, FieldKey.LoginUrl).join('\n');+ const logoUrls = useMemo(() => urlKey.split('\n'), [urlKey]);++ // The item's icon: a pick from the built-in catalog, or the website's own favicon resolved from the URL.+ const { logoSelection, isFetchingLogo, resolvedFaviconSource, websiteSource, selectLogo, fetchLogoFromWebsite } = useItemLogo({+ url: logoUrls,+ currentLogoKind: storedLogo?.Kind,+ isReady: !loading,+ isExistingItem: editMode,+ onLogoBytesChange: handleLogoBytesChange,+ });+ const logoPreviewItem = useMemo(() => ({ ...itemEditToItem(edit), LogoInfo: storedLogo, Logo: logoBytes }), [edit, storedLogo, logoBytes]);/*** Whether a system field is on the form: it applies to the type and was added, was there on load, has a value or@@ -385,7 +409,7 @@ const ItemAddEdit: React.FC = () => {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 });+ const saved = await saveItem(edit, { original: editMode && manifestId ? { Id: edit.Id, ManifestId: manifestId } : undefined, originalAttachmentIds: originalAttachmentIds.current, originalTotpCodeIds: originalTotpCodeIds.current, deletePasskeys: passkeyMarkedForDeletion, logoSelection, resolvedFaviconSource, resolvedFaviconBytes: logoBytes });// Keep the saving indicator up for a moment: a save that completes instantly reads as a flicker.await waitForMinimumDuration(startedAt, MIN_SAVE_INDICATOR_MS);notifications.addSuccessMessage(editMode ? t(`${tk}.ItemUpdatedSuccess`) : t(`${tk}.ItemCreatedSuccess`));@@ -491,12 +515,26 @@ const ItemAddEdit: React.FC = () => {<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))} />+ <FormLabel htmlFor="service-name">{t(`${tk}.ServiceNameLabel`)}</FormLabel>+ <div className="flex items-start gap-4">+ <ItemLogoPicker+ item={logoPreviewItem}+ pendingSelection={logoSelection}+ faviconSource={resolvedFaviconSource}+ websiteSource={websiteSource}+ isFetching={isFetchingLogo}+ onSelect={selectLogo}+ onFetchFromWebsite={() => void fetchLogoFromWebsite()}+ />+ <div className="flex-1 min-w-0">+ <input type="text" id="service-name" autoComplete="off" className={EDIT_INPUT_CLASSES} value={edit.ServiceName} placeholder={t(`${tk}.ServiceNamePlaceholder`)} autoCapitalize="off" autoCorrect="off" onChange={(e) => {+ setNameError('');+ update(current => ({ ...current, ServiceName: e.target.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>+ </div></div>{shouldShowField(FieldKey.LoginUrl) && (<div className="col-span-6 sm:col-span-3">@@ -718,4 +756,13 @@ const ItemAddEdit: React.FC = () => {);};+/**+ * The item create and edit page.+ */+const ItemAddEdit: React.FC = () => {+ const { manifestId, id } = useParams<{ manifestId: string; id: string }>();+ const location = useLocation();+ return <ItemAddEditForm key={`${manifestId}/${id}${location.search}`} />;+};+export default ItemAddEdit;