/
style.rs
619 lines (533 loc) · 19.8 KB
/
style.rs
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
//! # Style
//! Styles are divided into two parts:
//! [`ComputedStyle`]: A style with definite values for most fields.
//!
//! [`Style`]: A style with [`StyleValue`]s for the fields, where `Unset` falls back to the relevant
//! field in the [`ComputedStyle`] and `Base` falls back to the underlying [`Style`] or the
//! [`ComputedStyle`].
//!
//!
//! A loose analogy with CSS might be:
//! [`ComputedStyle`] is like the browser's default style sheet for any given element (view).
//!
//! [`Style`] is like the styling associated with a *specific* element (view):
//! ```html
//! <div style="color: red; font-size: 12px;">
//! ```
//!
//! An override [`Style`] is perhaps closest to classes that can be applied to an element, like
//! `div:hover { color: blue; }`.
//! However, we do not actually have 'classes' where you can define a separate collection of styles
//! in the same way. So, the hover styling is still defined with the view as you construct it, so
//! perhaps a closer pseudocode analogy is:
//! ```html
//! <div hover_style="color: blue;" style="color: red; font-size: 12px;">
//! ```
//!
use floem_renderer::cosmic_text::{LineHeightValue, Style as FontStyle, Weight};
pub use taffy::style::{
AlignContent, AlignItems, Dimension, Display, FlexDirection, JustifyContent, Position,
};
use taffy::{
prelude::Rect,
style::{LengthPercentage, LengthPercentageAuto, Style as TaffyStyle},
};
use vello::peniko::Color;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextOverflow {
Wrap,
Clip,
Ellipsis,
}
#[derive(Debug, Clone, Copy)]
pub enum CursorStyle {
Default,
Pointer,
Text,
}
/// The value for a [`Style`] property
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StyleValue<T> {
Val(T),
/// Use the default value for the style, typically from the underlying `ComputedStyle`
Unset,
/// Use whatever the base style is. For an overriding style like hover, this uses the base
/// style. For the base style, this is equivalent to `Unset`
Base,
}
impl<T> StyleValue<T> {
pub fn map<U>(self, f: impl FnOnce(T) -> U) -> StyleValue<U> {
match self {
Self::Val(x) => StyleValue::Val(f(x)),
Self::Unset => StyleValue::Unset,
Self::Base => StyleValue::Base,
}
}
pub fn unwrap_or(self, default: T) -> T {
match self {
Self::Val(x) => x,
Self::Unset => default,
Self::Base => default,
}
}
pub fn unwrap_or_else(self, f: impl FnOnce() -> T) -> T {
match self {
Self::Val(x) => x,
Self::Unset => f(),
Self::Base => f(),
}
}
}
impl<T> Default for StyleValue<T> {
fn default() -> Self {
// By default we let the `Style` decide what to do.
Self::Base
}
}
impl<T> From<T> for StyleValue<T> {
fn from(x: T) -> Self {
Self::Val(x)
}
}
// Creates `ComputedStyle` which has definite values for the fields, barring some specific cases.
// Creates `Style` which has `StyleValue<T>`s for the fields
macro_rules! define_styles {
(
$($name:ident $($opt:ident)?: $typ:ty = $val:expr),* $(,)?
) => {
/// A style with definite values for most fields.
#[derive(Debug, Clone)]
pub struct ComputedStyle {
$(
pub $name: $typ,
)*
}
impl ComputedStyle {
$(
pub fn $name(mut self, v: impl Into<$typ>) -> Self {
self.$name = v.into();
self
}
)*
}
impl Default for ComputedStyle {
fn default() -> Self {
Self {
$(
$name: $val,
)*
}
}
}
#[derive(Debug, Clone)]
pub struct Style {
$(
pub $name: StyleValue<$typ>,
)*
}
impl Style {
pub const BASE: Style = Style{
$(
$name: StyleValue::Base,
)*
};
pub const UNSET: Style = Style{
$(
$name: StyleValue::Unset,
)*
};
$(
define_styles!(decl: $name $($opt)?: $typ = $val);
)*
/// Convert this `Style` into a computed style, using the given `ComputedStyle` as a base
/// for any missing values.
pub fn compute(self, underlying: &ComputedStyle) -> ComputedStyle {
ComputedStyle {
$(
$name: self.$name.unwrap_or_else(|| underlying.$name.clone()),
)*
}
}
/// Apply another `Style` to this style, returning a new `Style` with the overrides
///
/// `StyleValue::Val` will override the value with the given value
/// `StyleValue::Unset` will unset the value, causing it to fall back to the underlying
/// `ComputedStyle` (aka setting it to `None`)
/// `StyleValue::Base` will leave the value as-is, whether falling back to the underlying
/// `ComputedStyle` or using the value in the `Style`.
pub fn apply(self, over: Style) -> Style {
Style {
$(
$name: match (self.$name, over.$name) {
(_, StyleValue::Val(x)) => StyleValue::Val(x),
(StyleValue::Val(x), StyleValue::Base) => StyleValue::Val(x),
(StyleValue::Val(_), StyleValue::Unset) => StyleValue::Unset,
(StyleValue::Base, StyleValue::Base) => StyleValue::Base,
(StyleValue::Unset, StyleValue::Base) => StyleValue::Unset,
(StyleValue::Base, StyleValue::Unset) => StyleValue::Unset,
(StyleValue::Unset, StyleValue::Unset) => StyleValue::Unset,
},
)*
}
}
/// Apply multiple `Style`s to this style, returning a new `Style` with the overrides.
/// Later styles take precedence over earlier styles.
pub fn apply_overriding_styles(self, overrides: impl Iterator<Item = Style>) -> Style {
overrides.fold(self, |acc, x| acc.apply(x))
}
}
};
// internal submacro
// 'nocb' doesn't add a builder function
(decl: $name:ident nocb: $typ:ty = $val:expr) => {};
(decl: $name:ident: $typ:ty = $val:expr) => {
pub fn $name(mut self, v: impl Into<StyleValue<$typ>>) -> Self {
self.$name = v.into();
self
}
}
}
define_styles!(
display: Display = Display::Flex,
position: Position = Position::Relative,
width: Dimension = Dimension::Auto,
height: Dimension = Dimension::Auto,
min_width: Dimension = Dimension::Auto,
min_height: Dimension = Dimension::Auto,
max_width: Dimension = Dimension::Auto,
max_height: Dimension = Dimension::Auto,
flex_direction: FlexDirection = FlexDirection::Row,
flex_grow: f32 = 0.0,
flex_shrink: f32 = 1.0,
flex_basis: Dimension = Dimension::Auto,
justify_content: Option<JustifyContent> = None,
align_items: Option<AlignItems> = None,
align_content: Option<AlignContent> = None,
border_left: f32 = 0.0,
border_top: f32 = 0.0,
border_right: f32 = 0.0,
border_bottom: f32 = 0.0,
border_radius: f32 = 0.0,
border_color: Color = Color::BLACK,
padding_left: f32 = 0.0,
padding_top: f32 = 0.0,
padding_right: f32 = 0.0,
padding_bottom: f32 = 0.0,
margin_left: f32 = 0.0,
margin_top: f32 = 0.0,
margin_right: f32 = 0.0,
margin_bottom: f32 = 0.0,
cursor nocb: Option<CursorStyle> = None,
color nocb: Option<Color> = None,
background nocb: Option<Color> = None,
font_size nocb: Option<f32> = None,
font_family nocb: Option<String> = None,
font_weight nocb: Option<Weight> = None,
font_style nocb: Option<FontStyle> = None,
text_overflow: TextOverflow = TextOverflow::Wrap,
line_height nocb: Option<LineHeightValue> = None,
);
impl Style {
pub fn width_px(self, width: f32) -> Self {
self.width(Dimension::Points(width))
}
pub fn width_pct(self, width: f32) -> Self {
self.width(Dimension::Percent(width))
}
pub fn height_px(self, height: f32) -> Self {
self.height(Dimension::Points(height))
}
pub fn height_pct(self, height: f32) -> Self {
self.height(Dimension::Percent(height))
}
pub fn dimension(
self,
width: impl Into<StyleValue<Dimension>>,
height: impl Into<StyleValue<Dimension>>,
) -> Self {
self.width(width).height(height)
}
pub fn dimension_px(self, width: f32, height: f32) -> Self {
self.width_px(width).height_px(height)
}
pub fn dimension_pct(self, width: f32, height: f32) -> Self {
self.width_pct(width).height_pct(height)
}
pub fn min_width_px(self, min_width: f32) -> Self {
self.min_width(Dimension::Points(min_width))
}
pub fn min_width_pct(self, min_width: f32) -> Self {
self.min_width(Dimension::Percent(min_width))
}
pub fn min_height_px(self, min_height: f32) -> Self {
self.min_height(Dimension::Points(min_height))
}
pub fn min_height_pct(self, min_height: f32) -> Self {
self.min_height(Dimension::Percent(min_height))
}
pub fn min_dimension(
self,
min_width: impl Into<StyleValue<Dimension>>,
min_height: impl Into<StyleValue<Dimension>>,
) -> Self {
self.min_width(min_width).min_height(min_height)
}
pub fn min_dimension_px(self, min_width: f32, min_height: f32) -> Self {
self.min_width_px(min_width).min_height_px(min_height)
}
pub fn min_dimension_pct(self, min_width: f32, min_height: f32) -> Self {
self.min_width_pct(min_width).min_height_pct(min_height)
}
pub fn max_width_px(self, max_width: f32) -> Self {
self.max_width(Dimension::Points(max_width))
}
pub fn max_width_pct(self, max_width: f32) -> Self {
self.max_width(Dimension::Percent(max_width))
}
pub fn max_height_px(self, max_height: f32) -> Self {
self.max_height(Dimension::Points(max_height))
}
pub fn max_height_pct(self, max_height: f32) -> Self {
self.max_height(Dimension::Percent(max_height))
}
pub fn max_dimension(
self,
max_width: impl Into<StyleValue<Dimension>>,
max_height: impl Into<StyleValue<Dimension>>,
) -> Self {
self.max_width(max_width).max_height(max_height)
}
pub fn max_dimension_px(self, max_width: f32, max_height: f32) -> Self {
self.max_width_px(max_width).max_height_px(max_height)
}
pub fn max_dimension_pct(self, max_width: f32, max_height: f32) -> Self {
self.max_width_pct(max_width).max_height_pct(max_height)
}
pub fn border(self, border: f32) -> Self {
self.border_left(border)
.border_top(border)
.border_right(border)
.border_bottom(border)
}
/// Sets `border_left` and `border_right` to `border`
pub fn border_horiz(self, border: f32) -> Self {
self.border_left(border).border_right(border)
}
/// Sets `border_top` and `border_bottom` to `border`
pub fn border_vert(self, border: f32) -> Self {
self.border_top(border).border_bottom(border)
}
/// Set padding on all directions
pub fn padding(self, padding: f32) -> Self {
self.padding_left(padding)
.padding_top(padding)
.padding_right(padding)
.padding_bottom(padding)
}
/// Sets `padding_left` and `padding_right` to `padding`
pub fn padding_horiz(self, padding: f32) -> Self {
self.padding_left(padding).padding_right(padding)
}
/// Sets `padding_top` and `padding_bottom` to `padding`
pub fn padding_vert(self, padding: f32) -> Self {
self.padding_top(padding).padding_bottom(padding)
}
pub fn margin(self, margin: f32) -> Self {
self.margin_left(margin)
.margin_top(margin)
.margin_right(margin)
.margin_bottom(margin)
}
/// Sets `margin_left` and `margin_right` to `margin`
pub fn margin_horiz(self, margin: f32) -> Self {
self.margin_left(margin).margin_right(margin)
}
/// Sets `margin_top` and `margin_bottom` to `margin`
pub fn margin_vert(self, margin: f32) -> Self {
self.margin_top(margin).margin_bottom(margin)
}
pub fn cursor(mut self, cursor: impl Into<StyleValue<CursorStyle>>) -> Self {
self.cursor = cursor.into().map(Some);
self
}
pub fn color(mut self, color: impl Into<StyleValue<Color>>) -> Self {
self.color = color.into().map(Some);
self
}
pub fn background(mut self, color: impl Into<StyleValue<Color>>) -> Self {
self.background = color.into().map(Some);
self
}
pub fn font_size(mut self, size: impl Into<StyleValue<f32>>) -> Self {
self.font_size = size.into().map(Some);
self
}
pub fn font_family(mut self, family: impl Into<StyleValue<String>>) -> Self {
self.font_family = family.into().map(Some);
self
}
pub fn font_weight(mut self, weight: impl Into<StyleValue<Weight>>) -> Self {
self.font_weight = weight.into().map(Some);
self
}
pub fn font_style(mut self, style: impl Into<StyleValue<FontStyle>>) -> Self {
self.font_style = style.into().map(Some);
self
}
pub fn line_height(mut self, normal: f32) -> Self {
self.line_height = Some(LineHeightValue::Normal(normal)).into();
self
}
pub fn text_ellipsis(self) -> Self {
self.text_overflow(TextOverflow::Ellipsis)
}
pub fn text_clip(self) -> Self {
self.text_overflow(TextOverflow::Clip)
}
pub fn absolute(self) -> Self {
self.position(Position::Absolute)
}
pub fn items_start(self) -> Self {
self.align_items(Some(AlignItems::FlexStart))
}
/// Defines the alignment along the cross axis as Centered
pub fn items_center(self) -> Self {
self.align_items(Some(AlignItems::Center))
}
/// Defines the alignment along the main axis as Centered
pub fn justify_center(self) -> Self {
self.justify_content(Some(JustifyContent::Center))
}
pub fn justify_end(self) -> Self {
self.justify_content(Some(JustifyContent::End))
}
pub fn hide(self) -> Self {
self.display(Display::None)
}
pub fn flex_basis_px(self, pt: f32) -> Self {
self.flex_basis(Dimension::Points(pt))
}
pub fn flex_row(self) -> Self {
self.flex_direction(FlexDirection::Row)
}
pub fn flex_col(self) -> Self {
self.flex_direction(FlexDirection::Column)
}
/// Allow the application of a function if the option exists.
/// This is useful for chaining together a bunch of optional style changes.
/// ```rust,ignore
/// let style = Style::default()
/// .apply_opt(Some(5.0), Style::padding) // ran
/// .apply_opt(None, Style::margin) // not ran
/// .apply_opt(Some(5.0), |s, v| s.border_right(v * 2.0))
/// .border_left(5.0); // ran, obviously
/// ```
pub fn apply_opt<T>(self, opt: Option<T>, f: impl FnOnce(Self, T) -> Self) -> Self {
if let Some(t) = opt {
f(self, t)
} else {
self
}
}
/// Allow the application of a function if the condition holds.
/// This is useful for chaining together a bunch of optional style changes.
/// ```rust,ignore
/// let style = Style::default()
/// .apply_if(true, |s| s.padding(5.0)) // ran
/// .apply_if(false, |s| s.margin(5.0)) // not ran
/// ```
pub fn apply_if(self, cond: bool, f: impl FnOnce(Self) -> Self) -> Self {
if cond {
f(self)
} else {
self
}
}
}
impl ComputedStyle {
pub fn to_taffy_style(&self) -> TaffyStyle {
TaffyStyle {
display: self.display,
position: self.position,
size: taffy::prelude::Size {
width: self.width,
height: self.height,
},
min_size: taffy::prelude::Size {
width: self.min_width,
height: self.min_height,
},
max_size: taffy::prelude::Size {
width: self.max_width,
height: self.max_height,
},
flex_direction: self.flex_direction,
flex_grow: self.flex_grow,
flex_shrink: self.flex_shrink,
flex_basis: self.flex_basis,
justify_content: self.justify_content,
align_items: self.align_items,
align_content: self.align_content,
border: Rect {
left: LengthPercentage::Points(self.border_left),
top: LengthPercentage::Points(self.border_top),
right: LengthPercentage::Points(self.border_right),
bottom: LengthPercentage::Points(self.border_bottom),
},
padding: Rect {
left: LengthPercentage::Points(self.padding_left),
top: LengthPercentage::Points(self.padding_top),
right: LengthPercentage::Points(self.padding_right),
bottom: LengthPercentage::Points(self.padding_bottom),
},
margin: Rect {
left: LengthPercentageAuto::Points(self.margin_left),
top: LengthPercentageAuto::Points(self.margin_top),
right: LengthPercentageAuto::Points(self.margin_right),
bottom: LengthPercentageAuto::Points(self.margin_bottom),
},
..Default::default()
}
}
}
#[cfg(test)]
mod tests {
use super::{Style, StyleValue};
#[test]
fn style_override() {
let style1 = Style::BASE.padding_left(32.0);
let style2 = Style::BASE.padding_left(64.0);
let style = style1.apply(style2);
assert_eq!(style.padding_left, StyleValue::Val(64.0));
let style1 = Style::BASE.padding_left(32.0).padding_bottom(45.0);
let style2 = Style::BASE
.padding_left(64.0)
.padding_bottom(StyleValue::Base);
let style = style1.apply(style2);
assert_eq!(style.padding_left, StyleValue::Val(64.0));
assert_eq!(style.padding_bottom, StyleValue::Val(45.0));
let style1 = Style::BASE.padding_left(32.0).padding_bottom(45.0);
let style2 = Style::BASE
.padding_left(64.0)
.padding_bottom(StyleValue::Unset);
let style = style1.apply(style2);
assert_eq!(style.padding_left, StyleValue::Val(64.0));
assert_eq!(style.padding_bottom, StyleValue::Unset);
let style1 = Style::BASE.padding_left(32.0).padding_bottom(45.0);
let style2 = Style::BASE
.padding_left(64.0)
.padding_bottom(StyleValue::Unset);
let style3 = Style::BASE.padding_bottom(StyleValue::Base);
let style = style1.apply_overriding_styles([style2, style3].into_iter());
assert_eq!(style.padding_left, StyleValue::Val(64.0));
assert_eq!(style.padding_bottom, StyleValue::Unset);
let style1 = Style::BASE.padding_left(32.0).padding_bottom(45.0);
let style2 = Style::BASE
.padding_left(64.0)
.padding_bottom(StyleValue::Unset);
let style3 = Style::BASE.padding_bottom(StyleValue::Val(100.0));
let style = style1.apply_overriding_styles([style2, style3].into_iter());
assert_eq!(style.padding_left, StyleValue::Val(64.0));
assert_eq!(style.padding_bottom, StyleValue::Val(100.0));
}
}