Skip to content

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

Add item logo picker scaffolding (#2159)

Leendert de Borst247cb24afb70
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/ItemLogoPicker.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/ItemLogoPicker.tsx
new file mode 100644
index 000000000..58d7302b3
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/ItemLogoPicker.tsx
@@ -0,0 +1,105 @@
+import React, { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import LogoPickerModal from '@/entrypoints/popup/components/Items/LogoPickerModal';
+
+import { getAppIconSvg } from '@/utils/dist/core/models/icons';
+import type { LogoSelection, Item, ItemLogo } from '@/utils/dist/core/models/vault';
+import { LogoKinds } from '@/utils/dist/core/models/vault';
+import SqliteClient from '@/utils/SqliteClient';
+
+import ItemIconComponent from './ItemIcon';
+
+type ItemLogoPickerProps = {
+ item: Item;
+ pendingSelection?: LogoSelection;
+ pendingPreview?: string | null;
+ onSelect: (selection: LogoSelection) => void;
+};
+
+/**
+ * The item's logo on the edit screen: shows what the item will look like and allows to opens the picker.
+ */
+const ItemLogoPicker: React.FC<ItemLogoPickerProps> = ({ item, pendingSelection, pendingPreview, onSelect }) => {
+ const { t } = useTranslation();
+ const [isPickerOpen, setIsPickerOpen] = useState(false);
+
+ /*
+ * What the item will show once saved: an unsaved choice takes precedence over the stored logo, so
+ * the preview matches the outcome rather than the past.
+ */
+ const effectiveLogo: ItemLogo | undefined = pendingSelection && pendingSelection.Kind !== LogoKinds.Favicon
+ ? { Id: '', Kind: pendingSelection.Kind, Source: pendingSelection.Source ?? '', Name: pendingSelection.Name }
+ : (pendingSelection ? undefined : item.LogoInfo);
+
+ /**
+ * Render the logo preview, favouring an upload that has not been stored yet.
+ */
+ const renderPreview = (): React.ReactNode => {
+ if (pendingPreview) {
+ return <img src={pendingPreview} alt="" className="w-8 h-8 object-contain" />;
+ }
+ if (effectiveLogo?.Kind === LogoKinds.Builtin) {
+ const svg = getAppIconSvg(effectiveLogo.Source);
+ if (svg) {
+ return <div className="w-8 h-8" dangerouslySetInnerHTML={{ __html: svg }} />;
+ }
+ }
+ if (effectiveLogo?.Kind === LogoKinds.Custom) {
+ const src = item.Logo ? SqliteClient.imgSrcFromBytes(item.Logo) : null;
+ if (src) {
+ return <img src={src} alt="" className="w-8 h-8 object-contain" />;
+ }
+ }
+ return <ItemIconComponent item={{ ...item, LogoInfo: effectiveLogo }} className="w-8 h-8" />;
+ };
+
+ /**
+ * One line saying where this logo comes from, so an automatic logo is never mistaken for a choice.
+ */
+ const renderProvenance = (): string => {
+ if (pendingSelection?.Kind === LogoKinds.Custom && pendingSelection.Data) {
+ return t('items.logo.sourceUploaded');
+ }
+ switch (effectiveLogo?.Kind) {
+ case LogoKinds.Builtin:
+ return t('items.logo.sourceBuiltin');
+ case LogoKinds.Custom:
+ return effectiveLogo.Name ? t('items.logo.sourceUploadedNamed', { name: effectiveLogo.Name }) : t('items.logo.sourceUploaded');
+ case LogoKinds.Favicon:
+ return t('items.logo.sourceFavicon', { domain: effectiveLogo.Source });
+ default:
+ return t('items.logo.sourceNone');
+ }
+ };
+
+ return (
+ <>
+ <div className="flex items-center gap-3">
+ <div className="flex items-center justify-center w-12 h-12 rounded-lg bg-gray-100 dark:bg-gray-700 flex-shrink-0">
+ {renderPreview()}
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium text-gray-700 dark:text-gray-300">{t('items.logo.logo')}</p>
+ <p className="text-xs text-gray-500 dark:text-gray-400 truncate">{renderProvenance()}</p>
+ </div>
+ <button
+ type="button"
+ onClick={() => setIsPickerOpen(true)}
+ className="px-3 py-1.5 text-sm rounded-lg border border-gray-200 dark:border-gray-600 text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
+ >
+ {t('items.logo.change')}
+ </button>
+ </div>
+
+ <LogoPickerModal
+ isOpen={isPickerOpen}
+ onClose={() => setIsPickerOpen(false)}
+ currentLogo={effectiveLogo}
+ onSelect={onSelect}
+ />
+ </>
+ );
+};
+
+export default ItemLogoPicker;
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/LogoPickerModal.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/LogoPickerModal.tsx
new file mode 100644
index 000000000..e5b3d75e5
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/LogoPickerModal.tsx
@@ -0,0 +1,201 @@
+import React, { useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import ModalWrapper from '@/entrypoints/popup/components/Dialogs/ModalWrapper';
+import { useDb } from '@/entrypoints/popup/context/DbContext';
+import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
+
+import type { CustomLogoEntry } from '@/utils/db/repositories/LogoRepository';
+import { AppIconSvgs, getAllAppIconKeys } from '@/utils/dist/core/models/icons';
+import type { LogoSelection, ItemLogo } from '@/utils/dist/core/models/vault';
+import { LogoKinds } from '@/utils/dist/core/models/vault';
+import { LogoImageError, LogoImageService } from '@/utils/LogoImageService';
+import SqliteClient from '@/utils/SqliteClient';
+
+type LogoPickerModalProps = {
+ isOpen: boolean;
+ onClose: () => void;
+ currentLogo?: ItemLogo;
+ onSelect: (selection: LogoSelection) => void;
+};
+
+/**
+ * Lets the user change an item's logo.
+ */
+const LogoPickerModal: React.FC<LogoPickerModalProps> = ({ isOpen, onClose, currentLogo, onSelect }) => {
+ const { t } = useTranslation();
+ const dbContext = useDb();
+ const { executeVaultMutationAsync } = useVaultMutate();
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const [library, setLibrary] = useState<CustomLogoEntry[]>([]);
+ const [uploadError, setUploadError] = useState<string | null>(null);
+ const [isManaging, setIsManaging] = useState(false);
+
+ /**
+ * Load the user's custom uploaded logos.
+ */
+ useEffect(() => {
+ if (!isOpen || !dbContext?.sqliteClient) {
+ return;
+ }
+ setUploadError(null);
+ setIsManaging(false);
+ setLibrary(dbContext.sqliteClient.logos.listCustom());
+ }, [isOpen, dbContext?.sqliteClient]);
+
+ /**
+ * Apply a choice and close: the item's save is what actually writes it.
+ */
+ const choose = useCallback((selection: LogoSelection): void => {
+ onSelect(selection);
+ onClose();
+ }, [onSelect, onClose]);
+
+ /**
+ * Decode, resize and hand over an uploaded file. The bytes are stored when the item is saved, so
+ * cancelling the edit leaves nothing behind.
+ */
+ const handleFile = useCallback(async (file: File | undefined): Promise<void> => {
+ if (!file) {
+ return;
+ }
+
+ try {
+ const prepared = await LogoImageService.prepare(file);
+ choose({ Kind: LogoKinds.Custom, Data: prepared.data, MimeType: prepared.mimeType, Name: file.name });
+ } catch (error) {
+ const reason = error instanceof LogoImageError ? error.reason : 'decodeFailed';
+ setUploadError(t(`items.logo.uploadErrors.${reason}`));
+ }
+ }, [choose, t]);
+
+ /**
+ * Remove a custom logo from the library.
+ */
+ const handleDelete = useCallback(async (logoId: string): Promise<void> => {
+ if (!dbContext?.sqliteClient) {
+ return;
+ }
+
+ try {
+ await executeVaultMutationAsync(async () => {
+ dbContext.sqliteClient!.logos.softDelete(logoId, new Date().toISOString());
+ });
+ setLibrary(dbContext.sqliteClient.logos.listCustom());
+ } catch (error) {
+ console.error('Error deleting logo:', error);
+ }
+ }, [dbContext?.sqliteClient, executeVaultMutationAsync]);
+
+ /**
+ * Whether a choice is the one the item shows today, so it reads as selected.
+ */
+ const isCurrent = (kind: string, source: string): boolean => currentLogo?.Kind === kind && currentLogo?.Source === source;
+
+ return (
+ <ModalWrapper isOpen={isOpen} onClose={onClose} title={t('items.logo.chooseLogo')} maxWidth="max-w-md">
+ <div className="space-y-4">
+ <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}`)}
+ onClick={() => choose({ Kind: LogoKinds.Builtin, Source: key })}
+ className={`flex items-center justify-center p-2 rounded-lg border transition-colors hover:bg-gray-100 dark:hover:bg-gray-700 ${
+ isCurrent(LogoKinds.Builtin, key)
+ ? 'border-primary-500 bg-primary-50 dark:bg-primary-900/30'
+ : 'border-gray-200 dark:border-gray-600'
+ }`}
+ >
+ <div className="w-7 h-7" dangerouslySetInnerHTML={{ __html: AppIconSvgs[key] }} />
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-2">
+ <h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">{t('items.logo.yourLogos')}</h3>
+ {library.length > 0 && (
+ <button
+ type="button"
+ onClick={() => setIsManaging(prev => !prev)}
+ className="text-xs text-primary-600 dark:text-primary-400 hover:underline"
+ >
+ {isManaging ? t('common.cancel') : t('items.logo.manage')}
+ </button>
+ )}
+ </div>
+ <div className="grid grid-cols-5 gap-2">
+ {library.map(logo => {
+ const src = logo.FileData ? SqliteClient.imgSrcFromBytes(logo.FileData) : null;
+ return src ? (
+ <div key={logo.Id} className="relative">
+ <button
+ type="button"
+ title={logo.Name ?? undefined}
+ onClick={() => choose({ Kind: LogoKinds.Custom, Source: logo.Source })}
+ className={`w-full flex items-center justify-center p-2 rounded-lg border transition-colors hover:bg-gray-100 dark:hover:bg-gray-700 ${
+ isCurrent(LogoKinds.Custom, logo.Source)
+ ? 'border-primary-500 bg-primary-50 dark:bg-primary-900/30'
+ : 'border-gray-200 dark:border-gray-600'
+ }`}
+ >
+ <img src={src} alt={logo.Name ?? ''} className="w-7 h-7 object-contain" />
+ </button>
+ {isManaging && (
+ <button
+ type="button"
+ title={t('common.delete')}
+ onClick={() => void handleDelete(logo.Id)}
+ className="absolute -top-1.5 -right-1.5 w-5 h-5 flex items-center justify-center rounded-full bg-red-600 text-white text-xs hover:bg-red-700"
+ >
+ <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" strokeWidth="2.5" stroke="currentColor">
+ <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
+ </svg>
+ </button>
+ )}
+ </div>
+ ) : null;
+ })}
+ <button
+ type="button"
+ onClick={() => fileInputRef.current?.click()}
+ className="flex items-center justify-center p-2 rounded-lg border border-dashed border-gray-300 dark:border-gray-600 text-gray-400 hover:text-primary-500 hover:border-primary-500 transition-colors"
+ title={t('items.logo.uploadLogo')}
+ >
+ <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
+ <path strokeLinecap="round" strokeLinejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
+ </svg>
+ </button>
+ </div>
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept={LogoImageService.acceptAttribute}
+ className="hidden"
+ onChange={(e) => {
+ void handleFile(e.target.files?.[0]);
+ e.target.value = '';
+ }}
+ />
+ <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">{t('items.logo.uploadHint')}</p>
+ {uploadError && <p className="mt-1 text-xs text-red-600 dark:text-red-400">{uploadError}</p>}
+ </div>
+
+ <button
+ type="button"
+ onClick={() => choose({ Kind: LogoKinds.Favicon })}
+ className="w-full px-4 py-2 text-sm rounded-lg border border-gray-200 dark:border-gray-600 text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
+ >
+ {t('items.logo.useAutomatic')}
+ </button>
+ </div>
+ </ModalWrapper>
+ );
+};
+
+export default LogoPickerModal;
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
index cb8c8f05c..da4b62ea6 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
@@ -17,6 +17,7 @@ import { HeaderIconType } from '@/entrypoints/popup/components/Icons/HeaderIcons
import AttachmentUploader from '@/entrypoints/popup/components/Items/Details/AttachmentUploader';
import PasskeyEditor from '@/entrypoints/popup/components/Items/Details/PasskeyEditor';
import TotpEditor from '@/entrypoints/popup/components/Items/Details/TotpEditor';
+import ItemLogoPicker from '@/entrypoints/popup/components/Items/ItemLogoPicker';
import ItemNameInput from '@/entrypoints/popup/components/Items/ItemNameInput';
import ItemTypeSelector from '@/entrypoints/popup/components/Items/ItemTypeSelector';
import LoadingSpinner from '@/entrypoints/popup/components/LoadingSpinner';
@@ -30,11 +31,12 @@ import useServiceDetection from '@/entrypoints/popup/hooks/useServiceDetection';
import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
import { UsernameEmailGenerator, Gender } from '@/utils/dist/core/identity-generator';
-import type { Item, ItemField, ItemType, FieldType, Attachment, TotpCode, PasswordSettings } from '@/utils/dist/core/models/vault';
-import { FieldCategories, FieldTypes, ItemTypes, getSystemFieldsForItemType, getOptionalFieldsForItemType, isFieldShownByDefault, getSystemField, fieldAppliesToType } from '@/utils/dist/core/models/vault';
+import type { Item, ItemField, ItemType, FieldType, Attachment, TotpCode, PasswordSettings, LogoSelection } from '@/utils/dist/core/models/vault';
+import { FieldCategories, FieldTypes, LogoKinds, ItemTypes, getSystemFieldsForItemType, getOptionalFieldsForItemType, isFieldShownByDefault, getSystemField, fieldAppliesToType } from '@/utils/dist/core/models/vault';
import { FaviconService } from '@/utils/FaviconService';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
+import SqliteClient from '@/utils/SqliteClient';
import { browser } from '#imports';
@@ -114,6 +116,8 @@ const ItemAddEdit: React.FC = () => {
// UI visibility state
const [showTypeDropdown, setShowTypeDropdown] = useState(false);
+ const [logoSelection, setLogoSelection] = useState<LogoSelection | undefined>(undefined);
+ const [logoPreview, setLogoPreview] = useState<string | null>(null);
const [show2FA, setShow2FA] = useState(false);
const [showAttachments, setShowAttachments] = useState(false);
@@ -663,6 +667,14 @@ const ItemAddEdit: React.FC = () => {
}));
}, []);
+ /**
+ * Handle the user choosing a logo. Changes are only persisted when the item itself is saved.
+ */
+ const handleLogoSelect = useCallback((selection: LogoSelection) => {
+ setLogoSelection(selection);
+ setLogoPreview(selection.Data ? SqliteClient.imgSrcFromBytes(selection.Data) : null);
+ }, []);
+
/**
* After creating a credential from a page's "create new item" flow, autofill the freshly
* created item back into the originating tab and close this popup window. Returns true when the
@@ -781,7 +793,8 @@ const ItemAddEdit: React.FC = () => {
* Only call if we have a URL value to avoid unnecessary processing.
*/
const urlValue = fieldValues['login.url'];
- if (dbContext?.sqliteClient && urlValue) {
+ const usesAutomaticLogo = !logoSelection || logoSelection.Kind === LogoKinds.Favicon;
+ if (dbContext?.sqliteClient && urlValue && usesAutomaticLogo) {
updatedItem = await FaviconService.fetchAndAttachFavicon(
updatedItem,
urlValue,
@@ -809,7 +822,8 @@ const ItemAddEdit: React.FC = () => {
originalAttachmentIds,
attachments,
originalTotpCodeIds,
- totpCodes
+ totpCodes,
+ logoSelection
);
// Delete passkeys marked for deletion
@@ -819,7 +833,7 @@ const ItemAddEdit: React.FC = () => {
}
}
} else {
- await dbContext.sqliteClient!.items.create(updatedItem, attachments, totpCodes);
+ await dbContext.sqliteClient!.items.create(updatedItem, attachments, totpCodes, logoSelection);
}
});
@@ -849,7 +863,7 @@ const ItemAddEdit: React.FC = () => {
console.error('Error saving item:', err);
setIsSaving(false);
}
- }, [item, isSaving, fieldValues, applicableSystemFields, customFields, dbContext, isEditMode, executeVaultMutationAsync, navigate, location.state, originalAttachmentIds, attachments, originalTotpCodeIds, totpCodes, passkeyIdsMarkedForDeletion, webApi, clearPersistedValues, fillBackAndCloseWindow]);
+ }, [item, isSaving, fieldValues, applicableSystemFields, customFields, dbContext, isEditMode, executeVaultMutationAsync, navigate, location.state, originalAttachmentIds, attachments, originalTotpCodeIds, totpCodes, passkeyIdsMarkedForDeletion, logoSelection, webApi, clearPersistedValues, fillBackAndCloseWindow]);
/**
* Handle delete action.
@@ -1373,6 +1387,12 @@ const ItemAddEdit: React.FC = () => {
{/* Item Name and Primary fields block */}
<FormSection>
+ <ItemLogoPicker
+ item={item}
+ pendingSelection={logoSelection}
+ pendingPreview={logoPreview}
+ onSelect={handleLogoSelect}
+ />
<ItemNameInput
inputRef={nameInputRef}
value={item.Name || ''}