hyuskui

Portfolio Table

Holdings in a Data Table: asset, price, balance, value, 24h change and share of the portfolio, sortable and filterable. Values sort as integer cents, never as display strings.

Loading GPUI…
use gpui::{div, prelude::*, px, relative, Context, FontWeight, SharedString, Window};

use crate::theme::ActiveTheme;
use crate::ui::avatar::{Avatar, AvatarSize};
use crate::ui::data_table::{DataColumn, DataTable, DataTableState};
use crate::ui::input::TextInput;
use crate::ui::onchain::{format_amount, format_bps, format_usd_cents, mul_div, usd_cents, BPS};

#[derive(Clone)]
pub struct Holding {
    pub symbol: &'static str,
    pub name: &'static str,
    pub decimals: u8,
    pub balance: u128,
    /// Sample USD price, 8 decimals.
    pub price_e8: u128,
    /// 24h change in bps; negative is down.
    pub change_bps: i64,
}

impl Holding {
    pub fn cents(&self) -> u128 {
        usd_cents(self.balance, self.decimals, self.price_e8).unwrap_or(0)
    }
}

/// Sample holdings.
pub const HOLDINGS: [Holding; 7] = [
    Holding { symbol: "ETH", name: "Ether", decimals: 18, balance: 1_234_567_890_123_456_789, price_e8: 300_000_000_000, change_bps: 214 },
    Holding { symbol: "USDC", name: "USD Coin", decimals: 6, balance: 2_500_120_000, price_e8: 100_000_000, change_bps: 1 },
    Holding { symbol: "WBTC", name: "Wrapped Bitcoin", decimals: 8, balance: 4_210_337, price_e8: 6_000_000_000_000, change_bps: -87 },
    Holding { symbol: "DAI", name: "Dai Stablecoin", decimals: 18, balance: 820_500_000_000_000_000_000, price_e8: 99_980_000, change_bps: -2 },
    Holding { symbol: "stSMPL", name: "Sample Staked Ether", decimals: 18, balance: 500_000_000_000_000_000, price_e8: 301_200_000_000, change_bps: 198 },
    Holding { symbol: "SMPL", name: "Sample Governance", decimals: 18, balance: 120_000_000_000_000_000_000, price_e8: 420_000_000, change_bps: 512 },
    Holding { symbol: "LP", name: "Sample ETH/USDC LP", decimals: 18, balance: 3_000_000_000_000_000, price_e8: 21_000_000_000_000, change_bps: 96 },
];

/// Formats a signed bps change with a real minus sign.
pub fn signed_bps(bps: i64) -> String {
    format!("{}{}", if bps < 0 { "\u{2212}" } else { "+" }, format_bps(bps.unsigned_abs() as u128))
}

#[derive(Default)]
pub struct PortfolioTablePattern {
    table: DataTableState,
}

impl Render for PortfolioTablePattern {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let filter = window.use_keyed_state("portfolio-filter", cx, |_, cx| TextInput::new(cx).placeholder("Filter assets..."));
        let theme = cx.theme().clone();
        let total: u128 = HOLDINGS.iter().map(Holding::cents).sum();
        let (muted, destructive, bar, track) = (theme.muted_foreground, theme.destructive, theme.foreground, theme.muted);

