refactor(react-doctor): raise score from 79 to 90

This commit is contained in:
plebeius
2026-02-24 15:15:44 +08:00
parent 5bd1dc0e71
commit e51f5b968c
36 changed files with 2372 additions and 1030 deletions
@@ -8,6 +8,23 @@ import { useLocation, useNavigate } from 'react-router-dom';
const isAndroid = Capacitor.getPlatform() === 'android';
const safeParseJSON = <T,>(value: string): T | null => {
try {
return JSON.parse(value) as T;
} catch {
return null;
}
};
const withErrorHandling = async <T,>(fn: () => Promise<T>, onError: (e: unknown) => void): Promise<T | undefined> => {
try {
return await fn();
} catch (e) {
onError(e);
return undefined;
}
};
// Inner component keyed by account id so state resets when user switches account
const AccountSettingsEditor = ({
account,
@@ -47,17 +64,21 @@ const AccountSettingsEditor = ({
}, [accounts]);
const handleCreateAccount = async () => {
try {
switchToNewAccountRef.current = true;
await createAccount();
} catch (error) {
if (error instanceof Error) {
alert(error.message);
console.log(error);
} else {
console.error('An unknown error occurred:', error);
}
}
const result = await withErrorHandling(
async () => {
switchToNewAccountRef.current = true;
await createAccount();
},
(error) => {
if (error instanceof Error) {
alert(error.message);
console.log(error);
} else {
console.error('An unknown error occurred:', error);
}
},
);
void result;
};
const _deleteAccount = (accountName: string) => {
@@ -73,53 +94,56 @@ const AccountSettingsEditor = ({
};
const saveAccount = async () => {
try {
const newAccount = JSON.parse(text).account;
// force keeping the same id, makes it easier to copy paste
await setAccount({ ...newAccount, id: account?.id });
const parsed = safeParseJSON<{ account: Record<string, unknown> }>(text);
if (!parsed?.account) {
alert('Invalid JSON');
return;
}
const newAccount = parsed.account;
const result = await withErrorHandling(
() => setAccount({ ...newAccount, id: account?.id }),
(error) => {
if (error instanceof Error) {
alert(error.message);
console.log(error);
} else {
console.error('An unknown error occurred:', error);
}
},
);
if (result !== undefined) {
alert(`Saved ${newAccount.name}`);
} catch (error) {
if (error instanceof Error) {
alert(error.message);
console.log(error);
} else {
console.error('An unknown error occurred:', error);
}
}
};
const handleExportAccount = async () => {
try {
const accountString = await exportAccount();
const accountObject = JSON.parse(accountString);
const formattedAccountJson = JSON.stringify(accountObject, null, 2);
// Create a Blob from the JSON string
const blob = new Blob([formattedAccountJson], { type: 'application/json' });
// Create a URL for the Blob
const fileUrl = URL.createObjectURL(blob);
// Create a temporary download link
const link = document.createElement('a');
link.href = fileUrl;
link.download = `${account?.name ?? 'account'}.json`;
// Append the link, trigger the download, then remove the link
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// Release the Blob URL
URL.revokeObjectURL(fileUrl);
} catch (error) {
if (error instanceof Error) {
alert(error.message);
console.log(error);
} else {
console.error('An unknown error occurred:', error);
}
const accountString = await withErrorHandling(
() => exportAccount(),
(error) => {
if (error instanceof Error) {
alert(error.message);
console.log(error);
} else {
console.error('An unknown error occurred:', error);
}
},
);
if (accountString === undefined) return;
const accountObject = safeParseJSON<Record<string, unknown>>(accountString);
if (!accountObject) {
alert('Failed to parse account');
return;
}
const formattedAccountJson = JSON.stringify(accountObject, null, 2);
const blob = new Blob([formattedAccountJson], { type: 'application/json' });
const fileUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = fileUrl;
link.download = `${account?.name ?? 'account'}.json`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(fileUrl);
};
const handleImportAccount = async () => {
@@ -128,78 +152,73 @@ const AccountSettingsEditor = ({
fileInput.accept = '.json';
fileInput.onchange = async (event) => {
try {
const files = (event.target as HTMLInputElement).files;
if (!files || files.length === 0) {
throw new Error('No file selected.');
const files = (event.target as HTMLInputElement).files;
if (!files || files.length === 0) {
alert('No file selected.');
return;
}
const file = files[0];
const reader = new FileReader();
reader.onload = async (e) => {
const fileContent = e.target!.result;
if (typeof fileContent !== 'string') {
alert('File content is not a string.');
return;
}
const file = files[0];
const reader = new FileReader();
reader.onload = async (e) => {
try {
const fileContent = e.target!.result;
if (typeof fileContent !== 'string') {
throw new Error('File content is not a string.');
const accountData = safeParseJSON<{
account?: { subplebbits?: Record<string, unknown>; subscriptions?: string[]; author?: { address?: string }; name?: string };
}>(fileContent);
if (!accountData) {
alert('Invalid JSON in file.');
return;
}
if (accountData.account?.subplebbits) {
const subplebbitAddresses = Object.keys(accountData.account.subplebbits);
if (!accountData.account.subscriptions) {
accountData.account.subscriptions = [];
}
const uniqueSubscriptions = [...accountData.account.subscriptions];
for (const address of subplebbitAddresses) {
if (!uniqueSubscriptions.includes(address)) {
uniqueSubscriptions.push(address);
}
}
accountData.account.subscriptions = uniqueSubscriptions;
}
const accountData = JSON.parse(fileContent);
// Add subplebbit addresses to subscriptions if they exist
if (accountData.account?.subplebbits) {
const subplebbitAddresses = Object.keys(accountData.account.subplebbits);
if (!accountData.account.subscriptions) {
accountData.account.subscriptions = [];
}
const uniqueSubscriptions = [...accountData.account.subscriptions];
for (const address of subplebbitAddresses) {
if (!uniqueSubscriptions.includes(address)) {
uniqueSubscriptions.push(address);
}
}
accountData.account.subscriptions = uniqueSubscriptions;
}
const modifiedAccountJson = JSON.stringify(accountData);
const modifiedAccountJson = JSON.stringify(accountData);
const result = await withErrorHandling(
async () => {
await importAccount(modifiedAccountJson);
if (accountData.account?.author?.address) {
localStorage.setItem('importedAccountAddress', accountData.account.author.address);
}
if (accountData.account?.name) {
await setActiveAccount(accountData.account.name);
}
alert(`Imported ${accountData.account?.name}`);
const currentPath = location.pathname;
if (!currentPath.includes('/settings#account-settings')) {
navigate(`${currentPath}#account-settings`, { replace: true });
}
window.location.reload();
} catch (error) {
},
(error) => {
if (error instanceof Error) {
alert(error.message);
console.log(error);
} else {
console.error('An unknown error occurred:', error);
}
}
};
reader.readAsText(file);
} catch (error) {
if (error instanceof Error) {
alert(error.message);
console.log(error);
} else {
console.error('An unknown error occurred:', error);
},
);
if (result === undefined) return;
alert(`Imported ${accountData.account?.name}`);
const currentPath = location.pathname;
if (!currentPath.includes('/settings#account-settings')) {
navigate(`${currentPath}#account-settings`, { replace: true });
}
}
window.location.reload();
};
reader.readAsText(file);
};
fileInput.click();
@@ -3,6 +3,15 @@ import { useTranslation } from 'react-i18next';
import { useAccount, setAccount, useResolvedAuthorAddress } from '@plebbit/plebbit-react-hooks';
import styles from './crypto-address-setting.module.css';
const withErrorHandling = async <T,>(fn: () => Promise<T>, onError: (e: unknown) => void): Promise<T | undefined> => {
try {
return await fn();
} catch (e) {
onError(e);
return undefined;
}
};
const CryptoAddressSetting = () => {
const { t } = useTranslation();
const account = useAccount();
@@ -75,27 +84,26 @@ const CryptoAddressSetting = () => {
alert(t('crypto_address_not_resolved'));
return;
} else if (resolvedAddress && resolvedAddress === account?.signer?.address) {
try {
await setAccount({ ...account, author: { ...account?.author, address: cryptoState.cryptoAddress } });
const result = await withErrorHandling(
() => setAccount({ ...account, author: { ...account?.author, address: cryptoState.cryptoAddress } }),
(error) => {
if (error instanceof Error) {
alert(error.message);
console.log(error);
} else {
console.error('An unknown error occurred:', error);
}
},
);
if (result !== undefined) {
setSavedCryptoAddress(true);
setTimeout(() => {
setSavedCryptoAddress(false);
}, 2000);
setTimeout(() => setSavedCryptoAddress(false), 2000);
setCryptoState((prevState) => ({
...prevState,
savedCryptoAddress: true,
cryptoAddress: '',
checkingCryptoAddress: false,
}));
} catch (error) {
if (error instanceof Error) {
alert(error.message);
console.log(error);
} else {
console.error('An unknown error occurred:', error);
}
}
setSavedCryptoAddress(true);
setCryptoState((prevState) => ({
@@ -168,8 +168,8 @@ const CryptoWalletsForm = ({ account }: { account: Account | undefined }) => {
<div className={styles.addWallet}>
<select onChange={(e) => setSelectedWallet(Number(e.target.value))} value={selectedWallet}>
{walletsArray.length === 0 && <option>{t('none')}</option>}
{walletsArray.map((_, index) => (
<option key={index} value={index}>
{walletsArray.map((wallet, index) => (
<option key={wallet.address || (wallet.chainTicker ? `${wallet.chainTicker}-${index}` : `wallet-${index}`)} value={index}>
{t('wallet')} #{index + 1}
</option>
))}
@@ -10,52 +10,54 @@ import Version from '../../version';
const commitRef = process.env.VITE_COMMIT_REF;
const isElectron = window.electronApi?.isElectron === true;
const fetchLatestVersionInfo = async (t: (key: string, opts?: Record<string, unknown>) => string): Promise<void> => {
try {
const packageRes = await fetch('https://raw.githubusercontent.com/bitsocialhq/5chan/master/package.json', { cache: 'no-cache' });
const packageData = await packageRes.json();
let updateAvailable = false;
if (packageJson.version !== packageData.version) {
const newVersionText = t('new_stable_version', { newVersion: packageData.version, oldVersion: packageJson.version });
const updateActionText = isElectron
? t('download_latest_desktop', { link: 'https://github.com/bitsocialhq/5chan/releases/latest', interpolation: { escapeValue: false } })
: t('refresh_to_update');
alert(newVersionText + ' ' + updateActionText);
updateAvailable = true;
}
if (commitRef && commitRef.length > 0) {
const commitRes = await fetch('https://api.github.com/repos/bitsocialhq/5chan/commits?per_page=1&sha=development', { cache: 'no-cache' });
const commitData = await commitRes.json();
const latestCommitHash = commitData[0].sha;
if (latestCommitHash.trim() !== commitRef.trim()) {
const newVersionText = t('new_development_version', { newCommit: latestCommitHash.slice(0, 7), oldCommit: commitRef.slice(0, 7) }) + ' ' + t('refresh_to_update');
alert(newVersionText);
updateAvailable = true;
}
}
if (!updateAvailable) {
alert(
commitRef
? `${t('latest_development_version', { commit: commitRef.slice(0, 7), link: 'https://5chan.app/#/', interpolation: { escapeValue: false } })}`
: `${t('latest_stable_version', { version: packageJson.version })}`,
);
}
} catch (error) {
alert('Failed to fetch latest version info: ' + error);
}
};
const CheckForUpdates = () => {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const checkForUpdates = async () => {
try {
setLoading(true);
const packageRes = await fetch('https://raw.githubusercontent.com/bitsocialhq/5chan/master/package.json', { cache: 'no-cache' });
const packageData = await packageRes.json();
let updateAvailable = false;
if (packageJson.version !== packageData.version) {
const newVersionText = t('new_stable_version', { newVersion: packageData.version, oldVersion: packageJson.version });
const updateActionText = isElectron
? t('download_latest_desktop', { link: 'https://github.com/bitsocialhq/5chan/releases/latest', interpolation: { escapeValue: false } })
: t('refresh_to_update');
alert(newVersionText + ' ' + updateActionText);
updateAvailable = true;
}
if (commitRef && commitRef.length > 0) {
const commitRes = await fetch('https://api.github.com/repos/bitsocialhq/5chan/commits?per_page=1&sha=development', { cache: 'no-cache' });
const commitData = await commitRes.json();
const latestCommitHash = commitData[0].sha;
if (latestCommitHash.trim() !== commitRef.trim()) {
const newVersionText =
t('new_development_version', { newCommit: latestCommitHash.slice(0, 7), oldCommit: commitRef.slice(0, 7) }) + ' ' + t('refresh_to_update');
alert(newVersionText);
updateAvailable = true;
}
}
if (!updateAvailable) {
alert(
commitRef
? `${t('latest_development_version', { commit: commitRef.slice(0, 7), link: 'https://5chan.app/#/', interpolation: { escapeValue: false } })}`
: `${t('latest_stable_version', { version: packageJson.version })}`,
);
}
} catch (error) {
alert('Failed to fetch latest version info: ' + error);
} finally {
setLoading(false);
}
setLoading(true);
await fetchLatestVersionInfo(t);
setLoading(false);
};
return (
@@ -34,13 +34,15 @@ const SettingsModal = () => {
};
}, [closeModal]);
const [showInterfaceSettings, setShowInterfaceSettings] = useState(false);
const [showMediaHostingSettings, setShowMediaHostingSettings] = useState(false);
const [showAccountSettings, setShowAccountSettings] = useState(false);
const [showSubscriptionsSettings, setShowSubscriptionsSettings] = useState(false);
const [showAdvancedSettings, setShowAdvancedSettings] = useState(false);
const [expandAll, setExpandAll] = useState(false);
const expandAccount = hash === 'account-settings' || hash === 'crypto-address-settings' || hash === 'crypto-wallet-settings';
const showInterfaceSettings = expandAll || hash === 'interface-settings';
const showMediaHostingSettings = expandAll || hash === 'media-hosting-settings';
const showAccountSettings = expandAll || expandAccount;
const showSubscriptionsSettings = expandAll || hash === 'subscriptions-settings';
const showAdvancedSettings = expandAll || hash === 'advanced-settings';
const getExpandedCount = () => {
return (
Number(showInterfaceSettings) + Number(showMediaHostingSettings) + Number(showAccountSettings) + Number(showSubscriptionsSettings) + Number(showAdvancedSettings)
@@ -56,13 +58,10 @@ const SettingsModal = () => {
return null;
};
const handleCategoryClick = (categoryId: string, isShowing: boolean, setShowing: (value: boolean) => void) => {
const handleCategoryClick = (categoryId: string, isShowing: boolean) => {
const newState = !isShowing;
setShowing(newState);
const currentPath = location.pathname;
const baseSettingsPath = currentPath.split('#')[0];
const currentExpandedCount = getExpandedCount();
if (newState) {
@@ -83,57 +82,50 @@ const SettingsModal = () => {
}
};
useEffect(() => {
if (hash) {
const expandAccount = hash === 'account-settings' || hash === 'crypto-address-settings' || hash === 'crypto-wallet-settings';
setShowInterfaceSettings(hash === 'interface-settings');
setShowMediaHostingSettings(hash === 'media-hosting-settings');
setShowAccountSettings(expandAccount);
setShowSubscriptionsSettings(hash === 'subscriptions-settings');
setShowAdvancedSettings(hash === 'advanced-settings');
}
}, [hash]);
const handleExpandAll = () => {
const newExpandState = !expandAll;
setExpandAll(newExpandState);
setShowInterfaceSettings(newExpandState);
setShowMediaHostingSettings(newExpandState);
setShowAccountSettings(newExpandState);
setShowSubscriptionsSettings(newExpandState);
setShowAdvancedSettings(newExpandState);
setExpandAll((prev) => !prev);
const baseSettingsPath = location.pathname.split('#')[0];
navigate(baseSettingsPath, { replace: true });
};
const handleKeyDown = (handler: () => void) => (e: React.KeyboardEvent) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
handler();
}
};
return (
<>
<div className={styles.overlay} onClick={closeModal} />
<div className={styles.overlay} role='button' tabIndex={0} onClick={closeModal} onKeyDown={handleKeyDown(closeModal)} />
<div className={styles.settingsModal}>
<div className={styles.header}>
<span className={styles.title}>{t('settings')}</span>
<span className={styles.closeButton} title='close' onClick={closeModal} />
<span className={styles.closeButton} role='button' tabIndex={0} title='close' onClick={closeModal} onKeyDown={handleKeyDown(closeModal)} />
</div>
<div className={styles.expandAllSettings}>
[<span onClick={handleExpandAll}>{expandAll ? t('collapse_all_settings') : t('expand_all_settings')}</span>]
[
<span role='button' tabIndex={0} onClick={handleExpandAll} onKeyDown={handleKeyDown(handleExpandAll)}>
{expandAll ? t('collapse_all_settings') : t('expand_all_settings')}
</span>
]
</div>
<div id='interface-settings' className={`${styles.setting} ${styles.category}`}>
<label onClick={() => handleCategoryClick('interface-settings', showInterfaceSettings, setShowInterfaceSettings)}>
<label onClick={() => handleCategoryClick('interface-settings', showInterfaceSettings)}>
<span className={showInterfaceSettings ? styles.hideButton : styles.showButton} />
{t('interface')}
</label>
</div>
{showInterfaceSettings && <InterfaceSettings />}
<div id='media-hosting-settings' className={`${styles.setting} ${styles.category}`}>
<label onClick={() => handleCategoryClick('media-hosting-settings', showMediaHostingSettings, setShowMediaHostingSettings)}>
<label onClick={() => handleCategoryClick('media-hosting-settings', showMediaHostingSettings)}>
<span className={showMediaHostingSettings ? styles.hideButton : styles.showButton} />
{t('media_hosting')}
</label>
</div>
{showMediaHostingSettings && <MediaHostingSettings />}
<div id='account-settings' className={`${styles.setting} ${styles.category}`}>
<label onClick={() => handleCategoryClick('account-settings', showAccountSettings, setShowAccountSettings)}>
<label onClick={() => handleCategoryClick('account-settings', showAccountSettings)}>
<span className={showAccountSettings ? styles.hideButton : styles.showButton} />
{t('bitsocial_account')}
</label>
@@ -148,14 +140,14 @@ const SettingsModal = () => {
</>
)}
<div id='subscriptions-settings' className={`${styles.setting} ${styles.category}`}>
<label onClick={() => handleCategoryClick('subscriptions-settings', showSubscriptionsSettings, setShowSubscriptionsSettings)}>
<label onClick={() => handleCategoryClick('subscriptions-settings', showSubscriptionsSettings)}>
<span className={showSubscriptionsSettings ? styles.hideButton : styles.showButton} />
{t('board_subscriptions')}
</label>
</div>
{showSubscriptionsSettings && <SubscriptionsSetting />}
<div id='advanced-settings' className={`${styles.setting} ${styles.category}`}>
<label onClick={() => handleCategoryClick('advanced-settings', showAdvancedSettings, setShowAdvancedSettings)}>
<label onClick={() => handleCategoryClick('advanced-settings', showAdvancedSettings)}>
<span className={showAdvancedSettings ? styles.hideButton : styles.showButton} />
{t('advanced_settings')}
</label>
@@ -22,7 +22,18 @@ const SubscriptionButton = ({ address }: { address: string }) => {
return (
<span className={styles.subscriptionButton}>
[
<span className={styles.button} onClick={handleClick}>
<span
className={styles.button}
role='button'
tabIndex={0}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
handleClick();
}
}}
onClick={handleClick}
>
{recentlyUnsubscribed || !subscribed ? t('subscribe') : t('unsubscribe')}
</span>
]
@@ -48,7 +59,18 @@ const SubscriptionsSetting = () => {
{subscriptions?.length > 1 && (
<div className={styles.unsubscribeAll}>
[
<span className={styles.button} onClick={unsubscribeAll}>
<span
className={styles.button}
role='button'
tabIndex={0}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
unsubscribeAll();
}
}}
onClick={unsubscribeAll}
>
{t('unsubscribe_all')}
</span>
]