Skip to main content

Module lens

Module lens 

Source
Expand description

Bidirectional lenses for state-widget binding.

A lens focuses on a part of a larger structure, providing both read (view) and write (set) access with algebraic guarantees:

  • GetPut: Setting the value you just read is a no-op.
  • PutGet: Reading after a set returns the value you set.

§Usage

use ftui_runtime::lens::{Lens, field_lens, compose};

#[derive(Clone, Debug, PartialEq)]
struct Config { volume: u8, brightness: u8 }

let volume = field_lens(
    |c: &Config| c.volume,
    |c: &mut Config, v| c.volume = v,
);

let mut config = Config { volume: 50, brightness: 100 };
assert_eq!(volume.view(&config), 50);

volume.set(&mut config, 75);
assert_eq!(config.volume, 75);

§Composition

Lenses compose for nested state access:

use ftui_runtime::lens::{Lens, field_lens, compose};

#[derive(Clone, Debug, PartialEq)]
struct App { settings: Settings }

#[derive(Clone, Debug, PartialEq)]
struct Settings { font_size: u16 }

let settings = field_lens(
    |a: &App| a.settings.clone(),
    |a: &mut App, s| a.settings = s,
);
let font_size = field_lens(
    |s: &Settings| s.font_size,
    |s: &mut Settings, v| s.font_size = v,
);

let app_font_size = compose(settings, font_size);

let mut app = App { settings: Settings { font_size: 14 } };
assert_eq!(app_font_size.view(&app), 14);

app_font_size.set(&mut app, 18);
assert_eq!(app.settings.font_size, 18);

Structs§

AtIndex
Lens into a Vec element by index.
Composed
Composed lens: outer ∘ inner.
FieldLens
A lens built from getter and setter closures.
Fst
Lens into the first element of a tuple.
Identity
Identity lens that focuses on the whole value.
Snd
Lens into the second element of a tuple.
SomePrism
Prism into an Option<T> value.

Traits§

Lens
A bidirectional lens focusing on part A of a whole S.
Prism
A prism for optional focusing (lens that may fail to view).

Functions§

at_index
Create a lens that focuses on a Vec element by index.
compose
Compose two lenses: outer then inner.
field_lens
Create a lens from getter and setter functions.