Skip to content

About

material3 theme for egui eframe.

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

 
 

Latest commit

 

History

426 Commits

Folders and files

Repository files navigation

egui-material3

crates.io docs.rs license

Material Design 3 components for egui 0.37: buttons, chips, text fields, cards, lists, data tables, dialogs, navigation and more. Every component takes its colors from a Material theme, so the whole UI follows light/dark mode and any theme you export from the Material Theme Builder. Token values (colour roles, type scale, shapes, elevation, state layers, motion and component sizes) come from the Jetpack Compose material3 token files.

A project dashboard built with egui-material3: top app bar, navigation drawer, filter chips, cards, switches, a data table and an extended FAB
  • Material 3 components: the standard set (buttons, chips, selection controls, text fields, menus, dialogs, sheets, snackbars, lists, cards, navigation, app bars, pickers, progress) plus data table, tree view, timeline, image list, carousel and an optional spreadsheet. See the component list.
  • Per-context themes: each egui context holds its own MaterialTheme (light or dark, Normal, Medium or High contrast), from Compose's baseline scheme or a Material Theme Builder export, and you can switch it at runtime.
  • Builder API: components implement egui::Widget, so they work with ui.add(...) like any built-in widget.
  • Depends only on egui: no eframe requirement, so it fits any egui integration.
  • Accessible and desktop-friendly: AccessKit roles and states, keyboard focus with the Material focus ring, right-to-left layouts, dense controls and virtualised lists.

Contents

Installation

cargo add egui-material3

The crate targets egui 0.37. No feature is on by default; see Optional features.

Quick start

use eframe::egui;
use egui_material3::{
    fonts,
    theme::{apply_theme_context, theme_context_of, ThemeMode},
    MaterialButton, MaterialCheckbox, MaterialChip, MaterialSlider, MaterialSwitch, MaterialTheme,
};

fn main() -> eframe::Result {
    eframe::run_native(
        "My app",
        eframe::NativeOptions::default(),
        Box::new(|cc| {
            // Roboto at the type scale's weights, Material Symbols (used by icon
            // names such as "check"), and the type scale mapped into egui's text styles.
            fonts::install(&cc.egui_ctx);
            // Compose's baseline light scheme for this context's widgets.
            MaterialTheme::set(&cc.egui_ctx, MaterialTheme::baseline(false));
            Ok(Box::<App>::default())
        }),
    )
}

#[derive(Default)]
struct App {
    notifications: bool,
    dark_mode: bool,
    volume: f32,
    starred: bool,
}

impl eframe::App for App {
    fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ui, |ui| {
            ui.add(MaterialCheckbox::new(
                &mut self.notifications,
                "Email notifications",
            ));

            if ui
                .add(MaterialSwitch::new(&mut self.dark_mode).text("Dark mode"))
                .changed()
            {
                // Also themes egui's own visuals, so the panel background follows.
                let mut settings = theme_context_of(ui.ctx());
                settings.theme_mode = if self.dark_mode {
                    ThemeMode::Dark
                } else {
                    ThemeMode::Light
                };
                apply_theme_context(ui.ctx(), &settings, None::<fn() -> ThemeMode>);
            }

            ui.add(MaterialSlider::new(&mut self.volume, 0.0..=100.0).text("Volume"));
            ui.add(MaterialChip::filter("Starred only", &mut self.starred));

            if ui
                .add(MaterialButton::filled("Save").leading_icon("check"))
                .clicked()
            {
                // ...
            }
        });
    }
}

The same program lives in examples/quickstart.rs:

cargo run --example quickstart

fonts::install registers the Material Symbols and Roboto fonts that ship with the crate, so there is nothing to copy into your project.

Theming

Six bundled themes rendered with the same widgets: three in light mode, three in dark mode

A theme is the JSON file the Material Theme Builder exports (Export → JSON). It holds light, dark and medium/high-contrast schemes generated from one seed color. The repository includes seven of them in resources/.

MaterialTheme::set gives one egui context's widgets their colours, and other contexts are not affected. apply_theme_context also maps the scheme onto egui's own visuals (panels, windows, selection, text cursor), so plain egui widgets match the Material components next to them, and it is how you switch mode and contrast at runtime:

use egui_material3::theme::{
    apply_theme_context, load_theme_from_json_str, load_themes, setup_local_theme,
    theme_context_of, ContrastLevel, ThemeMode,
};

