Skip to content

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

Remember previous field values in memory after switching item type in edit mode (#2455)

Leendert de Borst39c7f013d35d
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/ItemTypeSelector.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/ItemTypeSelector.tsx
index ae0ff0c0f..886d411a6 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/ItemTypeSelector.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/ItemTypeSelector.tsx
@@ -81,6 +81,7 @@ const ItemTypeSelector: React.FC<ItemTypeSelectorProps> = ({
<div className="relative w-full px-4 py-2 bg-primary-50 dark:bg-primary-900/20 border border-primary-200 dark:border-primary-800 rounded-lg flex items-center gap-2">
<button
type="button"
+ id="item-type-selector"
onClick={() => onDropdownToggle(!showDropdown)}
className="peer absolute inset-0 rounded-lg"
aria-label={t('itemTypes.typeLabel')}
@@ -120,6 +121,7 @@ const ItemTypeSelector: React.FC<ItemTypeSelectorProps> = ({
<button
key={option.type}
type="button"
+ id={`item-type-option-${option.type}`}
onClick={() => onTypeChange(option.type)}
className={`w-full px-4 py-3 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 border-b border-gray-100 dark:border-gray-700 last:border-b-0 ${
selectedType === option.type
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 a448d0c75..c0955070c 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
@@ -2,6 +2,7 @@ import { scopedKey } from '@aliasvault/client/database/ItemRef';
import { manifestForItemIn } from '@aliasvault/client/database/ItemRef';
import { FaviconService } from '@aliasvault/client/items/FaviconService';
import { usesWebsiteLogo } from '@aliasvault/client/items/ItemLogoView';
+import { switchItemTypeFieldValues, type FormFieldValue } from '@aliasvault/client/items/ItemTypeSwitch';
import * as RustCore from '@aliasvault/client/rust/RustCore';
import { FieldCategories, FieldTypes, ItemTypes, isItemType, getSystemFieldsForItemType, getOptionalFieldsForItemType, isFieldShownByDefault, getSystemField, fieldAppliesToType } from '@aliasvault/models/vault';
import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
@@ -58,6 +59,7 @@ const DEFAULT_ITEM_TYPE: ItemType = ItemTypes.Login;
type PersistedFormData = {
item: Item | null;
fieldValues: Record<string, string | string[]>;
+ typeSwitchStash?: Record<string, FormFieldValue>;
customFields: CustomFieldDefinition[];
totpEditorState?: {
isAddFormVisible: boolean;
@@ -117,6 +119,7 @@ const ItemAddEdit: React.FC = () => {
// Form state for dynamic fields
const [fieldValues, setFieldValues] = useState<Record<string, string | string[]>>({});
+ const [typeSwitchStash, setTypeSwitchStash] = useState<Record<string, FormFieldValue>>({});
// Custom field definitions (temporary until saved)
const [customFields, setCustomFields] = useState<CustomFieldDefinition[]>([]);
@@ -188,6 +191,9 @@ const ItemAddEdit: React.FC = () => {
if (data.fieldValues) {
setFieldValues(data.fieldValues);
}
+ if (data.typeSwitchStash) {
+ setTypeSwitchStash(data.typeSwitchStash);
+ }
if (data.customFields) {
setCustomFields(data.customFields);
}
@@ -221,6 +227,7 @@ const ItemAddEdit: React.FC = () => {
formData: {
item,
fieldValues,
+ typeSwitchStash,
customFields,
totpEditorState,
show2FA,
@@ -962,8 +969,7 @@ const ItemAddEdit: React.FC = () => {
}, []);
/**
- * Handle item type change from dropdown.
- * Clears field values that don't apply to the new item type.
+ * Handle item type change from dropdown. Fields the new type does not have are stashed, so switching back restores them.
*/
const handleTypeChange = useCallback((newType: ItemType) => {
if (!item) {
@@ -971,56 +977,29 @@ const ItemAddEdit: React.FC = () => {
}
const oldType = item.ItemType;
+ let nextValues = fieldValues;
- // Clear field values that don't apply to the new type
- if (!isEditMode && oldType !== newType) {
- setFieldValues(prev => {
- const newValues: Record<string, string | string[]> = {};
- Object.entries(prev).forEach(([key, value]) => {
- // Check if this field applies to the new type
- const systemField = getSystemField(key);
- if (systemField) {
- // Keep the field only if it applies to the new type
- if (fieldAppliesToType(systemField, newType)) {
- newValues[key] = value;
- }
- } else {
- // Custom fields are always kept
- newValues[key] = value;
- }
- });
- return newValues;
- });
+ if (oldType !== newType) {
+ const switched = switchItemTypeFieldValues(fieldValues, typeSwitchStash, newType);
+ nextValues = switched.values;
+ setFieldValues(switched.values);
+ setTypeSwitchStash(switched.stash);
- // Clear manually added fields that don't apply to new type
- setManuallyAddedFields(prev => {
- const newSet = new Set<string>();
- prev.forEach(fieldKey => {
- const systemField = getSystemField(fieldKey);
- if (!systemField || fieldAppliesToType(systemField, newType)) {
- newSet.add(fieldKey);
- }
- });
- return newSet;
- });
-
- // Clear initially visible fields that don't apply to new type
- setInitiallyVisibleFields(prev => {
- const newSet = new Set<string>();
- prev.forEach(fieldKey => {
- const systemField = getSystemField(fieldKey);
- if (!systemField || fieldAppliesToType(systemField, newType)) {
- newSet.add(fieldKey);
- }
- });
- return newSet;
- });
+ /**
+ * Whether a field key applies to the new type.
+ */
+ const applies = (fieldKey: string): boolean => {
+ const systemField = getSystemField(fieldKey);
+ return !systemField || fieldAppliesToType(systemField, newType);
+ };
+ setManuallyAddedFields(prev => new Set([...[...prev].filter(applies), ...switched.restored]));
+ setInitiallyVisibleFields(prev => new Set([...prev].filter(applies)));
}
// Reset alias generated flag, so alias fields will be filled (again) if they are shown by the new type
aliasGeneratedRef.current = false;
aliasRequestedByTypeChangeRef.current = isEditMode && oldType !== newType && newType === ItemTypes.Alias &&
- ['alias.first_name', 'alias.last_name', 'alias.gender', 'alias.birthdate'].every(key => !((fieldValues[key] as string) ?? '').trim());
+ ['alias.first_name', 'alias.last_name', 'alias.gender', 'alias.birthdate'].every(key => !((nextValues[key] as string) ?? '').trim());
/*
* Update email field mode based on new item type
@@ -1035,7 +1014,7 @@ const ItemAddEdit: React.FC = () => {
});
setShowTypeDropdown(false);
- }, [item, isEditMode, fieldValues]);
+ }, [item, isEditMode, fieldValues, typeSwitchStash]);
/**
* Remove notes section - clears value and removes from manually added fields.
diff --git a/apps/mobile-app/components/items/AddEditItemScreen.tsx b/apps/mobile-app/components/items/AddEditItemScreen.tsx
index f11cb9896..fa7fcc4f3 100644
--- a/apps/mobile-app/components/items/AddEditItemScreen.tsx
+++ b/apps/mobile-app/components/items/AddEditItemScreen.tsx
@@ -1,6 +1,7 @@
import { manifestForItemIn, type ItemRef } from '@aliasvault/client/database/ItemRef';
import { FaviconService } from '@aliasvault/client/items/FaviconService';
import { usesWebsiteLogo } from '@aliasvault/client/items/ItemLogoView';
+import { switchItemTypeFieldValues, type FormFieldValue } from '@aliasvault/client/items/ItemTypeSwitch';
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';
@@ -112,6 +113,7 @@ export default function AddEditItemScreen({ editRef }: AddEditItemScreenProps):
const [manuallyAddedFields, setManuallyAddedFields] = useState<Set<string>>(new Set());
const [initiallyVisibleFields, setInitiallyVisibleFields] = useState<Set<string>>(new Set());
const aliasGeneratedRef = useRef(false);
+ const typeSwitchStashRef = useRef<Record<string, FormFieldValue>>({});
// Set when an existing item without alias identity values is switched to the alias type, so the identity gets generated
const aliasRequestedByTypeChangeRef = useRef(false);
const [lastGeneratedValues, setLastGeneratedValues] = useState<{
@@ -588,7 +590,7 @@ export default function AddEditItemScreen({ editRef }: AddEditItemScreenProps):
}, [isEditMode, aliasFieldsShownByDefault, item, dbContext?.sqliteClient, generateRandomAlias]);
/**
- * Handle item type change.
+ * Handle item type change. Fields the new type does not have are stashed, so switching back restores them.
*/
const handleTypeChange = useCallback((newType: ItemType) => {
if (!item) {
@@ -596,56 +598,31 @@ export default function AddEditItemScreen({ editRef }: AddEditItemScreenProps):
}
const oldType = item.ItemType;
+ let nextValues = fieldValues;
- // Clear field values that don't apply to the new type
if (oldType !== newType) {
- setFieldValues(prev => {
- const newValues: Record<string, string | string[]> = {};
- Object.entries(prev).forEach(([key, value]) => {
- const systemField = getSystemField(key);
- if (systemField) {
- if (fieldAppliesToType(systemField, newType)) {
- newValues[key] = value;
- }
- } else {
- // Custom fields are always kept
- newValues[key] = value;
- }
- });
- return newValues;
- });
+ const switched = switchItemTypeFieldValues(fieldValues, typeSwitchStashRef.current, newType);
+ nextValues = switched.values;
+ typeSwitchStashRef.current = switched.stash;
+ setFieldValues(switched.values);
- // Clear manually added fields that don't apply to new type
- setManuallyAddedFields(prev => {
- const newSet = new Set<string>();
- prev.forEach(fieldKey => {
- const systemField = getSystemField(fieldKey);
- if (!systemField || fieldAppliesToType(systemField, newType)) {
- newSet.add(fieldKey);
- }
- });
- return newSet;
- });
-
- // Clear initially visible fields that don't apply to new type (edit mode)
+ /**
+ * Whether a field key applies to the new type.
+ */
+ const applies = (fieldKey: string): boolean => {
+ const systemField = getSystemField(fieldKey);
+ return !systemField || fieldAppliesToType(systemField, newType);
+ };
+ setManuallyAddedFields(prev => new Set([...[...prev].filter(applies), ...switched.restored]));
if (isEditMode) {
- setInitiallyVisibleFields(prev => {
- const newSet = new Set<string>();
- prev.forEach(fieldKey => {
- const systemField = getSystemField(fieldKey);
- if (!systemField || fieldAppliesToType(systemField, newType)) {
- newSet.add(fieldKey);
- }
- });
- return newSet;
- });
+ setInitiallyVisibleFields(prev => new Set([...prev].filter(applies)));
}
}
// Reset alias generated flag
aliasGeneratedRef.current = false;
aliasRequestedByTypeChangeRef.current = isEditMode && oldType !== newType && newType === ItemTypes.Alias &&
- ['alias.first_name', 'alias.last_name', 'alias.gender', 'alias.birthdate'].every(key => !((fieldValues[key] as string) ?? '').trim());
+ ['alias.first_name', 'alias.last_name', 'alias.gender', 'alias.birthdate'].every(key => !((nextValues[key] as string) ?? '').trim());
setItem({
...item,
diff --git a/apps/web/src/components/items/ItemTypeSelector.tsx b/apps/web/src/components/items/ItemTypeSelector.tsx
index c880f8d67..ffcc85b79 100644
--- a/apps/web/src/components/items/ItemTypeSelector.tsx
+++ b/apps/web/src/components/items/ItemTypeSelector.tsx
@@ -65,7 +65,7 @@ export const ItemTypePill: React.FC<ItemTypePillProps> = ({ itemType, onClick, i
}
return (
- <button type="button" onClick={onClick} className="inline-flex items-center gap-1.5 pl-2.5 pr-2 py-0.5 bg-primary-50 dark:bg-primary-900/20 border border-primary-200 dark:border-primary-800 rounded-full hover:bg-primary-100 dark:hover:bg-primary-900/40 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors">
+ <button type="button" id="itemTypeSelectorToggle" onClick={onClick} className="inline-flex items-center gap-1.5 pl-2.5 pr-2 py-0.5 bg-primary-50 dark:bg-primary-900/20 border border-primary-200 dark:border-primary-800 rounded-full hover:bg-primary-100 dark:hover:bg-primary-900/40 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors">
<span className="shrink-0 text-primary-600 dark:text-primary-400"><TypeIcon itemType={itemType} className="w-3.5 h-3.5" /></span>
<span className="text-xs font-medium whitespace-nowrap text-primary-700 dark:text-primary-300">{t(typeNameKey(itemType))}</span>
<span className="ml-1 text-xs whitespace-nowrap text-primary-600/70 dark:text-primary-400/70">{t('itemTypes.typeLabel')}</span>
diff --git a/apps/web/src/models/ItemEdit.ts b/apps/web/src/models/ItemEdit.ts
index 2bcb380ea..45e24a111 100644
--- a/apps/web/src/models/ItemEdit.ts
+++ b/apps/web/src/models/ItemEdit.ts
@@ -176,9 +176,13 @@ export function setFieldValues(edit: ItemEdit, fieldKey: string, values: string[
*/
export function hasFieldValue(edit: ItemEdit, fieldKey: string): boolean {
const field = getField(edit, fieldKey);
- if (!field) {
- return false;
- }
+ return field ? isFieldFilledIn(field) : false;
+}
+
+/**
+ * Whether a field edit has a non-empty value.
+ */
+export function isFieldFilledIn(field: FieldEdit): boolean {
return field.IsMultiValue ? field.Values.some(v => v.length > 0) : field.Value.length > 0;
}
diff --git a/apps/web/src/pages/items/AddEdit.tsx b/apps/web/src/pages/items/AddEdit.tsx
index be751641c..0466cbbbf 100644
--- a/apps/web/src/pages/items/AddEdit.tsx
+++ b/apps/web/src/pages/items/AddEdit.tsx
@@ -1,4 +1,5 @@
-import { fieldAppliesToType, FieldKey, getFieldConfigForType, getOptionalFieldsForItemType, getSystemField, getSystemFieldsForItemType, type Item, type ItemLogo, type ItemType, ItemTypes, SystemFieldRegistry } from '@aliasvault/models/vault';
+import { switchItemTypeFields } from '@aliasvault/client/items/ItemTypeSwitch';
+import { fieldAppliesToType, FieldKey, getFieldConfigForType, getOptionalFieldsForItemType, getSystemField, getSystemFieldsForItemType, type Item, type ItemLogo, type ItemType, ItemTypes } 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';
@@ -35,8 +36,8 @@ 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, itemEditToItem, removeCustomField, reorderCustomFields, setFieldValue, setFieldValues, setFolder, updateCustomField,
+ addCustomField, createNewItemEdit, DEFAULT_SERVICE_URL, type FieldEdit, getCustomFields, getFieldValue, getFieldValues, hasAliasValues, hasFieldValue,
+ isFieldFilledIn, 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';
@@ -98,6 +99,7 @@ const ItemAddEditForm: React.FC = () => {
const originalTotpCodeIds = useRef<string[]>([]);
const originalAttachmentIds = useRef<string[]>([]);
const lastGenerated = useRef<GeneratedAliasData | null>(null);
+ const typeSwitchStash = useRef<Record<string, FieldEdit>>({});
const [storedLogo, setStoredLogo] = useState<ItemLogo | undefined>(undefined);
const [logoBytes, setLogoBytes] = useState<Item['Logo']>(undefined);
@@ -146,18 +148,15 @@ const ItemAddEditForm: React.FC = () => {
}, [dbContext.sqliteClient, webApi]);
/**
- * Switch the item type, dropping the fields that do not apply to the new type.
+ * Switch the item type. Fields the new type does not have are stashed, so switching back restores them.
*/
const handleItemTypeChange = useCallback(async (current: ItemEdit, newType: ItemType): Promise<ItemEdit> => {
if (current.ItemType === newType) {
return current;
}
- let next: ItemEdit = { ...current, ItemType: newType };
- for (const definition of Object.values(SystemFieldRegistry)) {
- if (!fieldAppliesToType(definition, newType)) {
- next = setFieldValue(next, definition.FieldKey, '');
- }
- }
+ const switched = switchItemTypeFields(Object.fromEntries(current.Fields.map(f => [f.FieldKey, f])), typeSwitchStash.current, newType, isFieldFilledIn);
+ typeSwitchStash.current = switched.stash;
+ let next: ItemEdit = { ...current, ItemType: newType, Fields: Object.values(switched.values) };
/**
* Whether a field key applies to the new type.
*/
@@ -165,7 +164,7 @@ const ItemAddEditForm: React.FC = () => {
const definition = getSystemField(fieldKey);
return !definition || fieldAppliesToType(definition, newType);
};
- setManuallyAddedFields(prev => new Set([...prev].filter(applies)));
+ setManuallyAddedFields(prev => new Set([...[...prev].filter(applies), ...switched.restored]));
setInitiallyVisibleFields(prev => new Set([...prev].filter(applies)));
if (newType === ItemTypes.Alias && !hasAliasValues(next)) {
@@ -188,6 +187,7 @@ const ItemAddEditForm: React.FC = () => {
*/
const initialize = async (): Promise<void> => {
setLoading(true);
+ typeSwitchStash.current = {};
setManuallyAddedFields(new Set());
setInitiallyVisibleFields(new Set());
setPasskeyMarkedForDeletion(false);
diff --git a/core/client/src/items/ItemTypeSwitch.ts b/core/client/src/items/ItemTypeSwitch.ts
new file mode 100644
index 000000000..7be1951ea
--- /dev/null
+++ b/core/client/src/items/ItemTypeSwitch.ts
@@ -0,0 +1,73 @@
+import { fieldAppliesToType, getSystemField } from '@aliasvault/models/vault';
+
+import type { ItemType } from '@aliasvault/models/vault';
+
+/**
+ * A field value on an item form: one string, or a list for multi-value fields.
+ */
+export type FormFieldValue = string | string[];
+
+/**
+ * The outcome of switching an item form to another type.
+ */
+export type ItemTypeSwitchResult<T> = {
+ /** The form values for the new type. */
+ values: Record<string, T>;
+ /** Values set aside because they do not apply to the new type. */
+ stash: Record<string, T>;
+ /** Keys of the stashed fields that were put back on the form. */
+ restored: string[];
+};
+
+/**
+ * Whether a form value is filled in.
+ */
+export function hasFormFieldValue(value: FormFieldValue | undefined): boolean {
+ if (value === undefined) {
+ return false;
+ }
+ return Array.isArray(value) ? value.some(v => v.trim().length > 0) : value.trim().length > 0;
+}
+
+/**
+ * Move the form values to another item type: stash what does not apply, put back stashed values that apply again.
+ * @param values - The current form values, keyed by field key
+ * @param stash - The values stashed by earlier switches on this form
+ * @param newType - The type switched to
+ * @param hasValue - Whether a value is filled in
+ */
+export function switchItemTypeFields<T>(values: Record<string, T>, stash: Record<string, T>, newType: ItemType, hasValue: (value: T) => boolean): ItemTypeSwitchResult<T> {
+ const nextValues: Record<string, T> = {};
+ const nextStash: Record<string, T> = { ...stash };
+ const restored: string[] = [];
+
+ for (const [key, value] of Object.entries(values)) {
+ const definition = getSystemField(key);
+ if (!definition || fieldAppliesToType(definition, newType)) {
+ nextValues[key] = value;
+ } else if (hasValue(value)) {
+ nextStash[key] = value;
+ }
+ }
+
+ for (const [key, value] of Object.entries(nextStash)) {
+ const definition = getSystemField(key);
+ if (!definition || !fieldAppliesToType(definition, newType)) {
+ continue;
+ }
+ if (!(key in nextValues) || !hasValue(nextValues[key])) {
+ nextValues[key] = value;
+ restored.push(key);
+ }
+ delete nextStash[key];
+ }
+
+ return { values: nextValues, stash: nextStash, restored };
+}
+
+/**
+ * {@link switchItemTypeFields} for forms that keep their values as strings or string lists.
+ */
+export function switchItemTypeFieldValues(values: Record<string, FormFieldValue>, stash: Record<string, FormFieldValue>, newType: ItemType): ItemTypeSwitchResult<FormFieldValue> {
+ return switchItemTypeFields(values, stash, newType, hasFormFieldValue);
+}