Skip to content

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

Update ItemLogoPicker UI/UX (#2159)

Leendert de Borsta7498126d2df
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/ItemLogoPicker.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/ItemLogoPicker.tsx
index 5f7c1ff3a..e96a5c021 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/ItemLogoPicker.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/ItemLogoPicker.tsx
@@ -4,24 +4,24 @@ import { useTranslation } from 'react-i18next';
import LogoPickerModal from '@/entrypoints/popup/components/Items/LogoPickerModal';
import type { DraftItem } from '@/utils/db/ItemRef';
-import { getAppIconSvg } 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 SqliteClient from '@/utils/SqliteClient';
import ItemIconComponent from './ItemIcon';
type ItemLogoPickerProps = {
item: DraftItem;
pendingSelection?: LogoSelection;
- pendingPreview?: string | null;
+ faviconSource?: string | null;
+ isFetching?: boolean;
onSelect: (selection: LogoSelection) => void;
+ onFetchFromWebsite: () => void;
};
/**
- * The item's logo on the edit screen: shows what the item will look like and allows to opens the picker.
+ * The item's icon on the edit screen: shows what the item will look like and opens the picker.
*/
-const ItemLogoPicker: React.FC<ItemLogoPickerProps> = ({ item, pendingSelection, pendingPreview, onSelect }) => {
+const ItemLogoPicker: React.FC<ItemLogoPickerProps> = ({ item, pendingSelection, faviconSource, isFetching = false, onSelect, onFetchFromWebsite }) => {
const { t } = useTranslation();
const [isPickerOpen, setIsPickerOpen] = useState(false);
@@ -29,44 +29,22 @@ const ItemLogoPicker: React.FC<ItemLogoPickerProps> = ({ item, pendingSelection,
* 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);
+ let effectiveLogo: ItemLogo | undefined = item.LogoInfo;
+ if (pendingSelection?.Kind === LogoKinds.Favicon) {
+ effectiveLogo = faviconSource ? { Id: '', Kind: LogoKinds.Favicon, Source: faviconSource } : undefined;
+ } else if (pendingSelection) {
+ effectiveLogo = { Id: '', Kind: pendingSelection.Kind, Source: pendingSelection.Source ?? '', Name: pendingSelection.Name };
+ }
/**
- * Render the logo preview, favouring an upload that has not been stored yet.
+ * Display the source of the logo.
*/
- const renderPreview = (): React.ReactNode => {
- if (pendingPreview) {
- return <img src={pendingPreview} alt="" className="w-6 h-6 object-contain" />;
- }
- if (effectiveLogo?.Kind === LogoKinds.Builtin) {
- const svg = getAppIconSvg(effectiveLogo.Source);
- if (svg) {
- return <div className="w-6 h-6" 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-6 h-6 object-contain" />;
- }
- }
- return <ItemIconComponent item={{ ...item, LogoInfo: effectiveLogo }} className="w-6 h-6" />;
- };
-
- /**
- * 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');
- }
+ const renderSource = (): string => {
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');
+ return t('items.logo.sourceCustom');
case LogoKinds.Favicon:
return t('items.logo.sourceFavicon', { domain: effectiveLogo.Source });
default:
@@ -79,11 +57,18 @@ const ItemLogoPicker: React.FC<ItemLogoPickerProps> = ({ item, pendingSelection,
<button
type="button"
onClick={() => setIsPickerOpen(true)}
- title={`${t('items.logo.chooseLogo')} — ${renderProvenance()}`}
+ title={`${t('items.logo.chooseLogo')} — ${renderSource()}`}
aria-label={t('items.logo.chooseLogo')}
className="group relative flex items-center justify-center w-[calc(2.5rem+2px)] h-[calc(2.5rem+2px)] flex-shrink-0 cursor-pointer rounded-md bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 hover:bg-gray-200 dark:hover:bg-gray-600 hover:border-primary-500 dark:hover:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors"
>
- {renderPreview()}
+ {isFetching ? (
+ <svg className="animate-spin w-5 h-5 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>
+ ) : (
+ <ItemIconComponent item={{ ...item, LogoInfo: effectiveLogo }} className="w-6 h-6" />
+ )}
{/* Hovering dims the logo and reveals a full-size pencil, so the click target reads as "edit" without a badge too small to recognise. */}
<span className="absolute inset-0 flex items-center justify-center rounded-md bg-gray-900/60 text-white opacity-0 group-hover:opacity-100 transition-opacity">
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
@@ -97,6 +82,7 @@ const ItemLogoPicker: React.FC<ItemLogoPickerProps> = ({ item, pendingSelection,
onClose={() => setIsPickerOpen(false)}
currentLogo={effectiveLogo}
onSelect={onSelect}
+ onFetchFromWebsite={onFetchFromWebsite}
/>
</>
);
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/LogoPickerModal.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/LogoPickerModal.tsx
index e75faf282..d8c314394 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/LogoPickerModal.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/LogoPickerModal.tsx
@@ -1,47 +1,25 @@
-import React, { useCallback, useEffect, useRef, useState } from 'react';
+import React, { useCallback } 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;
+ onFetchFromWebsite: () => void;
};
/**
- * Lets the user change an item's logo.
+ * Lets the user change an item's icon.
*/
-const LogoPickerModal: React.FC<LogoPickerModalProps> = ({ isOpen, onClose, currentLogo, onSelect }) => {
+const LogoPickerModal: React.FC<LogoPickerModalProps> = ({ isOpen, onClose, currentLogo, onSelect, onFetchFromWebsite }) => {
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.
@@ -52,45 +30,12 @@ const LogoPickerModal: React.FC<LogoPickerModalProps> = ({ isOpen, onClose, curr
}, [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.deleteById(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.
+ * Start the favicon fetch from the website.
*/
- const isCurrent = (kind: string, source: string): boolean => currentLogo?.Kind === kind && currentLogo?.Source === source;
+ const fetchFromWebsite = useCallback((): void => {
+ onFetchFromWebsite();
+ onClose();
+ }, [onFetchFromWebsite, onClose]);
return (
<ModalWrapper isOpen={isOpen} onClose={onClose} title={t('items.logo.chooseLogo')} maxWidth="max-w-md">
@@ -105,7 +50,7 @@ const LogoPickerModal: React.FC<LogoPickerModalProps> = ({ isOpen, onClose, curr
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)
+ currentLogo?.Kind === LogoKinds.Builtin && currentLogo.Source === key
? 'border-primary-500 bg-primary-50 dark:bg-primary-900/30'
: 'border-gray-200 dark:border-gray-600'
}`}
@@ -116,82 +61,13 @@ const LogoPickerModal: React.FC<LogoPickerModalProps> = ({ isOpen, onClose, curr
</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>
-
+ {/* Fetching is also how an item goes back to the website's icon after a built-in one was picked. */}
<button
type="button"
- onClick={() => choose({ Kind: LogoKinds.Favicon })}
+ onClick={fetchFromWebsite}
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')}
+ {currentLogo?.Kind === LogoKinds.Favicon ? t('items.logo.refetchFromWebsite') : t('items.logo.fetchFromWebsite')}
</button>
</div>
</ModalWrapper>
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useItemLogo.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useItemLogo.ts
new file mode 100644
index 000000000..dc4b6c4e7
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useItemLogo.ts
@@ -0,0 +1,152 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import { useDb } from '@/entrypoints/popup/context/DbContext';
+import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
+
+import type { LogoKind, LogoSelection } from '@/utils/dist/core/models/vault';
+import { LogoKinds } from '@/utils/dist/core/models/vault';
+import { FaviconService } from '@/utils/FaviconService';
+
+/**
+ * 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;
+ 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 [resolvedFaviconSource, setResolvedFaviconSource] = useState<string | null>(null);
+
+ const resolvedSourceRef = useRef<string | null>(null);
+ const requestIdRef = useRef(0);
+ const hasInitialisedRef = useRef(false);
+ const usesWebsiteIcon = logoSelection ? logoSelection.Kind === LogoKinds.Favicon : (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 normalizedUrl = FaviconService.extractFirstValidUrl(url);
+ const source = normalizedUrl ? FaviconService.extractSourceFromUrl(normalizedUrl) : 'unknown';
+ const previousSource = resolvedSourceRef.current;
+ const requestId = ++requestIdRef.current;
+
+ resolvedSourceRef.current = source;
+ setResolvedFaviconSource(source === 'unknown' ? null : source);
+ setLogoSelection({ Kind: LogoKinds.Favicon });
+
+ // Without a domain there is nothing to fetch from, so automatic means no icon at all.
+ if (!normalizedUrl || source === 'unknown') {
+ onLogoBytesChange(undefined);
+ return;
+ }
+
+ // The vault already holds this domain's favicon: show that one.
+ if (!force) {
+ const stored = FaviconService.getStoredFavicon(normalizedUrl, sqliteClient);
+ if (stored) {
+ onLogoBytesChange(stored);
+ return;
+ }
+ }
+
+ if (previousSource !== source) {
+ onLogoBytesChange(undefined);
+ }
+
+ setIsFetchingLogo(true);
+ try {
+ const result = await FaviconService.fetchFavicon(normalizedUrl, sqliteClient, webApi, { ignoreStored: true });
+ if (requestId !== requestIdRef.current) {
+ return;
+ }
+
+ if (result.success && result.imageData) {
+ onLogoBytesChange(result.imageData);
+ setLogoSelection(force ? { Kind: LogoKinds.Favicon, Data: result.imageData } : { Kind: LogoKinds.Favicon });
+ } else if (previousSource !== source) {
+ onLogoBytesChange(undefined);
+ }
+ } 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;
+ }
+
+ const normalizedUrl = FaviconService.extractFirstValidUrl(url);
+ const source = normalizedUrl ? FaviconService.extractSourceFromUrl(normalizedUrl) : 'unknown';
+
+ if (!hasInitialisedRef.current) {
+ hasInitialisedRef.current = true;
+ if (isExistingItem) {
+ resolvedSourceRef.current = source;
+ return;
+ }
+ }
+
+ if (!usesWebsiteIcon || resolvedSourceRef.current === source) {
+ return;
+ }
+
+ const timer = setTimeout(() => void resolveFromWebsite(false), URL_SETTLE_MS);
+ return (): void => 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);
+ 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, resolvedFaviconSource, selectLogo, fetchLogoFromWebsite };
+};
+
+export default useItemLogo;
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 098055d37..ce5d26aa7 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
@@ -27,19 +27,19 @@ import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import useAliasGenerator from '@/entrypoints/popup/hooks/useAliasGenerator';
import useFormPersistence from '@/entrypoints/popup/hooks/useFormPersistence';
+import useItemLogo from '@/entrypoints/popup/hooks/useItemLogo';
import useServiceDetection from '@/entrypoints/popup/hooks/useServiceDetection';
import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
import type { DraftItem } from '@/utils/db/ItemRef';
import type { Folder } from '@/utils/db/repositories/FolderRepository';
-import type { ItemField, ItemType, FieldType, Attachment, TotpCode, PasswordSettings, LogoSelection } from '@/utils/dist/core/models/vault';
+import type { ItemField, ItemType, FieldType, Attachment, TotpCode, PasswordSettings } 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 { NavigationStateService } from '@/utils/NavigationStateService';
import * as RustCore from '@/utils/RustCore';
-import SqliteClient from '@/utils/SqliteClient';
import { browser } from '#imports';
@@ -120,8 +120,6 @@ 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);
@@ -662,13 +660,23 @@ const ItemAddEdit: React.FC = () => {
}, []);
/**
- * Handle the user choosing a logo. Changes are only persisted when the item itself is saved.
+ * Put icon bytes on the item so the editor previews exactly what saving will store.
*/
- const handleLogoSelect = useCallback((selection: LogoSelection) => {
- setLogoSelection(selection);
- setLogoPreview(selection.Data ? SqliteClient.imgSrcFromBytes(selection.Data) : null);
+ const handleLogoBytesChange = useCallback((data?: Uint8Array) => {
+ setItem(prev => (!prev || prev.Logo === data) ? prev : { ...prev, Logo: data });
}, []);
+ /*
+ * The item's favicon: a pick from the built-in catalog, or the website's own favicon extracted from the URL.
+ */
+ const { logoSelection, isFetchingLogo, resolvedFaviconSource, selectLogo, fetchLogoFromWebsite } = useItemLogo({
+ url: fieldValues['login.url'],
+ currentLogoKind: item?.LogoInfo?.Kind,
+ isReady: !localLoading && item !== null,
+ isExistingItem: isEditMode,
+ onLogoBytesChange: handleLogoBytesChange
+ });
+
/**
* 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
@@ -794,11 +802,13 @@ const ItemAddEdit: React.FC = () => {
/*
* Fetch and attach favicon from URL if needed (handles deduplication internally).
- * Only call if we have a URL value to avoid unnecessary processing.
+ * Only call if we have a URL value to avoid unnecessary processing, and not when the editor
+ * already resolved this URL's icon: if a preview fetched the icon and stored it in memory, we don't need to fetch it again.
*/
const urlValue = fieldValues['login.url'];
const usesAutomaticLogo = !logoSelection || logoSelection.Kind === LogoKinds.Favicon;
- if (dbContext?.sqliteClient && urlValue && usesAutomaticLogo) {
+ const isLogoResolved = usesAutomaticLogo && resolvedFaviconSource === FaviconService.extractSourceFromUrl(FaviconService.extractFirstValidUrl(urlValue));
+ if (dbContext?.sqliteClient && urlValue && usesAutomaticLogo && !isLogoResolved) {
updatedItem = await FaviconService.fetchAndAttachFavicon(
updatedItem,
urlValue,
@@ -867,7 +877,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, logoSelection, webApi, clearPersistedValues, fillBackAndCloseWindow]);
+ }, [item, isSaving, fieldValues, applicableSystemFields, customFields, dbContext, isEditMode, executeVaultMutationAsync, navigate, location.state, originalAttachmentIds, attachments, originalTotpCodeIds, totpCodes, passkeyIdsMarkedForDeletion, logoSelection, resolvedFaviconSource, webApi, clearPersistedValues, fillBackAndCloseWindow]);
/**
* Handle delete action.
@@ -1402,8 +1412,10 @@ const ItemAddEdit: React.FC = () => {
<ItemLogoPicker
item={item}
pendingSelection={logoSelection}
- pendingPreview={logoPreview}
- onSelect={handleLogoSelect}
+ faviconSource={resolvedFaviconSource}
+ isFetching={isFetchingLogo}
+ onSelect={selectLogo}
+ onFetchFromWebsite={() => void fetchLogoFromWebsite()}
/>
}
/>
diff --git a/apps/browser-extension/src/i18n/locales/en.json b/apps/browser-extension/src/i18n/locales/en.json
index 0a50471a5..0445290d4 100644
--- a/apps/browser-extension/src/i18n/locales/en.json
+++ b/apps/browser-extension/src/i18n/locales/en.json
@@ -277,6 +277,28 @@
"publicEmailDescription": "Anonymous but limited privacy. Email content is readable by anyone that knows the address.",
"validation": {
"required": "This field is required"
+ },
+ "logo": {
+ "chooseLogo": "Choose icon",
+ "builtinLogos": "Built-in icons",
+ "fetchFromWebsite": "Fetch icon from website",
+ "refetchFromWebsite": "(Re)fetch icon from website",
+ "sourceFavicon": "From {{domain}}",
+ "sourceBuiltin": "Built-in icon",
+ "sourceCustom": "Custom icon",
+ "sourceNone": "No icon",
+ "builtin": {
+ "Shopping": "Shopping",
+ "Bank": "Banking",
+ "Mail": "Mail",
+ "Social": "Social",
+ "Work": "Work",
+ "Game": "Games",
+ "Media": "Media",
+ "Travel": "Travel",
+ "Health": "Health",
+ "Dev": "Development"
+ }
}
},
"itemTypes": {
diff --git a/apps/browser-extension/src/utils/FaviconService.ts b/apps/browser-extension/src/utils/FaviconService.ts
index e752b5ad8..603ed0754 100644
--- a/apps/browser-extension/src/utils/FaviconService.ts
+++ b/apps/browser-extension/src/utils/FaviconService.ts
@@ -14,6 +14,20 @@ export type FaviconFetchResult = {
error?: string;
};
+/**
+ * Options for a favicon fetch.
+ */
+export type FaviconFetchOptions = {
+ /**
+ * Fetch even when the vault already holds a favicon for the domain. Set for an explicit re-fetch,
+ * where the point is to replace a favicon that has gone stale.
+ */
+ ignoreStored?: boolean;
+
+ /** Timeout in milliseconds (default: 5000ms). */
+ timeoutMs?: number;
+};
+
/**
* Default timeout for favicon fetch operations (5 seconds).
*/
@@ -104,21 +118,32 @@ export class FaviconService {
return sqliteClient.logos.hasFaviconForSource(source);
}
+ /**
+ * The icon the vault already holds for this URL's domain, if any.
+ * @param urlString The URL to look an icon up for
+ * @param sqliteClient The SQLite client instance
+ * @returns The stored icon bytes, or null when the vault holds none
+ */
+ public static getStoredFavicon(urlString: string | undefined | null, sqliteClient: SqliteClient): Uint8Array | null {
+ const source = FaviconService.extractSourceFromUrl(urlString);
+ return source === 'unknown' ? null : sqliteClient.logos.getFaviconData(source);
+ }
+
/**
* Fetch favicon for a URL from the server API.
- * Includes deduplication check and timeout handling.
* @param urlString The URL to fetch favicon for
* @param sqliteClient The SQLite client for deduplication check
* @param webApi The WebAPI service for making the request
- * @param timeoutMs Optional timeout in milliseconds (default: 5000ms)
+ * @param options Optional fetch options
* @returns FaviconFetchResult with success status and image data
*/
public static async fetchFavicon(
urlString: string | undefined | null,
sqliteClient: SqliteClient,
webApi: WebApiService,
- timeoutMs: number = FAVICON_FETCH_TIMEOUT_MS
+ options: FaviconFetchOptions = {}
): Promise<FaviconFetchResult> {
+ const timeoutMs = options.timeoutMs ?? FAVICON_FETCH_TIMEOUT_MS;
// Validate URL
const normalizedUrl = FaviconService.normalizeUrl(urlString);
if (!normalizedUrl) {
@@ -132,7 +157,7 @@ export class FaviconService {
}
// Check if logo already exists (deduplication)
- if (sqliteClient.logos.hasFaviconForSource(source)) {
+ if (!options.ignoreStored && sqliteClient.logos.hasFaviconForSource(source)) {
return { success: false, skipped: true };
}
diff --git a/apps/browser-extension/src/utils/LogoImageService.ts b/apps/browser-extension/src/utils/LogoImageService.ts
deleted file mode 100644
index 109199f1d..000000000
--- a/apps/browser-extension/src/utils/LogoImageService.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-/**
- * Prepares user-supplied images for storage as item logos.
- */
-
-const LOGO_MAX_SIZE = 128;
-const MAX_UPLOAD_BYTES = 5 * 1024 * 1024;
-const ACCEPTED_MIME_TYPES = ['image/png', 'image/jpeg', 'image/webp', 'image/gif', 'image/x-icon', 'image/vnd.microsoft.icon', 'image/svg+xml'];
-
-/**
- * The result of preparing an image for storage.
- */
-export type PreparedLogo = {
- data: Uint8Array;
- mimeType: string;
-};
-
-/**
- * Error thrown when an upload cannot be turned into a logo. The `reason` maps to a translation key
- * so the UI can explain what went wrong.
- */
-export class LogoImageError extends Error {
- /**
- * Create an error describing why an upload cannot become a logo.
- * @param reason Why the image was rejected; maps to a translation key.
- */
- public constructor(public readonly reason: 'tooLarge' | 'unsupportedType' | 'decodeFailed') {
- super(reason);
- this.name = 'LogoImageError';
- }
-}
-
-/**
- * Service for turning uploaded image files into stored logo bytes.
- */
-export class LogoImageService {
- /**
- * The `accept` attribute for the file picker, matching what prepare() can decode.
- * @returns A comma-separated MIME type list
- */
- public static get acceptAttribute(): string {
- return ACCEPTED_MIME_TYPES.join(',');
- }
-
- /**
- * Decode, scale and re-encode an uploaded file as a square-fitting PNG.
- * @param file The file the user picked
- * @returns The logo bytes to store
- * @throws LogoImageError when the file is too large, of an unsupported type, or undecodable
- */
- public static async prepare(file: File): Promise<PreparedLogo> {
- if (file.size > MAX_UPLOAD_BYTES) {
- throw new LogoImageError('tooLarge');
- }
- if (file.type && !ACCEPTED_MIME_TYPES.includes(file.type)) {
- throw new LogoImageError('unsupportedType');
- }
-
- const image = await LogoImageService.loadImage(file);
- const scale = Math.min(1, LOGO_MAX_SIZE / Math.max(image.width, image.height));
- const width = Math.max(1, Math.round(image.width * scale));
- const height = Math.max(1, Math.round(image.height * scale));
-
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
- const context = canvas.getContext('2d');
- if (!context) {
- throw new LogoImageError('decodeFailed');
- }
- context.drawImage(image, 0, 0, width, height);
-
- const blob = await new Promise<Blob | null>(resolve => canvas.toBlob(resolve, 'image/png'));
- if (!blob) {
- throw new LogoImageError('decodeFailed');
- }
-
- return { data: new Uint8Array(await blob.arrayBuffer()), mimeType: 'image/png' };
- }
-
- /**
- * Decode a file into an image element. Going through an object URL rather than createImageBitmap
- * keeps .ico and .svg working.
- * @param file The file to decode
- * @returns The loaded image
- */
- private static loadImage(file: File): Promise<HTMLImageElement> {
- return new Promise((resolve, reject) => {
- const objectUrl = URL.createObjectURL(file);
- const image = new Image();
-
- /**
- * Release the object URL once the browser is done with it, either way.
- */
- const cleanup = (): void => URL.revokeObjectURL(objectUrl);
-
- /**
- * The browser decoded the file: hand the image over.
- */
- image.onload = () : void => {
- cleanup();
- resolve(image);
- };
-
- /**
- * The browser could not decode the file (corrupt, or a type it does not support).
- */
- image.onerror = () : void => {
- cleanup();
- reject(new LogoImageError('decodeFailed'));
- };
- image.src = objectUrl;
- });
- }
-}
diff --git a/apps/browser-extension/src/utils/db/repositories/ItemRepository.ts b/apps/browser-extension/src/utils/db/repositories/ItemRepository.ts
index 2b2923e62..b9dd6b980 100644
--- a/apps/browser-extension/src/utils/db/repositories/ItemRepository.ts
+++ b/apps/browser-extension/src/utils/db/repositories/ItemRepository.ts
@@ -810,17 +810,14 @@ export class ItemRepository extends BaseRepository {
* go back to the automatic favicon;
* 2. otherwise a logo the user chose earlier (built-in or uploaded) is kept, so editing the URL
* never silently replaces a deliberate choice with a favicon;
- * 3. otherwise the favicon for the item's current domain, which is looked up rather than carried
- * over: an item whose URL changed must not keep the previous site's logo.
+ * 3. a favicon selection carrying bytes is a re-fetch of the current domain, which refreshes the
+ * image the domain's row holds;
*
- * Rule 2 also keeps the logo of an item inside a shared manifest pointing at the manifest's own row.
- * Re-resolving would swap in the personal-scope row, which the next push would then copy over the
- * shared manifest's logo: a write every member sees, every time anyone edits the item.
* @param item The item being created or updated
* @param currentDateTime The current date/time string for timestamps
- * @param existingLogoId The logo the item currently has, when updating
- * @param selection A logo the user explicitly picked or uploaded
- * @returns The logo ID to store on the item, or null when it should have none
+ * @param existingLogoId The favicon the item currently has, when updating
+ * @param selection A favicon the user explicitly picked or uploaded
+ * @returns The favicon ID to store on the item, or null when it should have none
*/
private async resolveLogoId(
item: DraftItem,
@@ -853,6 +850,15 @@ export class ItemRepository extends BaseRepository {
return null;
}
+ /*
+ * An explicit re-fetch: the user asked for this domain's favicon to be pulled again because the one
+ * on file went stale, so the fresh bytes replace it.
+ */
+ const refetched = selection?.Kind === LogoKinds.Favicon && selection.Data ? this.logoRepository.convertToUint8Array(selection.Data) : null;
+ if (refetched && refetched.length > 0) {
+ return this.logoRepository.getOrCreate(scope, LogoKinds.Favicon, source, refetched, currentDateTime, { mimeType: 'image/x-icon' });
+ }
+
// Keep the current favicon when it is already this domain's, whatever scope it lives in.
if (existing && existing.Kind === LogoKinds.Favicon && existing.Source === source) {
return this.logoRepository.adoptIntoScope(scope, LogoKinds.Favicon, source, currentDateTime);
diff --git a/apps/browser-extension/src/utils/db/repositories/LogoRepository.ts b/apps/browser-extension/src/utils/db/repositories/LogoRepository.ts
index ca2673025..f00874277 100644
--- a/apps/browser-extension/src/utils/db/repositories/LogoRepository.ts
+++ b/apps/browser-extension/src/utils/db/repositories/LogoRepository.ts
@@ -40,6 +40,16 @@ export class LogoRepository extends BaseRepository {
return rows.length > 0;
}
+ /**
+ * The image bytes the vault already holds for a domain, in any manifest.
+ * @param source The normalized source domain (e.g., 'github.com')
+ * @returns The favicon bytes, or null when no manifest holds one for this domain
+ */
+ public getFaviconData(source: string): Uint8Array | null {
+ const row = this.client.executeQuery<{ FileData: Uint8Array | null }>(LogoQueries.GET_BEST_FOR_KEY, [LogoKinds.Favicon, source])[0];
+ return row?.FileData && row.FileData.length > 0 ? new Uint8Array(row.FileData) : null;
+ }
+
/**
* Get the id of the logo with this kind and key inside one manifest, if that manifest holds it.
* @param manifestId The manifest to look in