fn theming(ctx: &egui::Context, json: &str) -> Result<(), String> {
    // Read a Theme Builder file at startup...
    setup_local_theme(Some("assets/my-theme.json"));
    load_themes();
    // ...or parse one you already hold in memory.
    load_theme_from_json_str(json)?;

    // Switch mode and contrast at any time. `Auto` follows the OS (`system-theme` feature).
    let mut settings = theme_context_of(ctx);
    settings.theme_mode = ThemeMode::Dark; // Light, Dark, or Auto
    settings.contrast_level = ContrastLevel::High; // Normal, Medium, High
    apply_theme_context(ctx, &settings, None::<fn() -> ThemeMode>);
    Ok(())
}

To use a theme color in your own painting, look it up by its Material role:

use egui_material3::{ColorRole, MaterialTheme};

fn custom_painting(ui: &mut egui::Ui) {
    let theme = MaterialTheme::of(ui.ctx());
    let fill = theme.color(ColorRole::PrimaryContainer);
    let text = theme.color(ColorRole::OnPrimaryContainer);
    let (rect, _) = ui.allocate_exact_size(egui::vec2(120.0, 40.0), egui::Sense::hover());
    ui.painter().rect_filled(rect, 8.0, fill);
    ui.painter().text(
        rect.center(),
        egui::Align2::CENTER_CENTER,
        "Hello",
        egui::FontId::proportional(14.0),
        text,
    );
}

Earlier releases kept one process-wide theme (get_global_color, update_global_theme and friends). Those functions still compile, deprecated; the crate docs list their replacements.

Icons

Icons come from the Material Symbols font that fonts::install registers. Every icon parameter takes the icon's name, as listed on Google Fonts, or an Icon for a glyph from your own font, an SVG or a texture:

use egui_material3::{MaterialButton, MaterialIcon, MaterialIconButton};

fn icons(ui: &mut egui::Ui) {
    ui.add(MaterialIconButton::filled("edit"));
    ui.add(MaterialButton::filled("Upload").leading_icon("upload"));
    ui.add(MaterialIcon::new("favorite").size(32.0));
}

To paint an icon yourself, use paint_icon, or get a glyph with material_symbol::material_symbol_text("edit").

Density and type scale

A dense desktop app does not have to pass .density(), .dense() or .small() to every widget. Set them once on the theme:

use egui_material3::{Density, MaterialTheme};

MaterialTheme::set(
    ctx,
    MaterialTheme::baseline(false)
        .with_density(Density::new(-3)) // -5..=0, default 0
        .with_type_scale(0.875),        // 0.75..=1.25, default 1.0
);

Density follows Compose's VisualDensity: each step below zero takes 4 dp off a control's container height, to 24 dp, and below zero the 48 dp minimum touch target is off. Text fields, number fields and selects keep their own 8 dp-per-step table (56, 48, 40, 32 dp, then 28 and 24 dp at -4 and -5); switches go dense at -2; checkbox and radio state layers shrink from 40 dp to 24 dp. Covered: buttons, icon buttons, text, number and select fields, segmented buttons, switches, checkboxes, radios, chips, tabs, list rows, menu items and navigation rail items. A widget's own explicit setting (.density(..), .dense(..), .compact(..), .small(), .size(..), .height(..)) always wins; the theme applies only to what the caller left unset.

type_scale multiplies every type-scale size and line height, in TypeStyle::font_id, text_format and layout_job and in the egui text styles. Custom widgets that need the numbers read TypeStyle::scaled(ctx). Density 0 and scale 1.0, the defaults, change nothing. theme::apply_theme_context keeps the density and scale already set on the context.

Components

Every image below is generated by examples/screenshots.rs. Its source shows the full code for each scene.

Buttons

Filled, tonal, elevated, outlined and text buttons; icon buttons; floating action buttons

use egui_material3::{FabSize, MaterialButton, MaterialFab, MaterialIconButton};

fn buttons(ui: &mut egui::Ui, saved: &mut bool) {
    ui.add(MaterialButton::filled("Filled"));
    ui.add(MaterialButton::filled_tonal("Tonal"));
    ui.add(MaterialButton::outlined("Next").trailing_icon("arrow_forward"));
    ui.add(MaterialIconButton::toggle("bookmark", saved));
    ui.add(MaterialFab::primary().icon("edit").text("Compose").size(FabSize::Extended));
}

MaterialButton (filled, tonal, elevated, outlined, text), MaterialIconButton (standard, filled, tonal, outlined, toggle), MaterialFab (surface, primary, secondary, tertiary; small, regular, large, extended). Also FabMenu, ButtonGroup, SplitButton and SegmentedButton.

