waterui-internal 0.3.0

Internal implementation crate for WaterUI
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
//! This module provides extension traits and builder patterns for creating and configuring views.
//!
//! # Overview
//!
//! The module implements:
//! - `ConfigViewExt`: Extends configurable views with common modifier patterns
//! - `ViewBuilder`: A trait for objects that can build views from an environment
//! - `ViewExt`: Extends all views with common styling and configuration methods
//!
//! These extensions help create a fluent API for constructing user interfaces.

use executor_core::spawn_local;
use nami::{Binding, Signal, SignalExt as _, signal::IntoComputed};
use waterui_core::IntoSignalF32;
pub use waterui_core::view::*;
use waterui_core::{
    AnyView, Environment, IgnorableMetadata, Retain,
    env::{With, use_env},
    extract::State,
    handler::{Handler, HandlerOnce},
    layout::{HorizontalAlignment, VerticalAlignment, ViewDimensions},
    metadata::MetadataKey,
    plugin::Plugin,
};
use waterui_graphics::color::Color;

/// All view-level GPU filter modifiers (`.blur()`, `.brightness()`, ...) come
/// from [`waterui_graphics::filter_view::FilterViewExt`]. This re-export
/// makes them part of the `WaterUI` prelude alongside [`ViewExt`], so a single
/// `use waterui::prelude::*;` is enough.
#[cfg(feature = "gpu")]
pub use waterui_graphics::filter_view::FilterViewExt;

use waterui_layout::{
    AspectRatio, ContentMode, EdgeSet, HorizontalAlignmentGuide, IgnoreSafeArea, LayoutPriority,
    Overlay, VerticalAlignmentGuide,
    frame::Frame,
    padding::{EdgeInsets, Padding},
    stack::Alignment,
};
use waterui_navigation::NavigationView;
use waterui_str::Str;

use crate::{
    accessibility::{
        self, AccessibilityChildren, AccessibilityHidden, AccessibilityIdentifier,
        AccessibilityLabel, AccessibilityRole, AccessibilityState,
    },
    background::IntoBackground,
    border::Border,
    drag_drop::{DragData, Draggable, DropDestination},
    filter::Opacity,
    gesture::{Gesture, GestureObserver, LongPressGesture, TapGesture},
    interaction::Hittable,
    metadata::secure::Secure,
    theme,
    view_ext::OnChange,
};
use crate::{
    component::{badge::Badge, focus::Focused},
    floating::Floating,
    prelude::Shadow,
    shape::{ClipShape, Shape},
    style::{Anchor, FloatingStyle, Offset, Rotation, Scale},
};
#[cfg(feature = "std")]
use waterkit_haptic::{Haptic, Intensity};
use waterui_core::Metadata;
use waterui_core::event::{Event, LifeCycle, LifeCycleHook, OnEvent};
use waterui_core::id::TaggedView;

#[cfg(feature = "std")]
fn trigger_impact_haptic(intensity: Intensity) {
    if let Err(error) = Haptic::impact(intensity) {
        tracing::debug!(%error, "failed to trigger impact haptic");
    }
}

/// Extension trait for views, adding common styling and configuration methods.
pub trait ViewExt: View + Sized {
    /// Attaches metadata to a view.
    ///
    /// # Arguments
    /// * `metadata` - The metadata to attach
    fn metadata<T: MetadataKey>(self, metadata: T) -> Metadata<T> {
        Metadata::new(self, metadata)
    }

    /// Selects the [`ColorSpace`](crate::metadata::secure::ColorSpace) for this subtree.
    ///
    /// Friendly wrapper over the underlying [`StandardDynamicRange`](crate::metadata::secure::StandardDynamicRange) /
    /// [`HighDynamicRange`](crate::metadata::secure::HighDynamicRange) metadata. Prefer this over
    /// `metadata(HighDynamicRange::new())` for new code.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use waterui::prelude::*;
    /// use waterui::metadata::secure::ColorSpace;
    ///
    /// let wide_gamut = text!("Sunset").color_space(ColorSpace::Hdr);
    /// let thumbnail = text!("Avatar").color_space(ColorSpace::Sdr);
    /// ```
    fn color_space(self, space: crate::metadata::secure::ColorSpace) -> AnyView {
        use crate::metadata::secure::{ColorSpace, HighDynamicRange, StandardDynamicRange};
        match space {
            ColorSpace::Sdr => AnyView::new(self.metadata(StandardDynamicRange::new())),
            ColorSpace::Hdr => AnyView::new(self.metadata(HighDynamicRange::new())),
        }
    }

    /// Adjusts the opacity (transparency) of this view.
    ///
    /// This produces a lightweight `Metadata<Opacity>` that maps directly to
    /// compositor-native operations (e.g. `CALayer.opacity` on Apple, `View.alpha`
    /// on Android, `push_layer()` with alpha on hydrolysis). No offscreen texture
    /// or GPU shader pass is involved.
    ///
    /// # Arguments
    /// * `amount` - The opacity value (0.0 = transparent, 1.0 = opaque). Can be reactive.
    fn opacity(self, amount: impl IntoSignalF32) -> Metadata<Opacity> {
        Metadata::new(self, Opacity::new(amount))
    }