        let table = DataTable::new("portfolio", HOLDINGS, |h: &Holding| SharedString::from(h.symbol), self.table.clone())
            .page_size(5)
            .filter(filter, |h, query| {
                let query = query.to_lowercase();
                h.symbol.to_lowercase().contains(&query) || h.name.to_lowercase().contains(&query)
            })
            .column(
                DataColumn::new("asset", "Asset", move |h: &Holding| {
                    div()
                        .flex()
                        .items_center()
                        .gap_2()
                        .child(Avatar::new(SharedString::from(h.symbol[..1].to_string())).size(AvatarSize::Custom(px(24.0))))
                        .child(
                            div()
                                .flex()
                                .flex_col()
                                .child(div().font_weight(FontWeight::MEDIUM).child(h.symbol))
                                .child(div().text_xs().text_color(muted).child(h.name)),
                        )
                })
                .sort_by_key(|h| h.symbol),
            )
            .column(
                DataColumn::new("price", "Price", |h: &Holding| format_usd_cents(h.price_e8 / 1_000_000))
                    .width(px(96.0))
                    .align_end()
                    .sort_by_key(|h| h.price_e8),
            )
            .column(
                DataColumn::new("balance", "Balance", |h: &Holding| format_amount(h.balance, h.decimals, 4))
                    .width(px(100.0))
                    .align_end(),
            )
            .column(
                DataColumn::new("value", "Value", |h: &Holding| div().font_weight(FontWeight::MEDIUM).child(format_usd_cents(h.cents())))
                    .width(px(110.0))
                    .align_end()
                    .sort_by_key(Holding::cents),
            )
            .column(
                DataColumn::new("change", "24h", move |h: &Holding| {
                    div().text_color(if h.change_bps < 0 { destructive } else { muted }).child(signed_bps(h.change_bps))
                })
                .width(px(80.0))
                .align_end()
                .sort_by_key(|h| h.change_bps),
            )
            .column(
                DataColumn::new("share", "Share", move |h: &Holding| {
                    let share = mul_div(h.cents(), BPS, total).unwrap_or(0);
                    div()
                        .flex()
                        .items_center()
                        .gap_2()
                        .child(
                            div()
                                .w(px(44.0))
                                .h(px(6.0))
                                .rounded_full()
                                .bg(track)
                                .child(div().h_full().w(relative(share as f32 / BPS as f32)).rounded_full().bg(bar)),
                        )
                        .child(div().flex_none().w(px(56.0)).text_right().child(format_bps(share)))
                })
                .width(px(130.0))
                .align_end()
                .sort_by_key(Holding::cents),
            )
            .on_change(cx.listener(|this, state: &DataTableState, _, cx| {
                this.table = state.clone();
                cx.notify();
            }));

        div()
            .w(px(680.0))
            .flex()
            .flex_col()
            .gap_2()
            .child(
                div()
                    .flex()
                    .items_end()
                    .justify_between()
                    .child(
                        div()
                            .flex()
                            .flex_col()
                            .child(div().text_xs().text_color(theme.muted_foreground).child("Portfolio value"))
                            .child(div().text_2xl().font_weight(FontWeight::SEMIBOLD).child(format_usd_cents(total))),
                    )
                    .child(div().text_xs().text_color(theme.muted_foreground).child("Sample holdings and prices")),
            )
            .child(div().h(px(340.0)).child(table))
    }
}

