Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PRO-235] Feature: name accounts #468

Merged
merged 5 commits into from
May 28, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/browser-wallet/src/assets/svg/edit-secondary.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ async function createAndSendCredential(credIn: CredentialInput): Promise<Credent
providerIndex,
credId,
credNumber,
credName: '',
status: CreationStatus.Pending,
deploymentHash,
};
Expand All @@ -64,6 +65,7 @@ async function createAndSendCredential(credIn: CredentialInput): Promise<Credent
providerIndex,
credId,
credNumber,
credName: '',
address: existingAddress,
status: CreationStatus.Confirmed,
},
Expand Down
1 change: 1 addition & 0 deletions packages/browser-wallet/src/background/recovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ async function recoverAccounts(
address: accountInfo.accountAddress.address,
credId,
credNumber,
credName: '',
status: CreationStatus.Confirmed,
identityIndex,
providerIndex,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,85 @@
import React, { forwardRef, useMemo } from 'react';
import React, { forwardRef, KeyboardEventHandler, useCallback, useMemo, useState } from 'react';
import clsx from 'clsx';
import { useAtomValue, useAtom } from 'jotai';
import { useAtom, useAtomValue } from 'jotai';
import { useNavigate } from 'react-router-dom';
import { ClassName, displayAsCcd } from 'wallet-common-helpers';
import CopyButton from '@popup/shared/CopyButton';
import CheckmarkIcon from '@assets/svg/checkmark-blue.svg';
import EditIcon from '@assets/svg/edit-secondary.svg';
import BakerIcon from '@assets/svg/validator.svg';
import DelegationIcon from '@assets/svg/delegation.svg';
import { absoluteRoutes } from '@popup/constants/routes';
import { credentialsAtom, selectedAccountAtom } from '@popup/store/account';
import { useTranslation } from 'react-i18next';
import { displaySplitAddress, useIdentityName } from '@popup/shared/utils/account-helpers';
import {
displayNameOrSplitAddress,
useIdentityName,
useWritableSelectedAccount,
} from '@popup/shared/utils/account-helpers';
import { WalletCredential } from '@shared/storage/types';
import { useAccountInfo } from '@popup/shared/AccountInfoListenerContext';
import { isDelegatorAccount, isBakerAccount, AccountInfo } from '@concordium/web-sdk';
import { AccountInfo, isBakerAccount, isDelegatorAccount } from '@concordium/web-sdk';
import IconButton from '@popup/shared/IconButton';
import { InlineInput } from '@popup/shared/Form/InlineInput';
import EntityList from '../EntityList';

const ACCOUNT_NAME_MAX_LENGTH = 15;
const ACCOUNT_NAME_INPUT_WIDTH = 100;

const useEditableAccountName = (account: WalletCredential) => {
const setAccount = useWritableSelectedAccount(account.address);
const [isEditing, setIsEditing] = useState(false);
const [name, setName] = useState(displayNameOrSplitAddress(account));

const handleSubmitName = useCallback(() => {
if (isEditing) {
setAccount({ credName: name } as WalletCredential);
setIsEditing(false);
}
}, [name]);

const keyHandlerEnter: KeyboardEventHandler<HTMLInputElement> = (e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleSubmitName();
}
};

Ivan-Mahda marked this conversation as resolved.
Show resolved Hide resolved
return [
() => (
<div role="none">
{isEditing ? (
<InlineInput
name="name"
onChange={setName}
value={name}
onKeyUp={keyHandlerEnter}
onMouseUp={(e) => e.stopPropagation()}
autoFocus
maxLength={ACCOUNT_NAME_MAX_LENGTH}
fixedWidth={ACCOUNT_NAME_INPUT_WIDTH}
/>
) : (
displayNameOrSplitAddress(account)
)}
</div>
),
() => (
<IconButton
className="entity-list-item__edit absolute r-0"
onMouseUp={(e) => {
e.stopPropagation();
e.preventDefault();
handleSubmitName();
setIsEditing(!isEditing);
}}
>
{isEditing ? <CheckmarkIcon /> : <EditIcon />}
</IconButton>
),
];
};

export type Account = { address: string };

