ghost-portal/packages/page-accounts/src/util.tsx
Vitaliy 734c3c653a
Add sorting for accounts view (#5923)
* Show basic balance info

* Show bonded summary

* Show redeemable summary

* Show unbonding summary

* Adopt linter suggestions

* Hide cards with zero balance

* Apply simplifications

Co-authored-by: Jaco <jacogr@gmail.com>

* Remove dead code

* Simplify balance==undefined case

* Add summary bar tests (#5890)

* Add tests for summary bar

* Improve test case name

Co-authored-by: Krzysztof Jelski <kjelski@gmail.com>

* Factor empty render into a beforeEach block

* Improve name of helper variable

Co-authored-by: Krzysztof Jelski <kjelski@gmail.com>

* Construct correct instance for StakingLedger.active

* Override only the relevant parts in each test case

* Simplify test cases

Co-authored-by: Krzysztof Jelski <kjelski@gmail.com>

* Sort by total balance and by type

* Rename "clas" to "htmlClass"

* Extract DEFAULT_SORT_CONTROLS constant

* Move stableSort to its own file

* Optimize sorting on accounts page

* Adopt new sorting design

* Apply suggestions from code review

Co-authored-by: Jaco <jacogr@gmail.com>

* Remove stableSort function

* Move Dropdown css to Account styles

* Add tests for sorting

* Adjust tests and apply lint fixes

* Apply lint fixes

* Improve row coloring and styling of button for sort direction

* Improve styling

* Fix tests setup and bug connected with cloning accounts

* Restore condition

* Fix imports

Co-authored-by: Jaco <jacogr@gmail.com>
Co-authored-by: Krzysztof Jelski <kjelski@gmail.com>
Co-authored-by: MiZiet <michalzietalak@o2.pl>
Co-authored-by: Ewa Kowalska <ewcia.kowalska@gmail.com>
2021-09-06 14:14:56 +02:00

116 lines
3.9 KiB
TypeScript

// Copyright 2017-2021 @polkadot/app-accounts authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ActionStatus } from '@polkadot/react-components/Status/types';
import type { AccountId, AccountIndex, Address } from '@polkadot/types/interfaces';
import type { CreateResult } from '@polkadot/ui-keyring/types';
import type { AccountBalance, SortedAccount } from './types';
import FileSaver from 'file-saver';
import React from 'react';
import { getEnvironment } from '@polkadot/react-api/util';
import { InputAddress, Menu } from '@polkadot/react-components';
import { getAccountCryptoType, getAddressMeta } from '@polkadot/react-components/util';
import { BN_ZERO } from '@polkadot/util';
export function createMenuGroup (key: string, items: (React.ReactNode | false | undefined | null)[], header?: string): React.ReactNode | null {
const filtered = items.filter((item): item is React.ReactNode => !!item);
return filtered.length
? <React.Fragment key={key}>
<Menu.Divider />
{header ? <Menu.Header>{header}</Menu.Header> : null}
{filtered}
</React.Fragment>
: null;
}
export type AccountIdIsh = AccountId | AccountIndex | Address | string | Uint8Array | null;
export function downloadAccount ({ json, pair }: CreateResult): void {
FileSaver.saveAs(
new Blob([JSON.stringify(json)], { type: 'application/json; charset=utf-8' }),
`${pair.address}.json`
);
}
export function tryCreateAccount (commitAccount: () => CreateResult, success: string): ActionStatus {
const status: ActionStatus = {
action: 'create',
message: success,
status: 'success'
};
try {
const result = commitAccount();
const address = result.pair.address;
status.account = address;
if (getEnvironment() === 'web') {
downloadAccount(result);
}
downloadAccount(result);
InputAddress.setLastValue('account', address);
} catch (error) {
status.status = 'error';
status.message = (error as Error).message;
}
return status;
}
export const sortCategory = ['parent', 'name', 'date', 'balances', 'type'] as const;
export type SortCategory = typeof sortCategory[number];
const comparator = (accounts: Record<string, SortedAccount | undefined>, balances: Record<string, AccountBalance | undefined>, category: SortCategory, fromMax: boolean) => {
function accountQualifiedName (account: SortedAccount | undefined): string {
if (account) {
const parent = (account.account?.meta.parentAddress || '') as string;
return accountQualifiedName(accounts[parent]) + account.address;
} else {
return '';
}
}
function make <T> (getValue: (acc: SortedAccount) => T, compare: (a: T, b: T) => number) {
const mult = fromMax ? 1 : -1;
return (a: SortedAccount, b: SortedAccount) =>
mult * compare(getValue(a), getValue(b));
}
switch (category) {
case 'parent':
// We need to ensure that parent will be adjacent to its children
// so we use format '...<grand-parent-addr><parent-addr><account-addr>'
return make(accountQualifiedName, (a, b) => a.localeCompare(b));
case 'name':
return make((acc) => getAddressMeta(acc.address).name ?? '', (a, b) => a.localeCompare(b));
case 'date':
return make((acc) => acc.account?.meta.whenCreated ?? 0, (a, b) => a - b);
case 'balances':
return make((acc) => balances[acc.address]?.total ?? BN_ZERO, (a, b) => a.cmp(b));
case 'type':
return make((acc) => getAccountCryptoType(acc.address), (a, b) => a.localeCompare(b));
}
};
export function sortAccounts (accountsList: SortedAccount[], accountsMap: Record<string, SortedAccount>, balances: Record<string, AccountBalance>, by: SortCategory, fromMax: boolean): SortedAccount[] {
return [...accountsList]
.sort(comparator(accountsMap, balances, by, fromMax))
.sort((a, b) =>
a.isFavorite === b.isFavorite
? 0
: b.isFavorite
? 1
: -1);
}