Installation

  1. Add the components

    $ cargo hyuskui add avatar data-table input onchain

    Uses Avatar, Data Table, Input and Onchain.

  2. Add the crates

    $ cargo add sha3@0.10

    onchain.rs hashes addresses with Keccak-256 for their EIP-55 checksum. cargo hyuskui add runs this for you; you need it only when copying the files by hand.

  3. Copy the pattern

    Paste the code into src/crypto/portfolio_table.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/portfolio_table.rs
    use gpui::{div, prelude::*, px, relative, Context, FontWeight, SharedString, Window};
    
    use crate::theme::ActiveTheme;
    use crate::ui::avatar::{Avatar, AvatarSize};
    use crate::ui::data_table::{DataColumn, DataTable, DataTableState};
    use crate::ui::input::TextInput;
    use crate::ui::onchain::{format_amount, format_bps, format_usd_cents, mul_div, usd_cents, BPS};
    
    #[derive(Clone)]
    pub struct Holding {
        pub symbol: &'static str,
        pub name: &'static str,
        pub decimals: u8,
        pub balance: u128,
        /// Sample USD price, 8 decimals.
        pub price_e8: u128,
        /// 24h change in bps; negative is down.
        pub change_bps: i64,
    }
    
    impl Holding {
        pub fn cents(&self) -> u128 {
            usd_cents(self.balance, self.decimals, self.price_e8).unwrap_or(0)
        }
    }
    
    /// Sample holdings.
    pub const HOLDINGS: [Holding; 7] = [
        Holding { symbol: "ETH", name: "Ether", decimals: 18, balance: 1_234_567_890_123_456_789, price_e8: 300_000_000_000, change_bps: 214 },
        Holding { symbol: "USDC", name: "USD Coin", decimals: 6, balance: 2_500_120_000, price_e8: 100_000_000, change_bps: 1 },
        Holding { symbol: "WBTC", name: "Wrapped Bitcoin", decimals: 8, balance: 4_210_337, price_e8: 6_000_000_000_000, change_bps: -87 },
        Holding { symbol: "DAI", name: "Dai Stablecoin", decimals: 18, balance: 820_500_000_000_000_000_000, price_e8: 99_980_000, change_bps: -2 },
        Holding { symbol: "stSMPL", name: "Sample Staked Ether", decimals: 18, balance: 500_000_000_000_000_000, price_e8: 301_200_000_000, change_bps: 198 },
        Holding { symbol: "SMPL", name: "Sample Governance", decimals: 18, balance: 120_000_000_000_000_000_000, price_e8: 420_000_000, change_bps: 512 },
        Holding { symbol: "LP", name: "Sample ETH/USDC LP", decimals: 18, balance: 3_000_000_000_000_000, price_e8: 21_000_000_000_000, change_bps: 96 },
    ];
    
    /// Formats a signed bps change with a real minus sign.
    pub fn signed_bps(bps: i64) -> String {
        format!("{}{}", if bps < 0 { "\u{2212}" } else { "+" }, format_bps(bps.unsigned_abs() as u128))
    }
    
    #[derive(Default)]
    pub struct PortfolioTablePattern {
        table: DataTableState,
    }
    
    impl Render for PortfolioTablePattern {
        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let filter = window.use_keyed_state("portfolio-filter", cx, |_, cx| TextInput::new(cx).placeholder("Filter assets..."));
            let theme = cx.theme().clone();
            let total: u128 = HOLDINGS.iter().map(Holding::cents).sum();
            let (muted, destructive, bar, track) = (theme.muted_foreground, theme.destructive, theme.foreground, theme.muted);
    
            let table = DataTable::new("portfolio", HOLDINGS, |h: &Holding| SharedString::from(h.symbol), self.table.clone())
                .page_size(5)
                .filter(filter, |h, query| {
                    let query = query.to_lowercase();
                    h.symbol.to_lowercase().contains(&query) || h.name.to_lowercase().contains(&query)
                })
                .column(
                    DataColumn::new("asset", "Asset", move |h: &Holding| {
                        div()
                            .flex()
                            .items_center()
                            .gap_2()
                            .child(Avatar::new(SharedString::from(h.symbol[..1].to_string())).size(AvatarSize::Custom(px(24.0))))
                            .child(
                                div()
                                    .flex()
                                    .flex_col()
                                    .child(div().font_weight(FontWeight::MEDIUM).child(h.symbol))
                                    .child(div().text_xs().text_color(muted).child(h.name)),
                            )
                    })
                    .sort_by_key(|h| h.symbol),
                )
                .column(
                    DataColumn::new("price", "Price", |h: &Holding| format_usd_cents(h.price_e8 / 1_000_000))
                        .width(px(96.0))
                        .align_end()
                        .sort_by_key(|h| h.price_e8),
                )
                .column(
                    DataColumn::new("balance", "Balance", |h: &Holding| format_amount(h.balance, h.decimals, 4))
                        .width(px(100.0))
                        .align_end(),
                )
                .column(
                    DataColumn::new("value", "Value", |h: &Holding| div().font_weight(FontWeight::MEDIUM).child(format_usd_cents(h.cents())))
                        .width(px(110.0))
                        .align_end()
                        .sort_by_key(Holding::cents),
                )
                .column(
                    DataColumn::new("change", "24h", move |h: &Holding| {
                        div().text_color(if h.change_bps < 0 { destructive } else { muted }).child(signed_bps(h.change_bps))
                    })
                    .width(px(80.0))
                    .align_end()
                    .sort_by_key(|h| h.change_bps),
                )
                .column(
                    DataColumn::new("share", "Share", move |h: &Holding| {
                        let share = mul_div(h.cents(), BPS, total).unwrap_or(0);
                        div()
                            .flex()
                            .items_center()
                            .gap_2()
                            .child(
                                div()
                                    .w(px(44.0))
                                    .h(px(6.0))
                                    .rounded_full()
                                    .bg(track)
                                    .child(div().h_full().w(relative(share as f32 / BPS as f32)).rounded_full().bg(bar)),
                            )
                            .child(div().flex_none().w(px(56.0)).text_right().child(format_bps(share)))
                    })
                    .width(px(130.0))
                    .align_end()
                    .sort_by_key(Holding::cents),
                )
                .on_change(cx.listener(|this, state: &DataTableState, _, cx| {
                    this.table = state.clone();
                    cx.notify();
                }));
    
            div()
                .w(px(680.0))
                .flex()
                .flex_col()
                .gap_2()
                .child(
                    div()
                        .flex()
                        .items_end()
                        .justify_between()
                        .child(
                            div()
                                .flex()
                                .flex_col()
                                .child(div().text_xs().text_color(theme.muted_foreground).child("Portfolio value"))
                                .child(div().text_2xl().font_weight(FontWeight::SEMIBOLD).child(format_usd_cents(total))),
                        )
                        .child(div().text_xs().text_color(theme.muted_foreground).child("Sample holdings and prices")),
                )
                .child(div().h(px(340.0)).child(table))
        }
    }