hyuskui

Network Switcher

A menu of networks with the current one checked. Picking another asks the wallet to switch and shows a spinner until it answers; a network the app doesn't support yet is disabled.

Loading GPUI…
use std::time::Duration;

use gpui::{div, prelude::*, px, ClickEvent, Context, FontWeight, SharedString, Task, Window};

use crate::icons::{icon, CHEVRON_DOWN, TRIANGLE_ALERT};
use crate::theme::ActiveTheme;
use crate::ui::avatar::{Avatar, AvatarSize};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
use crate::ui::popover::Align;
use crate::ui::spinner::{Spinner, SpinnerSize};

/// How long the demo pretends the wallet takes to switch.
const SWITCH: Duration = Duration::from_millis(1200);

struct Network {
    name: &'static str,
    /// What the menu shows beside the name.
    kind: &'static str,
    supported: bool,
}

/// Sample networks with generic names.
const NETWORKS: [Network; 5] = [
    Network { name: "Mainnet", kind: "L1", supported: true },
    Network { name: "Rollup One", kind: "L2", supported: true },
    Network { name: "Rollup Two", kind: "L2", supported: true },
    Network { name: "Testnet", kind: "Test", supported: true },
    Network { name: "Rollup Three", kind: "Soon", supported: false },
];

#[derive(Default)]
pub struct NetworkSwitcherPattern {
    current: usize,
    /// The network the wallet is being asked to switch to.
    switching: Option<usize>,
    open: bool,
    pending: Option<Task<()>>,
}

impl NetworkSwitcherPattern {
    /// A real app asks the wallet to switch here and updates `current` from the wallet's
    /// chain-changed event, since the user can also switch in the wallet itself.
    fn switch(&mut self, ix: usize, cx: &mut Context<Self>) {
        if ix == self.current {
            return;
        }
        self.switching = Some(ix);
        self.pending = Some(cx.spawn(async move |this, cx| {
            cx.background_executor().timer(SWITCH).await;
            this.update(cx, |this, cx| {
                this.current = ix;
                this.switching = None;
                cx.notify();
            })
            .ok();
        }));
        cx.notify();
    }
}

impl Render for NetworkSwitcherPattern {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let theme = cx.theme().clone();
        let network = &NETWORKS[self.current];

        let label: SharedString = match self.switching {
            Some(ix) => format!("Switching to {}\u{2026}", NETWORKS[ix].name).into(),
            None => network.name.into(),
        };
        let trigger = Button::new("network", label)
            .variant(ButtonVariant::Outline)
            .disabled(self.switching.is_some())
            .leading(match self.switching {
                Some(_) => Spinner::new().size(SpinnerSize::Sm).into_any_element(),
                None => chain_icon(network.name).into_any_element(),
            })
            .trailing(icon(CHEVRON_DOWN).size(px(14.0)).text_color(theme.muted_foreground));

        let menu = NETWORKS.iter().enumerate().fold(
            DropdownMenu::new("networks", self.open)
                .align(Align::Start)
                .width(px(240.0))
                .trigger(trigger)
                .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                    this.open = *open;
                    cx.notify();
                }))
                .label("Select a network"),
            |menu, (ix, network)| {
                menu.item(
                    MenuItem::new(network.name)
                        .icon(chain_icon(network.name))
                        .shortcut(network.kind)
                        .checked(ix == self.current)
                        .disabled(!network.supported)
                        .on_select(cx.listener(move |this, _: &ClickEvent, _, cx| this.switch(ix, cx))),
                )
            },
        );

        div()
            .size_full()
            .flex()
            .flex_col()
            .items_center()
            .pt_12()
            .gap_3()
            .child(menu)
            .child(
                div()
                    .flex()
                    .items_center()
                    .gap_1p5()
                    .text_xs()
                    .text_color(theme.muted_foreground)
                    // Hidden under the open menu, but kept in layout so nothing shifts.
                    .when(self.open, |this| this.opacity(0.0))
                    .when(self.switching.is_some(), |this| {
                        this.child(icon(TRIANGLE_ALERT).size(px(12.0)).text_color(theme.muted_foreground))
                            .child("Confirm the switch in your wallet")
                    })
                    .when(self.switching.is_none(), |this| {
                        this.child(
                            div()
                                .font_weight(FontWeight::MEDIUM)
                                .text_color(theme.foreground)
                                .child(format!("{} \u{00b7} {}", network.name, network.kind)),
                        )
                        .child("Sample networks")
                    }),
            )
    }
}

/// A network's stand-in logo: its first letter on a round tile.
fn chain_icon(name: &str) -> Avatar {
    Avatar::new(SharedString::from(name.chars().next().map(String::from).unwrap_or_default()))
        .size(AvatarSize::Custom(px(18.0)))
}