Selection controls

Checkboxes, radio buttons, switches and sliders

use egui_material3::{
    MaterialCheckbox, MaterialRadio, MaterialRangeSlider, MaterialSlider, MaterialSwitch,
    RangeValues,
};

fn selection(
    ui: &mut egui::Ui,
    wifi: &mut bool,
    size: &mut Option<usize>,
    airplane: &mut bool,
    volume: &mut f32,
    price: &mut RangeValues,
) {
    ui.add(MaterialCheckbox::new(wifi, "Wi-Fi"));
    ui.add(MaterialRadio::new(size, 1, "Medium"));
    ui.add(MaterialSwitch::new(airplane).text("Airplane mode"));
    ui.add(MaterialSlider::new(volume, 0.0..=100.0).step(10.0));
    ui.add(MaterialRangeSlider::new(price, 0.0..=100.0));
}

MaterialCheckbox (with indeterminate state), MaterialRadio, MaterialRadioGroup, RadioListTile, MaterialSwitch, MaterialSlider, MaterialRangeSlider.

Chips

Filter, assist, input and suggestion chips

use egui_material3::{assist_chip, input_chip, suggestion_chip, MaterialChip};

fn chips(ui: &mut egui::Ui, vegetarian: &mut bool) {
    ui.add(MaterialChip::filter("Vegetarian", vegetarian));
    ui.add(assist_chip("Add to calendar").leading_icon("event"));
    ui.add(input_chip("Ada Lovelace").removable(true));
    ui.add(suggestion_chip("Sounds good"));
}

Text fields and selects

Filled and outlined text fields with icons, error and helper text, and dropdown selects

use egui_material3::{MaterialInput, MaterialSelect};

fn text_fields(
    ui: &mut egui::Ui,
    name: &mut String,
    password: &mut String,
    country: &mut Option<usize>,
) {
    ui.add(MaterialInput::filled(name).label("Full name").leading_icon("person"));
    ui.add(MaterialInput::outlined(password).label("Password").password(true));
    ui.add(
        MaterialSelect::new(country)
            .label("Country")
            .option(0, "Canada")
            .option(1, "Korea"),
    );
}

Also MaterialNumberField and search::MaterialSearch.

  • MaterialNumberField takes .formatter(|v| ...) and .parser(|text| ...) (50 % for a stored 0.5), .speed(units_per_point) for dragging, and is 96 dp wide by default when the theme density is below zero (number_field::COMPACT_WIDTH).
  • MaterialSelect::for_value(&mut value) binds a select to any T: PartialEq + Clone with .options([(value, "label"), ...]); the index-based MaterialSelect::new is unchanged.
  • MaterialInput::edit_id(id) names the inner TextEdit, so the app can ctx.memory_mut(|m| m.request_focus(id)) (a Ctrl+F search box); MaterialInput::edit_id_for_salt(ui, salt) gives the id an .id_salt field uses.

Cards

Elevated, filled and outlined cards with header, media, text and actions

use egui_material3::{MaterialButton, MaterialCard2};

fn card(ui: &mut egui::Ui) {
    ui.add(
        MaterialCard2::elevated()
            .header("Elevated", Some("Card subtitle"))
            .media_area(|_ui| { /* image or illustration */ })
            .content(|ui| {
                ui.label("Group related content and actions.");
            })
            .actions(|ui| {
                ui.add(MaterialButton::filled_tonal("Open"));
                ui.add(MaterialButton::text("Share"));
            }),
    );
}

A card fills the width of a vertical layout and is 280pt wide in a horizontal one; set .width(..) to choose. Its height follows its content.

Lists

Single-line navigation list with a selected item, and a two-line list with dividers

use egui_material3::{ListItem, MaterialList};

fn lists(ui: &mut egui::Ui) {
    ui.add(
        MaterialList::new()
            .dividers(true)
            .item(ListItem::new("Inbox").leading_icon("inbox").trailing_text("24"))
            .item(ListItem::new("Starred").leading_icon("star").selected(true))
            .item(
                ListItem::new("Grace Hopper")
                    .secondary_text("Compiler review at 3pm?")
                    .trailing_text("10:24"),
            ),
    );
}

For long collections, MaterialList::show_rows virtualises the rows.

Data table

Sortable data table with row selection

use egui_material3::data_table;

