Additional useCallback (close to 100%) (#2527)

This commit is contained in:
Jaco Greeff 2020-04-07 16:07:11 +02:00 committed by GitHub
parent 9037fe6d03
commit 4d17d5236d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 614 additions and 471 deletions

View File

@ -199,11 +199,14 @@ function Create ({ className, onClose, onStatusChange, seed: propsSeed, type: pr
[derivePath, seed, seedType]
);
const _selectSeedType = (newSeedType: SeedType): void => {
if (newSeedType !== seedType) {
setAddress(generateSeed(null, derivePath, newSeedType, pairType));
}
};
const _selectSeedType = useCallback(
(newSeedType: SeedType): void => {
if (newSeedType !== seedType) {
setAddress(generateSeed(null, derivePath, newSeedType, pairType));
}
},
[derivePath, pairType, seedType]
);
const _onChangeName = useCallback(
(name: string) => setName({ isNameValid: !!name.trim(), name }),

View File

@ -6,10 +6,10 @@ import { DeriveAccountInfo, DeriveBalancesAll } from '@polkadot/api-derive/types
import { KeyringAddress } from '@polkadot/ui-keyring/types';
import { ActionStatus } from '@polkadot/react-components/Status/types';
import React, { useEffect, useState } from 'react';
import React, { useCallback, useEffect, useState } from 'react';
import styled from 'styled-components';
import { AddressSmall, AddressInfo, Button, ChainLock, Icon, InputTags, Input, LinkExternal, Forget, Menu, Popup, Tag } from '@polkadot/react-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { useApi, useCall, useToggle } from '@polkadot/react-hooks';
import keyring from '@polkadot/ui-keyring';
import { formatNumber } from '@polkadot/util';
@ -37,14 +37,17 @@ function Address ({ address, className, filter, isFavorite, toggleFavorite }: Pr
const [accName, setAccName] = useState('');
const [current, setCurrent] = useState<KeyringAddress | null>(null);
const [genesisHash, setGenesisHash] = useState<string | null>(null);
const [isEditingName, setIsEditingName] = useState(false);
const [isEditingTags, setIsEditingTags] = useState(false);
const [isForgetOpen, setIsForgetOpen] = useState(false);
const [isSettingPopupOpen, setIsSettingPopupOpen] = useState(false);
const [isTransferOpen, setIsTransferOpen] = useState(false);
const [isEditingName, toggleEditName] = useToggle();
const [isEditingTags, toggleEditTags] = useToggle();
const [isForgetOpen, toggleForget] = useToggle();
const [isSettingPopupOpen, toggleTransfer] = useToggle();
const [isTransferOpen, toggleSettingPopup] = useToggle();
const [isVisible, setIsVisible] = useState(true);
const _setTags = (tags: string[]): void => setTags(tags.sort());
const _setTags = useCallback(
(tags: string[]): void => setTags(tags.sort()),
[]
);
useEffect((): void => {
const current = keyring.getAddress(address);
@ -71,7 +74,7 @@ function Address ({ address, className, filter, isFavorite, toggleFavorite }: Pr
_setTags(account?.meta?.tags || []);
setAccName(account?.meta?.name || '');
}, [address]);
}, [_setTags, address]);
useEffect((): void => {
if (filter.length === 0) {
@ -87,78 +90,87 @@ function Address ({ address, className, filter, isFavorite, toggleFavorite }: Pr
}
}, [accName, filter, tags]);
const _onForget = useCallback(
(): void => {
if (address) {
const status: Partial<ActionStatus> = {
account: address,
action: 'forget'
};
try {
keyring.forgetAddress(address);
status.status = 'success';
status.message = t('address forgotten');
} catch (error) {
status.status = 'error';
status.message = error.message;
}
}
},
[address, t]
);
const _onGenesisChange = useCallback(
(genesisHash: string | null): void => {
setGenesisHash(genesisHash);
const account = keyring.getAddress(address);
account && keyring.saveAddress(address, { ...account.meta, genesisHash });
setGenesisHash(genesisHash);
},
[address]
);
const _onFavorite = useCallback(
(): void => toggleFavorite(address),
[address, toggleFavorite]
);
const _saveName = useCallback(
(): void => {
toggleEditName();
const meta = { name: accName, whenEdited: Date.now() };
if (address) {
try {
const currentKeyring = keyring.getPair(address);
currentKeyring && keyring.saveAccountMeta(currentKeyring, meta);
} catch (error) {
keyring.saveAddress(address, meta);
}
}
},
[accName, address, toggleEditName]
);
const _saveTags = useCallback(
(): void => {
toggleEditTags();
const meta = { tags, whenEdited: Date.now() };
if (address) {
try {
const currentKeyring = keyring.getPair(address);
currentKeyring && keyring.saveAccountMeta(currentKeyring, meta);
} catch (error) {
keyring.saveAddress(address, meta);
}
}
},
[address, tags, toggleEditTags]
);
if (!isVisible) {
return null;
}
const _toggleEditName = (): void => setIsEditingName(!isEditingName);
const _toggleEditTags = (): void => setIsEditingTags(!isEditingTags);
const _toggleForget = (): void => setIsForgetOpen(!isForgetOpen);
const _toggleSettingPopup = (): void => setIsSettingPopupOpen(!isSettingPopupOpen);
const _toggleTransfer = (): void => setIsTransferOpen(!isTransferOpen);
const _onForget = (): void => {
if (address) {
const status: Partial<ActionStatus> = {
account: address,
action: 'forget'
};
try {
keyring.forgetAddress(address);
status.status = 'success';
status.message = t('address forgotten');
} catch (error) {
status.status = 'error';
status.message = error.message;
}
}
};
const _onGenesisChange = (genesisHash: string | null): void => {
setGenesisHash(genesisHash);
const account = keyring.getAddress(address);
account && keyring.saveAddress(address, { ...account.meta, genesisHash });
setGenesisHash(genesisHash);
};
const _onFavorite = (): void => toggleFavorite(address);
const _saveName = (): void => {
_toggleEditName();
const meta = { name: accName, whenEdited: Date.now() };
if (address) {
try {
const currentKeyring = keyring.getPair(address);
currentKeyring && keyring.saveAccountMeta(currentKeyring, meta);
} catch (error) {
keyring.saveAddress(address, meta);
}
}
};
const _saveTags = (): void => {
_toggleEditTags();
const meta = { tags, whenEdited: Date.now() };
if (address) {
try {
const currentKeyring = keyring.getPair(address);
currentKeyring && keyring.saveAccountMeta(currentKeyring, meta);
} catch (error) {
keyring.saveAddress(address, meta);
}
}
};
return (
<tr className={className}>
<td className='favorite'>
@ -170,7 +182,7 @@ function Address ({ address, className, filter, isFavorite, toggleFavorite }: Pr
</td>
<td className='address'>
<AddressSmall
onClickName={_toggleEditName}
onClickName={toggleEditName}
overrideName={
isEditingName
? (
@ -196,14 +208,14 @@ function Address ({ address, className, filter, isFavorite, toggleFavorite }: Pr
address={current.address}
key='modal-forget-account'
mode='address'
onClose={_toggleForget}
onClose={toggleForget}
onForget={_onForget}
/>
)}
{isTransferOpen && (
<Transfer
key='modal-transfer'
onClose={_toggleTransfer}
onClose={toggleTransfer}
recipientId={address}
/>
)}
@ -227,7 +239,7 @@ function Address ({ address, className, filter, isFavorite, toggleFavorite }: Pr
: (
<div
className='tags--toggle'
onClick={_toggleEditTags}
onClick={toggleEditTags}
>
{tags.length
? tags.map((tag): React.ReactNode => (
@ -258,30 +270,30 @@ function Address ({ address, className, filter, isFavorite, toggleFavorite }: Pr
icon='paper plane'
key='deposit'
label={t('deposit')}
onClick={_toggleTransfer}
onClick={toggleTransfer}
size='small'
tooltip={t('Send funds to this address')}
/>
<Popup
className='theme--default'
isOpen={isSettingPopupOpen}
onClose={_toggleSettingPopup}
onClose={toggleSettingPopup}
trigger={
<Button
icon='setting'
onClick={_toggleSettingPopup}
onClick={toggleSettingPopup}
size='small'
/>
}
>
<Menu
onClick={_toggleSettingPopup}
onClick={toggleSettingPopup}
text
vertical
>
<Menu.Item
disabled={!isEditable}
onClick={_toggleForget}
onClick={toggleForget}
>
{t('Forget this address')}
</Menu.Item>

View File

@ -2,23 +2,32 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import React from 'react';
import React, { useCallback } from 'react';
import { Card, Button } from '@polkadot/react-components';
import { I18nProps } from '@polkadot/react-components/types';
import AssetRow from './AssetRow';
import translate from './translate';
import { useTranslation } from './translate';
interface Props extends I18nProps {
interface Props {
assetId: string;
className?: string;
name: string;
onSaveName: (id: string, name: string) => void;
onForget: (id: string) => void;
}
function AssetCard ({ assetId, className, name, onForget, onSaveName, t }: Props): React.ReactElement<Props> {
const _onForget = (): void => onForget(assetId);
const _onSaveName = (name: string): void => onSaveName(assetId, name);
function AssetCard ({ assetId, className, name, onForget, onSaveName }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const _onForget = useCallback(
(): void => onForget(assetId),
[assetId, onForget]
);
const _onSaveName = useCallback(
(name: string): void => onSaveName(assetId, name),
[assetId, onSaveName]
);
return (
<Card className={className}>
@ -44,4 +53,4 @@ function AssetCard ({ assetId, className, name, onForget, onSaveName, t }: Props
);
}
export default translate(AssetCard);
export default React.memo(AssetCard);

View File

@ -4,7 +4,7 @@
import { BareProps } from '@polkadot/react-components/types';
import React, { useState } from 'react';
import React, { useCallback, useState } from 'react';
import { Button as SUIB, Popup } from 'semantic-ui-react';
import { Button, Input } from '@polkadot/react-components';
@ -25,23 +25,31 @@ function ActionButtons ({ className, isCustomExample, isRunning, removeSnippet,
const [isOpen, setIsOpen] = useState(false);
const [snippetName, setSnippetName] = useState('');
const _onChangeName = (snippetName: string): void => {
setSnippetName(snippetName);
};
const _onChangeName = useCallback(
(snippetName: string) => setSnippetName(snippetName),
[]
);
const _onPopupOpen = (): void => {
setIsOpen(true);
};
const _onPopupOpen = useCallback(
() => setIsOpen(true),
[]
);
const _onPopupClose = (): void => {
setSnippetName('');
setIsOpen(false);
};
const _onPopupClose = useCallback(
(): void => {
setSnippetName('');
setIsOpen(false);
},
[]
);
const _saveSnippet = (): void => {
saveSnippet(snippetName);
_onPopupClose();
};
const _saveSnippet = useCallback(
(): void => {
saveSnippet(snippetName);
_onPopupClose();
},
[_onPopupClose, saveSnippet, snippetName]
);
return (
<div className={`${className} action-button`}>

View File

@ -8,7 +8,7 @@ import { ApiProps } from '@polkadot/react-api/types';
import { AppProps as Props } from '@polkadot/react-components/types';
import { Log, LogType, Snippet } from './types';
import React, { useRef, useState, useEffect } from 'react';
import React, { useCallback, useRef, useState, useEffect } from 'react';
import styled from 'styled-components';
import { Button, Dropdown, Editor } from '@polkadot/react-components';
import { useApi } from '@polkadot/react-hooks';
@ -113,90 +113,111 @@ function Playground ({ className }: Props): React.ReactElement<Props> {
setCode(selected.code);
}, [selected]);
const _clearConsole = (): void => setLogs([]);
const _clearConsole = useCallback(
(): void => setLogs([]),
[]
);
const _hookConsole = (type: LogType, args: any[]): void => {
logs.push({ args, type });
setLogs(logs.slice(0));
};
const _hookConsole = useCallback(
(type: LogType, args: any[]): void => {
logs.push({ args, type });
setLogs(logs.slice(0));
},
[logs]
);
const _stopJs = (): void => {
if (injectedRef.current) {
injectedRef.current.api.disconnect();
injectedRef.current = null;
}
setIsRunning(false);
};
const _runJs = async (): Promise<void> => {
setIsRunning(true);
_clearConsole();
injectedRef.current = setupInjected(apiProps, setIsRunning, _hookConsole);
await injectedRef.current.api.isReady;
try {
// squash into a single line so exceptions (with line numbers) maps to the
// same line/origin as we have in the editor view
// TODO: Make the console.error here actually return the full stack
const exec = `(async ({${Object.keys(injectedRef.current).sort().join(',')}}) => { try { ${code} \n } catch (error) { console.error(error); setIsRunning(false); } })(injected);`;
// eslint-disable-next-line no-new-func
new Function('injected', exec).bind({}, injectedRef.current)();
} catch (error) {
injectedRef.current.console.error(error);
}
setIsRunning(false);
};
const _selectExample = (value: string): void => {
_stopJs();
if (value.length) {
const option = options.find((option): boolean => option.value === value);
if (option) {
localStorage.setItem(STORE_SELECTED, value);
_clearConsole();
setIsCustomExample(option.type === 'custom');
setSelected(option);
const _stopJs = useCallback(
(): void => {
if (injectedRef.current) {
injectedRef.current.api.disconnect();
injectedRef.current = null;
}
}
};
const _removeSnippet = (): void => {
const filtered = customExamples.filter((value): boolean => value.value !== selected.value);
const nextOptions = [...filtered, ...snippets];
setIsRunning(false);
},
[]
);
setCustomExamples(filtered);
setIsCustomExample(nextOptions[0].type === 'custom');
setOptions(nextOptions);
_selectExample(nextOptions[0].value);
localStorage.setItem(STORE_EXAMPLES, JSON.stringify(filtered));
};
const _runJs = useCallback(
async (): Promise<void> => {
setIsRunning(true);
_clearConsole();
const _saveSnippet = (snippetName: string): void => {
// The <Dropdown> component doesn't take boolean custom props and no
// camelCase keys, that's why 'custom' is passed as a string here
const snapshot: Snippet = {
code,
label: CUSTOM_LABEL,
text: snippetName,
type: 'custom',
value: `custom-${Date.now()}`
};
const options = [snapshot, ...customExamples, ...snippets];
injectedRef.current = setupInjected(apiProps, setIsRunning, _hookConsole);
localStorage.setItem(STORE_EXAMPLES, JSON.stringify([snapshot, ...customExamples]));
setCustomExamples([snapshot, ...customExamples]);
setIsCustomExample(true);
setOptions(options);
setSelected(snapshot);
};
await injectedRef.current.api.isReady;
try {
// squash into a single line so exceptions (with line numbers) maps to the
// same line/origin as we have in the editor view
// TODO: Make the console.error here actually return the full stack
const exec = `(async ({${Object.keys(injectedRef.current).sort().join(',')}}) => { try { ${code} \n } catch (error) { console.error(error); setIsRunning(false); } })(injected);`;
// eslint-disable-next-line no-new-func
new Function('injected', exec).bind({}, injectedRef.current)();
} catch (error) {
injectedRef.current.console.error(error);
}
setIsRunning(false);
},
[_clearConsole, _hookConsole, apiProps, code]
);
const _selectExample = useCallback(
(value: string): void => {
_stopJs();
if (value.length) {
const option = options.find((option): boolean => option.value === value);
if (option) {
localStorage.setItem(STORE_SELECTED, value);
_clearConsole();
setIsCustomExample(option.type === 'custom');
setSelected(option);
}
}
},
[_clearConsole, _stopJs, options]
);
const _removeSnippet = useCallback(
(): void => {
const filtered = customExamples.filter((value): boolean => value.value !== selected.value);
const nextOptions = [...filtered, ...snippets];
setCustomExamples(filtered);
setIsCustomExample(nextOptions[0].type === 'custom');
setOptions(nextOptions);
_selectExample(nextOptions[0].value);
localStorage.setItem(STORE_EXAMPLES, JSON.stringify(filtered));
},
[_selectExample, customExamples, selected.value]
);
const _saveSnippet = useCallback(
(snippetName: string): void => {
// The <Dropdown> component doesn't take boolean custom props and no
// camelCase keys, that's why 'custom' is passed as a string here
const snapshot: Snippet = {
code,
label: CUSTOM_LABEL,
text: snippetName,
type: 'custom',
value: `custom-${Date.now()}`
};
const options = [snapshot, ...customExamples, ...snippets];
localStorage.setItem(STORE_EXAMPLES, JSON.stringify([snapshot, ...customExamples]));
setCustomExamples([snapshot, ...customExamples]);
setIsCustomExample(true);
setOptions(options);
setSelected(snapshot);
},
[code, customExamples]
);
const snippetName = selected.type === 'custom' ? selected.text : undefined;

View File

@ -4,7 +4,7 @@
import { DeriveParachain } from '@polkadot/api-derive/types';
import React from 'react';
import React, { useCallback } from 'react';
import { useHistory } from 'react-router-dom';
import styled from 'styled-components';
import { Badge, Icon } from '@polkadot/react-components';
@ -21,9 +21,12 @@ function Parachain ({ className, parachain: { didUpdate, id, info, pendingSwapId
const { t } = useTranslation();
const history = useHistory();
const _onClick = (): void => {
history.push(`/parachains/${id.toString()}`);
};
const _onClick = useCallback(
(): void => {
history.push(`/parachains/${id.toString()}`);
},
[history, id]
);
return (
<tr

View File

@ -4,7 +4,7 @@
import { AppProps as Props } from '@polkadot/react-components/types';
import React, { useEffect, useState } from 'react';
import React, { useCallback, useEffect, useState } from 'react';
import { Trans } from 'react-i18next';
import store from 'store';
import styled from 'styled-components';
@ -17,6 +17,14 @@ import { useTranslation } from './translate';
const EMPTY_CODE = '{\n\n}';
const EMPTY_TYPES = {};
interface AllState {
code: string;
isJsonValid: boolean;
isTypesValid: boolean;
types: Record<string, any>;
typesPlaceholder: string | null;
}
function Developer ({ className, onStatusChange }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [code, setCode] = useState(EMPTY_CODE);
@ -35,87 +43,102 @@ function Developer ({ className, onStatusChange }: Props): React.ReactElement<Pr
}
}, []);
const _setState = ({ code, isJsonValid, isTypesValid, types, typesPlaceholder }: { code: string; isJsonValid: boolean; isTypesValid: boolean; types: Record<string, any>; typesPlaceholder: string | null }): void => {
setCode(code);
setIsJsonValid(isJsonValid);
setIsTypesValid(isTypesValid);
setTypes(types);
setTypesPlaceholder(typesPlaceholder);
};
const _setState = useCallback(
({ code, isJsonValid, isTypesValid, types, typesPlaceholder }: AllState): void => {
setCode(code);
setIsJsonValid(isJsonValid);
setIsTypesValid(isTypesValid);
setTypes(types);
setTypesPlaceholder(typesPlaceholder);
},
[]
);
const _clearTypes = (): void => {
store.remove('types');
_setState({
code: EMPTY_CODE,
isJsonValid: true,
isTypesValid: true,
types: EMPTY_TYPES,
typesPlaceholder: null
});
};
const _onChangeTypes = (data: Uint8Array): void => {
const code = u8aToString(data);
try {
const types = JSON.parse(code);
const typesPlaceholder = Object.keys(types).join(', ');
console.log('Detected types:', typesPlaceholder);
const _clearTypes = useCallback(
(): void => {
store.remove('types');
_setState({
code,
code: EMPTY_CODE,
isJsonValid: true,
isTypesValid: true,
types: Object.keys(types).length === 0 ? {} : types,
typesPlaceholder
types: EMPTY_TYPES,
typesPlaceholder: null
});
} catch (error) {
console.error('Error registering types:', error);
},
[_setState]
);
_setState({
code,
isJsonValid: false,
isTypesValid: false,
types: {},
typesPlaceholder: error.message
});
}
};
const _onChangeTypes = useCallback(
(data: Uint8Array): void => {
const code = u8aToString(data);
const _onEditTypes = (code: string): void => {
try {
if (!isJsonObject(code)) {
throw Error(t('This is not a valid JSON object.'));
try {
const types = JSON.parse(code);
const typesPlaceholder = Object.keys(types).join(', ');
console.log('Detected types:', typesPlaceholder);
_setState({
code,
isJsonValid: true,
isTypesValid: true,
types: Object.keys(types).length === 0 ? {} : types,
typesPlaceholder
});
} catch (error) {
console.error('Error registering types:', error);
_setState({
code,
isJsonValid: false,
isTypesValid: false,
types: {},
typesPlaceholder: error.message
});
}
},
[_setState]
);
_onChangeTypes(stringToU8a(code));
} catch (e) {
setCode(code);
setIsJsonValid(false);
setTypesPlaceholder(e.message);
}
};
const _onEditTypes = useCallback(
(code: string): void => {
try {
if (!isJsonObject(code)) {
throw Error(t('This is not a valid JSON object.'));
}
const _saveDeveloper = (): void => {
try {
registry.register(types);
store.set('types', types);
setIsTypesValid(true);
onStatusChange({
action: t('Your custom types have been added'),
status: 'success'
});
} catch (error) {
console.error(error);
setIsTypesValid(false);
onStatusChange({
action: t(`Error saving your custom types. ${error.message}`),
status: 'error'
});
}
};
_onChangeTypes(stringToU8a(code));
} catch (e) {
setCode(code);
setIsJsonValid(false);
setTypesPlaceholder(e.message);
}
},
[_onChangeTypes, t]
);
const _saveDeveloper = useCallback(
(): void => {
try {
registry.register(types);
store.set('types', types);
setIsTypesValid(true);
onStatusChange({
action: t('Your custom types have been added'),
status: 'success'
});
} catch (error) {
console.error(error);
setIsTypesValid(false);
onStatusChange({
action: t(`Error saving your custom types. ${error.message}`),
status: 'error'
});
}
},
[onStatusChange, t, types]
);
const typesHasNoEntries = Object.keys(types).length === 0;

View File

@ -6,7 +6,7 @@ import { DeriveHeartbeats, DeriveStakingOverview } from '@polkadot/api-derive/ty
import { AccountId } from '@polkadot/types/interfaces';
import { AddressDetails } from './types';
import React, { useEffect, useReducer, useState } from 'react';
import React, { useCallback, useEffect, useReducer, useState } from 'react';
import { Input, Table } from '@polkadot/react-components';
import { useFavorites } from '@polkadot/react-hooks';
@ -114,25 +114,28 @@ function CurrentList ({ authorsMap, hasQueries, isIntentions, lastAuthors, next,
}
}, [favorites, next, stakingOverview]);
const _renderRows = (addresses?: AccountExtend[], isMain?: boolean): React.ReactNode[] =>
(addresses || []).map(([address, isElected, isFavorite]): React.ReactNode => (
<Address
address={address}
filterName={nameFilter}
hasQueries={hasQueries}
isAuthor={lastAuthors && lastAuthors.includes(address)}
isElected={isElected}
isFavorite={isFavorite}
isMain={isMain}
key={address}
lastBlock={authorsMap[address]}
onlineCount={isMain && recentlyOnline?.[address]?.blockCount.toNumber()}
onlineMessage={isMain && recentlyOnline?.[address]?.hasMessage}
points={isMain && addressDetails[address] && addressDetails[address].points}
setNominators={isIntentions && setNominators}
toggleFavorite={toggleFavorite}
/>
));
const _renderRows = useCallback(
(addresses?: AccountExtend[], isMain?: boolean): React.ReactNode[] =>
(addresses || []).map(([address, isElected, isFavorite]): React.ReactNode => (
<Address
address={address}
filterName={nameFilter}
hasQueries={hasQueries}
isAuthor={lastAuthors && lastAuthors.includes(address)}
isElected={isElected}
isFavorite={isFavorite}
isMain={isMain}
key={address}
lastBlock={authorsMap[address]}
onlineCount={isMain && recentlyOnline?.[address]?.blockCount.toNumber()}
onlineMessage={isMain && recentlyOnline?.[address]?.hasMessage}
points={isMain && addressDetails[address] && addressDetails[address].points}
setNominators={isIntentions && setNominators}
toggleFavorite={toggleFavorite}
/>
)),
[addressDetails, authorsMap, hasQueries, isIntentions, lastAuthors, nameFilter, recentlyOnline, setNominators, toggleFavorite]
);
return isIntentions
? (

View File

@ -6,7 +6,7 @@ import { RenderFn, DefaultProps, ComponentRenderer } from '@polkadot/react-api/h
import { ConstValue } from '@polkadot/react-components/InputConsts/types';
import { QueryTypes, StorageEntryPromise, StorageModuleQuery } from './types';
import React, { useEffect, useState } from 'react';
import React, { useCallback, useEffect, useState } from 'react';
import styled from 'styled-components';
import { unwrapStorageType } from '@polkadot/types/primitive/StorageKey';
import { Button, Labelled } from '@polkadot/react-components';
@ -135,18 +135,6 @@ function Query ({ className, onRemove, value }: Props): React.ReactElement<Props
useEffect((): void => {
setComponent(getCachedComponent(value));
// setInputs(
// isU8a(value.key)
// ? []
// // FIXME We need to render the actual key params
// // const { key, params } = value;
// // const inputs = key.params.map(({ name, type }, index) => (
// // <span key={`param_${name}_${index}`}>
// // {name}={valueToText(type, params[index].value)}
// // </span>
// // ));
// : []
// );
setIsSpreadable(
(value.key as StorageEntryPromise).creator &&
(value.key as StorageEntryPromise).creator.meta &&
@ -154,6 +142,28 @@ function Query ({ className, onRemove, value }: Props): React.ReactElement<Props
);
}, [value]);
const _spreadHandler = useCallback(
(id: number): () => void => {
return (): void => {
cache[id].Component = cache[id].refresh(true, !!spread[id]);
spread[id] = !spread[id];
setComponent(cache[id]);
setSpread({ ...spread });
};
},
[spread]
);
const _onRemove = useCallback(
(): void => {
delete cache[value.id];
onRemove(value.id);
},
[onRemove, value]
);
const { id, isConst, key } = value;
const type = isConst
? (key as unknown as ConstValue).meta.type.toString()
@ -165,22 +175,6 @@ function Query ({ className, onRemove, value }: Props): React.ReactElement<Props
return null;
}
const _spreadHandler = (id: number): () => void => {
return (): void => {
cache[id].Component = cache[id].refresh(true, !!spread[id]);
spread[id] = !spread[id];
setComponent(cache[id]);
setSpread({ ...spread });
};
};
const _onRemove = (): void => {
delete cache[value.id];
onRemove(value.id);
};
return (
<div className={`storage--Query storage--actionrow ${className}`}>
<div className='storage--actionrow-value'>

View File

@ -6,7 +6,7 @@ import { ConstantCodec } from '@polkadot/metadata/Decorated/types';
import { ConstValue } from '@polkadot/react-components/InputConsts/types';
import { ComponentProps as Props } from '../types';
import React, { useState } from 'react';
import React, { useCallback, useState } from 'react';
import { Button, InputConsts } from '@polkadot/react-components';
import { useApi } from '@polkadot/react-hooks';
@ -27,7 +27,10 @@ function Consts ({ onAdd }: Props): React.ReactElement<Props> {
});
const [value, setValue] = useState(defaultValue);
const _onAdd = (): void => onAdd({ isConst: true, key: value });
const _onAdd = useCallback(
() => onAdd({ isConst: true, key: value }),
[onAdd, value]
);
const { method, section } = value;
const meta = (api.consts[section][method] as ConstantCodec).meta;

View File

@ -6,7 +6,7 @@ import { TypeDef } from '@polkadot/types/types';
import { RawParams } from '@polkadot/react-params/types';
import { ComponentProps as Props, StorageEntryPromise } from '../types';
import React, { useState } from 'react';
import React, { useCallback, useState } from 'react';
import ApiPromise from '@polkadot/api/promise';
import { Button, InputStorage } from '@polkadot/react-components';
import { useApi } from '@polkadot/react-hooks';
@ -70,24 +70,33 @@ function Modules ({ onAdd }: Props): React.ReactElement<Props> {
const [{ defaultValues, isIterable, key, params }, setKey] = useState<KeyState>({ defaultValues: undefined, isIterable: false, key: api.query.timestamp.now, params: [] });
const [{ isValid, values }, setValues] = useState<{ isValid: boolean; values: RawParams }>({ isValid: true, values: [] });
const _onAdd = (): void => {
isValid && onAdd({
isConst: false,
key,
params: values.filter(({ value }): boolean => !isIterable || !isNull(value))
});
};
const _onAdd = useCallback(
(): void => {
isValid && onAdd({
isConst: false,
key,
params: values.filter(({ value }): boolean => !isIterable || !isNull(value))
});
},
[isIterable, isValid, key, onAdd, values]
);
const _onChangeValues = (values: RawParams): void =>
setValues({
isValid: areParamsValid(key, values),
values
});
const _onChangeValues = useCallback(
(values: RawParams): void =>
setValues({
isValid: areParamsValid(key, values),
values
}),
[key]
);
const _onChangeKey = (key: StorageEntryPromise): void => {
setKey(expandKey(api, key));
_onChangeValues([]);
};
const _onChangeKey = useCallback(
(key: StorageEntryPromise): void => {
setKey(expandKey(api, key));
_onChangeValues([]);
},
[_onChangeValues, api]
);
const { creator: { meta, method, section } } = key;

View File

@ -4,7 +4,7 @@
import { ComponentProps as Props } from '../types';
import React, { useState } from 'react';
import React, { useCallback, useState } from 'react';
import { Button, Input } from '@polkadot/react-components';
import { useTranslation } from '../translate';
@ -15,19 +15,24 @@ function Raw ({ onAdd }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [{ isValid, key }, setValue] = useState<{ isValid: boolean; key: Uint8Array }>({ isValid: false, key: new Uint8Array([]) });
const _onAdd = (): void => {
isValid && onAdd({ isConst: false, key });
};
const _onAdd = useCallback(
(): void => {
isValid && onAdd({ isConst: false, key });
},
[isValid, key, onAdd]
);
const _onChangeKey = (key: string): void => {
const u8a = u8aToU8a(key);
const isValid = u8a.length !== 0;
const _onChangeKey = useCallback(
(key: string): void => {
const u8a = u8aToU8a(key);
setValue({
isValid,
key: Compact.addLengthPrefix(u8a)
});
};
setValue({
isValid: u8a.length !== 0,
key: Compact.addLengthPrefix(u8a)
});
},
[]
);
return (
<section className='storage--actionrow'>

View File

@ -5,7 +5,7 @@
import { AccountId } from '@polkadot/types/interfaces';
import BN from 'bn.js';
import React, { useState } from 'react';
import React, { useCallback, useState } from 'react';
import { Button, Icon, Modal, VoteAccount, VoteActions, VoteToggle } from '@polkadot/react-components';
import { useAccounts, useToggle } from '@polkadot/react-hooks';
import { isBoolean } from '@polkadot/util';
@ -25,11 +25,15 @@ function Voting ({ hash, prime, proposalId }: Props): React.ReactElement<Props>
const [isVotingOpen, toggleVoting] = useToggle();
const [voteValue, setVoteValue] = useState(true);
const _onChangeVote = useCallback(
(vote?: boolean): void => setVoteValue(isBoolean(vote) ? vote : true),
[]
);
if (!hasAccounts) {
return null;
}
const _onChangeVote = (vote?: boolean): void => setVoteValue(isBoolean(vote) ? vote : true);
const isPrime = accountId === prime?.toString();
return (

View File

@ -5,10 +5,11 @@
import { Signer } from '@polkadot/api/types';
import { KeyringPair } from '@polkadot/keyring/types';
import React, { useEffect, useState } from 'react';
import React, { useCallback, useEffect, useState } from 'react';
import styled from 'styled-components';
import { web3FromSource } from '@polkadot/extension-dapp';
import { Button, Input, InputAddress, Output, Static } from '@polkadot/react-components';
import { useToggle } from '@polkadot/react-hooks';
import keyring from '@polkadot/ui-keyring';
import { hexToU8a, isFunction, isHex, stringToHex, stringToU8a, u8aToHex } from '@polkadot/util';
@ -37,7 +38,7 @@ function Sign ({ className }: Props): React.ReactElement<Props> {
const [isLocked, setIsLocked] = useState(false);
const [{ isUsable, signer }, setSigner] = useState<{ isUsable: boolean; signer: Signer | null }>({ isUsable: true, signer: null });
const [signature, setSignature] = useState('');
const [isUnlockVisible, setIsUnlockVisible] = useState<boolean>(false);
const [isUnlockVisible, toggleUnlock] = useToggle();
useEffect((): void => {
const isExternal = currentPair?.meta.isExternal || false;
@ -71,42 +72,54 @@ function Sign ({ className }: Props): React.ReactElement<Props> {
}
}, [currentPair]);
const _toggleUnlock = (): void => setIsUnlockVisible(!isUnlockVisible);
const _onChangeAccount = (accountId: string | null): void => setCurrentPair(keyring.getPair(accountId || ''));
const _onChangeData = (data: string): void => setData({ data, isHexData: isHex(data) });
const _onChangeAccount = useCallback(
(accountId: string | null) => setCurrentPair(keyring.getPair(accountId || '')),
[]
);
const _onSign = (): void => {
if (isLocked || !isUsable || !currentPair) {
return;
}
const _onChangeData = useCallback(
(data: string) => setData({ data, isHexData: isHex(data) }),
[]
);
if (signer?.signRaw) {
setSignature('');
const _onSign = useCallback(
(): void => {
if (isLocked || !isUsable || !currentPair) {
return;
}
signer
.signRaw({
address: currentPair.address,
data: isHexData
? data
: stringToHex(data),
type: 'bytes'
})
.then(({ signature }): void => setSignature(signature));
} else {
setSignature(u8aToHex(
currentPair.sign(
isHexData
? hexToU8a(data)
: stringToU8a(data)
)
));
}
};
if (signer?.signRaw) {
setSignature('');
const _onUnlock = (): void => {
setIsLocked(false);
_toggleUnlock();
};
signer
.signRaw({
address: currentPair.address,
data: isHexData
? data
: stringToHex(data),
type: 'bytes'
})
.then(({ signature }): void => setSignature(signature));
} else {
setSignature(u8aToHex(
currentPair.sign(
isHexData
? hexToU8a(data)
: stringToU8a(data)
)
));
}
},
[currentPair, data, isHexData, isLocked, isUsable, signer]
);
const _onUnlock = useCallback(
(): void => {
setIsLocked(false);
toggleUnlock();
},
[toggleUnlock]
);
return (
<div className={`toolbox--Sign ${className}`}>
@ -166,7 +179,7 @@ function Sign ({ className }: Props): React.ReactElement<Props> {
<Button
icon='unlock'
label={t('Unlock account')}
onClick={_toggleUnlock}
onClick={toggleUnlock}
/>
</Button.Group>
</div>
@ -187,7 +200,7 @@ function Sign ({ className }: Props): React.ReactElement<Props> {
</div>
{isUnlockVisible && (
<Unlock
onClose={_toggleUnlock}
onClose={toggleUnlock}
onUnlock={_onUnlock}
pair={currentPair}
/>

View File

@ -4,7 +4,7 @@
import { KeypairType } from '@polkadot/util-crypto/types';
import React, { useEffect, useState } from 'react';
import React, { useCallback, useEffect, useState } from 'react';
import { Dropdown, Icon, Input, InputAddress, Static } from '@polkadot/react-components';
import keyring from '@polkadot/ui-keyring';
import uiSettings from '@polkadot/ui-settings';
@ -78,23 +78,30 @@ function Verify (): React.ReactElement<{}> {
setValidity({ cryptoType, isValid });
}, [data, isValidPk, isValidSignature, publicKey, signature]);
const _onChangeAddress = (accountId: string | null): void => {
let publicKey: Uint8Array | null = null;
const _onChangeAddress = useCallback(
(accountId: string | null): void => {
let publicKey: Uint8Array | null = null;
try {
publicKey = keyring.decodeAddress(accountId || '');
} catch (err) {
console.error(err);
}
try {
publicKey = keyring.decodeAddress(accountId || '');
} catch (err) {
console.error(err);
}
setPublicKey({ isValidPk: !!publicKey && publicKey.length === 32, publicKey });
};
setPublicKey({ isValidPk: !!publicKey && publicKey.length === 32, publicKey });
},
[]
);
const _onChangeData = (data: string): void =>
setData({ data, isHexData: isHex(data) });
const _onChangeData = useCallback(
(data: string) => setData({ data, isHexData: isHex(data) }),
[]
);
const _onChangeSignature = (signature: string): void =>
setSignature({ isValidSignature: isHex(signature) && signature.length === 130, signature });
const _onChangeSignature = useCallback(
(signature: string) => setSignature({ isValidSignature: isHex(signature) && signature.length === 130, signature }),
[]
);
return (
<div className='toolbox--Verify'>

View File

@ -5,7 +5,7 @@
import { DeriveTreasuryProposal } from '@polkadot/api-derive/types';
import { AccountId, Balance } from '@polkadot/types/interfaces';
import React, { useEffect, useState } from 'react';
import React, { useCallback, useEffect, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { Table } from '@polkadot/react-components';
import { useApi, useAccounts, useCall } from '@polkadot/react-hooks';
@ -35,9 +35,12 @@ function ProposalsBase ({ className, isApprovals, proposals }: Props): React.Rea
);
}, [allAccounts, members]);
const _onRespond = (): void => {
history.push('/council/motions');
};
const _onRespond = useCallback(
(): void => {
history.push('/council/motions');
},
[history]
);
return (
<Table

View File

@ -5,7 +5,7 @@
import { DeriveCollectiveProposal } from '@polkadot/api-derive/types';
import { ProposalIndex, Hash } from '@polkadot/types/interfaces';
import React, { useEffect, useState } from 'react';
import React, { useCallback, useEffect, useState } from 'react';
import { Button, Dropdown, Input, Modal, VoteAccount, VoteActions, VoteToggle } from '@polkadot/react-components';
import { useAccounts, useToggle } from '@polkadot/react-hooks';
import { isBoolean } from '@polkadot/util';
@ -44,24 +44,29 @@ function Voting ({ councilProposals, isDisabled }: Props): React.ReactElement<Pr
setCouncilOpts(available);
}, [councilProposals]);
const _onChangeVote = useCallback(
(vote?: boolean) => setVoteValue(isBoolean(vote) ? vote : true),
[]
);
const _onChangeProposal = useCallback(
(optionId: number): void => {
const councilProp = councilProposals.find(({ votes }): boolean => !!(votes?.index.eq(optionId)));
if (councilProp && councilProp.votes) {
setCouncilInfo({ councilHash: councilProp.hash, councilId: councilProp.votes.index });
setCouncilOptId(councilOptId);
} else {
setCouncilInfo({ councilHash: null, councilId: null });
}
},
[councilOptId, councilProposals]
);
if (!hasAccounts || !councilOpts.length) {
return null;
}
const _onChangeVote = (vote?: boolean): void =>
setVoteValue(isBoolean(vote) ? vote : true);
const _onChangeProposal = (optionId: number): void => {
const councilProp = councilProposals.find(({ votes }): boolean => !!(votes?.index.eq(optionId)));
if (councilProp && councilProp.votes) {
setCouncilInfo({ councilHash: councilProp.hash, councilId: councilProp.votes.index });
setCouncilOptId(councilOptId);
} else {
setCouncilInfo({ councilHash: null, councilId: null });
}
};
return (
<>
{isOpen && (

View File

@ -6,7 +6,7 @@ import { ConstantCodec } from '@polkadot/metadata/Decorated/types';
import { DropdownOptions } from '../util/types';
import { ConstValue, ConstValueBase } from './types';
import React, { useState } from 'react';
import React, { useCallback, useState } from 'react';
import { ApiPromise } from '@polkadot/api';
import { useApi } from '@polkadot/react-hooks';
@ -46,29 +46,35 @@ function InputConsts ({ className, defaultValue, help, label, onChange, style, w
const [optionsSection] = useState<DropdownOptions>(sectionOptions(api));
const [value, setValue] = useState<ConstValue>(getValue(api, defaultValue));
const _onKeyChange = (newValue: ConstValueBase): void => {
if (value.section === newValue.section && value.method === newValue.method) {
return;
}
const _onKeyChange = useCallback(
(newValue: ConstValueBase): void => {
if (value.section === newValue.section && value.method === newValue.method) {
return;
}
const { method, section } = newValue;
const meta = (api.consts[section][method] as ConstantCodec).meta;
const updated = { meta, method, section };
const { method, section } = newValue;
const meta = (api.consts[section][method] as ConstantCodec).meta;
const updated = { meta, method, section };
setValue(updated);
onChange && onChange(updated);
};
setValue(updated);
onChange && onChange(updated);
},
[api, onChange, value]
);
const _onSectionChange = (section: string): void => {
if (section === value.section) {
return;
}
const _onSectionChange = useCallback(
(section: string): void => {
if (section === value.section) {
return;
}
const optionsMethod = keyOptions(api, section);
const optionsMethod = keyOptions(api, section);
setOptionsMethod(optionsMethod);
_onKeyChange({ method: optionsMethod[0].value, section });
};
setOptionsMethod(optionsMethod);
_onKeyChange({ method: optionsMethod[0].value, section });
},
[_onKeyChange, api, value]
);
return (
<LinkedWrapper

View File

@ -5,7 +5,7 @@
import { SubmittableExtrinsicFunction } from '@polkadot/api/types';
import { DropdownOptions } from '../util/types';
import React, { useState } from 'react';
import React, { useCallback, useState } from 'react';
import { useApi } from '@polkadot/react-hooks';
import LinkedWrapper from './LinkedWrapper';
@ -33,26 +33,32 @@ function InputExtrinsic ({ className, defaultValue, help, label, onChange, style
const [optionsSection] = useState<DropdownOptions>(sectionOptions(api));
const [value, setValue] = useState<SubmittableExtrinsicFunction<'promise'>>((): SubmittableExtrinsicFunction<'promise'> => defaultValue);
const _onKeyChange = (newValue: SubmittableExtrinsicFunction<'promise'>): void => {
if (value.section === newValue.section && value.method === newValue.method) {
return;
}
const _onKeyChange = useCallback(
(newValue: SubmittableExtrinsicFunction<'promise'>): void => {
if (value.section === newValue.section && value.method === newValue.method) {
return;
}
// set this via callback, since the we are setting a function (alternatively... we have issues)
setValue((): SubmittableExtrinsicFunction<'promise'> => newValue);
onChange(newValue);
};
// set this via callback, since the we are setting a function (alternatively... we have issues)
setValue((): SubmittableExtrinsicFunction<'promise'> => newValue);
onChange(newValue);
},
[onChange, value]
);
const _onSectionChange = (section: string): void => {
if (section === value.section) {
return;
}
const _onSectionChange = useCallback(
(section: string): void => {
if (section === value.section) {
return;
}
const optionsMethod = methodOptions(api, section);
const optionsMethod = methodOptions(api, section);
setOptionsMethod(optionsMethod);
_onKeyChange(api.tx[section][optionsMethod[0].value]);
};
setOptionsMethod(optionsMethod);
_onKeyChange(api.tx[section][optionsMethod[0].value]);
},
[_onKeyChange, api, value]
);
return (
<LinkedWrapper

View File

@ -7,7 +7,7 @@
import { DropdownOptions } from '../util/types';
import { StorageEntryPromise } from './types';
import React, { useState } from 'react';
import React, { useCallback, useState } from 'react';
import { useApi } from '@polkadot/react-hooks';
import LinkedWrapper from '../InputExtrinsic/LinkedWrapper';
@ -33,26 +33,32 @@ function InputStorage ({ className, defaultValue, help, label, onChange, style,
const [optionsSection] = useState<DropdownOptions>(sectionOptions(api));
const [value, setValue] = useState<StorageEntryPromise>((): StorageEntryPromise => defaultValue);
const _onKeyChange = (newValue: StorageEntryPromise): void => {
if (value.creator.section === newValue.creator.section && value.creator.method === newValue.creator.method) {
return;
}
const _onKeyChange = useCallback(
(newValue: StorageEntryPromise): void => {
if (value.creator.section === newValue.creator.section && value.creator.method === newValue.creator.method) {
return;
}
// set via callback
setValue((): StorageEntryPromise => newValue);
onChange && onChange(newValue);
};
// set via callback
setValue((): StorageEntryPromise => newValue);
onChange && onChange(newValue);
},
[onChange, value]
);
const _onSectionChange = (section: string): void => {
if (section === value.creator.section) {
return;
}
const _onSectionChange = useCallback(
(section: string): void => {
if (section === value.creator.section) {
return;
}
const optionsMethod = keyOptions(api, section);
const optionsMethod = keyOptions(api, section);
setOptionsMethod(optionsMethod);
_onKeyChange(api.query[section][optionsMethod[0].value]);
};
setOptionsMethod(optionsMethod);
_onKeyChange(api.query[section][optionsMethod[0].value]);
},
[_onKeyChange, api, value]
);
return (
<LinkedWrapper