Skip to main content

ViewCtx

Struct ViewCtx 

Source
pub struct ViewCtx<'a, Msg> {
    pub ui: &'a mut Ui,
    /* private fields */
}
Expand description

Context passed to view functions, enabling message emission from any depth

§Example

fn view(model: &Model, ctx: &mut ViewCtx<Msg>) {
    if ctx.ui.button("Click me").clicked() {
        ctx.emit(Msg::ButtonClicked);
    }

    // Or use the helper
    ctx.button("Another", Msg::AnotherClicked);
}

Fields§

§ui: &'a mut Ui

The egui UI handle

Implementations§

Source§

impl<'a, ParentMsg> ViewCtx<'a, ParentMsg>

Extension trait for ViewCtx to mount components

Source

pub fn mount<C>( &mut self, props: &C::Props, state: &C::State, map_msg: impl Fn(C::Msg) -> ParentMsg, )
where C: Component,

Mount a child component, mapping its messages to parent messages

§Example
ctx.mount::<Counter>(
    &counter_props,
    &counter_state,
    |counter_msg| AppMsg::Counter(counter_msg),
);
Source

pub fn mount_mut<C>( &mut self, props: &C::Props, state: &mut C::State, map_msg: impl Fn(C::Msg) -> ParentMsg, )
where C: Component,

Mount a child component with mutable state access Use this when you need to update child state immediately

Source§

impl<'a, Msg> ViewCtx<'a, Msg>

Source

pub fn navigate<P>(&mut self, page: P, to_msg: impl FnOnce(RouterMsg<P>) -> Msg)

Navigate to a page (convenience method)

Source

pub fn router_back<P>(&mut self, to_msg: impl FnOnce(RouterMsg<P>) -> Msg)

Go back in router history

Source

pub fn router_forward<P>(&mut self, to_msg: impl FnOnce(RouterMsg<P>) -> Msg)

Go forward in router history

Source§

impl<'a, Msg> ViewCtx<'a, Msg>

Source

pub fn emit(&mut self, msg: Msg)

Emit a message to be processed in the next update cycle

Source

pub fn emit_all(&mut self, msgs: impl IntoIterator<Item = Msg>)

Emit multiple messages

Source

pub fn emit_result<T, E>( &mut self, result: Result<T, E>, on_ok: impl FnOnce(T) -> Msg, on_err: impl FnOnce(E) -> Msg, )

Emit a Result, converting Ok/Err to appropriate messages

§Example
ctx.emit_result(
    parse_input(&text),
    |value| Msg::Parsed(value),
    |err| Msg::Error(err.to_string()),
);
Source

pub fn emit_if_err<T, E>( &mut self, result: Result<T, E>, on_err: impl FnOnce(E) -> Msg, )

Emit only if Result is Err (for error-only handling)

§Example
ctx.emit_if_err(
    validate(&input),
    |err| Msg::ValidationError(err),
);
Source

pub fn child<'b, ChildMsg, F>( &'b mut self, child_emitter: &'b mut Vec<ChildMsg>, ui: &'b mut Ui, ) -> ViewCtx<'b, ChildMsg>

Create a child context for nested UI regions

Messages from the child are mapped to parent messages via map_msg

Source

pub fn with_ui<'b>(&'b mut self, ui: &'b mut Ui) -> ViewCtx<'b, Msg>
where 'a: 'b,

Reborrow with same emitter but different UI (for nested layouts)

Source§

impl<'a, Msg> ViewCtx<'a, Msg>

Source

pub fn button(&mut self, text: impl Into<String>, msg: Msg) -> bool

Button that emits a message when clicked

Source