fn table(ui: &mut egui::Ui) {
    ui.add(
        data_table()
            .sortable_column("Dessert", 220.0, false)
            .sortable_column("Calories", 110.0, true)
            .allow_selection(true)
            .row(|r| r.cell("Frozen yogurt").cell("159"))
            .row(|r| r.cell("Eclair").cell("262")),
    );
}

Supports sorting, selection, sticky headers, per-row expandable drawers, custom cell widgets and a progress bar. examples/nobel_prizes_example.rs loads a real dataset into it.

Navigation

Center-aligned top app bar, primary tabs with icons, secondary tabs, and breadcrumbs

use egui_material3::{breadcrumbs, MaterialTabs, MaterialTopAppBar};

fn navigation(ui: &mut egui::Ui, tab: &mut usize) {
    ui.add(
        MaterialTopAppBar::center_aligned("Top app bar")
            .navigation_icon("arrow_back", || {})
            .action_icon("more_vert", || {}),
    );
    ui.add(
        MaterialTabs::primary(tab)
            .tab_with_icon("Flights", "flight")
            .tab_with_icon("Trips", "luggage"),
    );
    ui.add(breadcrumbs().item("Home").item("Products").active_item("Laptops"));
}

Also: NavigationBar, NavigationRail, MaterialDrawer (permanent, dismissible, modal; see the dashboard at the top), MaterialBottomAppBar, MaterialToolbar, MaterialMenu.

Progress and badges

Circular and linear progress indicators, and badges on icon buttons

use egui_material3::{badge, BadgeColor, BadgePosition, MaterialIconButton, MaterialProgress};

fn feedback(ui: &mut egui::Ui) {
    ui.add(MaterialProgress::circular().value(0.7));
    ui.add(MaterialProgress::linear().value(0.3).buffer(0.6));

    let bell = ui.add(MaterialIconButton::standard("notifications"));
    badge("99+")
        .color(BadgeColor::Error)
        .draw_on(ui, bell.rect, BadgePosition::TopRight);
}

Also: MaterialSnackbar and SnackbarHost, MaterialNotification, MaterialBanner, MaterialTooltip, LoadingIndicator, MaterialActionSheet.

Dialogs

Dark-mode confirmation dialog with an icon, supporting text and two actions

use egui_material3::dialog;

fn confirm(ctx: &egui::Context, open: &mut bool) {
    dialog(egui::Id::new("delete_dialog"), "Delete 3 files?", open)
        .icon("delete")
        .content(|ui, _| {
            ui.label("These files will be moved to the trash.");
        })
        .action("Cancel", || {})
        .primary_action("Delete", || {})
        .show(ctx);
}

Also FullScreenDialog, BottomSheet and SideSheet.

Timeline

Alternating timeline with timestamps and an icon dot, and a single-column timeline with wrapped text

use egui_material3::{
    MaterialTimeline, TimelineDot, TimelineDotColor, TimelineItem, TimelinePosition,
};

fn timeline(ui: &mut egui::Ui) {
    ui.add(
        MaterialTimeline::new()
            .position(TimelinePosition::Alternate)
            .item(
                TimelineItem::new()
                    .content("Order placed")
                    .opposite_content("09:30")
                    .dot(TimelineDot::new().color(TimelineDotColor::Primary)),
            )
            .item(
                TimelineItem::new()
                    .content("Out for delivery")
                    .opposite_content("14:40")
                    .dot(TimelineDot::new().icon("local_shipping").size(28.0)),
            ),
    );
}

Positions: Right (default), Left, Alternate, AlternateReverse. Long content wraps and the row grows to fit.

Tree view

Expandable file tree

use egui_material3::{MaterialTreeView, TreeViewItem, TreeViewState};

fn tree(ui: &mut egui::Ui, state: &mut TreeViewState) {
    let items = vec![TreeViewItem::new("src", "src").icon("folder").children(vec![
        TreeViewItem::new("lib", "lib.rs").icon("description"),
    ])];
    ui.add(MaterialTreeView::new(&items, state));
}

Full component list