    /// Constrains this view to a width-to-height ratio.
    ///
    /// The view shrinks to fit inside whatever it is offered, leaving slack on
    /// the longer axis — `SwiftUI`'s `.aspectRatio(_, contentMode: .fit)`. Use
    /// [`AspectRatio::new`] for the filling mode.
    ///
    /// # Arguments
    /// * `ratio` - Width divided by height. Must be positive and finite.
    fn aspect_ratio(self, ratio: impl IntoSignalF32 + 'static) -> impl View {
        AspectRatio::new(self, ratio, ContentMode::Fit)
    }

    /// Sets how strongly this view holds on to space when its stack runs short.
    ///
    /// A stack compresses its lowest-priority children first, so raising one
    /// child above its siblings keeps it at its ideal size while they give way.
    /// The default is `0`.
    ///
    /// # Arguments
    /// * `priority` - Higher keeps more space; ties share the shortfall.
    fn layout_priority(self, priority: i32) -> Metadata<LayoutPriority> {
        Metadata::new(self, LayoutPriority::new(priority))
    }

    /// Sets the visibility of this view.
    ///
    /// # Arguments
    /// * `visible` - A reactive boolean indicating whether the view should be visible
    fn visible(self, visible: impl IntoComputed<bool>) -> impl View {
        let visible = visible.into_computed();
        let accessibility_state = visible.map(|visible| AccessibilityState::new().hidden(!visible));
        let opacity_value = visible.map(|visible| if visible { 1.0 } else { 0.0 });
        let hittable_value = visible;

        self.a11y_state_signal(accessibility_state)
            .opacity(opacity_value)
            .hittable(hittable_value)
    }