pub fn horizontal<R>(&mut self, f: impl FnOnce(&mut ViewCtx<'_, Msg>) -> R) -> R

Horizontal layout

Source

pub fn vertical<R>(&mut self, f: impl FnOnce(&mut ViewCtx<'_, Msg>) -> R) -> R

Vertical layout

Source

pub fn group<R>(&mut self, f: impl FnOnce(&mut ViewCtx<'_, Msg>) -> R) -> R

Group (framed region)

Source

pub fn collapsing<R>( &mut self, heading: impl Into<String>, f: impl FnOnce(&mut ViewCtx<'_, Msg>) -> R, ) -> Option<R>

Collapsing header

Source

pub fn scroll_area<R>( &mut self, f: impl FnOnce(&mut ViewCtx<'_, Msg>) -> R, ) -> R

Scroll area (vertical, default settings)

Source

pub fn scroll_area_id<R>( &mut self, id: impl Hash, f: impl FnOnce(&mut ViewCtx<'_, Msg>) -> R, ) -> R

Scroll area with custom id (avoids ID clashes)

Source

pub fn scroll_area_with<R>( &mut self, builder: impl FnOnce(ScrollArea) -> ScrollArea, f: impl FnOnce(&mut ViewCtx<'_, Msg>) -> R, ) -> R

Scroll area with full customization via builder

§Example
ctx.scroll_area_with(
    |area| area.max_height(300.0).auto_shrink([false, false]),
    |ctx| {
        for i in 0..100 {
            ctx.ui.label(format!("Item {}", i));
        }
    },
);
Source

pub fn sidebar_layout( &mut self, id: impl Into<Id>, width: f32, sidebar: impl FnOnce(&mut ViewCtx<'_, Msg>), main: impl FnOnce(&mut ViewCtx<'_, Msg>), )

Two-panel layout with left sidebar

Uses egui::SidePanel internally for clean layout.

§Example
ctx.sidebar_layout(
    "my_sidebar",
    200.0,
    |ctx| {
        // Sidebar content
        ctx.ui.label("Navigation");
    },
    |ctx| {
        // Main content
        ctx.ui.label("Content");
    },
);
Source

pub fn sidebar_right_layout( &mut self, id: impl Into<Id>, width: f32, main: impl FnOnce(&mut ViewCtx<'_, Msg>), sidebar: impl FnOnce(&mut ViewCtx<'_, Msg>), )

Two-panel layout with right sidebar

Source

pub fn top_panel_layout( &mut self, id: impl Into<Id>, top: impl FnOnce(&mut ViewCtx<'_, Msg>), main: impl FnOnce(&mut ViewCtx<'_, Msg>), )

Top + Main panel layout

Source

pub fn two_columns( &mut self, left: impl FnOnce(&mut ViewCtx<'_, Msg>), right: impl FnOnce(&mut ViewCtx<'_, Msg>), )

Two-column layout using allocate_ui_at_rect

Divides the available space into two equal columns. Each column gets its own ViewCtx with full emit() capability.

§Example
ctx.two_columns(
    |ctx| {
        ctx.ui.label("Left column");
        ctx.button("Click", Msg::LeftClicked);
    },
    |ctx| {
        ctx.ui.label("Right column");
        ctx.button("Click", Msg::RightClicked);
    },
);
Source

pub fn three_columns( &mut self, col1: impl FnOnce(&mut ViewCtx<'_, Msg>), col2: impl FnOnce(&mut ViewCtx<'_, Msg>), col3: impl FnOnce(&mut ViewCtx<'_, Msg>), )

Three-column layout

Divides the available space into three equal columns.

Source

pub fn four_columns( &mut self, col1: impl FnOnce(&mut ViewCtx<'_, Msg>), col2: impl FnOnce(&mut ViewCtx<'_, Msg>), col3: impl FnOnce(&mut ViewCtx<'_, Msg>), col4: impl FnOnce(&mut ViewCtx<'_, Msg>), )

Four-column layout

Divides the available space into four equal columns.

Source

pub fn columns( &mut self, columns: Vec<Box<dyn FnOnce(&mut ViewCtx<'_, Msg>) + '_>>, )

Variable-length column layout

Divides the available space into N equal columns. Use this when you need more than 4 columns or dynamic column count.

§Example
ctx.columns(vec![
    Box::new(|ctx| { ctx.ui.label("Col 1"); }),
    Box::new(|ctx| { ctx.ui.label("Col 2"); }),
    Box::new(|ctx| { ctx.ui.label("Col 3"); }),
    Box::new(|ctx| { ctx.ui.label("Col 4"); }),
    Box::new(|ctx| { ctx.ui.label("Col 5"); }),
]);
Source

pub fn show_if<R>( &mut self, condition: bool, f: impl FnOnce(&mut ViewCtx<'_, Msg>) -> R, ) -> Option<R>

Conditionally show content

§Example
ctx.show_if(model.is_logged_in, |ctx| {
    ctx.ui.label("Welcome!");
    ctx.button("Logout", Msg::Logout);
});
Source

pub fn show_if_else<R>( &mut self, condition: bool, if_true: impl FnOnce(&mut ViewCtx<'_, Msg>) -> R, if_false: impl FnOnce(&mut ViewCtx<'_, Msg>) -> R, ) -> R

Conditionally show content with else branch

§Example
ctx.show_if_else(
    model.is_logged_in,
    |ctx| { ctx.ui.label("Welcome!"); },
    |ctx| { ctx.button("Login", Msg::Login); },
);
Source

pub fn enabled_if<R>( &mut self, enabled: bool, f: impl FnOnce(&mut ViewCtx<'_, Msg>) -> R, ) -> R

Render content with disabled state

§Example
ctx.enabled_if(model.can_submit, |ctx| {
    ctx.button("Submit", Msg::Submit);
});
Source

pub fn visible_if<R>( &mut self, visible: bool, f: impl FnOnce(&mut ViewCtx<'_, Msg>) -> R, ) -> R

Render content with visible state (hidden but still takes space)

§Example
ctx.visible_if(model.show_hint, |ctx| {
    ctx.ui.label("This is a hint");
});
Source§

impl<'a, Msg> ViewCtx<'a, Msg>

Source

pub fn on_shortcut(&mut self, shortcut: KeyboardShortcut, msg: Msg) -> bool

Check if a keyboard shortcut was pressed and emit a message

Uses consume_shortcut internally, so the shortcut won’t trigger other handlers after being consumed.

§Example
use egui::{Key, KeyboardShortcut, Modifiers};

// Define shortcuts
const SAVE: KeyboardShortcut = KeyboardShortcut::new(Modifiers::COMMAND, Key::S);
const UNDO: KeyboardShortcut = KeyboardShortcut::new(Modifiers::COMMAND, Key::Z);

// In view function
ctx.on_shortcut(SAVE, Msg::Save);
ctx.on_shortcut(UNDO, Msg::Undo);
Source

pub fn on_shortcuts(&mut self, shortcuts: &[(KeyboardShortcut, Msg)])
where Msg: Clone,

Check multiple shortcuts at once

More efficient than calling on_shortcut multiple times.

§Example
ctx.on_shortcuts(&[
    (SAVE, Msg::Save),
    (UNDO, Msg::Undo),
    (REDO, Msg::Redo),
]);
Source

pub fn on_key(&mut self, key: Key, msg: Msg) -> bool

Check if a specific key was pressed (without modifiers)

§Example
ctx.on_key(Key::Escape, Msg::Cancel);
ctx.on_key(Key::Enter, Msg::Confirm);
Source

pub fn on_binding(&mut self, binding: &impl InputBinding, msg: Msg) -> bool

Check if an input binding was triggered and emit a message.

Works with any type implementing InputBinding, including KeyboardShortcut, DynamicShortcut, and ShortcutGroup.

§Example
use egui_cha::bindings::{DynamicShortcut, InputBinding};

let custom = DynamicShortcut::new(Modifiers::CTRL, Key::K);
ctx.on_binding(&custom, Msg::Custom);

// Also works with static shortcuts
ctx.on_binding(&shortcuts::SAVE, Msg::Save);
Source

pub fn on_action<A>( &mut self, bindings: &ActionBindings<A>, action: &A, msg: Msg, ) -> bool
where A: Eq + Hash + Clone,

Check if an action from ActionBindings was triggered.

This is the preferred way to handle keyboard shortcuts when using the dynamic binding system.

§Example
use egui_cha::bindings::ActionBindings;

#[derive(Clone, PartialEq, Eq, Hash)]
enum Action { Save, Undo, Redo }

let bindings = ActionBindings::new()
    .with_default(Action::Save, shortcuts::SAVE)
    .with_default(Action::Undo, shortcuts::UNDO);

// In view function
ctx.on_action(&bindings, &Action::Save, Msg::Save);
ctx.on_action(&bindings, &Action::Undo, Msg::Undo);
Source

pub fn triggered_actions<A>( &mut self, bindings: &ActionBindings<A>, ) -> Option<A>
where A: Eq + Hash + Clone,

Check all actions in ActionBindings and return triggered ones.

Useful when you want to handle multiple actions in a single call.

§Example
for action in ctx.triggered_actions(&bindings) {
    match action {
        Action::Save => ctx.emit(Msg::Save),
        Action::Undo => ctx.emit(Msg::Undo),
        _ => {}
    }
}
Source§

impl<'a, Msg> ViewCtx<'a, Msg>

Source

pub fn drag_source<P, R>( &mut self, id: impl Into<Id>, payload: P, content: impl FnOnce(&mut ViewCtx<'_, Msg>) -> R, ) -> DragSourceResponse<R>
where P: Clone + Send + Sync + 'static,

Create a draggable source

§Example
ctx.drag_source("item_1", item.clone(), |ctx| {
    ctx.ui.label(&item.name);
}).on_drag_start(ctx, Msg::DragStart { id: item.id });
Source

pub fn drop_zone<P, R>( &mut self, content: impl FnOnce(&mut ViewCtx<'_, Msg>) -> R, ) -> DropZoneResponse<P, R>
where P: Clone + Send + Sync + 'static,

Create a drop zone that accepts payloads of type P

§Example
ctx.drop_zone::<Item, _>(|ctx| {
    ctx.ui.label("Drop items here");
}).on_drop(ctx, |item| Msg::ItemDropped(item));

Auto Trait Implementations§

§

impl<'a, Msg> Freeze for ViewCtx<'a, Msg>

§

impl<'a, Msg> !RefUnwindSafe for ViewCtx<'a, Msg>

§

impl<'a, Msg> Send for ViewCtx<'a, Msg>
where Msg: Send,

§

impl<'a, Msg> Sync for ViewCtx<'a, Msg>
where Msg: Sync,

§

impl<'a, Msg> Unpin for ViewCtx<'a, Msg>

§

impl<'a, Msg> UnsafeUnpin for ViewCtx<'a, Msg>

§

impl<'a, Msg> !UnwindSafe for ViewCtx<'a, Msg>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more