Group Components
Buttons MaterialButton, MaterialIconButton, MaterialFab, FabMenu, ButtonGroup, SplitButton, SegmentedButton
Selection MaterialCheckbox, MaterialRadio, MaterialRadioGroup, RadioListTile, MaterialSwitch, MaterialSlider, MaterialRangeSlider, MaterialChip
Text input MaterialInput (filled, outlined), MaterialNumberField, MaterialSelect, search::MaterialSearch
Pickers date_picker::DatePicker, DatePickerDialog, DockedDatePicker, time_picker::TimePicker
Menus MaterialMenu, MaterialMenuItem (full-width rows for egui's own ui.menu_button and context menus)
Navigation NavigationBar, NavigationRail, MaterialDrawer, MaterialTabs (per-tab tooltips and accessible labels), MaterialBreadcrumbs
App bars and toolbars MaterialTopAppBar, MaterialBottomAppBar, MaterialToolbar, MaterialFloatingToolbar
Containment MaterialCard2, MaterialDialog (with destructive_action), FullScreenDialog, BottomSheet, SideSheet, MaterialActionSheet, MaterialDivider
Communication MaterialSnackbar, SnackbarHost, MaterialTooltip, RichTooltip, MaterialBanner, MaterialNotification, MaterialBadge, MaterialProgress, LoadingIndicator
Lists and data MaterialList, MaterialDataTable, MaterialTreeView, MaterialTimeline, MaterialDashCounter, MaterialSpreadsheet (feature spreadsheet)
Media and layout MaterialCarousel, MaterialImageList (standard, masonry, woven), MaterialLayoutGrid
Icons MaterialIcon, Icon, the material_symbol and noto_emoji codepoint tables

Each component's builder methods are documented on docs.rs. egui_material3::mvvm adds optional reactive state helpers (ValState, RefState, ViewModel).

Optional features

No feature is on by default.

Feature Adds
svg SVG icons rasterised with resvg (Icon::Svg, MaterialIconButton::svg, MaterialFab::svg_data). Without it an SVG icon paints nothing.
system-theme ThemeMode::Auto follows the OS light/dark setting. Without it, Auto means light.
symbols_rounded, symbols_sharp Material Symbols Rounded and Sharp besides Outlined.
ondemand Loading MaterialImageList items from URLs (with an on-disk cache), and downloading Google Fonts named in setup_google_fonts.
spreadsheet MaterialSpreadsheet: an editable grid backed by SQLite with CSV and Excel import/export.
svg_solar ~1,200 Solar icons as embedded SVG (~5 MB).
svg_noto ~3,600 Noto emoji as embedded SVG (~36 MB).
svg_twemoji ~3,700 Twemoji emoji as embedded SVG (~17 MB).
svg_emoji All three SVG sets, and the svg_emoji module that exposes them.
cargo add egui-material3 --features ondemand,spreadsheet

Image lists accept local paths, URLs (with ondemand) or raw bytes:

use egui_material3::image_list;

fn gallery(ui: &mut egui::Ui) {
    ui.add(
        image_list()
            .columns(3)
            .item_spacing(8.0)
            .item("Architecture", "assets/building.png")
            .items_from_urls(["https://example.com/photo.jpg"]),
    );
}

With svg_emoji enabled, the SVG sets are lookup tables keyed by name or codepoint:

use egui_material3::svg_emoji::{NOTO_EMOJIS, SOLAR_ICONS, TWEMOJI};

let home = SOLAR_ICONS.get("home");
let grin = NOTO_EMOJIS.get("emoji_u1f600");
let grin = TWEMOJI.get("1f600");

The SVG sets are downloaded during the build when you depend on the crates.io release.

Examples

Command What it shows
cargo run --example quickstart The quick start above.
cargo run --example stories --features spreadsheet,svg,system-theme Interactive gallery: one window per component with live controls, plus a theme editor.
cargo run --example widget_gallery_example The components on one page, with theme mode and contrast switches.
cargo run --example nobel_prizes_example Data table over a real dataset.
cargo run --example mvvm_counter_example MVVM state helpers, minimal.
cargo run --example mvvm_todo_example MVVM state helpers in a todo app.
cargo run --example svg_icon_demo --features svg_emoji Browsing the SVG icon and emoji sets.
cargo run --example screenshots Regenerates every image in this README into docs/images/.
cd examples/ondemand && cargo run Image lists loading from URLs.
cd examples/package && cargo run A standalone app with its own bundled font and theme.

Contributing

Issues and pull requests are welcome at github.com/nikescar/egui-material3. If you change how a component looks, run cargo run --example screenshots and commit the updated images with your change. The snippets above are compiled as doctests, so cargo test --doc fails when one stops matching the API.

See also CHANGELOG.md, TROUBLESHOOT.md and CREDITS.md.

License

Licensed under either of

at your option.

About

material3 theme for egui eframe.

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages