Переглянути джерело

feat: hooks that you can use to create custom wallet connection UI components (#789)

* feat: hooks that you can use to create custom wallet connection UI components
## Summary

In this PR we create hooks that track the state of the wallet connection specifically for the purpose of rendering wallet connection UI. This will allow UI developers to create custom controls easily, using their own UI frameworks, localization infrastructure, and styles.

In the next PR we rebuild the React, Material UI, and Ant Design libraries atop this hook. This gives three concrete examples of how it can be used to build custom UI with a minimum of effort.

## Test Plan

See next PR where we rebuild the React, Material UI, and Ant Design starters atop this hook.

Implements #658.
Steven Luscher 2 роки тому
батько
коміт
7c6f2e1

+ 6 - 0
.changeset/short-adults-bathe.md

@@ -0,0 +1,6 @@
+---
+"@solana/wallet-adapter-react": patch
+---
+
+feat: hooks that you can use to create custom wallet connection UI components
+Hooks that track the state of the wallet connection specifically for the purpose of rendering wallet connection UI. This will allow UI developers to create custom controls easily, using their own UI frameworks, localization infrastructure, and styles.

+ 94 - 2
packages/core/react/README.md

@@ -1,5 +1,97 @@
 # `@solana/wallet-adapter-react`
 
-<!-- @TODO -->
+## Creating a custom connect button
 
-Coming soon.
+This package exports a series of hooks that you can use to create custom wallet connection buttons. They manage the state of the wallet connection for you, and return helper methods that you can attach to your event handlers.
+
+What follows is the documentation for `useWalletMultiButton()`.
+
+### States
+
+-   `no-wallet` \
+    In this state you are neither connected nor is there a wallet selected. Allow your users to select from the list of `wallets`, then call `onSelectWallet()` with the name of the wallet they chose.
+-   `has-wallet` \
+    This state implies that there is a wallet selected, but that your app is not connected to it. Render a connect button that calls `onConnect()` when clicked.
+-   `disconnecting` \
+    When in this state, the last-connected wallet is in mid-disconnection.
+-   `connected` \
+    In this state, you have access to the connected `publicKey` and an `onDisconnect()` method that you can call to disconnect from the wallet. At any time you can call `onSelectWallet()` to change wallets.
+-   `connecting` \
+    When in this state, the wallet is in mid-connection.
+
+### Functions
+
+-   `onConnect` \
+     Connects the currently selected wallet. Available in the `has-wallet` state.
+-   `onDisconnect` \
+     Disconnects the currently selected wallet. Available in the `has-wallet`, `connected`, and `connecting` states.
+-   `onSelectWallet()` \
+     Calls the `onSelectWallet()` function that you supplied as config to `useWalletMultiButton`. That function receives the list of `wallets` and offers you an `onSelectWallet()` callback that you can call with the name of the wallet to switch to.
+
+### Example
+
+```ts
+function CustomConnectButton() {
+    const [walletModalConfig, setWalletModalConfig] = useState<Readonly<{
+        onSelectWallet(walletName: WalletName): void;
+        wallets: Wallet[];
+    }> | null>(null);
+    const { buttonState, onConnect, onDisconnect, onSelectWallet } = useWalletMultiButton({
+        onSelectWallet: setWalletModalConfig,
+    });
+    let label;
+    switch (buttonState) {
+        case 'connected':
+            label = 'Disconnect';
+            break;
+        case 'connecting':
+            label = 'Connecting';
+            break;
+        case 'disconnecting':
+            label = 'Disconnecting';
+            break;
+        case 'has-wallet':
+            label = 'Connect';
+            break;
+        case 'no-wallet':
+            label = 'Select Wallet';
+            break;
+    }
+    const handleClick = useCallback(() => {
+        switch (buttonState) {
+            case 'connected':
+                return onDisconnect;
+            case 'connecting':
+            case 'disconnecting':
+                break;
+            case 'has-wallet':
+                return onConnect;
+            case 'no-wallet':
+                return onSelectWallet;
+                break;
+        }
+    }, [buttonState, onDisconnect, onConnect, onSelectWallet]);
+    return (
+        <>
+            <button disabled={buttonState === 'connecting' || buttonState === 'disconnecting'} onClick={handleClick}>
+                {label}
+            </button>
+            {walletModalConfig ? (
+                <Modal>
+                    {walletModalConfig.wallets.map((wallet) => (
+                        <button
+                            key={wallet.adapter.name}
+                            onClick={() => {
+                                walletModalConfig.onSelectWallet(wallet.adapter.name);
+                                setWalletModalConfig(null);
+                            }}
+                        >
+                            {wallet.adapter.name}
+                        </button>
+                    ))}
+                </Modal>
+            ) : null}
+        </>
+    );
+}
+```

+ 3 - 0
packages/core/react/src/index.ts

@@ -4,4 +4,7 @@ export * from './useAnchorWallet.js';
 export * from './useConnection.js';
 export * from './useLocalStorage.js';
 export * from './useWallet.js';
+export * from './useWalletConnectButton.js';
+export * from './useWalletDisconnectButton.js';
+export * from './useWalletMultiButton.js';
 export * from './WalletProvider.js';

+ 37 - 0
packages/core/react/src/useWalletConnectButton.ts

@@ -0,0 +1,37 @@
+import { useCallback } from 'react';
+import type { Wallet } from './useWallet.js';
+import { useWallet } from './useWallet.js';
+
+type ButtonState = {
+    buttonDisabled: boolean;
+    buttonState: 'connecting' | 'connected' | 'has-wallet' | 'no-wallet';
+    onButtonClick?: () => void;
+    walletIcon?: Wallet['adapter']['icon'];
+    walletName?: Wallet['adapter']['name'];
+};
+
+export function useWalletConnectButton(): ButtonState {
+    const { connect, connected, connecting, wallet } = useWallet();
+    let buttonState: ButtonState['buttonState'];
+    if (connecting) {
+        buttonState = 'connecting';
+    } else if (connected) {
+        buttonState = 'connected';
+    } else if (wallet) {
+        buttonState = 'has-wallet';
+    } else {
+        buttonState = 'no-wallet';
+    }
+    const handleConnectButtonClick = useCallback(() => {
+        connect().catch(() => {
+            // Silently catch because any errors are caught by the context `onError` handler
+        });
+    }, [connect]);
+    return {
+        buttonDisabled: buttonState !== 'has-wallet',
+        buttonState,
+        onButtonClick: buttonState === 'has-wallet' ? handleConnectButtonClick : undefined,
+        walletIcon: wallet?.adapter.icon,
+        walletName: wallet?.adapter.name,
+    };
+}

+ 35 - 0
packages/core/react/src/useWalletDisconnectButton.ts

@@ -0,0 +1,35 @@
+import { useCallback } from 'react';
+import type { Wallet } from './useWallet.js';
+import { useWallet } from './useWallet.js';
+
+type ButtonState = {
+    buttonDisabled: boolean;
+    buttonState: 'disconnecting' | 'has-wallet' | 'no-wallet';
+    onButtonClick?: () => void;
+    walletIcon?: Wallet['adapter']['icon'];
+    walletName?: Wallet['adapter']['name'];
+};
+
+export function useWalletDisconnectButton(): ButtonState {
+    const { disconnecting, disconnect, wallet } = useWallet();
+    let buttonState: ButtonState['buttonState'];
+    if (disconnecting) {
+        buttonState = 'disconnecting';
+    } else if (wallet) {
+        buttonState = 'has-wallet';
+    } else {
+        buttonState = 'no-wallet';
+    }
+    const handleDisconnectButtonClick = useCallback(() => {
+        disconnect().catch(() => {
+            // Silently catch because any errors are caught by the context `onError` handler
+        });
+    }, [disconnect]);
+    return {
+        buttonDisabled: buttonState !== 'has-wallet',
+        buttonState,
+        onButtonClick: buttonState === 'has-wallet' ? handleDisconnectButtonClick : undefined,
+        walletIcon: wallet?.adapter.icon,
+        walletName: wallet?.adapter.name,
+    };
+}

+ 60 - 0
packages/core/react/src/useWalletMultiButton.ts

@@ -0,0 +1,60 @@
+import type { PublicKey } from '@solana/web3.js';
+import { useCallback } from 'react';
+import type { Wallet } from './useWallet.js';
+import { useWallet } from './useWallet.js';
+
+type ButtonState = {
+    buttonState: 'connecting' | 'connected' | 'disconnecting' | 'has-wallet' | 'no-wallet';
+    onConnect?: () => void;
+    onDisconnect?: () => void;
+    onSelectWallet?: () => void;
+    publicKey?: PublicKey;
+    walletIcon?: Wallet['adapter']['icon'];
+    walletName?: Wallet['adapter']['name'];
+};
+
+type Config = {
+    onSelectWallet: (config: {
+        onSelectWallet: (walletName: Wallet['adapter']['name']) => void;
+        wallets: Wallet[];
+    }) => void;
+};
+
+export function useWalletMultiButton({ onSelectWallet }: Config): ButtonState {
+    const { connect, connected, connecting, disconnect, disconnecting, publicKey, select, wallet, wallets } =
+        useWallet();
+    let buttonState: ButtonState['buttonState'];
+    if (connecting) {
+        buttonState = 'connecting';
+    } else if (connected) {
+        buttonState = 'connected';
+    } else if (disconnecting) {
+        buttonState = 'disconnecting';
+    } else if (wallet) {
+        buttonState = 'has-wallet';
+    } else {
+        buttonState = 'no-wallet';
+    }
+    const handleConnect = useCallback(() => {
+        connect().catch(() => {
+            // Silently catch because any errors are caught by the context `onError` handler
+        });
+    }, [connect]);
+    const handleDisconnect = useCallback(() => {
+        disconnect().catch(() => {
+            // Silently catch because any errors are caught by the context `onError` handler
+        });
+    }, [disconnect]);
+    const handleSelectWallet = useCallback(() => {
+        onSelectWallet({ onSelectWallet: select, wallets });
+    }, [onSelectWallet, select, wallets]);
+    return {
+        buttonState,
+        onConnect: buttonState === 'has-wallet' ? handleConnect : undefined,
+        onDisconnect: buttonState !== 'disconnecting' && buttonState !== 'no-wallet' ? handleDisconnect : undefined,
+        onSelectWallet: handleSelectWallet,
+        publicKey: publicKey ?? undefined,
+        walletIcon: wallet?.adapter.icon,
+        walletName: wallet?.adapter.name,
+    };
+}