Skip to content

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

Add logo picker UI to mobile app (#2159)

Leendert de Borstf0cb755cc10b
diff --git a/apps/mobile-app/components/items/AddEditItemScreen.tsx b/apps/mobile-app/components/items/AddEditItemScreen.tsx
index d23e8cc4e..0bfd79d10 100644
--- a/apps/mobile-app/components/items/AddEditItemScreen.tsx
+++ b/apps/mobile-app/components/items/AddEditItemScreen.tsx
@@ -1,6 +1,6 @@
-import { Buffer } from 'buffer';
-
import { manifestForItemIn, type ItemRef } from '@aliasvault/client/database/ItemRef';
+import { FaviconService } from '@aliasvault/client/items/FaviconService';
+import { usesWebsiteLogo } from '@aliasvault/client/items/ItemLogoView';
import * as RustCore from '@aliasvault/client/rust/RustCore';
import { IdentityHelperUtils } from '@aliasvault/models/identity';
import { ItemTypes, isItemType, getSystemFieldsForItemType, getOptionalFieldsForItemType, isFieldShownByDefault, getSystemField, fieldAppliesToType, FieldCategories, FieldTypes } from '@aliasvault/models/vault';
@@ -13,13 +13,14 @@ import { useTranslation } from 'react-i18next';
import { StyleSheet, View, Keyboard, Platform, ScrollView, KeyboardAvoidingView, TouchableOpacity } from 'react-native';
import Toast from 'react-native-toast-message';
-import type { DisplayItem } from '@/utils/DisplayItem';
+import { logoToDataUri, type DisplayItem } from '@/utils/DisplayItem';
import emitter, { type ItemChangedEvent } from '@/utils/EventEmitter';
import { HapticsUtility } from '@/utils/HapticsUtility';
import { itemRoute } from '@/utils/ItemRoute';
import { extractServiceNameFromUrl, sanitizeServiceUrl } from '@/utils/UrlUtility';
import { useColors } from '@/hooks/useColorScheme';
+import { useItemLogo } from '@/hooks/useItemLogo';
import { useVaultMutate } from '@/hooks/useVaultMutate';
import { ConfirmDialog } from '@/components/common/ConfirmDialog';
@@ -35,6 +36,7 @@ import { MultiValueField } from '@/components/form/MultiValueField';
import { ResizableTextArea } from '@/components/form/ResizableTextArea';
import { AttachmentUploader } from '@/components/items/details/AttachmentUploader';
import { TotpEditor } from '@/components/items/details/TotpEditor';
+import { ItemLogoPicker } from '@/components/items/ItemLogoPicker';
import { ItemTypeSelector } from '@/components/items/ItemTypeSelector';
import LoadingOverlay from '@/components/LoadingOverlay';
import { ThemedContainer } from '@/components/themed/ThemedContainer';
@@ -47,7 +49,6 @@ import { useWebApi } from '@/context/WebApiContext';
import type { Folder } from '@aliasvault/client/database/repositories/FolderRepository';
import type { Identity } from '@aliasvault/models/identity';
import type { Attachment, Item, ItemField, TotpCode, ItemType, FieldType, PasswordSettings } from '@aliasvault/models/vault';
-import type { FaviconExtractModel } from '@aliasvault/models/webapi';
// Default item type for new items
const DEFAULT_ITEM_TYPE: ItemType = ItemTypes.Login;
@@ -95,6 +96,8 @@ export default function AddEditItemScreen({ editRef }: AddEditItemScreenProps):
const totpShowAddFormRef = useRef<(() => void) | null>(null);
const [passkeyIds, setPasskeyIds] = useState<string[]>([]);
const [passkeyIdsMarkedForDeletion, setPasskeyIdsMarkedForDeletion] = useState<string[]>([]);
+ // The favicon bytes the editor resolved, kept out of React state; the item only carries them as a data URI.
+ const pendingLogoBytesRef = useRef<Uint8Array | undefined>(undefined);
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [showDiscardConfirm, setShowDiscardConfirm] = useState(false);
@@ -381,6 +384,26 @@ export default function AddEditItemScreen({ editRef }: AddEditItemScreenProps):
handleFieldChange('login.email', email);
}, [dbContext.sqliteClient, handleFieldChange]);
+ /**
+ * Update the logo preview in the editor when the resolved icon bytes change.
+ */
+ const handleLogoBytesChange = useCallback((data?: Uint8Array): void => {
+ pendingLogoBytesRef.current = data;
+ const logoDataUri = data ? logoToDataUri(data) : undefined;
+ setItem(prev => (!prev || prev.LogoDataUri === logoDataUri) ? prev : { ...prev, LogoDataUri: logoDataUri });
+ }, []);
+
+ /*
+ * The item's icon: a pick from the built-in catalog, or the website's own favicon extracted from the URL.
+ */
+ const { logoSelection, isFetchingLogo, resolvedFaviconSource, websiteSource, selectLogo, fetchLogoFromWebsite } = useItemLogo({
+ url: fieldValues['login.url'],
+ currentLogoKind: item?.LogoInfo?.Kind,
+ isReady: item !== null,
+ isExistingItem: isEditMode,
+ onLogoBytesChange: handleLogoBytesChange
+ });
+
/**
* Prevent accidental dismissal when there are unsaved changes.
* Shows custom dialog on Android, stores pending action for later execution.
@@ -817,36 +840,18 @@ export default function AddEditItemScreen({ editRef }: AddEditItemScreenProps):
UpdatedAt: new Date().toISOString()
};
- // Extract favicon from URL if present.
- const faviconTarget = await RustCore.selectFaviconTarget(RustCore.toUrlList(fieldValues['login.url']));
-
- if (faviconTarget && dbContext.sqliteClient) {
- // Only fetch favicon if no logo exists for this source (deduplication)
- const hasExistingLogo = await dbContext.sqliteClient.logos.hasFaviconForSource(faviconTarget.source);
-
- if (!hasExistingLogo) {
- // Only show loading indicator when fetching favicon
+ // Save the logo to the item.
+ if (usesWebsiteLogo(logoSelection) && dbContext.sqliteClient) {
+ const faviconTarget = await FaviconService.resolveTarget(fieldValues['login.url']);
+ if (faviconTarget && resolvedFaviconSource === faviconTarget.source) {
+ itemToSave.Logo = pendingLogoBytesRef.current;
+ } else if (faviconTarget && !(await dbContext.sqliteClient.logos.hasFaviconForSource(faviconTarget.source))) {
+ // Only show the loading indicator when fetching the favicon.
setIsSaving(true);
setSaveStatus(t('vault.savingChangesToVault'));
-
- try {
- const timeoutPromise = new Promise((_, reject) =>
- setTimeout(() => reject(new Error('Favicon extraction timed out')), 5000)
- );
-
- const faviconPromise = webApi.get<FaviconExtractModel>('Favicon/Extract?url=' + encodeURIComponent(faviconTarget.url));
- const faviconResponse = await Promise.race([faviconPromise, timeoutPromise]) as FaviconExtractModel;
- if (faviconResponse?.image) {
- const decodedImage = Uint8Array.from(Buffer.from(faviconResponse.image as string, 'base64'));
- itemToSave.Logo = decodedImage;
- }
- } catch {
- // Favicon extraction failed or timed out - not critical, continue with save
- }
+ const result = await FaviconService.fetchFavicon(faviconTarget, dbContext.sqliteClient.logos, webApi, { ignoreStored: true });
+ itemToSave.Logo = result.success ? result.imageData : undefined;
}
- } else if (!faviconTarget) {
- // No valid URL found: clear any existing logo.
- itemToSave.Logo = undefined;
}
// Only newly picked attachments are inserted, so only they need their bytes back.
@@ -865,9 +870,9 @@ export default function AddEditItemScreen({ editRef }: AddEditItemScreenProps):
await dbContext.sqliteClient!.passkeys.deleteById(passkeyId, editRef.ManifestId);
}
- savedRef = await dbContext.sqliteClient!.items.update(editRef, itemToSave, originalAttachmentIds, attachmentsToSave, originalTotpCodeIds, totpCodes) ?? editRef;
+ savedRef = await dbContext.sqliteClient!.items.update(editRef, itemToSave, originalAttachmentIds, attachmentsToSave, originalTotpCodeIds, totpCodes, logoSelection) ?? editRef;
} else {
- savedRef = await dbContext.sqliteClient!.items.create(itemToSave, attachmentsToSave, totpCodes);
+ savedRef = await dbContext.sqliteClient!.items.create(itemToSave, attachmentsToSave, totpCodes, logoSelection);
}
});
const currentRef = savedRef as ItemRef | null;
@@ -917,7 +922,7 @@ export default function AddEditItemScreen({ editRef }: AddEditItemScreenProps):
setIsSaving(false);
setIsSaveDisabled(false);
}
- }, [isEditMode, editRef, itemUrl, router, executeVaultMutation, dbContext.sqliteClient, webApi, isSaveDisabled, item, fieldValues, applicableSystemFields, customFields, t, originalAttachmentIds, attachments, originalTotpCodeIds, totpCodes, passkeyIdsMarkedForDeletion]);
+ }, [isEditMode, editRef, itemUrl, router, executeVaultMutation, dbContext.sqliteClient, webApi, isSaveDisabled, item, fieldValues, applicableSystemFields, customFields, t, originalAttachmentIds, attachments, originalTotpCodeIds, totpCodes, passkeyIdsMarkedForDeletion, logoSelection, resolvedFaviconSource]);
/**
* Handle the delete button press.
@@ -1389,6 +1394,23 @@ export default function AddEditItemScreen({ editRef }: AddEditItemScreenProps):
setItem(prev => prev ? { ...prev, FolderId: folder?.Id ?? null, ManifestId: manifestForItemIn(folder, personalManifestId) } : prev);
setHasUnsavedChanges(true);
}}
+ logoSlot={
+ <ItemLogoPicker
+ item={item}
+ pendingSelection={logoSelection}
+ faviconSource={resolvedFaviconSource}
+ websiteSource={websiteSource}
+ isFetching={isFetchingLogo}
+ onSelect={(selection) => {
+ selectLogo(selection);
+ setHasUnsavedChanges(true);
+ }}
+ onFetchFromWebsite={() => {
+ void fetchLogoFromWebsite();
+ setHasUnsavedChanges(true);
+ }}
+ />
+ }
/>
{/* Primary fields (like URL) */}
{primaryFields.map(field => (
diff --git a/apps/mobile-app/components/items/AppIconComponents.tsx b/apps/mobile-app/components/items/AppIconComponents.tsx
new file mode 100644
index 000000000..f876508e9
--- /dev/null
+++ b/apps/mobile-app/components/items/AppIconComponents.tsx
@@ -0,0 +1,104 @@
+// <auto-generated />
+// This file is auto-generated from core/models/src/icons/AppIcons.ts
+// Do not edit this file directly. Run 'npm run generate:models' to regenerate.
+
+import React from 'react';
+import Svg, { Circle, Path, Rect, Text as SvgText } from 'react-native-svg';
+
+export const ShoppingIcon = ({ width = 32, height = 32 }: { width?: number; height?: number }): React.ReactElement => (
+ <Svg width={width} height={height} viewBox="0 0 32 32" fill="none">
+ <Path d="M4 5H7L9.5 19H24L27 9H10" stroke="#f49541" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
+ <Circle cx="11" cy="25" r="2.5" fill="#d68338" />
+ <Circle cx="22" cy="25" r="2.5" fill="#d68338" />
+ </Svg>
+);
+
+export const BankIcon = ({ width = 32, height = 32 }: { width?: number; height?: number }): React.ReactElement => (
+ <Svg width={width} height={height} viewBox="0 0 32 32" fill="none">
+ <Path d="M16 4L29 11H3L16 4Z" fill="#f49541" />
+ <Rect x="6" y="13" width="3" height="11" fill="#f49541" />
+ <Rect x="14.5" y="13" width="3" height="11" fill="#f49541" />
+ <Rect x="23" y="13" width="3" height="11" fill="#f49541" />
+ <Rect x="3" y="25" width="26" height="3" rx="1" fill="#d68338" />
+ </Svg>
+);
+
+export const MailIcon = ({ width = 32, height = 32 }: { width?: number; height?: number }): React.ReactElement => (
+ <Svg width={width} height={height} viewBox="0 0 32 32" fill="none">
+ <Rect x="3" y="7" width="26" height="18" rx="3" fill="#f49541" />
+ <Path d="M4 10L16 18L28 10" stroke="#ffe096" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
+ </Svg>
+);
+
+export const SocialIcon = ({ width = 32, height = 32 }: { width?: number; height?: number }): React.ReactElement => (
+ <Svg width={width} height={height} viewBox="0 0 32 32" fill="none">
+ <Circle cx="12" cy="11" r="5" fill="#f49541" />
+ <Path d="M3 27C3 21.5 7 18 12 18C17 18 21 21.5 21 27H3Z" fill="#f49541" />
+ <Circle cx="23" cy="12" r="4" fill="#d68338" />
+ <Path d="M20 27C20 22 23 19.5 26 19.5C28.5 19.5 30 22 30 27H20Z" fill="#d68338" />
+ </Svg>
+);
+
+export const WorkIcon = ({ width = 32, height = 32 }: { width?: number; height?: number }): React.ReactElement => (
+ <Svg width={width} height={height} viewBox="0 0 32 32" fill="none">
+ <Path d="M12 8V6C12 5 12.9 4 14 4H18C19.1 4 20 5 20 6V8" stroke="#d68338" strokeWidth="2.5" strokeLinecap="round" />
+ <Rect x="3" y="8" width="26" height="18" rx="3" fill="#f49541" />
+ <Rect x="3" y="15" width="26" height="2.5" fill="#d68338" />
+ <Rect x="13.5" y="14" width="5" height="5" rx="1" fill="#ffe096" />
+ </Svg>
+);
+
+export const GameIcon = ({ width = 32, height = 32 }: { width?: number; height?: number }): React.ReactElement => (
+ <Svg width={width} height={height} viewBox="0 0 32 32" fill="none">
+ <Rect x="2" y="9" width="28" height="15" rx="7.5" fill="#f49541" />
+ <Rect x="7" y="14" width="6" height="2" rx="1" fill="#ffe096" />
+ <Rect x="9" y="12" width="2" height="6" rx="1" fill="#ffe096" />
+ <Circle cx="21" cy="14.5" r="1.8" fill="#d68338" />
+ <Circle cx="24.5" cy="18" r="1.8" fill="#d68338" />
+ </Svg>
+);
+
+export const MediaIcon = ({ width = 32, height = 32 }: { width?: number; height?: number }): React.ReactElement => (
+ <Svg width={width} height={height} viewBox="0 0 32 32" fill="none">
+ <Rect x="3" y="5" width="26" height="22" rx="4" fill="#f49541" />
+ <Path d="M13 11.5L21 16L13 20.5V11.5Z" fill="#ffe096" />
+ </Svg>
+);
+
+export const TravelIcon = ({ width = 32, height = 32 }: { width?: number; height?: number }): React.ReactElement => (
+ <Svg width={width} height={height} viewBox="0 0 32 32" fill="none">
+ <Path d="M15 3C16.1 3 17 3.9 17 5V12.5L29 19V22L17 18.5V24L20 26.5V29L15 27.5L10 29V26.5L13 24V18.5L1 22V19L13 12.5V5C13 3.9 13.9 3 15 3Z" fill="#f49541" />
+ </Svg>
+);
+
+export const HealthIcon = ({ width = 32, height = 32 }: { width?: number; height?: number }): React.ReactElement => (
+ <Svg width={width} height={height} viewBox="0 0 32 32" fill="none">
+ <Path d="M16 27C16 27 3 19.5 3 11.5C3 7.4 6.1 4.5 9.8 4.5C12.2 4.5 14.5 5.9 16 8C17.5 5.9 19.8 4.5 22.2 4.5C25.9 4.5 29 7.4 29 11.5C29 19.5 16 27 16 27Z" fill="#f49541" />
+ <Path d="M14.5 11H17.5V14H20.5V17H17.5V20H14.5V17H11.5V14H14.5V11Z" fill="#ffe096" />
+ </Svg>
+);
+
+export const DevIcon = ({ width = 32, height = 32 }: { width?: number; height?: number }): React.ReactElement => (
+ <Svg width={width} height={height} viewBox="0 0 32 32" fill="none">
+ <Rect x="2" y="5" width="28" height="22" rx="4" fill="#f49541" />
+ <Path d="M12 12L8 16.5L12 21" stroke="#ffe096" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
+ <Path d="M20 12L24 16.5L20 21" stroke="#ffe096" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
+ </Svg>
+);
+/**
+ * Map of icon key to React Native SVG component.
+ */
+export const appIconComponents = {
+ Shopping: ShoppingIcon,
+ Bank: BankIcon,
+ Mail: MailIcon,
+ Social: SocialIcon,
+ Work: WorkIcon,
+ Game: GameIcon,
+ Media: MediaIcon,
+ Travel: TravelIcon,
+ Health: HealthIcon,
+ Dev: DevIcon,
+};
+
+export type AppIconKey = keyof typeof appIconComponents;
diff --git a/apps/mobile-app/components/items/ItemIcon.tsx b/apps/mobile-app/components/items/ItemIcon.tsx
index bec4d716c..793b02a73 100644
--- a/apps/mobile-app/components/items/ItemIcon.tsx
+++ b/apps/mobile-app/components/items/ItemIcon.tsx
@@ -7,12 +7,14 @@ import { SvgXml } from 'react-native-svg';
import {
ItemTypes,
FieldKey,
+ LogoKinds,
} from '@aliasvault/models/vault';
import servicePlaceholder from '@/assets/images/service-placeholder.webp';
import type { DisplayItem } from '@/utils/DisplayItem';
-// Import centralized icon components (auto-generated from core/models/src/icons/ItemTypeIcons.ts)
+// Import centralized icon components (auto-generated from core/models/src/icons/AppIcons.ts and ItemTypeIcons.ts)
+import { appIconComponents, type AppIconKey } from './AppIconComponents';
import {
iconComponents,
PlaceholderIcon,
@@ -50,6 +52,13 @@ const detectCardBrand = (cardNumber: string | undefined): IconKey => {
return 'CreditCard';
};
+/**
+ * The component for a built-in icon key, or null when the key is unknown to this client (a newer version may have added it).
+ */
+export const getAppIconComponent = (key: string): typeof appIconComponents[AppIconKey] | null => {
+ return Object.prototype.hasOwnProperty.call(appIconComponents, key) ? appIconComponents[key as AppIconKey] : null;
+};
+
/**
* Get the appropriate icon component for a card number.
*/
@@ -58,12 +67,29 @@ const getCardIconComponent = (cardNumber: string | undefined) => {
};
/**
- * Item icon component: a type icon for notes and cards, the item's logo otherwise.
+ * Item icon component: a logo the user picked wins, then a type icon for notes and cards, then the item's logo.
*/
export function ItemIcon({ item, style }: ItemIconProps) : React.ReactNode {
const width = Number(style?.width ?? styles.logo.width);
const height = Number(style?.height ?? styles.logo.height);
+ // A built-in icon carries no bytes: every platform draws it from the shared catalog.
+ if (item.LogoInfo?.Kind === LogoKinds.Builtin) {
+ const BuiltinIcon = getAppIconComponent(item.LogoInfo.Source);
+ if (BuiltinIcon) {
+ return (
+ <View style={[styles.iconContainer, style]}>
+ <BuiltinIcon width={width} height={height} />
+ </View>
+ );
+ }
+ }
+
+ // An uploaded image is shown like any other logo; a custom row without bytes falls through to the placeholder.
+ if (item.LogoInfo?.Kind === LogoKinds.Custom && item.LogoDataUri) {
+ return <LogoImage dataUri={item.LogoDataUri} style={style} />;
+ }
+
// For Note type, always show note icon
if (item.ItemType === ItemTypes.Note) {
return (
diff --git a/apps/mobile-app/components/items/ItemLogoPicker.tsx b/apps/mobile-app/components/items/ItemLogoPicker.tsx
new file mode 100644
index 000000000..4bf6bd7e2
--- /dev/null
+++ b/apps/mobile-app/components/items/ItemLogoPicker.tsx
@@ -0,0 +1,78 @@
+import { effectiveItemLogo } from '@aliasvault/client/items/ItemLogoView';
+import React, { useState } from 'react';
+import { ActivityIndicator, StyleSheet } from 'react-native';
+
+import type { DisplayItem } from '@/utils/DisplayItem';
+
+import { useColors } from '@/hooks/useColorScheme';
+
+import { ItemIcon } from '@/components/items/ItemIcon';
+import { LogoPickerModal } from '@/components/items/LogoPickerModal';
+import { RobustPressable } from '@/components/ui/RobustPressable';
+
+import type { LogoSelection } from '@aliasvault/models/vault';
+
+type ItemLogoPickerProps = {
+ item: DisplayItem;
+ pendingSelection?: LogoSelection;
+ faviconSource?: string | null;
+ websiteSource?: string | null;
+ isFetching?: boolean;
+ onSelect: (selection: LogoSelection) => void;
+ onFetchFromWebsite: () => void;
+};
+
+/**
+ * The item's icon on the edit screen: shows what the item will look like and opens the picker.
+ */
+export const ItemLogoPicker: React.FC<ItemLogoPickerProps> = ({ item, pendingSelection, faviconSource, websiteSource, isFetching = false, onSelect, onFetchFromWebsite }) => {
+ const colors = useColors();
+ const [isPickerOpen, setIsPickerOpen] = useState(false);
+
+ const effectiveLogo = effectiveItemLogo(item.LogoInfo, pendingSelection, faviconSource);
+
+ const styles = StyleSheet.create({
+ button: {
+ alignItems: 'center',
+ alignSelf: 'stretch',
+ borderRightColor: colors.accentBorder,
+ borderRightWidth: 1,
+ justifyContent: 'center',
+ minWidth: 52,
+ paddingHorizontal: 10,
+ },
+ icon: {
+ borderRadius: 6,
+ height: 28,
+ width: 28,
+ },
+ });
+
+ return (
+ <>
+ <RobustPressable
+ style={styles.button}
+ onPress={() => setIsPickerOpen(true)}
+ testID="item-logo-picker"
+ >
+ {isFetching ? (
+ <ActivityIndicator size="small" color={colors.textMuted} />
+ ) : (
+ <ItemIcon item={{ ...item, LogoInfo: effectiveLogo }} style={styles.icon} />
+ )}
+ </RobustPressable>
+
+ <LogoPickerModal
+ isOpen={isPickerOpen}
+ onClose={() => setIsPickerOpen(false)}
+ item={item}
+ currentLogo={effectiveLogo}
+ websiteSource={websiteSource}
+ onSelect={onSelect}
+ onFetchFromWebsite={onFetchFromWebsite}
+ />
+ </>
+ );
+};
+
+export default ItemLogoPicker;
diff --git a/apps/mobile-app/components/items/LogoPickerModal.tsx b/apps/mobile-app/components/items/LogoPickerModal.tsx
new file mode 100644
index 000000000..aeec3d878
--- /dev/null
+++ b/apps/mobile-app/components/items/LogoPickerModal.tsx
@@ -0,0 +1,231 @@
+import { logoSourceTranslationKey } from '@aliasvault/client/items/ItemLogoView';
+import { getAllAppIconKeys } from '@aliasvault/models/icons';
+import { LogoKinds } from '@aliasvault/models/vault';
+import MaterialIcons from '@expo/vector-icons/MaterialIcons';
+import React, { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';
+
+import type { DisplayItem } from '@/utils/DisplayItem';
+import { HapticsUtility } from '@/utils/HapticsUtility';
+
+import { useColors } from '@/hooks/useColorScheme';
+
+import { ModalWrapper } from '@/components/common/ModalWrapper';
+import { appIconComponents } from '@/components/items/AppIconComponents';
+import { ItemIcon } from '@/components/items/ItemIcon';
+
+import type { ItemLogo, LogoSelection } from '@aliasvault/models/vault';
+
+type LogoPickerModalProps = {
+ isOpen: boolean;
+ onClose: () => void;
+ item: DisplayItem;
+ currentLogo?: ItemLogo;
+ websiteSource?: string | null;
+ onSelect: (selection: LogoSelection) => void;
+ onFetchFromWebsite: () => void;
+};
+
+const COLUMNS = 4;
+
+/**
+ * Lets the user change an item's icon.
+ */
+export const LogoPickerModal: React.FC<LogoPickerModalProps> = ({ isOpen, onClose, item, currentLogo, websiteSource, onSelect, onFetchFromWebsite }) => {
+ const { t } = useTranslation();
+ const colors = useColors();
+
+ /**
+ * Apply a choice and close.
+ */
+ const choose = useCallback((selection: LogoSelection): void => {
+ HapticsUtility.selection();
+ 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 });
+ };
+
+ const styles = StyleSheet.create({
+ header: {
+ alignItems: 'center',
+ flexDirection: 'row',
+ justifyContent: 'space-between',
+ marginBottom: 12,
+ },
+ title: {
+ color: colors.text,
+ fontSize: 18,
+ fontWeight: '600',
+ },
+ closeButton: {
+ padding: 4,
+ },
+ currentRow: {
+ alignItems: 'center',
+ backgroundColor: colors.modalSurfaceRaised,
+ borderColor: colors.accentBorder,
+ borderRadius: 10,
+ borderWidth: 1,
+ flexDirection: 'row',
+ gap: 12,
+ marginBottom: 16,
+ paddingHorizontal: 12,
+ paddingVertical: 10,
+ },
+ previewIconFrame: {
+ alignItems: 'center',
+ backgroundColor: colors.modalSurface,
+ borderRadius: 8,
+ height: 44,
+ justifyContent: 'center',
+ width: 44,
+ },
+ previewIcon: {
+ borderRadius: 6,
+ height: 30,
+ width: 30,
+ },
+ previewText: {
+ flex: 1,
+ },
+ previewCaption: {
+ color: colors.textMuted,
+ fontSize: 11,
+ fontWeight: '500',
+ textTransform: 'uppercase',
+ },
+ previewSource: {
+ color: colors.text,
+ fontSize: 14,
+ marginTop: 2,
+ },
+ sectionLabel: {
+ color: colors.textMuted,
+ fontSize: 13,
+ fontWeight: '500',
+ marginBottom: 8,
+ textTransform: 'uppercase',
+ },
+ grid: {
+ flexDirection: 'row',
+ flexWrap: 'wrap',
+ marginHorizontal: -4,
+ },
+ cell: {
+ padding: 4,
+ width: `${100 / COLUMNS}%`,
+ },
+ tile: {
+ alignItems: 'center',
+ backgroundColor: colors.modalSurfaceRaised,
+ borderColor: colors.accentBorder,
+ borderRadius: 10,
+ borderWidth: 1,
+ justifyContent: 'center',
+ minHeight: 76,
+ paddingHorizontal: 4,
+ paddingVertical: 8,
+ },
+ tileLabel: {
+ color: colors.textMuted,
+ fontSize: 11,
+ marginTop: 6,
+ textAlign: 'center',
+ },
+ fetchButton: {
+ alignItems: 'center',
+ backgroundColor: colors.modalSurfaceRaised,
+ borderColor: colors.accentBorder,
+ borderRadius: 10,
+ borderWidth: 1,
+ flexDirection: 'row',
+ gap: 10,
+ marginTop: 16,
+ minHeight: 48,
+ paddingHorizontal: 14,
+ paddingVertical: 10,
+ },
+ fetchButtonText: {
+ color: colors.text,
+ fontSize: 15,
+ fontWeight: '500',
+ },
+ fetchButtonSource: {
+ color: colors.textMuted,
+ fontSize: 12,
+ marginTop: 2,
+ },
+ });
+
+ return (
+ <ModalWrapper isOpen={isOpen} onClose={onClose} showHeaderBorder={false} showFooterBorder={false} closeOnBackdropPress scrollable maxScrollHeight={560}>
+ <View style={styles.header}>
+ <Text style={styles.title}>{t('items.logo.chooseLogo')}</Text>
+ <TouchableOpacity style={styles.closeButton} onPress={onClose} hitSlop={8}>
+ <MaterialIcons name="close" size={24} color={colors.textMuted} />
+ </TouchableOpacity>
+ </View>
+
+ {/* What the item shows now; a tap below replaces it once the item is saved. */}
+ <View style={styles.currentRow}>
+ <View style={styles.previewIconFrame}>
+ <ItemIcon item={{ ...item, LogoInfo: currentLogo }} style={styles.previewIcon} />
+ </View>
+ <View style={styles.previewText}>
+ <Text style={styles.previewCaption}>{t('items.logo.currentLogo')}</Text>
+ <Text style={styles.previewSource} numberOfLines={1}>{describe(currentLogo)}</Text>
+ </View>
+ </View>
+
+ <Text style={styles.sectionLabel}>{t('items.logo.builtinLogos')}</Text>
+ <View style={styles.grid}>
+ {getAllAppIconKeys().map(key => {
+ const Icon = appIconComponents[key];
+ return (
+ <View key={key} style={styles.cell}>
+ <TouchableOpacity
+ style={styles.tile}
+ onPress={() => choose({ Kind: LogoKinds.Builtin, Source: key })}
+ accessibilityRole="button"
+ accessibilityLabel={t(`items.logo.builtin.${key}`)}
+ testID={`logo-builtin-${key}`}
+ >
+ <Icon width={32} height={32} />
+ <Text style={styles.tileLabel} numberOfLines={1}>
+ {t(`items.logo.builtin.${key}`)}
+ </Text>
+ </TouchableOpacity>
+ </View>
+ );
+ })}
+ </View>
+
+ {/* Only offered when the URL field contains a valid value. */}
+ {websiteSource && (
+ <TouchableOpacity style={styles.fetchButton} onPress={() => choose({ Kind: LogoKinds.Favicon })} accessibilityRole="button" testID="logo-fetch-from-website">
+ <MaterialIcons name="language" size={22} color={colors.tint} />
+ <View style={styles.previewText}>
+ <Text style={styles.fetchButtonText}>
+ {currentLogo?.Kind === LogoKinds.Favicon ? t('items.logo.refetchFromWebsite') : t('items.logo.fetchFromWebsite')}
+ </Text>
+ <Text style={styles.fetchButtonSource} numberOfLines={1}>{t('items.logo.sourceFavicon', { domain: websiteSource })}</Text>
+ </View>
+ <MaterialIcons name="chevron-right" size={22} color={colors.textMuted} />
+ </TouchableOpacity>
+ )}
+ </ModalWrapper>
+ );
+};
+
+export default LogoPickerModal;
diff --git a/apps/mobile-app/hooks/useItemLogo.ts b/apps/mobile-app/hooks/useItemLogo.ts
new file mode 100644
index 000000000..878224891
--- /dev/null
+++ b/apps/mobile-app/hooks/useItemLogo.ts
@@ -0,0 +1,167 @@
+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: the same flow as the browser extension's hook, on the
+ * app's async repositories.
+ * @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
+ */
+export function useItemLogo({ url, currentLogoKind, isReady, isExistingItem, onLogoBytesChange }: UseItemLogoOptions): UseItemLogoResult {
+ const { sqliteClient } = useDb();
+ const webApi = useWebApi();
+
+ const [logoSelection, setLogoSelection] = useState<LogoSelection | undefined>(undefined);
+ const [isFetchingLogo, setIsFetchingLogo] = useState(false);
+ 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 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> => {
+ if (!sqliteClient) {
+ return;
+ }
+
+ const target = await FaviconService.resolveTarget(url);
+ const source = target?.source ?? null;
+ const previousSource = resolvedSourceRef.current;
+ const requestId = ++requestIdRef.current;
+
+ resolvedSourceRef.current = source;
+ setResolvedFaviconSource(source);
+ setLogoSelection({ Kind: LogoKinds.Favicon });
+
+ // Without a domain there is nothing to fetch from, so automatic means no icon at all.
+ if (!target) {
+ onLogoBytesChange(undefined);
+ return;
+ }
+
+ // The vault already holds this domain's favicon: show that one.
+ if (!force) {
+ const stored = await FaviconService.getStoredFavicon(target, sqliteClient.logos);
+ if (requestId !== requestIdRef.current) {
+ return;
+ }
+ if (stored) {
+ onLogoBytesChange(stored);
+ return;
+ }
+ }
+
+ if (previousSource !== source) {
+ onLogoBytesChange(undefined);
+ }
+
+ setIsFetchingLogo(true);
+ try {
+ const result = await FaviconService.fetchFavicon(target, sqliteClient.logos, 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);
+ }
+ }
+ }, [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);
+
+ if (!hasInitialisedRef.current) {
+ hasInitialisedRef.current = true;
+ if (isExistingItem) {
+ resolvedSourceRef.current = source;
+ return;
+ }
+ }
+
+ if (!usesWebsiteIcon || resolvedSourceRef.current === source) {
+ return;
+ }
+
+ timer = setTimeout(() => void resolveFromWebsite(false), URL_SETTLE_MS);
+ })();
+
+ return (): void => {
+ cancelled = true;
+ clearTimeout(timer);
+ };
+ }, [isExistingItem, isReady, resolveFromWebsite, url, usesWebsiteIcon]);
+
+ /**
+ * Apply an icon 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, websiteSource, selectLogo, fetchLogoFromWebsite };
+}
diff --git a/apps/mobile-app/utils/DisplayItem.ts b/apps/mobile-app/utils/DisplayItem.ts
index a5d576062..a8658c2cf 100644
--- a/apps/mobile-app/utils/DisplayItem.ts
+++ b/apps/mobile-app/utils/DisplayItem.ts
@@ -76,11 +76,11 @@ export function toDisplayItems<T extends Item>(items: T[]): DisplayItem<T>[] {
return undefined;
}
if (!item.LogoInfo) {
- return toDataUri(item.Logo);
+ return logoToDataUri(item.Logo);
}
const key = `${item.ManifestId}/${item.LogoInfo.Id}`;
if (!dataUris.has(key)) {
- dataUris.set(key, toDataUri(item.Logo));
+ dataUris.set(key, logoToDataUri(item.Logo));
}
return dataUris.get(key);
};
@@ -95,7 +95,7 @@ export function toDisplayItems<T extends Item>(items: T[]): DisplayItem<T>[] {
/**
* Encode logo bytes as a data URI, or undefined when they cannot be encoded.
*/
-function toDataUri(logo: Uint8Array | number[]): string | undefined {
+export function logoToDataUri(logo: Uint8Array | number[]): string | undefined {
try {
const bytes = logo instanceof Uint8Array ? logo : Uint8Array.from(logo);
return `data:${detectMimeType(bytes)};base64,${Buffer.from(bytes).toString('base64')}`;