type ItemProps = {
Expand All @@ -36,6 +100,7 @@ function BakerOrDelegatorIcon({ accountInfo, className }: { accountInfo: Account

function AccountListItem({ account, checked, selected }: ItemProps) {
const accountInfo = useAccountInfo(account);
const [EditableName, EditNameIcon] = useEditableAccountName(account);
const totalBalance = useMemo(
() => accountInfo?.accountAmount?.microCcdAmount || 0n,
[accountInfo?.accountAmount.microCcdAmount]
Expand All @@ -46,9 +111,7 @@ function AccountListItem({ account, checked, selected }: ItemProps) {
<div className={clsx('main-layout__header-list-item', checked && 'main-layout__header-list-item--checked')}>
<div className="main-layout__header-list-item__primary">
<div className="flex align-center">
{/* TODO add account name */}
{displaySplitAddress(account.address)}{' '}
{selected && <CheckmarkIcon className="main-layout__header-list-item__check" />}
<EditableName /> {selected && <CheckmarkIcon className="main-layout__header-list-item__check" />}
</div>
{accountInfo && <BakerOrDelegatorIcon accountInfo={accountInfo} className="absolute r-25" />}
<CopyButton
Expand All @@ -57,6 +120,7 @@ function AccountListItem({ account, checked, selected }: ItemProps) {
onMouseUp={(e) => e.stopPropagation()}
tabIndex={-1}
/>
<EditNameIcon />
</div>
<div className="main-layout__header-list-item__secondary">{identityName}</div>
<div className="main-layout__header-list-item__secondary mono">{displayAsCcd(totalBalance)}</div>
Expand Down Expand Up @@ -86,7 +150,7 @@ const AccountList = forwardRef<HTMLDivElement, Props>(({ className, onSelect },
getKey={(a) => a.address}
newText={t('accountList.new')}
ref={ref}
searchableKeys={['address']}
searchableKeys={['address', 'credName']}
>
{(a, checked) => <AccountListItem account={a} checked={checked} selected={a.address === selectedAccount} />}
</EntityList>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,4 +120,18 @@ $entity-list-top-height: rem(25px);
fill: $color-text;
}
}

&__edit {
width: rem(18px);
height: rem(18px);
top: rem(15px);

path {
fill: $color-text;
}

svg {
transform: scale(1.2);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import clsx from 'clsx';
import React, { useEffect, useState } from 'react';
import { displayAsCcd, getPublicAccountAmounts, PublicAccountAmounts } from 'wallet-common-helpers';
import { useTranslation } from 'react-i18next';
import { displaySplitAddress, useIdentityName } from '@popup/shared/utils/account-helpers';
import { displayNameOrSplitAddress, useIdentityName } from '@popup/shared/utils/account-helpers';
import VerifiedIcon from '@assets/svg/verified-stamp.svg';
import { CreationStatus, WalletCredential } from '@shared/storage/types';
import { useAccountInfo } from '@popup/shared/AccountInfoListenerContext';
Expand Down Expand Up @@ -68,7 +68,7 @@ export default function AccountDetails({ expanded, account, className }: Props)

return (
<div className={clsx('account-page-details', expanded && 'account-page-details--expanded', className)}>
<div className="account-page-details__address">{displaySplitAddress(account.address)}</div>
<div className="account-page-details__address">{displayNameOrSplitAddress(account)}</div>
<div className="account-page-details__id">{identityName}</div>
<div className="account-page-details__balance">
<Amount label={t('total')} amount={balances.total} />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import AccountInfoListenerContextProvider, { useAccountInfo } from '@popup/shared/AccountInfoListenerContext';
import { displaySplitAddress, useIdentityName } from '@popup/shared/utils/account-helpers';
import { displayNameOrSplitAddress, useIdentityName } from '@popup/shared/utils/account-helpers';
import React, { useMemo, useState } from 'react';
import { Checkbox } from '@popup/shared/Form/Checkbox';
import { WalletCredential } from '@shared/storage/types';
Expand All @@ -25,7 +25,7 @@ function AccountListItem({ account, checked, onToggleChecked }: ItemProps) {
return (
<div className="allowlist-entry-view__accounts__item">
<div className="allowlist-entry-view__accounts__item__primary">
<div className="flex align-center">{displaySplitAddress(account.address)} </div>
<div className="flex align-center">{displayNameOrSplitAddress(account)} </div>
<Checkbox
className="allowlist-entry-view__accounts__item__check-box"
onClick={(e) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { absoluteRoutes } from '@popup/constants/routes';
import { fullscreenPromptContext } from '@popup/page-layouts/FullscreenPromptLayout';
import { selectedAccountAtom, storedAllowlistAtom } from '@popup/store/account';
import { selectedCredentialAtom, storedAllowlistAtom } from '@popup/store/account';
import { sessionPasscodeAtom } from '@popup/store/settings';
import { useAtom, useAtomValue } from 'jotai';
import React, { useContext, useEffect, useState } from 'react';
Expand All @@ -9,7 +9,7 @@ import { useLocation, Navigate } from 'react-router-dom';
import ExternalRequestLayout from '@popup/page-layouts/ExternalRequestLayout';
import Button from '@popup/shared/Button';
import { displayUrl } from '@popup/shared/utils/string-helpers';
import { displaySplitAddress } from '@popup/shared/utils/account-helpers';
import { displayNameOrSplitAddress } from '@popup/shared/utils/account-helpers';
import { handleAllowlistEntryUpdate } from '../Allowlist/util';

type Props = {
Expand All @@ -21,7 +21,7 @@ export default function ConnectionRequest({ onAllow, onReject }: Props) {
const { state } = useLocation();
const { t } = useTranslation('connectionRequest');
const { onClose, withClose } = useContext(fullscreenPromptContext);
const selectedAccount = useAtomValue(selectedAccountAtom);
const selectedAccount = useAtomValue(selectedCredentialAtom);
const [allowlistLoading, setAllowlist] = useAtom(storedAllowlistAtom);
const allowlist = allowlistLoading.value;
const passcode = useAtomValue(sessionPasscodeAtom);
Expand Down Expand Up @@ -56,7 +56,7 @@ export default function ConnectionRequest({ onAllow, onReject }: Props) {
<div className="account-page__connection-box connection-request__connection-box">{t('waiting')}</div>
<div className="h-full flex-column align-center">
<header className="m-v-20">
<h1>{t('title', { dApp: urlDisplay, account: displaySplitAddress(selectedAccount) })}</h1>
<h1>{t('title', { dApp: urlDisplay, account: displayNameOrSplitAddress(selectedAccount) })}</h1>
</header>
<p className="connection-request__description">{t('descriptionP1', { dApp: urlDisplay })}</p>
<p className="connection-request__description">{t('descriptionP2')}</p>
Expand All @@ -69,7 +69,7 @@ export default function ConnectionRequest({ onAllow, onReject }: Props) {
disabled={connectButtonDisabled}
onClick={() => {
setConnectButtonDisabled(true);
connectAccount(selectedAccount, new URL(url).origin).then(withClose(onAllow));
connectAccount(selectedAccount.address, new URL(url).origin).then(withClose(onAllow));
}}
>
{t('actions.connect')}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { identitiesAtom } from '@popup/store/identity';
import Button from '@popup/shared/Button';
import { absoluteRoutes } from '@popup/constants/routes';
import { noOp, displayAsCcd } from 'wallet-common-helpers';
import { displaySplitAddress } from '@popup/shared/utils/account-helpers';
import { displayNameOrSplitAddress } from '@popup/shared/utils/account-helpers';
import { IdentityIdentifier, BackgroundResponseStatus, RecoveryBackgroundResponse } from '@shared/utils/types';
import { fullscreenPromptContext } from '@popup/page-layouts/FullscreenPromptLayout';
import PageHeader from '@popup/shared/PageHeader';
Expand Down Expand Up @@ -69,7 +69,7 @@ export function DisplaySuccess({ added }: Props) {
</p>
{addedAccounts.filter(isIdentityOfCredential(identity)).map((cred) => (
<div className="recovery__main__credential" key={cred.credId}>
<p>{displaySplitAddress(cred.address)}</p>
<p>{displayNameOrSplitAddress(cred)}</p>
<p>
{displayAsCcd(
added.accounts.find((pair) => pair.address === cred.address)?.balance ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
RevealStatementV2,
StatementTypes,
} from '@concordium/web-sdk';
import { displaySplitAddress, useIdentityName, useIdentityOf } from '@popup/shared/utils/account-helpers';
import { displayNameOrSplitAddress, useIdentityName, useIdentityOf } from '@popup/shared/utils/account-helpers';
import { useDisplayAttributeValue } from '@popup/shared/utils/identity-helpers';
import { ConfirmedIdentity, WalletCredential } from '@shared/storage/types';
import { getCredentialIdFromSubjectDID } from '@shared/utils/verifiable-credential-helpers';
Expand All @@ -29,7 +29,7 @@ export function DisplayAccount({ option }: { option: WalletCredential }) {
return (
<header className="verifiable-credential__header">
<div className="web3-id-proof-request__selector-title flex-column align-start">
<div className="display5">{displaySplitAddress(option.address)}</div>
<div className="display5">{displayNameOrSplitAddress(option)}</div>
<div className="bodyS">{identityName}</div>
</div>
</header>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@ import { scaleFieldWidth } from '../../utils/html-helpers';
import { CommonFieldProps, RequiredControlledFieldProps } from '../common/types';
import { makeControlled } from '../common/utils';

type Props = Pick<InputHTMLAttributes<HTMLInputElement>, 'type' | 'className' | 'autoFocus'> &
type Props = Pick<
InputHTMLAttributes<HTMLInputElement>,
'type' | 'className' | 'autoFocus' | 'onKeyUp' | 'onMouseUp' | 'maxLength'
> &
RequiredControlledFieldProps &
CommonFieldProps & {
fallbackValue?: string;
fallbackOnError?: boolean;
fixedWidth?: number;
};

export function InlineInput({
Expand All @@ -20,14 +24,17 @@ export function InlineInput({
fallbackOnError = false,
onChange = noOp,
onBlur = noOp,
fixedWidth,
error,
...props
}: Props) {
const ref = useRef<HTMLInputElement>(null);
const [innerValue, setInnerValue] = useState(value ?? fallbackValue);

useLayoutEffect(() => {
scaleFieldWidth(ref.current);
if (!fixedWidth) {
scaleFieldWidth(ref.current);
}
}, [innerValue]);

useUpdateEffect(() => {
Expand All @@ -53,7 +60,7 @@ export function InlineInput({
autoComplete="off"
spellCheck="false"
{...props}
style={{ width: 6 }} // To prevent initial UI jitter.
style={{ width: fixedWidth || 6 }} // To prevent initial UI jitter.
/>
);
}
Expand Down
19 changes: 16 additions & 3 deletions packages/browser-wallet/src/popup/shared/utils/account-helpers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { credentialsAtom, selectedAccountAtom } from '@popup/store/account';
import { credentialsAtom, selectedAccountAtom, writableCredentialAtom } from '@popup/store/account';
import { networkConfigurationAtom } from '@popup/store/settings';
import { useAtomValue } from 'jotai';
import { useAtom, useAtomValue } from 'jotai';
import { useEffect, useMemo, useState } from 'react';
import { identitiesAtom } from '@popup/store/identity';
import { AccountInfo, ConcordiumHdWallet } from '@concordium/web-sdk';
Expand All @@ -10,7 +10,10 @@ import { isIdentityOfCredential } from '@shared/utils/identity-helpers';
import { getNextUnused } from '@shared/utils/number-helpers';
import { useDecryptedSeedPhrase } from './seed-phrase-helpers';

export const displaySplitAddress = (address: string) => `${address.slice(0, 4)}...${address.slice(address.length - 4)}`;
export const displayNameOrSplitAddress = (account: WalletCredential | undefined) => {
const { credName, address } = account || { address: '' };
return credName || `${address.slice(0, 4)}...${address.slice(address.length - 4)}`;
};

export function useIdentityOf(cred?: WalletCredential) {
const identities = useAtomValue(identitiesAtom);
Expand Down Expand Up @@ -40,6 +43,16 @@ export function useIdentityName(credential: WalletCredential, fallback?: string)
return identityName;
}

export function useWritableSelectedAccount(accountAddress: string) {
const [accounts, setAccounts] = useAtom(writableCredentialAtom);
const setAccount = (update: WalletCredential) =>
setAccounts(
accounts.map((account) => (account.address === accountAddress ? { ...account, ...update } : account))
);

return setAccount;
}

export function useCredential(accountAddress?: string) {
const credentials = useAtomValue(credentialsAtom);

Expand Down
13 changes: 13 additions & 0 deletions packages/browser-wallet/src/popup/store/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ export const credentialsAtomWithLoading = atomWithChromeStorage<WalletCredential
);
export const credentialsAtom = selectAtom(credentialsAtomWithLoading, (v) => v.value);

export const writableCredentialAtom = atom<WalletCredential[], WalletCredential[]>(
(get) => get(credentialsAtom),
async (_, set, update) => {
await set(credentialsAtomWithLoading, update);
}
);

export const storedConnectedSitesAtom = atomWithChromeStorage<Record<string, string[]>>(
ChromeStorageKey.ConnectedSites,
{},
Expand All @@ -34,6 +41,12 @@ export const selectedAccountAtom = atom<string | undefined, string | undefined,
}
);

export const selectedCredentialAtom = atom<WalletCredential | undefined>((get) => {
const selectedAccount = get(selectedAccountAtom);
const credentials = get(credentialsAtom);
return credentials.find((cred) => cred.address === selectedAccount);
});

export const accountsAtom = selectAtom(credentialsAtom, (cs) => cs.map((c) => c.address));

export const accountsPerIdentityAtom = selectAtom(credentialsAtom, (cs) => {
Expand Down
Loading
Loading