ribir_widgets 0.3.0

A non-intrusive declarative GUI framework, to build modern native/wasm cross-platform applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use std::{collections::HashMap, hash::Hash};

use ribir_core::prelude::*;

use crate::prelude::*;

#[derive(Declare, Default)]
pub struct TextField {
  /// textfield's input value
  #[declare(skip)]
  text: CowArc<str>,
}

impl TextField {
  pub fn text(&self) -> CowArc<str> { self.text.clone() }
  pub fn set_text(&mut self, text: CowArc<str>) { self.text = text; }
}

#[derive(Template, Default)]
pub struct TextFieldTml {
  /// Label text is used to inform users as to what information is requested for
  /// a text field.
  label: Option<Label>,

  /// The placeholder text is displayed in the input field before the user
  /// enters a value.
  placeholder: Option<Placeholder>,

  /// Use prefix text before the editable text to show symbols or abbreviations
  /// that help users enter the right type of information in a form’s text
  /// input
  prefix: Option<LeadingText>,

  /// Use suffix text after the editable text to show symbols or abbreviations
  /// that help users enter the right type of information in a form’s text
  /// input
  suffix: Option<TrailingText>,

  /// An icon that appears before the editable part of the text field
  leading_icon: Option<WidgetOf<Leading>>,

  /// An icon that appears after the editable part of the text field
  trailing_icon: Option<WidgetOf<Trailing>>,
}

#[derive(Clone)]
pub struct TextFieldTheme {
  /// text foreground.
  pub foreground: Brush,
  /// textfield input's text style
  pub text: CowArc<TextStyle>,

  /// textfield's background color
  pub container_color: Color,

  /// textfield component's height
  pub container_height: f32,

  /// indicator's color
  pub indicator: Color,
  pub indicator_height: f32,

  /// label text color
  pub label_color: Color,

  /// label's text style when collapse
  pub label_collapse: CowArc<TextStyle>,

  /// label's text style when expand
  pub label_expand: CowArc<TextStyle>,

  /// edit area's padding when collapse
  pub input_collapse_padding: EdgeInsets,

  /// edit area's padding when expand
  pub input_expand_padding: EdgeInsets,
}

#[derive(Clone)]
pub struct ThemeSuit<S, T>
where
  S: Hash + Eq,
{
  themes: HashMap<S, T>,
}

impl<S, T> ThemeSuit<S, T>
where
  S: Hash + Eq,
{
  fn get(&self, state: S) -> Option<&T> { self.themes.get(&state) }
}

#[derive(Declare)]
struct ThemeSuitProxy<S: 'static, T: 'static>
where
  S: Hash + Eq,
{
  suit: ThemeSuit<S, T>,
  state: S,
}

type TextFieldThemeProxy = ThemeSuitProxy<TextFieldState, TextFieldTheme>;

impl ComposeChild for TextFieldThemeProxy {
  type Child = Widget;
  fn compose_child(this: impl StateWriter<Value = Self>, child: Self::Child) -> impl WidgetBuilder {
    fn_widget! {
      @ $child {
        on_tap: move |_| {
          let mut this = $this.write();
          match this.state {
            TextFieldState::Enabled => this.state = TextFieldState::Focused,
            TextFieldState::Hovered => this.state = TextFieldState::Focused,
            _ => (),
          };
        },
        on_pointer_move: move |_| {
          let mut this = $this.write();
          if this.state == TextFieldState::Enabled { this.state = TextFieldState::Hovered }
        },
        on_pointer_leave: move |_| {
          let mut this = $this.write();
          if this.state == TextFieldState::Hovered { this.state = TextFieldState::Enabled }
        },
        on_focus_out: move |_| {
          let mut this = $this.write();
          if this.state == TextFieldState::Focused { this.state = TextFieldState::Enabled }
        },
      }
    }
  }
}

impl TextFieldThemeProxy {
  fn theme(&self) -> Option<&TextFieldTheme> { self.suit.get(self.state) }

  fn label_style(&self, is_text_empty: bool) -> CowArc<TextStyle> {
    if self.is_collapse(is_text_empty) {
      self.label_collapse.clone()
    } else {
      self.label_expand.clone()
    }
  }

