-
Notifications
You must be signed in to change notification settings - Fork 213
Expand file tree
/
Copy pathstyle.rs
More file actions
5567 lines (4971 loc) · 187 KB
/
Copy pathstyle.rs
File metadata and controls
5567 lines (4971 loc) · 187 KB
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! # Style
//! Traits and functions that allow for styling `Views`.
//!
//! # The Floem Style System
//!
//! ## The [Style] struct
//!
//! The style system is centered around a [Style] struct.
//! `Style` internally is just a hashmap (although one from the im crate so it is cheap to clone).
//! It maps from a [StyleKey] to `Rc<dyn Any>`.
//!
//! ## The [StyleKey]
//!
//! [StyleKey] holds a static reference (that is used as the hash value) to a [StyleKeyInfo] enum which enumerates the different kinds of values that can be in the map.
//! Which value is in the `StyleKeyInfo` enum is used to know how to downcast the `Rc<dyn Any`.
//!
//! The key types from the [StyleKeyInfo] are: (these are all of the different things that can be added to a [Style]).
//! - Transition,
//! - Prop(StylePropInfo),
//! - Selector(StyleSelectors),
//! - Class(StyleClassInfo),
//! - ContextMappings,
//!
//! Transitions and context mappings don't hold any extra information, they are just used to know how to downcast the `Rc<dyn Any>`.
//!
//! [StyleSelectors] is a bit mask of which selectors are active.
//!
//! [StyleClassInfo] holds a function pointer that returns the name of the class as a String.
//! The function pointer is basically used as a vtable for the class.
//! If classes needed more methods other than `name`, those methods would be added to `StyleClassInfo`.
//!
//! [StylePropInfo] is another vtable, similar to `StyleClassInfo` and holds function pointers for getting the name of a prop, the props interpolation function from the [StylePropValue] trait, the associated transition key for the prop, and others.
//!
//! Props store props.
//! Transitions store transition values.
//! Classes, context mappings, and selectors store nested [Style] maps.
//!
//! ## Applying `Style`s to `View`s
//!
//! A style can be applied to a view in two different ways.
//! A single `Style` can be added to the [view_style](crate::view::View::view_style) method of the view trait or multiple `Style`s can be added by calling [style](crate::views::Decorators::style) on an `IntoView` from the [Decorators](crate::views::Decorators) trait.
//!
//! Calls to `style` from the decorators trait have a higher precedence than the `view_style` method, meaning calls to `style` will override any matching `StyleKeyInfo` that came from the `view_style` method.
//!
//! If you make repeated calls to `style` from the decorators trait, each will be added separately to the `ViewState` that is managed by Floem and associated with the `ViewId` of the view that `style` was called on.
//! The `ViewState` stores a `Stack` of styles and later calls to `style` (and thus larger indicies in the style stack) will take precedence over earlier calls.
//!
//! `style` from the deocrators trait is reactive and the function that returns the style map with be re-run in response to any reactive updates that it depends on.
//! If it gets a reactive update, it will have tracked which index into the style stack it had when it was first called and will overrite that index and only that index so that other calls to `style` are not affected.
//!
//! ## Style Resolution
//!
//! A final `computed_style` is resolved in the `style_pass` of the `View` trait.
//!
//! ### Context
//!
//! It first received a `Style` map that is used as context.
//! The context is passed down the view tree and carries the inherited properties that were applied to any parent.
//! Inherited properties include all classes and any prop that has been marked as `inherited`.
//!
//! ### View Style
//!
//! The `style` first gets the `Style` (if any) from the `view_style` method.
//!
//! ### Style
//!
//! Then it gets the style from any calls to `style` from the decorators trait.
//! It starts with the first index in the style `Stack` and applies each successive `Style` over the combination of any previous ones.
//!
//! Then the style from the `Decorators` / `ViewState` is applied over (overriding any matching props) the style from `view_style`.
//!
//!
//! ### Nested map resolution
//!
//! Then any classes that have been applied to the view, and the active selector set are used to resolve nested maps.
//!
//! Nested maps such as classes and selectors are recursively applied, breadth first. So, deeper / more nested style maps take precendence.
//!
//! This style map is the combined style of the `View`.
//!
//! ### Updated context
//!
//! Finally, the context style is updated using the combined style, applying any style key that is `inherited` to the context so that the children will have acces to them.
//!
//! ## Prop Extraction
//!
//! The final computed style of a view will be passed to the `style_pass` method from the `View` trait.
//!
//! Views will store fields that are struct that are prop extractors.
//! These structs are created using the `prop_extractor!` macro.
//!
//! These structs can then be used from in the `style_pass` to extract props using the `read` (or `read_exact`) methods that are created by the `prop_extractor` macro.
//!
//! The read methods will take in the combined style for that `View` and will automatically extract any matching prop values and transitions for those props.
//!
//! ### Transition interpolation
//!
//! If there is a transition for a prop, the extractor will keep track of the current time and transition state and will set the final extracted value to a properly interpolated value using the state and current time.
//!
//!
//! ## Custom Style Props, Classes, and Extractors.
//!
//!
//! You can create custom style props with the [prop!] macro, classes with the [style_class!] macro, and extractors with the [prop_extractor!] macro.
//!
//!
//! ### Custom Props
//!
//! You can create custom props.
//!
//! Doing this allows you to store arbitrary values in the style system.
//!
//! You can use these to style the view, change it's behavior, update it's state, or anything else.
//!
//! By implementing the [StylePropValue] trait for your prop (which you must do) you can
//!
//! - optionally set how the prop should be interpolated (allowing you to customize what interpolating means in the context of your prop)
//!
//! - optionally provide a `debug_view` for your prop, which debug view will be used in the Floem inspector. This means that you can customize a complex debug experience for your prop with very little effort (and it really can be any arbitrary view. no restrictions.)
//!
//! - optionally add a custom implementation of how a prop should be combined with another prop. This is different from interpolation and is useful when you want to specify how properties should override each other. The default implementation just replaces the old value with a new value, but if you have a prop with multiple optional fields, you might want to only replace the fields that have a `Some` value.
//!
//! ### Custom Classes
//!
//! If you create a custom class, you can apply that class to any view, and when the final style for that view is being resolved, if the style has that class as a nested map, it will be applied, overriding any prviously set values.
//!
//! ### Custom Extractors
//!
//! You can create custom extractors and embed them in your custom views so that you can get out any built in prop, or any of your custom props from the final combined style that is applied to your `View`.
use floem_reactive::{RwSignal, SignalGet, SignalUpdate as _, create_updater};
use floem_renderer::Renderer;
use floem_renderer::text::{LineHeightValue, Weight};
use imbl::hashmap::Entry;
use imbl::shared_ptr::DefaultSharedPtr;
use peniko::color::{HueDirection, palette};
use peniko::kurbo::{self, Point, Stroke};
use peniko::{
Brush, Color, ColorStop, ColorStops, Gradient, GradientKind, InterpolationAlphaSpace,
LinearGradientPosition,
};
use rustc_hash::FxHasher;
use smallvec::SmallVec;
use std::any::{Any, type_name};
use std::collections::HashMap;
use std::fmt::{self, Debug};
use std::hash::Hasher;
use std::hash::{BuildHasherDefault, Hash};
use std::ptr;
use std::rc::Rc;
use taffy::GridTemplateComponent;
use taffy::prelude::{auto, fr};
#[cfg(not(target_arch = "wasm32"))]
use std::time::{Duration, Instant};
#[cfg(target_arch = "wasm32")]
use web_time::{Duration, Instant};
pub use taffy::style::{
AlignContent, AlignItems, BoxSizing, Dimension, Display, FlexDirection, FlexWrap,
JustifyContent, JustifyItems, Position,
};
use taffy::{
geometry::{MinMax, Size},
prelude::{GridPlacement, Line, Rect},
style::{
LengthPercentage, MaxTrackSizingFunction, MinTrackSizingFunction, Overflow,
Style as TaffyStyle,
},
};
use crate::context::InteractionState;
use crate::prelude::ViewTuple;
use crate::responsive::{ScreenSize, ScreenSizeBp};
use crate::theme::StyleThemeExt;
use crate::unit::{Pct, Px, PxPct, PxPctAuto, UnitExt};
use crate::view::{IntoView, View};
use crate::view_tuple::ViewTupleFlat;
use crate::views::{
ContainerExt, Decorators, TooltipExt, canvas, empty, h_stack, label, stack, text, v_stack,
v_stack_from_iter,
};
use crate::{AnyView, easing::*};
pub enum CombineResult<T> {
Other, // The result is semantically `other` - caller can reuse it
New(T), // A new value was created
}
pub trait StylePropValue: Clone + PartialEq + Debug {
fn debug_view(&self) -> Option<Box<dyn View>> {
None
}
fn interpolate(&self, _other: &Self, _value: f64) -> Option<Self> {
None
}
fn combine(&self, _other: &Self) -> CombineResult<Self> {
CombineResult::Other
}
}
impl StylePropValue for i32 {
fn interpolate(&self, other: &Self, value: f64) -> Option<Self> {
Some((*self as f64 + (*other as f64 - *self as f64) * value).round() as i32)
}
}
impl StylePropValue for bool {}
impl StylePropValue for f32 {
fn interpolate(&self, other: &Self, value: f64) -> Option<Self> {
Some(*self * (1.0 - value as f32) + *other * value as f32)
}
}
impl StylePropValue for u16 {
fn interpolate(&self, other: &Self, value: f64) -> Option<Self> {
Some((*self as f64 + (*other as f64 - *self as f64) * value).round() as u16)
}
}
impl StylePropValue for usize {
fn interpolate(&self, other: &Self, value: f64) -> Option<Self> {
Some((*self as f64 + (*other as f64 - *self as f64) * value).round() as usize)
}
}
impl StylePropValue for f64 {
fn interpolate(&self, other: &Self, value: f64) -> Option<Self> {
Some(*self * (1.0 - value) + *other * value)
}
}
impl StylePropValue for Overflow {}
impl StylePropValue for Display {}
impl StylePropValue for Position {}
impl StylePropValue for FlexDirection {}
impl StylePropValue for FlexWrap {}
impl StylePropValue for AlignItems {}
impl StylePropValue for BoxSizing {}
impl StylePropValue for AlignContent {}
impl StylePropValue for GridTemplateComponent<String> {}
impl StylePropValue for MinTrackSizingFunction {}
impl StylePropValue for MaxTrackSizingFunction {}
impl<T: StylePropValue, M: StylePropValue> StylePropValue for MinMax<T, M> {}
impl<T: StylePropValue> StylePropValue for Line<T> {}
impl StylePropValue for taffy::GridAutoFlow {}
impl StylePropValue for GridPlacement {}
impl StylePropValue for CursorStyle {}
impl StylePropValue for BoxShadow {
fn debug_view(&self) -> Option<Box<dyn View>> {
// Create a preview container that shows a visual representation of the shadow
let shadow = *self;
// Shadow preview box
let shadow_preview = empty()
.style(move |s| s.width(50.0).height(50.0))
.container()
.style(move |s| {
s.with_theme(|s, t| {
s.background(Color::TRANSPARENT)
.border_color(t.border())
.border(1.)
.border_radius(t.border_radius())
})
.apply_box_shadows(vec![shadow])
.margin(10.0)
});
// Create a details section showing the shadow properties
let details_view = move || {
v_stack((
h_stack((
"Color:".style(|s| s.font_weight(Weight::BOLD).width(80.0)),
shadow.color.debug_view().unwrap(),
))
.style(|s| s.items_center().gap(4.0)),
h_stack((
"Blur:".style(|s| s.font_weight(Weight::BOLD).width(80.0)),
format!("{:?}", shadow.blur_radius),
))
.style(|s| s.items_center().gap(4.0)),
h_stack((
"Spread:".style(|s| s.font_weight(Weight::BOLD).width(80.0)),
format!("{:?}", shadow.spread),
))
.style(|s| s.items_center().gap(4.0)),
h_stack((
"Offset:".style(|s| s.font_weight(Weight::BOLD).width(80.0)),
format!(
"L: {:?}, R: {:?}, T: {:?}, B: {:?}",
shadow.left_offset,
shadow.right_offset,
shadow.top_offset,
shadow.bottom_offset
),
))
.style(|s| s.items_center().gap(4.0)),
))
.style(|s| s.gap(4.0).padding(8.0))
};
// Combine preview and details
let view = shadow_preview.tooltip(details_view);
Some(view.into_any())
}
fn interpolate(&self, other: &Self, value: f64) -> Option<Self> {
Some(Self {
blur_radius: self
.blur_radius
.interpolate(&other.blur_radius, value)
.unwrap(),
color: self.color.interpolate(&other.color, value).unwrap(),
spread: self.spread.interpolate(&other.spread, value).unwrap(),
left_offset: self
.left_offset
.interpolate(&other.left_offset, value)
.unwrap(),
right_offset: self
.right_offset
.interpolate(&other.right_offset, value)
.unwrap(),
top_offset: self
.top_offset
.interpolate(&other.top_offset, value)
.unwrap(),
bottom_offset: self
.bottom_offset
.interpolate(&other.bottom_offset, value)
.unwrap(),
})
}
}
impl<A: smallvec::Array> StylePropValue for SmallVec<A>
where
<A as smallvec::Array>::Item: StylePropValue,
{
fn debug_view(&self) -> Option<Box<dyn View>> {
if self.is_empty() {
return Some(
text("smallvec\n[]")
.style(|s| s.with_theme(|s, t| s.color(t.text_muted())))
.into_any(),
);
}
let count = self.len();
let is_spilled = self.spilled();
// Create a preview that shows count and whether it has spilled to heap
let preview = label(move || {
if is_spilled {
format!("smallvec\n[{}] (heap)", count)
} else {
format!("smallvec\n[{}] (inline)", count)
}
})
.style(|s| {
s.padding(2.0)
.padding_horiz(6.0)
.items_center()
.justify_center()
.text_align(floem_renderer::text::Align::Center)
.border(1.)
.border_radius(5.0)
.margin_left(6.0)
.with_theme(|s, t| s.color(t.text()).border_color(t.border()))
.with_context_opt::<FontSize, _>(|s, fs| s.font_size(fs * 0.85))
});
// Clone items for the tooltip view
let items = self.clone();
let tooltip_view = move || {
v_stack_from_iter(items.iter().enumerate().map(|(i, item)| {
let index_label = text(format!("[{}]", i))
.style(|s| s.with_theme(|s, t| s.color(t.text_muted())));
let item_view = item.debug_view().unwrap_or_else(|| {
text(format!("{:?}", item))
.style(|s| s.flex_grow(1.0))
.into_any()
});
stack((index_label, item_view)).style(|s| s.items_center().gap(8.0).padding(4.0))
}))
.style(|s| s.gap(4.0))
};
// Return the tooltip view wrapped in the preview
Some(
stack((preview, tooltip_view()))
.style(|s| s.gap(8.0))
.into_any(),
)
}
fn interpolate(&self, other: &Self, value: f64) -> Option<Self> {
self.iter().zip(other.iter()).try_fold(
SmallVec::with_capacity(self.len()),
|mut acc, (v1, v2)| {
if let Some(interpolated) = v1.interpolate(v2, value) {
acc.push(interpolated);
Some(acc)
} else {
None
}
},
)
}
}
impl StylePropValue for String {}
impl StylePropValue for Weight {
fn debug_view(&self) -> Option<Box<dyn View>> {
let clone = *self;
Some(
format!("{clone:?}")
.style(move |s| s.font_weight(clone))
.into_any(),
)
}
fn interpolate(&self, other: &Self, value: f64) -> Option<Self> {
self.0.interpolate(&other.0, value).map(Weight)
}
}
impl StylePropValue for crate::text::Style {
fn debug_view(&self) -> Option<Box<dyn View>> {
let clone = *self;
Some(
format!("{clone:?}")
.style(move |s| s.font_style(clone))
.into_any(),
)
}
}
impl StylePropValue for crate::text::Align {}
impl StylePropValue for TextOverflow {}
impl StylePropValue for PointerEvents {}
impl StylePropValue for LineHeightValue {
fn interpolate(&self, other: &Self, value: f64) -> Option<Self> {
match (self, other) {
(LineHeightValue::Normal(v1), LineHeightValue::Normal(v2)) => {
v1.interpolate(v2, value).map(LineHeightValue::Normal)
}
(LineHeightValue::Px(v1), LineHeightValue::Px(v2)) => {
v1.interpolate(v2, value).map(LineHeightValue::Px)
}
_ => None,
}
}
}
impl StylePropValue for Size<LengthPercentage> {}
impl<T: StylePropValue> StylePropValue for Option<T> {
fn debug_view(&self) -> Option<Box<dyn View>> {
self.as_ref().and_then(|v| v.debug_view())
}
fn interpolate(&self, other: &Self, value: f64) -> Option<Self> {
self.as_ref().and_then(|this| {
other
.as_ref()
.and_then(|other| this.interpolate(other, value).map(Some))
})
}
}
impl<T: StylePropValue + 'static> StylePropValue for Vec<T> {
fn debug_view(&self) -> Option<Box<dyn View>> {
if self.is_empty() {
return Some(
text("[]")
.style(|s| s.with_theme(|s, t| s.color(t.text_muted())))
.into_any(),
);
}
let count = self.len();
let _preview = label(move || format!("[{}]", count)).style(|s| {
s.padding(2.0)
.padding_horiz(6.0)
.border(1.)
.border_radius(5.0)
.margin_left(6.0)
.with_theme(|s, t| s.color(t.text()).border_color(t.border()))
.with_context_opt::<FontSize, _>(|s, fs| s.font_size(fs * 0.85))
});
let items = self.clone();
let tooltip_view = move || {
v_stack_from_iter(items.iter().enumerate().map(|(i, item)| {
let index_label = text(format!("[{}]", i))
.style(|s| s.with_theme(|s, t| s.color(t.text_muted())));
let item_view = item.debug_view().unwrap_or_else(|| {
text(format!("{:?}", item))
.style(|s| s.flex_grow(1.0))
.into_any()
});
stack((index_label, item_view)).style(|s| s.items_center().gap(8.0).padding(4.0))
}))
.style(|s| s.gap(4.0))
};
Some(
// preview
tooltip_view().into_any(),
)
}
fn interpolate(&self, other: &Self, value: f64) -> Option<Self> {
self.iter().zip(other.iter()).try_fold(
Vec::with_capacity(self.len()),
|mut acc, (v1, v2)| {
if let Some(interpolated) = v1.interpolate(v2, value) {
acc.push(interpolated);
Some(acc)
} else {
None
}
},
)
}
}
impl StylePropValue for Px {
fn debug_view(&self) -> Option<Box<dyn View>> {
Some(text(format!("{} px", self.0)).into_any())
}
fn interpolate(&self, other: &Self, value: f64) -> Option<Self> {
self.0.interpolate(&other.0, value).map(Px)
}
}
impl StylePropValue for Pct {
fn debug_view(&self) -> Option<Box<dyn View>> {
Some(text(format!("{}%", self.0)).into_any())
}
fn interpolate(&self, other: &Self, value: f64) -> Option<Self> {
self.0.interpolate(&other.0, value).map(Pct)
}
}
impl StylePropValue for PxPctAuto {
fn debug_view(&self) -> Option<Box<dyn View>> {
let label = match self {
Self::Px(v) => format!("{v} px"),
Self::Pct(v) => format!("{v}%"),
Self::Auto => "auto".to_string(),
};
Some(text(label).into_any())
}
fn interpolate(&self, other: &Self, value: f64) -> Option<Self> {
match (self, other) {
(Self::Px(v1), Self::Px(v2)) => Some(Self::Px(v1 + (v2 - v1) * value)),
(Self::Pct(v1), Self::Pct(v2)) => Some(Self::Pct(v1 + (v2 - v1) * value)),
(Self::Auto, Self::Auto) => Some(Self::Auto),
// TODO: Figure out some way to get in the relevant layout information in order to interpolate between pixels and percent
_ => None,
}
}
}
impl StylePropValue for PxPct {
fn debug_view(&self) -> Option<Box<dyn View>> {
let label = match self {
Self::Px(v) => format!("{v} px"),
Self::Pct(v) => format!("{v}%"),
};
Some(text(label).into_any())
}
fn interpolate(&self, other: &Self, value: f64) -> Option<Self> {
match (self, other) {
(Self::Px(v1), Self::Px(v2)) => Some(Self::Px(v1 + (v2 - v1) * value)),
(Self::Pct(v1), Self::Pct(v2)) => Some(Self::Pct(v1 + (v2 - v1) * value)),
// TODO: Figure out some way to get in the relevant layout information in order to interpolate between pixels and percent
_ => None,
}
}
}
fn views(views: impl ViewTuple) -> Vec<AnyView> {
views.into_views()
}
impl StylePropValue for Color {
fn debug_view(&self) -> Option<Box<dyn View>> {
let color = *self;
let swatch = empty()
.style(move |s| {
s.background(color)
.width(22.0)
.height(14.0)
.border(1.)
.border_color(palette::css::WHITE.with_alpha(0.5))
.border_radius(5.0)
})
.container()
.style(|s| {
s.border(1.)
.border_color(palette::css::BLACK.with_alpha(0.5))
.border_radius(5.0)
});
let tooltip_view = move || {
// Convert to RGBA8 for standard representations
let c = color.to_rgba8();
let (r, g, b, a) = (c.r, c.g, c.b, c.a);
// Hex representation
let hex = if a == 255 {
format!("#{:02X}{:02X}{:02X}", r, g, b)
} else {
format!("#{:02X}{:02X}{:02X}{:02X}", r, g, b, a)
};
// RGBA string
let rgba_str = format!("rgba({}, {}, {}, {:.3})", r, g, b, a as f32 / 255.0);
// Alpha percentage
let alpha_str = format!(
"{:.1}% ({:.3})",
(a as f32 / 255.0) * 100.0,
a as f32 / 255.0
);
let components = color.components;
let color_space_str = format!("{:?}", color.cs);
let hex = views((
"Hex:".style(|s| s.font_bold().min_width(80.0).justify_end()),
label(move || hex.clone()),
));
let rgba = views((
"RGBA:".style(|s| s.font_bold().min_width(80.0).justify_end()),
label(move || rgba_str.clone()),
));
let components = views((
"Components:".style(|s| s.font_bold().min_width(80.0).justify_end()),
(
label(move || format!("[0]: {:.3}", components[0])),
label(move || format!("[1]: {:.3}", components[1])),
label(move || format!("[2]: {:.3}", components[2])),
label(move || format!("[3]: {:.3}", components[3])),
)
.v_stack()
.style(|s| s.gap(2.0)),
));
let color_space = views((
"Color Space:".style(|s| s.font_bold().min_width(80.0).justify_end()),
label(move || color_space_str.clone()),
));
let alpha = views((
"Alpha:".style(|s| s.font_bold().min_width(80.0).justify_end()),
label(move || alpha_str.clone()),
));
(hex, rgba, components, color_space, alpha)
.flatten()
.style(|s| {
s.grid()
.grid_template_columns([auto(), fr(1.)])
.justify_center()
.items_center()
.row_gap(20)
.col_gap(10)
.padding(30)
})
};
Some(
swatch
.tooltip(tooltip_view)
.style(|s| s.items_center())
.into_any(),
)
}
fn interpolate(&self, other: &Self, value: f64) -> Option<Self> {
Some(self.lerp(*other, value as f32, HueDirection::default()))
}
}
impl StylePropValue for Gradient {
fn debug_view(&self) -> Option<Box<dyn View>> {
let box_width = 22.;
let box_height = 14.;
let mut grad = self.clone();
grad.kind = match grad.kind {
GradientKind::Linear(LinearGradientPosition { start, end }) => {
let dx = end.x - start.x;
let dy = end.y - start.y;
let scale_x = box_width / dx.abs();
let scale_y = box_height / dy.abs();
let scale = scale_x.min(scale_y);
let new_dx = dx * scale;
let new_dy = dy * scale;
let new_start = Point {
x: if dx > 0.0 { 0.0 } else { box_width },
y: if dy > 0.0 { 0.0 } else { box_height },
};
let new_end = Point {
x: new_start.x + new_dx,
y: new_start.y + new_dy,
};
GradientKind::Linear(LinearGradientPosition {
start: new_start,
end: new_end,
})
}
_ => grad.kind,
};
let color = empty().style(move |s| {
s.background(grad.clone())
.width(box_width)
.height(box_height)
.border(1.)
.border_color(palette::css::WHITE.with_alpha(0.5))
.border_radius(5.0)
});
let color = color.container().style(|s| {
s.border(1.)
.border_color(palette::css::BLACK.with_alpha(0.5))
.border_radius(5.0)
.margin_left(6.0)
});
Some(
stack((text(format!("{self:?}")), color))
.style(|s| s.items_center())
.into_any(),
)
}
fn interpolate(&self, _other: &Self, _value: f64) -> Option<Self> {
None
/*
let mut interpolated_stops = ColorStops::new();
let mut i = 0;
let mut j = 0;
while i < self.stops.len() && j < other.stops.len() {
let stop1 = &self.stops[i];
let stop2 = &other.stops[j];
if stop1.offset == stop2.offset {
let interpolated_color = stop1.color.interpolate(&stop2.color, value).unwrap();
interpolated_stops.push(ColorStop::from((stop1.offset, interpolated_color)));
i += 1;
j += 1;
} else if stop1.offset < stop2.offset {
if j > 0 {
let prev_stop2 = &other.stops[j - 1];
let t = (stop1.offset - prev_stop2.offset) / (stop2.offset - prev_stop2.offset);
let interpolated_color = prev_stop2
.color
.interpolate(&stop2.color, t as f64)
.unwrap();
interpolated_stops.push(ColorStop::from((stop1.offset, interpolated_color)));
} else {
interpolated_stops.push(*stop1);
}
i += 1;
} else {
if i > 0 {
let prev_stop1 = &self.stops[i - 1];
let t = (stop2.offset - prev_stop1.offset) / (stop1.offset - prev_stop1.offset);
let interpolated_color = prev_stop1
.color
.interpolate(&stop1.color, t as f64)
.unwrap();
interpolated_stops.push(ColorStop::from((stop2.offset, interpolated_color)));
} else {
interpolated_stops.push(*stop2);
}
j += 1;
}
}
while i < self.stops.len() {
let stop1 = &self.stops[i];
if !other.stops.is_empty() {
let last_stop2 = &other.stops.last().unwrap();
let interpolated_color = stop1.color.interpolate(&last_stop2.color, value).unwrap();
interpolated_stops.push(ColorStop::from((stop1.offset, interpolated_color)));
} else {
interpolated_stops.push(*stop1);
}
i += 1;
}
while j < other.stops.len() {
let stop2 = &other.stops[j];
if !self.stops.is_empty() {
let last_stop1 = &self.stops.last().unwrap();
let interpolated_color = last_stop1.color.interpolate(&stop2.color, value).unwrap();
interpolated_stops.push(ColorStop::from((stop2.offset, interpolated_color)));
} else {
interpolated_stops.push(*stop2);
}
j += 1;
}
Some(Self {
kind: self.kind,
extend: self.extend,
stops: interpolated_stops,
})
*/
}
}
// this is necessary because Stroke doesn't impl partial eq. it probably should...
#[derive(Clone, Debug, Default)]
pub struct StrokeWrap(pub Stroke);
impl StrokeWrap {
fn new(width: f64) -> Self {
Self(Stroke::new(width))
}
}
impl PartialEq for StrokeWrap {
fn eq(&self, other: &Self) -> bool {
let self_stroke = &self.0;
let other_stroke = &other.0;
self_stroke.width == other_stroke.width
&& self_stroke.join == other_stroke.join
&& self_stroke.miter_limit == other_stroke.miter_limit
&& self_stroke.start_cap == other_stroke.start_cap
&& self_stroke.end_cap == other_stroke.end_cap
&& self_stroke.dash_pattern == other_stroke.dash_pattern
&& self_stroke.dash_offset == other_stroke.dash_offset
}
}
impl From<Stroke> for StrokeWrap {
fn from(value: Stroke) -> Self {
Self(value)
}
}
impl From<f32> for StrokeWrap {
fn from(value: f32) -> Self {
Self(Stroke::new(value.into()))
}
}
impl From<f64> for StrokeWrap {
fn from(value: f64) -> Self {
Self(Stroke::new(value))
}
}
impl From<i32> for StrokeWrap {
fn from(value: i32) -> Self {
Self(Stroke::new(value.into()))
}
}
impl StylePropValue for StrokeWrap {
fn debug_view(&self) -> Option<Box<dyn View>> {
let stroke = self.0.clone();
let clone = stroke.clone();
let color = RwSignal::new(palette::css::RED);
// Visual preview of the stroke
let preview = canvas(move |cx, size| {
cx.stroke(
&kurbo::Line::new(
Point::new(0., size.height / 2.),
Point::new(size.width, size.height / 2.),
),
color.get(),
&clone,
);
})
.style(move |s| s.width(80.0).height(20.0))
.container()
.style(move |s| {
s.with_theme(move |s, t| {
color.set(t.primary());
s.border_color(t.border())
})
.padding(4.0)
});
let tooltip_view = move || {
let stroke = stroke.clone();
let width_row = views((
"Width:".style(|s| s.font_bold().min_width(100.0).justify_end()),
label(move || format!("{:.1}px", stroke.width)),
));
let join_row = views((
"Join:".style(|s| s.font_bold().min_width(100.0).justify_end()),
label(move || format!("{:?}", stroke.join)),
));
let miter_row = views((
"Miter Limit:".style(|s| s.font_bold().min_width(100.0).justify_end()),
label(move || format!("{:.2}", stroke.miter_limit)),
));
let start_cap_row = views((
"Start Cap:".style(|s| s.font_bold().min_width(100.0).justify_end()),
label(move || format!("{:?}", stroke.start_cap)),
));
let end_cap_row = views((
"End Cap:".style(|s| s.font_bold().min_width(100.0).justify_end()),
label(move || format!("{:?}", stroke.end_cap)),
));
let pattern_clone = stroke.dash_pattern.clone();
let dash_pattern_row = views((
"Dash Pattern:".style(|s| s.font_bold().min_width(100.0).justify_end()),
label(move || {
if pattern_clone.is_empty() {
"Solid".to_string()
} else {
format!("{:?}", pattern_clone.as_slice())
}
}),
));
let dash_offset_row = if !stroke.dash_pattern.is_empty() {
Some(views((
"Dash Offset:".style(|s| s.font_bold().min_width(100.0).justify_end()),
label(move || format!("{:.1}", stroke.dash_offset)),
)))
} else {
None
};
let mut rows = vec![
width_row.into_any(),
join_row.into_any(),
miter_row.into_any(),
start_cap_row.into_any(),
end_cap_row.into_any(),
dash_pattern_row.into_any(),
];
if let Some(offset_row) = dash_offset_row {
rows.push(offset_row.into_any());
}
v_stack_from_iter(rows).style(|s| {
s.grid()
.grid_template_columns([auto(), fr(1.)])
.justify_center()
.items_center()
.row_gap(12)
.col_gap(10)
.padding(20)
})
};
Some(
preview
.tooltip(tooltip_view)
.style(|s| s.items_center())
.into_any(),
)
}
}
impl StylePropValue for Brush {
fn debug_view(&self) -> Option<Box<dyn View>> {
match self {
Brush::Solid(color) => color.debug_view(),
Brush::Gradient(grad) => grad.debug_view(),
Brush::Image(_) => None,
}
}
fn interpolate(&self, other: &Self, value: f64) -> Option<Self> {
match (self, other) {
(Brush::Solid(color), Brush::Solid(other)) => Some(Self::Solid(color.lerp(
*other,
value as f32,
HueDirection::default(),
))),
(Brush::Gradient(gradient), Brush::Solid(solid)) => {
let interpolated_stops: Vec<ColorStop> = gradient
.stops
.iter()
.map(|stop| {
let interpolated_color = stop.color.to_alpha_color().lerp(
*solid,
value as f32,
HueDirection::default(),
);
ColorStop::from((stop.offset, interpolated_color))
})
.collect();
Some(Brush::Gradient(Gradient {
kind: gradient.kind,
extend: gradient.extend,
interpolation_cs: gradient.interpolation_cs,
hue_direction: gradient.hue_direction,
stops: ColorStops::from(&*interpolated_stops),
interpolation_alpha_space: InterpolationAlphaSpace::Premultiplied,
}))