    /// Associates  a value with this view in the environment.
    fn with<T: 'static>(self, value: T) -> With<Self, T> {
        With::new(self, value)
    }

    /// Sets this view as the content of a navigation view with the specified title.
    ///
    /// # Arguments
    /// * `title` - The semantic title for the navigation view
    fn title(self, title: impl crate::text::IntoText) -> NavigationView {
        NavigationView::new(title, self)
    }

    /// Marks this view as focused when the binding matches the specified value.
    ///
    /// # Arguments
    /// * `value` - Binding to the focused value
    /// * `equals` - The value to compare against for focus
    fn focused<T: 'static + Eq + Clone>(
        self,
        value: &Binding<Option<T>>,
        equals: T,
    ) -> Metadata<Focused> {
        Metadata::new(self, Focused::new(value, equals))
    }

    /// Monitors a signal for changes and triggers a handler when the signal's value changes.
    ///
    /// Compare to manual watching, this method automatically manages the watcher lifecycle.
    fn on_change<C, F>(self, source: &C, handler: F) -> OnChange<Self, C::Guard>
    where
        C: Signal,
        C::Output: PartialEq + Clone,
        F: Fn(C::Output) + 'static,
    {
        OnChange::<Self, C::Guard>::new(self, source, handler)
    }

    /// Spawns an asynchronous task tied to the lifecycle of this view.
    ///
    /// The task will be cancelled when the view is dropped.
    ///
    /// # Arguments
    /// * `task` - The asynchronous task to run
    fn task<Fut>(self, task: Fut) -> Metadata<Retain>
    where
        Fut: std::future::Future<Output = ()> + 'static,
    {
        let local_task = spawn_local(task);
        self.retain(local_task)
    }

    /// Converts this view to an `AnyView` type-erased container.
    fn anyview(self) -> AnyView {
        AnyView::new(self)
    }

    /// Sets the background of this view.
    ///
    /// The background view renders behind this view, with this view determining
    /// the layout size. This uses a layout-based approach where the background
    /// fills the bounds and the content renders on top.
    ///
    /// # Arguments
    /// * `background` - Any view or `Material` to render as the background
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    ///
    /// // Color background
    /// text!("Hello").background(Color::red());
    ///
    /// // Material background (platform backend best-effort)
    /// text!("Hello").background(Material::Regular);
    ///
    /// // Any view as background
    /// let my_gradient_view = stack::hstack((Color::red(), Color::blue()));
    /// text!("Hello").background(my_gradient_view);
    /// ```
    fn background<B: IntoBackground>(self, background: B) -> B::Output<Self> {
        background.apply_background(self)
    }

    /// Sets the foreground color for this view and all its descendants.
    ///
    /// This injects the color into the environment as the `Foreground` color token,
    /// which affects all text and icons in the subtree that don't have an explicit color set.
    ///
    /// # Arguments
    /// * `color` - The foreground color to apply
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    ///
    /// // All text in this VStack will be red
    /// vstack((
    ///     text!("Hello"),
    ///     text!("World"),
    /// )).foreground(Color::red());
    /// ```
    fn foreground(self, color: impl Into<Color>) -> impl View {
        self.install(theme::ForegroundOverride::new(color))
    }

    /// Adds an overlay to this view.
    ///
    /// Unlike `ZStack`, `Overlay` will not affect the size of the base view.
    ///
    /// # Arguments
    /// * `overlay` - The overlay view to add
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    ///
    /// text("Hello").overlay(Color::red().with_opacity(0.5));
    /// ```
    fn overlay<V>(self, overlay: V) -> Overlay<Self, V> {
        Overlay::new(self, overlay)
    }

    /// Adds a lifecycle hook for the specified lifecycle event.
    ///
    /// You may want to use `ViewExt::on_appear` or `ViewExt::on_disappear` for convenience.
    ///
    /// # Arguments
    /// * `lifecycle` - The lifecycle event to listen for
    /// * `handler` - The action to execute when the event occurs (called once)
    fn lifecycle<H, Args>(self, lifecycle: LifeCycle, handler: H) -> Metadata<LifeCycleHook>
    where
        H: HandlerOnce<Args, ()>,
    {
        Metadata::new(self, LifeCycleHook::new(lifecycle, handler))
    }

    /// Adds a handler that triggers when the view disappears.
    ///
    /// Warning: This handler will be called when the view is removed from the view hierarchy,
    /// not when the view is hidden. Also, removed from the view hierarchy does not mean the view is destroyed,
    /// if you want to release resources when the view is destroyed, consider to use [`ViewExt::retain`] to keep the view alive.
    ///
    /// # Arguments
    /// * `handler` - The action to execute when the view disappears
    fn on_disappear<H, Args>(self, handler: H) -> Metadata<LifeCycleHook>
    where
        H: HandlerOnce<Args, ()>,
    {
        self.lifecycle(LifeCycle::Disappear, handler)
    }

    /// Adds a handler that triggers when the view appears.
    ///
    /// In `WaterUI`, a struct that implements `View` trait is a descriptor of a view,
    /// `View` has a `body` method which would be called when the view is rendered.
    /// However, even if `body` is called, the view is not guaranteed to be visible yet.
    /// For instance, a lazy view may resolve bunch of views by calling `body` method,
    /// but delay the actual rendering of the view until it is needed.
    ///
    /// So, if you want to execute some code when the view is visible, you should use this method
    /// to add a handler that triggers when the view appears.
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    /// use waterui::reactive::binding;
    ///
    /// let count:Binding<i32> = binding(0);
    /// text("Hello").on_appear(|| {});
    /// ```
    ///
    /// # Arguments
    /// * `handler` - The action to execute when the view appears
    fn on_appear<H, Args>(self, handler: H) -> Metadata<LifeCycleHook>
    where
        H: HandlerOnce<Args, ()>,
    {
        self.lifecycle(LifeCycle::Appear, handler)
    }

    /// Adds an event handler for the specified interaction event.
    ///
    /// You may want to use `ViewExt::on_hover_enter` or `ViewExt::on_hover_exit` for convenience.
    ///
    /// # Arguments
    /// * `event` - The event to listen for
    /// * `handler` - The action to execute when the event occurs (can be called multiple times)
    fn event<H, Args>(self, event: Event, handler: H) -> Metadata<OnEvent>
    where
        H: Handler<Args, ()>,
    {
        Metadata::new(self, OnEvent::new(event, handler))
    }

    /// Adds a handler that triggers when the cursor enters this view's bounds.
    ///
    /// This event can fire multiple times as the cursor moves in and out of the view.
    /// Only affects platforms with cursor support (macOS, iPadOS with trackpad, Android API 24+).
    ///
    /// # Arguments
    /// * `handler` - The action to execute when hover starts
    fn on_hover_enter<H, Args>(self, handler: H) -> Metadata<OnEvent>
    where
        H: Handler<Args, ()>,
    {
        self.event(Event::HoverEnter, handler)
    }

    /// Adds a handler that triggers when the cursor exits this view's bounds.
    ///
    /// This event can fire multiple times as the cursor moves in and out of the view.
    /// Only affects platforms with cursor support (macOS, iPadOS with trackpad, Android API 24+).
    ///
    /// # Arguments
    /// * `handler` - The action to execute when hover ends
    fn on_hover_exit<H, Args>(self, handler: H) -> Metadata<OnEvent>
    where
        H: Handler<Args, ()>,
    {
        self.event(Event::HoverExit, handler)
    }

    /// Sets the cursor style when hovering over this view.
    ///
    /// The cursor style is scoped to the view's bounds - when the cursor exits
    /// the view, the cursor automatically reverts to the parent view's cursor
    /// or the system default.
    ///
    /// Only affects platforms with cursor support (macOS, iPadOS with trackpad, Android API 24+).
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    /// use waterui::cursor::CursorStyle;
    ///
    /// let clickable = text!("Click me").cursor(CursorStyle::PointingHand);
    /// ```
    ///
    /// # Arguments
    /// * `style` - The cursor style to display (can be reactive)
    fn cursor(
        self,
        style: impl IntoComputed<crate::cursor::CursorStyle>,
    ) -> Metadata<crate::cursor::Cursor> {
        Metadata::new(self, crate::cursor::Cursor::new(style))
    }

    /// Adds a badge to this view.
    ///
    /// # Arguments
    /// * `value` - The numeric value to display in the badge
    fn badge(self, value: impl IntoComputed<i32>) -> Badge
    where
        Self: Clone,
    {
        Badge::new(value, self)
    }

    /// Fixes this view's width to the provided value.
    fn width(self, width: f32) -> Frame {
        Frame::new(self).width(width)
    }

    /// Fixes this view's height to the provided value.
    fn height(self, height: f32) -> Frame {
        Frame::new(self).height(height)
    }

    /// Applies a minimum width constraint.
    fn min_width(self, width: f32) -> Frame {
        Frame::new(self).min_width(width)
    }

    /// Applies a maximum width constraint.
    fn max_width(self, width: f32) -> Frame {
        Frame::new(self).max_width(width)
    }

    /// Applies a minimum height constraint.
    fn min_height(self, height: f32) -> Frame {
        Frame::new(self).min_height(height)
    }

    /// Applies a maximum height constraint.
    fn max_height(self, height: f32) -> Frame {
        Frame::new(self).max_height(height)
    }

    /// Fixes both width and height simultaneously.
    fn size(self, width: f32, height: f32) -> Frame {
        Frame::new(self).width(width).height(height)
    }

    /// Applies minimum constraints on both axes.
    fn min_size(self, width: f32, height: f32) -> Frame {
        Frame::new(self).min_width(width).min_height(height)
    }

    /// Applies maximum constraints on both axes.
    fn max_size(self, width: f32, height: f32) -> Frame {
        Frame::new(self).max_width(width).max_height(height)
    }

    /// Aligns this view within its frame using the provided alignment.
    fn alignment(self, alignment: Alignment) -> Frame {
        Frame::new(self).alignment(alignment)
    }

    /// Overrides a horizontal alignment guide for this view.
    fn horizontal_alignment_guide<F>(
        self,
        alignment: HorizontalAlignment,
        compute: F,
    ) -> HorizontalAlignmentGuide<Self, F>
    where
        F: Fn(&ViewDimensions) -> f32 + 'static,
    {
        HorizontalAlignmentGuide::new(self, alignment, compute)
    }

    /// Overrides a vertical alignment guide for this view.
    fn vertical_alignment_guide<F>(
        self,
        alignment: VerticalAlignment,
        compute: F,
    ) -> VerticalAlignmentGuide<Self, F>
    where
        F: Fn(&ViewDimensions) -> f32 + 'static,
    {
        VerticalAlignmentGuide::new(self, alignment, compute)
    }

    /// Adds padding to this view with custom edge insets.
    ///
    /// # Arguments
    /// * `edge` - The edge insets to apply as padding
    fn padding_with(self, edge: impl IntoComputed<EdgeInsets>) -> Padding {
        Padding::new(edge, self)
    }

    /// Adds default padding to this view.
    ///
    /// By default, the padding is 14.0 points.
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    ///
    /// text!("Hello").padding();
    /// ```
    fn padding(self) -> Padding {
        Padding::new(EdgeInsets::all(14.0), self)
    }

    /// Marks this view as secure.
    ///
    /// User would be forbidden to take a screenshot of the view.
    ///
    /// # Arguments
    /// * `secure` - The secure metadata to apply
    fn secure(self) -> Metadata<Secure> {
        Metadata::new(self, Secure::new())
    }

    /// Tags this view with a custom tag for identification.
    ///
    /// # Arguments
    /// * `tag` - The tag to associate with this view
    fn tag<T>(self, tag: T) -> TaggedView<T, Self> {
        TaggedView::new(tag, self)
    }

    /// Sets the accessibility label for this view.
    ///
    /// The label is reactive: pass a signal and a label derived from app state
    /// (`"3 unread messages"`) stays current without rebuilding the subtree.
    ///
    /// # Arguments
    /// * `label` - The accessibility label to apply, constant or reactive
    fn a11y_label(self, label: impl IntoComputed<Str>) -> IgnorableMetadata<AccessibilityLabel> {
        IgnorableMetadata::new(self, accessibility::AccessibilityLabel::new(label))
    }

    /// Sets the accessibility role for this view.
    ///
    /// # Arguments
    /// * `role` - The accessibility role to apply
    fn a11y_role(
        self,
        role: accessibility::AccessibilityRole,
    ) -> IgnorableMetadata<AccessibilityRole> {
        IgnorableMetadata::new(self, role)
    }

    /// Sets a stable automation identifier for locating this view in UI tests.
    ///
    /// Identifiers are invisible to end users and assistive technologies; they
    /// exist for `waterui-testing` selectors and native automation frameworks
    /// (`XCUITest` `accessibilityIdentifier`, Android `UiAutomator`).
    fn a11y_id(self, identifier: impl Into<Str>) -> IgnorableMetadata<AccessibilityIdentifier> {
        IgnorableMetadata::new(
            self,
            accessibility::AccessibilityIdentifier::new(identifier),
        )
    }

    /// Overrides whether this view is hidden from assistive technologies.
    fn a11y_hidden(self, hidden: bool) -> IgnorableMetadata<AccessibilityHidden> {
        IgnorableMetadata::new(self, accessibility::AccessibilityHidden::new(hidden))
    }

    /// Controls how descendants contribute semantics for this view.
    fn a11y_children(
        self,
        behavior: accessibility::AccessibilityChildren,
    ) -> IgnorableMetadata<AccessibilityChildren> {
        IgnorableMetadata::new(self, behavior)
    }

    /// Applies explicit accessibility state metadata.
    fn a11y_state(
        self,
        state: accessibility::AccessibilityState,
    ) -> IgnorableMetadata<AccessibilityState> {
        IgnorableMetadata::new(self, state)
    }

    /// Applies reactive accessibility state metadata.
    fn a11y_state_signal(
        self,
        state: impl IntoComputed<accessibility::AccessibilityState>,
    ) -> IgnorableMetadata<accessibility::AccessibilityStateSignal> {
        IgnorableMetadata::new(self, accessibility::AccessibilityStateSignal::new(state))
    }

    /// Observes a gesture and executes an action when the gesture is recognized.
    ///
    /// # Arguments
    /// * `gesture` - The gesture to observe
    /// * `action` - The action to execute when the gesture is recognized
    fn gesture<H, Args>(self, gesture: impl Into<Gesture>, action: H) -> Metadata<GestureObserver>
    where
        H: Handler<Args, ()>,
    {
        Metadata::new(self, GestureObserver::new(gesture, action))
    }

    /// Attaches a pre-built gesture observer to this view.
    ///
    /// Use this method when you need the builder pattern for state capture.
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    /// use waterui::gesture::{GestureObserver, TapGesture};
    ///
    /// let counted = text!("Tap twice").gesture_observer(
    ///     GestureObserver::new(
    ///         TapGesture::repeat(2),
    ///         |State(counter): State<Binding<i32>>| *counter.get_mut() += 1,
    ///     )
    /// );
    /// ```
    fn gesture_observer(self, observer: GestureObserver) -> Metadata<GestureObserver> {
        Metadata::new(self, observer)
    }

    /// Adds a tap gesture recognizer to this view that triggers the specified action.
    ///
    /// # Arguments
    /// * `action` - The action to execute when the tap gesture is recognized
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    ///
    /// text!("Click me").on_tap(|| {});
    /// ```
    fn on_tap<H, Args>(self, action: H) -> Metadata<GestureObserver>
    where
        H: Handler<Args, ()>,
    {
        self.gesture(TapGesture::new(), action)
    }

    /// Adds a tap gesture recognizer to this view (`SwiftUI` naming style).
    ///
    /// Equivalent to [`ViewExt::on_tap`].
    fn on_tap_gesture<H, Args>(self, action: H) -> Metadata<GestureObserver>
    where
        H: Handler<Args, ()>,
    {
        self.on_tap(action)
    }

    /// Adds a tap gesture recognizer requiring an exact tap count.
    fn on_tap_gesture_count<H, Args>(self, count: u32, action: H) -> Metadata<GestureObserver>
    where
        H: Handler<Args, ()>,
    {
        self.gesture(TapGesture::repeat(count.max(1)), action)
    }

    /// Adds a long-press gesture recognizer to this view.
    ///
    /// `minimum_duration_ms` is expressed in milliseconds.
    fn on_long_press_gesture<H, Args>(
        self,
        minimum_duration_ms: u32,
        action: H,
    ) -> Metadata<GestureObserver>
    where
        H: Handler<Args, ()>,
    {
        self.gesture(LongPressGesture::new(minimum_duration_ms), action)
    }

    /// Adds a tap gesture recognizer and triggers haptic impact feedback.
    #[cfg(feature = "std")]
    fn on_tap_haptic<H, Args>(self, intensity: Intensity, action: H) -> Metadata<GestureObserver>
    where
        H: Handler<Args, ()>,
    {
        let mut action = action;
        self.gesture(TapGesture::new(), move |env: Environment| {
            trigger_impact_haptic(intensity);
            action.call(&env);
        })
    }

    /// Adds a tap gesture recognizer with medium haptic impact feedback.
    #[cfg(feature = "std")]
    fn on_tap_haptic_default<H, Args>(self, action: H) -> Metadata<GestureObserver>
    where
        H: Handler<Args, ()>,
    {
        self.on_tap_haptic(Intensity::MEDIUM, action)
    }

    /// Adds a long-press gesture recognizer and triggers haptic impact feedback.
    #[cfg(feature = "std")]
    fn on_long_press_haptic<H, Args>(
        self,
        minimum_duration_ms: u32,
        intensity: Intensity,
        action: H,
    ) -> Metadata<GestureObserver>
    where
        H: Handler<Args, ()>,
    {
        let mut action = action;
        self.gesture(
            LongPressGesture::new(minimum_duration_ms),
            move |env: Environment| {
                trigger_impact_haptic(intensity);
                action.call(&env);
            },
        )
    }

    /// Adds a long-press gesture recognizer with medium haptic impact feedback.
    #[cfg(feature = "std")]
    fn on_long_press_haptic_default<H, Args>(
        self,
        minimum_duration_ms: u32,
        action: H,
    ) -> Metadata<GestureObserver>
    where
        H: Handler<Args, ()>,
    {
        self.on_long_press_haptic(minimum_duration_ms, Intensity::MEDIUM, action)
    }

    /// Applies a shadow effect to this view.
    fn shadow(self, shadow: impl Into<Shadow>) -> Metadata<Shadow> {
        Metadata::new(self, shadow.into())
    }

    /// Promotes this view to a themed floating surface with elevation.
    ///
    /// Floating presentation is an attribute: applying it to a semantic button
    /// preserves the button's identity while changing its container, state-layer
    /// geometry, and elevation.
    fn floating(self) -> Floating<Self> {
        Floating::new(self)
    }

    /// Promotes this view with explicit floating-surface theme tokens.
    fn floating_with(self, style: FloatingStyle) -> Floating<Self> {
        Floating::with_style(self, style)
    }

    /// Applies a border around this view.
    ///
    /// Creates a border with the specified color and width on all edges
    /// with square corners.
    ///
    /// For rounded corners or edge-specific borders, use [`border_with`](ViewExt::border_with)
    /// with a configured [`Border`] instance.
    ///
    /// # Arguments
    /// * `color` - The border color
    /// * `width` - The border width in points
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    ///
    /// // Simple border on all edges
    /// text!("Hello").border(Color::red(), 2.0);
    /// ```
    fn border(self, color: impl Into<Color>, width: f32) -> Metadata<Border> {
        Metadata::new(self, Border::new(color, width))
    }

    /// Applies a border with full customization.
    ///
    /// Use this method when you need to configure all border properties at once.
    ///
    /// # Arguments
    /// * `border` - A fully configured `Border` instance
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    /// use waterui::border::Border;
    ///
    /// let border = Border::new(Color::blue(), 2.0)
    ///     .corner_radius(12.0)
    ///     .edges(EdgeSet::HORIZONTAL);
    ///
    /// text!("Custom").border_with(border);
    /// ```
    fn border_with(self, border: Border) -> Metadata<Border> {
        Metadata::new(self, border)
    }

    /// Applies a uniform scale transform to this view around its center.
    ///
    /// Scales are purely visual and do not affect layout calculations.
    ///
    /// # Arguments
    /// * `factor` - The scale factor (1.0 = no scale, 0.5 = half size, 2.0 = double size)
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    ///
    /// // Scale uniformly to 150%
    /// let bigger = text!("Hello").scale(1.5, 1.5);
    ///
    /// // Scale X only (stretch horizontally)
    /// let wider = text!("Hello").scale(2.0, 1.0);
    ///
    /// // Animate scale
    /// let x = binding::<f32>(1.0_f32).animated();
    /// let y = binding::<f32>(1.0_f32).animated();
    /// let animated = text!("Hello").scale(x, y);
    /// ```
    fn scale(self, x: impl IntoSignalF32, y: impl IntoSignalF32) -> Metadata<Scale> {
        Metadata::new(self, Scale::xy(x, y))
    }

    /// Applies a scale transform around a specific anchor point.
    ///
    /// # Arguments
    /// * `x` - The horizontal scale factor
    /// * `y` - The vertical scale factor
    /// * `anchor` - The anchor point for the scale (e.g., `Anchor::TOP_LEFT`)
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    /// use waterui::style::Anchor;
    ///
    /// // Scale from top-left corner
    /// let shrunk = text!("Hello").scale_from(0.5, 0.5, Anchor::TOP_LEFT);
    /// ```
    fn scale_from(
        self,
        x: impl IntoSignalF32,
        y: impl IntoSignalF32,
        anchor: Anchor,
    ) -> Metadata<Scale> {
        Metadata::new(self, Scale::xy_from(x, y, anchor))
    }

    /// Applies a rotation transform to this view around its center.
    ///
    /// Rotations are purely visual and do not affect layout calculations.
    ///
    /// # Arguments
    /// * `degrees` - The rotation angle in degrees (positive = clockwise)
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    ///
    /// // Rotate 45 degrees
    /// let tilted = text!("Hello").rotation(45.0);
    ///
    /// // Animate rotation
    /// let angle = binding::<f32>(0.0_f32).animated();
    /// let spinning = text!("Hello").rotation(angle);
    /// ```
    fn rotation(self, degrees: impl IntoSignalF32) -> Metadata<Rotation> {
        Metadata::new(self, Rotation::degrees(degrees))
    }

    /// Applies a rotation transform to this view around a specific anchor point.
    ///
    /// # Arguments
    /// * `degrees` - The rotation angle in degrees
    /// * `anchor` - The anchor point for the rotation
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    /// use waterui::style::Anchor;
    ///
    /// // Rotate around top-left corner
    /// let tilted = text!("Hello").rotation_from(45.0, Anchor::TOP_LEFT);
    /// ```
    fn rotation_from(self, degrees: impl IntoSignalF32, anchor: Anchor) -> Metadata<Rotation> {
        Metadata::new(self, Rotation::degrees_from(degrees, anchor))
    }

    /// Applies an offset (translation) transform to this view.
    ///
    /// Offsets are purely visual and do not affect layout calculations.
    ///
    /// # Arguments
    /// * `x` - The offset along the X axis in points
    /// * `y` - The offset along the Y axis in points
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    ///
    /// // Move view by (10, 20) points
    /// let nudged = text!("Hello").offset(10.0, 20.0);
    ///
    /// // Animate offset
    /// let x = binding::<f32>(0.0_f32).animated();
    /// let sliding = text!("Hello").offset(x, 0.0);
    /// ```
    fn offset(self, x: impl IntoSignalF32, y: impl IntoSignalF32) -> Metadata<Offset> {
        Metadata::new(self, Offset::new(x, y))
    }

    /// Clips this view to the specified shape.
    ///
    /// The shape defines a mask - only the portion of the view inside the shape
    /// will be visible. Coordinates in the shape are normalized (0.0-1.0) and
    /// scale with the view's bounds.
    ///
    /// # Arguments
    /// * `shape` - The shape to clip to (e.g., `Circle`, `RoundedRectangle`, custom `Path`)
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    /// use waterui::shape::*;
    ///
    /// // Clip a view to a circle
    /// let avatar = Color::red().clip(Circle);
    ///
    /// // Clip to rounded rectangle
    /// let card = text!("Card").clip(RoundedRectangle::new(0.1));
    ///
    /// // Custom triangle shape
    /// let triangle = Path::new()
    ///     .move_to(0.5, 0.0)
    ///     .line_to(1.0, 1.0)
    ///     .line_to(0.0, 1.0)
    ///     .close();
    /// Color::red().size(100.0, 100.0).clip(triangle);
    /// ```
    fn clip(self, shape: impl Shape) -> Metadata<ClipShape> {
        Metadata::new(self, ClipShape::new(shape))
    }

    /// Attaches a context menu to this view.
    ///
    /// The context menu appears when the user:
    /// - Long-presses on iOS/Android
    /// - Right-clicks on macOS
    ///
    /// # Arguments
    /// * `items` - The menu items to display
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    ///
    /// text!("Right-click me")
    ///     .context_menu(vec![
    ///         "Copy".action(|| {}),
    ///         "Paste".action(|| {}),
    ///     ]);
    /// ```
    fn context_menu(
        self,
        items: impl crate::component::menu::MenuView,
    ) -> crate::metadata::context_menu::ContextMenuView<Self> {
        crate::metadata::context_menu::ContextMenuView {
            content: self,
            items: items.into_menu_items(),
        }
    }

    /// Extends this view's bounds to ignore safe area insets on the specified edges.
    ///
    /// This allows backgrounds, images, and other visual elements to extend edge-to-edge
    /// while content remains in the safe area. The native renderer will expand the
    /// view's frame to include the unsafe regions on the specified edges.
    ///
    /// # Arguments
    /// * `edges` - The edges on which to ignore safe area insets
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    ///
    /// // Extend background to fill entire screen
    /// let backdrop = Color::red()
    ///     .ignore_safe_area(EdgeSet::ALL);
    ///
    /// // Only extend to top (under status bar)
    /// let header = text!("Title")
    ///     .ignore_safe_area(EdgeSet::TOP);
    /// ```
    fn ignore_safe_area(self, edges: EdgeSet) -> Metadata<IgnoreSafeArea> {
        Metadata::new(self, IgnoreSafeArea::new(edges))
    }

    /// Installs a plugin into the environment.
    fn install(self, plugin: impl Plugin) -> impl View {
        use_env(move |mut env: Environment| {
            plugin.install(&mut env);
            Metadata::new(self, env)
        })
    }

    /// Retains a value for the lifetime of this view.
    ///
    /// This is useful for keeping watcher guards, subscriptions, or other values
    /// alive as long as the view exists. The retained value is dropped when the
    /// view is dropped.
    ///
    /// # Arguments
    /// * `value` - The value to retain (e.g., watcher guard, subscription)
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    /// use waterui::reactive::binding;
    ///
    /// fn view() -> impl View{
    ///     let count:Binding<i32> = binding(0);
    ///     let guard = count.clone().watch(|v| {
    ///         let _ = v.into_value();
    ///     });
    ///     text("Hello").retain(guard)
    /// }
    /// ```
    fn retain<T: 'static>(self, value: T) -> Metadata<Retain> {
        Metadata::new(self, Retain::new(value))
    }

    /// Makes this view draggable with the specified data.
    ///
    /// When the user drags this view (click-drag on macOS, long-press-drag on iOS/Android),
    /// the data will be transferred to any compatible drop destination.
    ///
    /// # Arguments
    /// * `data` - The data to transfer when dragging (can be reactive)
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    /// use waterui::drag_drop::DragData;
    ///
    /// text!("Drag me")
    ///     .draggable(DragData::text("Hello!"));
    /// ```
    fn draggable(self, data: impl IntoComputed<DragData>) -> Metadata<Draggable> {
        Metadata::new(self, Draggable::new(data))
    }

    /// Makes this view a drop destination for dragged content.
    ///
    /// For simple cases without state, pass a handler directly. To inject
    /// local state, use [`ViewExt::state`] and extract it in the handler.
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    /// use waterui::drag_drop::DragData;
    ///
    /// // Simple usage without state
    /// text!("Drop here")
    ///     .drop_destination(|data: DragData| {
    ///         let _ = data;
    ///     });
    ///
    /// // With injected state
    /// let items = binding::<Vec<String>>(Vec::new());
    /// let count = binding::<i32>(0);
    /// text!("Drop here")
    ///     .state(&items)
    ///     .state(&count)
    ///     .drop_destination(
    ///         |State(items): State<Binding<Vec<String>>>,
    ///          State(count): State<Binding<i32>>,
    ///          data: DragData| {
    ///             items.get_mut().push(data.as_str().to_string());
    ///             *count.get_mut() += 1;
    ///         },
    ///     );
    /// ```
    fn drop_destination<H, Args>(self, on_drop: H) -> Metadata<DropDestination>
    where
        H: Handler<Args, ()>,
    {
        Metadata::new(self, DropDestination::new(on_drop))
    }

    /// Controls whether this view responds to hit testing (touch/click events).
    ///
    /// When `enabled` is false, touch events pass through the view to views behind it.
    /// This modifier does NOT affect the visual appearance of the view.
    ///
    /// # Arguments
    /// * `enabled` - Whether hit testing is enabled (can be reactive)
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    ///
    /// // Make a view transparent to touch events
    /// let passthrough = text!("Click through me")
    ///     .hittable(false);
    ///
    /// // Reactive hit testing control
    /// let can_interact = binding::<bool>(true);
    /// button("Click me").action(|| {})
    ///     .hittable(can_interact);
    /// ```
    fn hittable(self, enabled: impl IntoComputed<bool>) -> Metadata<Hittable> {
        Metadata::new(self, Hittable::new(enabled))
    }

    /// Disables every interactive control in this view subtree.
    ///
    /// Installs a [`waterui_core::interaction::Disabled`] scope into the
    /// subtree's environment, so controls (toggles, buttons, sliders, …)
    /// render their platform-correct disabled appearance and stop responding
    /// to input. Nested `.disabled(...)` scopes OR-combine: a control stays
    /// disabled while any enclosing scope is disabled. The subtree also stops
    /// hit-testing entirely and its accessibility nodes report the disabled
    /// state to assistive technologies.
    ///
    /// # Arguments
    /// * `is_disabled` - Whether the subtree is disabled (can be reactive)
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    ///
    /// // Disable a button
    /// button("Submit").action(|| {})
    ///     .disabled(true);
    ///
    /// // Reactive disable based on form validity
    /// let is_submitting = binding::<bool>(false);
    /// let name = binding::<Str>(Str::default());
    /// vstack((
    ///     TextField::new("Name", &name),
    ///     button("Submit").action(|| {}),
    /// )).disabled(is_submitting);
    /// ```
    fn disabled(self, is_disabled: impl IntoComputed<bool>) -> impl View {
        let is_disabled = is_disabled.into_computed();

        let accessibility_state =
            is_disabled.map(|disabled| AccessibilityState::new().disabled(disabled));
        let hittable_value = is_disabled.map(|d| !d);
        let scope = is_disabled;

        use_env(move |mut env: Environment| {
            waterui_core::interaction::Disabled::install(&mut env, scope);
            Metadata::new(
                self.a11y_state_signal(accessibility_state)
                    .hittable(hittable_value),
                env,
            )
        })
    }

    /// Injects cloneable state into this view subtree's environment.
    ///
    /// Actions and event handlers can later extract the injected value using
    /// [`waterui_core::extract::State`] in their handler parameters.
    ///
    /// # Example
    ///
    /// ```rust
    /// use waterui::prelude::*;
    ///
    /// let hover_count = binding::<i32>(0);
    /// let is_hovered = binding::<bool>(false);
    /// let hoverable = text!("Hover Me!")
    ///     .state(&hover_count)
    ///     .state(&is_hovered)
    ///     .on_hover_enter(
    ///         |State(count): State<Binding<i32>>, State(hovered): State<Binding<bool>>| {
    ///             *count.get_mut() += 1;
    ///             hovered.set(true);
    ///         },
    ///     )
    ///     .on_hover_exit(|State(hovered): State<Binding<bool>>| {
    ///         hovered.set(false);
    ///     });
    /// ```
    fn state<T: Clone + 'static>(self, state: &T) -> With<Self, State<T>> {
        With::new(self, State(state.clone()))
    }
}

impl<V: View + Sized> ViewExt for V {}