  fn input_padding(&self, is_text_empty: bool) -> EdgeInsets {
    if self.is_collapse(is_text_empty) {
      self.input_collapse_padding
    } else {
      self.input_expand_padding
    }
  }

  fn is_collapse(&self, is_text_empty: bool) -> bool {
    !is_text_empty || self.state == TextFieldState::Focused
  }
}

pub type TextFieldThemeSuit = ThemeSuit<TextFieldState, TextFieldTheme>;

impl Deref for TextFieldThemeProxy {
  type Target = TextFieldTheme;
  fn deref(&self) -> &Self::Target { self.theme().unwrap() }
}

#[derive(Default, Debug, Clone, Copy, PartialEq, Hash, Eq)]
pub enum TextFieldState {
  #[default]
  Enabled,
  Focused,
  Hovered,
  // Disabled,
}

impl CustomStyle for TextFieldThemeSuit {
  fn default_style(ctx: &BuildCtx) -> Self {
    Self::from_theme(Palette::of(ctx), TypographyTheme::of(ctx))
  }
}

impl TextFieldThemeSuit {
  pub fn from_theme(palette: &Palette, typo_theme: &TypographyTheme) -> Self {
    let body: &CowArc<TextStyle> = &typo_theme.body_large.text;
    let header = &typo_theme.title_large.text;
    let caption = &typo_theme.label_small.text;

    let mut themes = HashMap::new();

    let input_expand_padding = EdgeInsets { left: 16., right: 16., bottom: 16., top: 16. };

    let input_collapse_padding = EdgeInsets { left: 16., right: 16., bottom: 8., top: 8. };

    themes.insert(
      TextFieldState::Enabled,
      TextFieldTheme {
        foreground: palette.on_surface().into(),
        text: body.clone(),
        container_color: palette.surface_variant(),
        indicator: palette.on_surface_variant(),
        indicator_height: 1.,
        label_color: palette.on_surface_variant(),

        container_height: 56.,
        label_collapse: caption.clone(),
        label_expand: header.clone(),
        input_collapse_padding,
        input_expand_padding,
      },
    );

    themes.insert(
      TextFieldState::Focused,
      TextFieldTheme {
        foreground: palette.on_surface().into(),
        text: body.clone(),
        container_color: palette.surface_variant(),
        indicator: palette.primary(),
        indicator_height: 2.,
        label_color: palette.primary(),

        container_height: 56.,
        label_collapse: caption.clone(),
        label_expand: header.clone(),
        input_collapse_padding,
        input_expand_padding,
      },
    );

    themes.insert(
      TextFieldState::Hovered,
      TextFieldTheme {
        foreground: palette.on_surface().into(),
        text: body.clone(),
        container_color: palette.surface_variant(),
        indicator: palette.on_surface(),
        indicator_height: 2.,
        label_color: palette.on_surface(),

        container_height: 56.,
        label_collapse: caption.clone(),
        label_expand: header.clone(),
        input_collapse_padding,
        input_expand_padding,
      },
    );

    // themes.insert(
    //   TextFieldState::Disabled,
    //   TextFieldTheme {
    //     text: body.clone(),
    //     container_color: palette.on_surface(),
    //     indicator: palette.on_surface(),
    //     indicator_height: 2.,
    //     label_color: palette.on_surface(),

    //     container_height: 56.,
    //     label_collapse: caption.clone(),
    //     label_expand: header.clone(),
    //     input_collapse_padding: input_collapse_padding.clone(),
    //     input_expand_padding: input_expand_padding.clone(),
    //   },
    // );
    Self { themes }
  }
}

macro_rules! take_option_field {
  ({$($f: ident),+}, $c: ident) => {
    $(let $f = $c.$f.take();)+
  }
}

