Allow saving custom endpoints (#3410)

* save button

* save/restore

* prevent saving twice

* useMemo rather than useEffect + useState

* delete feature

* set constant in app settings

* use ternary instead

* rework the save behavior

Co-authored-by: Jaco Greeff <jacogr@gmail.com>
This commit is contained in:
Thibaut Sardan 2020-08-14 14:26:18 +02:00 committed by GitHub
parent 943004e2f1
commit 764b244a74
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 146 additions and 14 deletions

View File

@ -0,0 +1,5 @@
// Copyright 2017-2020 @polkadot/apps authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export const CUSTOM_ENDPOINT_KEY = 'polkadot-app-custom-endpoints';

View File

@ -5,6 +5,8 @@
import { TFunction } from 'i18next';
import { Option } from './types';
import { CUSTOM_ENDPOINT_KEY } from './constants';
export interface LinkOption extends Option {
dnslink?: string;
isChild?: boolean;
@ -17,6 +19,26 @@ interface EnvWindow {
}
}
function createOwn (t: TFunction): LinkOption[] {
try {
const storedItems = localStorage.getItem(CUSTOM_ENDPOINT_KEY);
if (storedItems) {
const items = JSON.parse(storedItems) as string[];
return items.map((item) => ({
info: 'local',
text: t<string>('rpc.custom.entry', 'Custom (custom, {{WS_URL}})', { ns: 'apps-config', replace: { WS_URL: item } }),
value: item
}));
}
} catch (e) {
console.error(e);
}
return [];
}
function createDev (t: TFunction): LinkOption[] {
return [
{
@ -177,7 +199,7 @@ function createCustom (t: TFunction): LinkOption[] {
// The available endpoints that will show in the dropdown. For the most part (with the exception of
// Polkadot) we try to keep this to live chains only, with RPCs hosted by the community/chain vendor
// info: The chain logo name as defined in ../logos, specifically in namedLogos
// text: The text to display on teh dropdown
// text: The text to display on the dropdown
// value: The actual hosted secure websocket endpoint
export default function create (t: TFunction): LinkOption[] {
return [
@ -199,6 +221,7 @@ export default function create (t: TFunction): LinkOption[] {
text: t<string>('rpc.header.dev', 'Development', { ns: 'apps-config' }),
value: ''
},
...createDev(t)
...createDev(t),
...createOwn(t)
].filter(({ isDisabled }) => !isDisabled);
}

View File

@ -5,9 +5,11 @@
import createEndpoints from './endpoints';
import createLanguages from './languages';
import createSs58 from './ss58';
import { CUSTOM_ENDPOINT_KEY } from './constants';
export {
createEndpoints,
createLanguages,
createSs58
createSs58,
CUSTOM_ENDPOINT_KEY
};

View File

@ -4,12 +4,12 @@
import type { LinkOption } from '@polkadot/apps-config/settings/endpoints';
import React, { useCallback, useState } from 'react';
import React, { useCallback, useMemo, useState } from 'react';
// ok, this seems to be an eslint bug, this _is_ a package import
/* eslint-disable-next-line node/no-deprecated-api */
import punycode from 'punycode';
import styled from 'styled-components';
import { createEndpoints } from '@polkadot/apps-config/settings';
import { createEndpoints, CUSTOM_ENDPOINT_KEY } from '@polkadot/apps-config/settings';
import { Button, ChainImg, Icon, Input, Sidebar, Toggle } from '@polkadot/react-components';
import uiSettings from '@polkadot/ui-settings';
import { isAscii } from '@polkadot/util';
@ -82,11 +82,84 @@ function combineEndpoints (endpoints: LinkOption[]): Endpoint[] {
}, []);
}
function getCustomEndpoints (): string[] {
try {
const storedAsset = localStorage.getItem(CUSTOM_ENDPOINT_KEY);
if (storedAsset) {
return JSON.parse(storedAsset) as string[];
}
} catch (e) {
console.error(e);
// ignore error
}
return [];
}
function Endpoints ({ className = '', offset, onClose }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [endpoints] = useState(combineEndpoints(createEndpoints(t)));
const linkOptions = createEndpoints(t);
const [endpoints, setEndpoints] = useState(combineEndpoints(linkOptions));
const [{ apiUrl, hasUrlChanged, isUrlValid }, setApiUrl] = useState<UrlState>({ apiUrl: uiSettings.get().apiUrl, hasUrlChanged: false, isUrlValid: true });
const [openIndex, setOpenIndex] = useState('');
const [storedCustomEndpoints, setStoredCustomEndpoints] = useState<string[]>(getCustomEndpoints());
const isKnownUrl = useMemo(() => {
let result = false;
linkOptions.some((endpoint) => {
if (endpoint.value === apiUrl) {
result = true;
return true;
}
return false;
});
return result;
}, [apiUrl, linkOptions]);
const isSavedCustomEndpoint = useMemo(() => {
let result = false;
storedCustomEndpoints.some((endpoint) => {
if (endpoint === apiUrl) {
result = true;
return true;
}
return false;
});
return result;
}, [apiUrl, storedCustomEndpoints]);
const _saveApiEndpoint = () => {
try {
localStorage.setItem(CUSTOM_ENDPOINT_KEY, JSON.stringify([...storedCustomEndpoints, apiUrl]));
_onApply();
} catch (e) {
console.error(e);
// ignore error
}
};
const _removeApiEndpoint = () => {
if (!isSavedCustomEndpoint) return;
const newStoredCurstomEndpoints = storedCustomEndpoints.filter((url) => url !== apiUrl);
try {
localStorage.setItem(CUSTOM_ENDPOINT_KEY, JSON.stringify(newStoredCurstomEndpoints));
setEndpoints(combineEndpoints(createEndpoints(t)));
setStoredCustomEndpoints(getCustomEndpoints());
} catch (e) {
console.error(e);
// ignore error
}
};
const _setApiUrl = useCallback(
(apiUrl: string) => () => setApiUrl({ apiUrl, hasUrlChanged: uiSettings.get().apiUrl !== apiUrl, isUrlValid: true }),
@ -179,21 +252,50 @@ function Endpoints ({ className = '', offset, onClose }: Props): React.ReactElem
})}
</div>
))}
<Input
className='endpointCustom'
isError={!isUrlValid}
isFull
label={t<string>('custom endpoint')}
onChange={_onChangeCustom}
value={apiUrl}
/>
<div className='endpointCustomWrapper'>
<Input
className='endpointCustom'
isError={!isUrlValid}
isFull
label={t<string>('custom endpoint')}
onChange={_onChangeCustom}
value={apiUrl}
/>
{isSavedCustomEndpoint
? <Button
className='customDeleteButton'
icon='trash-alt'
onClick={_removeApiEndpoint}
/>
: <Button
className='customSaveButton'
icon='save'
isDisabled={!isUrlValid || isKnownUrl}
onClick={_saveApiEndpoint}
/>
}
</div>
</Sidebar>
);
}
export default React.memo(styled(Endpoints)`
.customSaveButton, .customDeleteButton {
position: absolute;
top: 1rem;
right: 1rem;
}
.endpointCustom {
margin-top: 0.5rem;
input {
padding-right: 4rem;
}
}
.endpointCustomWrapper {
position: relative;
}
.endpointType {