Installation

  1. Add the components

    $ cargo hyuskui add avatar button dropdown-menu popover spinner icons

    Uses Avatar, Button, Dropdown Menu, Popover and Spinner.

  2. Copy the pattern

    Paste the code into src/crypto/network_switcher.rs and declare the module. The demo runs on sample data and fake addresses; feed it your wallet connection, balances and quotes, and send transactions from the handlers.

    src/crypto/network_switcher.rs
    use std::time::Duration;
    
    use gpui::{div, prelude::*, px, ClickEvent, Context, FontWeight, SharedString, Task, Window};
    
    use crate::icons::{icon, CHEVRON_DOWN, TRIANGLE_ALERT};
    use crate::theme::ActiveTheme;
    use crate::ui::avatar::{Avatar, AvatarSize};
    use crate::ui::button::{Button, ButtonVariant};
    use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
    use crate::ui::popover::Align;
    use crate::ui::spinner::{Spinner, SpinnerSize};
    
    /// How long the demo pretends the wallet takes to switch.
    const SWITCH: Duration = Duration::from_millis(1200);
    
    struct Network {
        name: &'static str,
        /// What the menu shows beside the name.
        kind: &'static str,
        supported: bool,
    }
    
    /// Sample networks with generic names.
    const NETWORKS: [Network; 5] = [
        Network { name: "Mainnet", kind: "L1", supported: true },
        Network { name: "Rollup One", kind: "L2", supported: true },
        Network { name: "Rollup Two", kind: "L2", supported: true },
        Network { name: "Testnet", kind: "Test", supported: true },
        Network { name: "Rollup Three", kind: "Soon", supported: false },
    ];
    
    #[derive(Default)]
    pub struct NetworkSwitcherPattern {
        current: usize,
        /// The network the wallet is being asked to switch to.
        switching: Option<usize>,
        open: bool,
        pending: Option<Task<()>>,
    }
    
    impl NetworkSwitcherPattern {
        /// A real app asks the wallet to switch here and updates `current` from the wallet's
        /// chain-changed event, since the user can also switch in the wallet itself.
        fn switch(&mut self, ix: usize, cx: &mut Context<Self>) {
            if ix == self.current {
                return;
            }
            self.switching = Some(ix);
            self.pending = Some(cx.spawn(async move |this, cx| {
                cx.background_executor().timer(SWITCH).await;
                this.update(cx, |this, cx| {
                    this.current = ix;
                    this.switching = None;
                    cx.notify();
                })
                .ok();
            }));
            cx.notify();
        }
    }
    
    impl Render for NetworkSwitcherPattern {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let theme = cx.theme().clone();
            let network = &NETWORKS[self.current];
    
            let label: SharedString = match self.switching {
                Some(ix) => format!("Switching to {}\u{2026}", NETWORKS[ix].name).into(),
                None => network.name.into(),
            };
            let trigger = Button::new("network", label)
                .variant(ButtonVariant::Outline)
                .disabled(self.switching.is_some())
                .leading(match self.switching {
                    Some(_) => Spinner::new().size(SpinnerSize::Sm).into_any_element(),
                    None => chain_icon(network.name).into_any_element(),
                })
                .trailing(icon(CHEVRON_DOWN).size(px(14.0)).text_color(theme.muted_foreground));
    
            let menu = NETWORKS.iter().enumerate().fold(
                DropdownMenu::new("networks", self.open)
                    .align(Align::Start)
                    .width(px(240.0))
                    .trigger(trigger)
                    .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                        this.open = *open;
                        cx.notify();
                    }))
                    .label("Select a network"),
                |menu, (ix, network)| {
                    menu.item(
                        MenuItem::new(network.name)
                            .icon(chain_icon(network.name))
                            .shortcut(network.kind)
                            .checked(ix == self.current)
                            .disabled(!network.supported)
                            .on_select(cx.listener(move |this, _: &ClickEvent, _, cx| this.switch(ix, cx))),
                    )
                },
            );
    
            div()
                .size_full()
                .flex()
                .flex_col()
                .items_center()
                .pt_12()
                .gap_3()
                .child(menu)
                .child(
                    div()
                        .flex()
                        .items_center()
                        .gap_1p5()
                        .text_xs()
                        .text_color(theme.muted_foreground)
                        // Hidden under the open menu, but kept in layout so nothing shifts.
                        .when(self.open, |this| this.opacity(0.0))
                        .when(self.switching.is_some(), |this| {
                            this.child(icon(TRIANGLE_ALERT).size(px(12.0)).text_color(theme.muted_foreground))
                                .child("Confirm the switch in your wallet")
                        })
                        .when(self.switching.is_none(), |this| {
                            this.child(
                                div()
                                    .font_weight(FontWeight::MEDIUM)
                                    .text_color(theme.foreground)
                                    .child(format!("{} \u{00b7} {}", network.name, network.kind)),
                            )
                            .child("Sample networks")
                        }),
                )
        }
    }
    
    /// A network's stand-in logo: its first letter on a round tile.
    fn chain_icon(name: &str) -> Avatar {
        Avatar::new(SharedString::from(name.chars().next().map(String::from).unwrap_or_default()))
            .size(AvatarSize::Custom(px(18.0)))
    }