impl ComposeChild for TextField {
  type Child = Option<TextFieldTml>;
  fn compose_child(
    this: impl StateWriter<Value = Self>, config: Self::Child,
  ) -> impl WidgetBuilder {
    fn_widget! {
      let mut config = config.unwrap_or_default();
      take_option_field!({leading_icon, trailing_icon}, config);

      let theme_suit = TextFieldThemeSuit::of(ctx!());
      let theme = @TextFieldThemeProxy {
        suit: theme_suit,
        state: TextFieldState::default(),
      }.into_inner();
      let indicator_size = pipe!(Size::new(f32::MAX, $theme.indicator_height));
      let indicator_bg =  pipe!($theme.indicator);
      @Stack {
        @Container {
          size: pipe!(Size::new(0., $theme.container_height)),
          background: pipe!($theme.container_color),
        }
        @Row {
          justify_content: JustifyContent::Center,
          align_items: Align::Stretch,
          @{
            leading_icon.map(|t| @Icon {
              size: IconSize::of(ctx!()).small,
              @{ t.child() }
            })
          }
          @Expanded {
            flex: 1.,
            @{ build_content_area(this, theme, config) }
          }
          @{
            trailing_icon.map(|t| @Icon {
              size: IconSize::of(ctx!()).small,
              @{ t.child() }
            })
          }
        }
        @Container {
          v_align: VAlign::Bottom,
          size: indicator_size,
          background: indicator_bg,
        }
      }
    }
  }
}

fn build_input_area(
  this: impl StateWriter<Value = TextField>, theme: State<TextFieldThemeProxy>,
  prefix: Option<LeadingText>, suffix: Option<TrailingText>, placeholder: Option<Placeholder>,
) -> impl WidgetBuilder {
  fn_widget! {
    let mut input_area = @Row {
      visible: pipe!(!$this.text.is_empty() || $theme.state == TextFieldState::Focused),
    };
    input_area.get_visibility_widget()
      .map_writer(|w| PartData::from_ref(&w.visible))
      .transition(transitions::LINEAR.of(ctx!()), ctx!());

    let mut input = @Input{ style: pipe!($theme.text.clone()) };
    $input.write().set_text(&$this.text);

    watch!($input.text().clone())
      .distinct_until_changed()
      .subscribe(move |val| $this.silent().text = val.clone());

    let u = watch!($this.text.clone())
      .distinct_until_changed()
      .subscribe(move |val| $input.write().set_text(&val));

    let h = watch!($theme.state)
      .distinct_until_changed()
      .filter(|state| state == &TextFieldState::Focused)
      .subscribe(move |_| $input.request_focus());
    input = input.on_disposed(move|_| {
      h.unsubscribe();
      u.unsubscribe();
    });

    @Row {
      @{
        prefix.map(|p| @Text{
          text: p.child(),
          foreground: pipe!($theme.foreground.clone()),
          text_style: pipe!($theme.text.clone()),
        })
      }
      @Expanded {
        flex: 1.,
        @ $input { @{placeholder} }
      }
      @{
        suffix.map(|s| @Text{
          text: s.child(),
          foreground: pipe!($theme.foreground.clone()),
          text_style: pipe!($theme.text.clone()),
        })
      }
    }
  }
}

#[derive(Declare)]
struct TextFieldLabel {
  text: CowArc<str>,
  style: CowArc<TextStyle>,
}

impl Compose for TextFieldLabel {
  fn compose(this: impl StateWriter<Value = Self>) -> impl WidgetBuilder {
    fn_widget! {
      let label = @Text {
        v_align: VAlign::Top,
        text: pipe!($this.text.clone()),
        text_style: pipe!($this.style.clone()),
      };

      this.map_writer(|w| PartData::from_ref(&w.style.font_size))
        .transition(transitions::LINEAR.of(ctx!()), ctx!());

      label
    }
  }
}

fn build_content_area(
  this: impl StateWriter<Value = TextField>, theme: State<TextFieldThemeProxy>,
  mut config: TextFieldTml,
) -> impl WidgetBuilder {
  fn_widget! {
    take_option_field!({label, prefix, suffix, placeholder}, config);
    let mut content_area = @Column {
      padding: pipe!($theme.input_padding($this.text.is_empty())),
    };

    content_area
      .get_padding_widget()
      .map_writer(|w| PartData::from_ref(&w.padding))
      .transition(transitions::LINEAR.of(ctx!()), ctx!());

    @ $content_area {
      @ {
        label.map(|label| @Expanded {
          flex: 1.,
          @TextFieldLabel {
            text: label.0,
            style: pipe!($theme.label_style($this.text.is_empty())),
          }
        })
      }
      @ { build_input_area(this, theme, prefix, suffix, placeholder)}
    }
  }
}