-
-
Notifications
You must be signed in to change notification settings - Fork 10.8k
Expand file tree
/
Copy pathdiv.rs
More file actions
5673 lines (5136 loc) · 221 KB
/
Copy pathdiv.rs
File metadata and controls
5673 lines (5136 loc) · 221 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
//! Div is the central, reusable element that most GPUI trees will be built from.
//! It functions as a container for other elements, and provides a number of
//! useful features for laying out and styling its children as well as binding
//! mouse events and action handlers. It is meant to be similar to the HTML `<div>`
//! element, but for GPUI.
//!
//! # Build your own div
//!
//! GPUI does not directly provide APIs for stateful, multi step events like `click`
//! and `drag`. We want GPUI users to be able to build their own abstractions for
//! their own needs. However, as a UI framework, we're also obliged to provide some
//! building blocks to make the process of building your own elements easier.
//! For this we have the [`Interactivity`] and the [`StyleRefinement`] structs, as well
//! as several associated traits. Together, these provide the full suite of Dom-like events
//! and Tailwind-like styling that you can use to build your own custom elements. Div is
//! constructed by combining these two systems into an all-in-one element.
use crate::{
Action, AnyDrag, AnyElement, AnyTooltip, AnyView, App, Bounds, ClickEvent, DispatchPhase,
Display, Element, ElementId, Entity, EntityId, ExternalDragPayload, ExternalDragPayloadSource,
FileDropEvent, FocusHandle, Global, GlobalElementId, Hitbox, HitboxBehavior, HitboxId,
InspectorElementId, IntoElement, IsZero, KeyContext, KeyDownEvent, KeyUpEvent, KeyboardButton,
KeyboardClickEvent, LayoutId, LongPressEvent, ModifiersChangedEvent, MouseButton,
MouseClickEvent, MouseDownEvent, MouseExitEvent, MouseMoveEvent, MousePressureEvent,
MouseUpEvent, OngoingScroll, Overflow, ParentElement, PinchEvent, Pixels, Point, Render,
ScrollWheelEvent, SharedString, Size, Style, StyleRefinement, Styled, Task, TooltipId,
TouchPhase, Visibility, Window, WindowControlArea, point, px, size,
};
use collections::HashMap;
use gpui_util::ResultExt;
use refineable::Refineable;
use smallvec::SmallVec;
use std::{
any::{Any, TypeId},
cell::{Cell, RefCell},
cmp::Ordering,
fmt::Debug,
marker::PhantomData,
mem,
rc::Rc,
sync::Arc,
time::Duration,
};
use super::ImageCacheProvider;
#[cfg(feature = "stacker")]
type StackSafe<T> = stacksafe::StackSafe<T>;
#[cfg(not(feature = "stacker"))]
type StackSafe<T> = T;
const DRAG_THRESHOLD: f64 = 2.;
const DEFAULT_TOOLTIP_SHOW_DELAY: Duration = Duration::from_millis(500);
const HOVERABLE_TOOLTIP_HIDE_DELAY: Duration = Duration::from_millis(500);
/// The styling information for a given group.
pub struct GroupStyle {
/// The identifier for this group.
pub group: SharedString,
/// The specific style refinement that this group would apply
/// to its children.
pub style: Box<StyleRefinement>,
}
/// An event for when a drag is moving over this element, with the given state type.
pub struct DragMoveEvent<T> {
/// The mouse move event that triggered this drag move event.
pub event: MouseMoveEvent,
/// The bounds of this element.
pub bounds: Bounds<Pixels>,
drag: PhantomData<T>,
dragged_item: Arc<dyn Any>,
}
impl<T: 'static> DragMoveEvent<T> {
/// Returns the drag state for this event.
pub fn drag<'b>(&self, cx: &'b App) -> &'b T {
cx.active_drag
.as_ref()
.and_then(|drag| drag.value.downcast_ref::<T>())
.expect("DragMoveEvent is only valid when the stored active drag is of the same type.")
}
/// An item that is about to be dropped.
pub fn dragged_item(&self) -> &dyn Any {
self.dragged_item.as_ref()
}
}
impl Interactivity {
/// Create an `Interactivity`, capturing the caller location in debug mode.
#[cfg(any(feature = "inspector", debug_assertions))]
#[track_caller]
pub fn new() -> Interactivity {
Interactivity {
source_location: Some(core::panic::Location::caller()),
..Default::default()
}
}
/// Create an `Interactivity`, capturing the caller location in debug mode.
#[cfg(not(any(feature = "inspector", debug_assertions)))]
pub fn new() -> Interactivity {
Interactivity::default()
}
/// Gets the source location of construction. Returns `None` when not in debug mode.
pub fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
#[cfg(any(feature = "inspector", debug_assertions))]
{
self.source_location
}
#[cfg(not(any(feature = "inspector", debug_assertions)))]
{
None
}
}
/// Bind the given callback to the mouse down event for the given mouse button, during the bubble phase.
/// The imperative API equivalent of [`InteractiveElement::on_mouse_down`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to the view state from this callback.
pub fn on_mouse_down(
&mut self,
button: MouseButton,
listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
) {
self.mouse_down_listeners
.push(Box::new(move |event, phase, hitbox, window, cx| {
if phase == DispatchPhase::Bubble
&& event.button == button
&& hitbox.is_hovered(window)
{
(listener)(event, window, cx)
}
}));
}
/// Bind the given callback to the mouse down event for any button, during the capture phase.
/// The imperative API equivalent of [`InteractiveElement::capture_any_mouse_down`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn capture_any_mouse_down(
&mut self,
listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
) {
self.mouse_down_listeners
.push(Box::new(move |event, phase, hitbox, window, cx| {
if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
(listener)(event, window, cx)
}
}));
}
/// Bind the given callback to the mouse down event for any button, during the bubble phase.
/// The imperative API equivalent to [`InteractiveElement::on_any_mouse_down`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_any_mouse_down(
&mut self,
listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
) {
self.mouse_down_listeners
.push(Box::new(move |event, phase, hitbox, window, cx| {
if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
(listener)(event, window, cx)
}
}));
}
/// Bind the given callback to the mouse pressure event, during the bubble phase
/// the imperative API equivalent to [`InteractiveElement::on_mouse_pressure`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_mouse_pressure(
&mut self,
listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
) {
self.mouse_pressure_listeners
.push(Box::new(move |event, phase, hitbox, window, cx| {
if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
(listener)(event, window, cx)
}
}));
}
/// Bind the given callback to the mouse pressure event, during the capture phase
/// the imperative API equivalent to [`InteractiveElement::on_mouse_pressure`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn capture_mouse_pressure(
&mut self,
listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
) {
self.mouse_pressure_listeners
.push(Box::new(move |event, phase, hitbox, window, cx| {
if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
(listener)(event, window, cx)
}
}));
}
/// Bind the given callback to the mouse up event for the given button, during the bubble phase.
/// The imperative API equivalent to [`InteractiveElement::on_mouse_up`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_mouse_up(
&mut self,
button: MouseButton,
listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
) {
self.mouse_up_listeners
.push(Box::new(move |event, phase, hitbox, window, cx| {
if phase == DispatchPhase::Bubble
&& event.button == button
&& hitbox.is_hovered(window)
{
(listener)(event, window, cx)
}
}));
}
/// Bind the given callback to the mouse up event for any button, during the capture phase.
/// The imperative API equivalent to [`InteractiveElement::capture_any_mouse_up`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn capture_any_mouse_up(
&mut self,
listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
) {
self.mouse_up_listeners
.push(Box::new(move |event, phase, hitbox, window, cx| {
if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
(listener)(event, window, cx)
}
}));
}
/// Bind the given callback to the mouse up event for any button, during the bubble phase.
/// The imperative API equivalent to [`Interactivity::on_any_mouse_up`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_any_mouse_up(
&mut self,
listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
) {
self.mouse_up_listeners
.push(Box::new(move |event, phase, hitbox, window, cx| {
if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
(listener)(event, window, cx)
}
}));
}
/// Bind the given callback to the mouse down event, on any button, during the capture phase,
/// when the mouse is outside of the bounds of this element.
/// The imperative API equivalent to [`InteractiveElement::on_mouse_down_out`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_mouse_down_out(
&mut self,
listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
) {
self.mouse_down_listeners
.push(Box::new(move |event, phase, hitbox, window, cx| {
if phase == DispatchPhase::Capture
&& !window.has_active_prompt()
&& !hitbox.contains(&window.mouse_position())
{
(listener)(event, window, cx)
}
}));
}
/// Bind the given callback to the mouse up event, for the given button, during the capture phase,
/// when the mouse is outside of the bounds of this element.
/// The imperative API equivalent to [`InteractiveElement::on_mouse_up_out`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_mouse_up_out(
&mut self,
button: MouseButton,
listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
) {
self.mouse_up_listeners
.push(Box::new(move |event, phase, hitbox, window, cx| {
if phase == DispatchPhase::Capture
&& event.button == button
&& !hitbox.is_hovered(window)
{
(listener)(event, window, cx);
}
}));
}
/// Bind the given callback to the mouse move event, during the bubble phase.
/// The imperative API equivalent to [`InteractiveElement::on_mouse_move`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_mouse_move(
&mut self,
listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
) {
self.mouse_move_listeners
.push(Box::new(move |event, phase, hitbox, window, cx| {
if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
(listener)(event, window, cx);
}
}));
}
/// Bind the given callback to the mouse exit event, during the bubble phase.
/// The imperative API equivalent to [`InteractiveElement::on_mouse_exit`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_mouse_exit(
&mut self,
listener: impl Fn(&MouseExitEvent, &mut Window, &mut App) + 'static,
) {
self.mouse_exit_listeners
.push(Box::new(move |event, phase, hitbox, window, cx| {
if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
(listener)(event, window, cx);
}
}));
}
/// Bind the given callback to [`FileDropEvent::Exited`] when a platform file drag
/// leaves this element's window while the element is hovered.
///
/// This is a window-local exit event, not notification that the platform drag session ended.
/// The imperative API equivalent to [`InteractiveElement::on_file_drop_exit`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_file_drop_exit(
&mut self,
listener: impl Fn(&FileDropEvent, &mut Window, &mut App) + 'static,
) {
self.file_drop_exit_listeners
.push(Box::new(move |event, phase, hitbox, window, cx| {
if phase == DispatchPhase::Bubble
&& matches!(event, FileDropEvent::Exited)
&& hitbox.id.is_hovered_ignoring_last_input(window)
{
(listener)(event, window, cx);
}
}));
}
/// Bind the given callback to the mouse drag event of the given type. Note that this
/// will be called for all move events, inside or outside of this element, as long as the
/// drag was started with this element under the mouse. Useful for implementing draggable
/// UIs that don't conform to a drag and drop style interaction, like resizing.
/// The imperative API equivalent to [`InteractiveElement::on_drag_move`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_drag_move<T>(
&mut self,
listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
) where
T: 'static,
{
self.mouse_move_listeners
.push(Box::new(move |event, phase, hitbox, window, cx| {
if phase == DispatchPhase::Capture
&& let Some(drag) = &cx.active_drag
&& drag.value.as_ref().type_id() == TypeId::of::<T>()
{
(listener)(
&DragMoveEvent {
event: event.clone(),
bounds: hitbox.bounds,
drag: PhantomData,
dragged_item: Arc::clone(&drag.value),
},
window,
cx,
);
}
}));
}
/// Bind the given callback to scroll wheel events during the bubble phase.
/// The imperative API equivalent to [`InteractiveElement::on_scroll_wheel`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_scroll_wheel(
&mut self,
listener: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static,
) {
self.scroll_wheel_listeners
.push(Box::new(move |event, phase, hitbox, window, cx| {
if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
(listener)(event, window, cx);
}
}));
}
/// Bind the given callback to pinch gesture events during the bubble phase.
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_pinch(&mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) {
self.pinch_listeners
.push(Box::new(move |event, phase, hitbox, window, cx| {
if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
(listener)(event, window, cx);
}
}));
}
/// Bind the given callback to pinch gesture events during the capture phase.
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn capture_pinch(
&mut self,
listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
) {
self.pinch_listeners
.push(Box::new(move |event, phase, _hitbox, window, cx| {
if phase == DispatchPhase::Capture {
(listener)(event, window, cx);
} else {
cx.propagate();
}
}));
}
/// Bind the given callback to an action dispatch during the capture phase.
/// The imperative API equivalent to [`InteractiveElement::capture_action`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn capture_action<A: Action>(
&mut self,
listener: impl Fn(&A, &mut Window, &mut App) + 'static,
) {
self.action_listeners.push((
TypeId::of::<A>(),
Box::new(move |action, phase, window, cx| {
let action = action.downcast_ref().unwrap();
if phase == DispatchPhase::Capture {
(listener)(action, window, cx)
} else {
cx.propagate();
}
}),
));
}
/// Bind the given callback to an action dispatch during the bubble phase.
/// The imperative API equivalent to [`InteractiveElement::on_action`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
#[track_caller]
#[inline(always)]
pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Window, &mut App) + 'static) {
self.action_listeners.push((
TypeId::of::<A>(),
Box::new(move |action, phase, window, cx| {
let action = action.downcast_ref().unwrap();
if phase == DispatchPhase::Bubble {
(listener)(action, window, cx)
}
}),
));
}
/// Bind the given callback to an action dispatch, based on a dynamic action parameter
/// instead of a type parameter. Useful for component libraries that want to expose
/// action bindings to their users.
/// The imperative API equivalent to [`InteractiveElement::on_boxed_action`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_boxed_action(
&mut self,
action: &dyn Action,
listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
) {
let action = action.boxed_clone();
self.action_listeners.push((
(*action).type_id(),
Box::new(move |_, phase, window, cx| {
if phase == DispatchPhase::Bubble {
(listener)(&*action, window, cx)
}
}),
));
}
/// Bind the given callback to key down events during the bubble phase.
/// The imperative API equivalent to [`InteractiveElement::on_key_down`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_key_down(
&mut self,
listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
) {
self.key_down_listeners
.push(Box::new(move |event, phase, window, cx| {
if phase == DispatchPhase::Bubble {
(listener)(event, window, cx)
}
}));
}
/// Bind the given callback to key down events during the capture phase.
/// The imperative API equivalent to [`InteractiveElement::capture_key_down`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn capture_key_down(
&mut self,
listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
) {
self.key_down_listeners
.push(Box::new(move |event, phase, window, cx| {
if phase == DispatchPhase::Capture {
listener(event, window, cx)
}
}));
}
/// Bind the given callback to key up events during the bubble phase.
/// The imperative API equivalent to [`InteractiveElement::on_key_up`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static) {
self.key_up_listeners
.push(Box::new(move |event, phase, window, cx| {
if phase == DispatchPhase::Bubble {
listener(event, window, cx)
}
}));
}
/// Bind the given callback to key up events during the capture phase.
/// The imperative API equivalent to [`InteractiveElement::on_key_up`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn capture_key_up(
&mut self,
listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
) {
self.key_up_listeners
.push(Box::new(move |event, phase, window, cx| {
if phase == DispatchPhase::Capture {
listener(event, window, cx)
}
}));
}
/// Bind the given callback to modifiers changing events.
/// The imperative API equivalent to [`InteractiveElement::on_modifiers_changed`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_modifiers_changed(
&mut self,
listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
) {
self.modifiers_changed_listeners.push(Box::new(listener));
}
/// Bind the given callback to drop events of the given type, whether or not the drag started on this element.
/// The imperative API equivalent to [`InteractiveElement::on_drop`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_drop<T: 'static>(&mut self, listener: impl Fn(&T, &mut Window, &mut App) + 'static) {
self.drop_listeners.push((
TypeId::of::<T>(),
Box::new(move |dragged_value, window, cx| {
listener(dragged_value.downcast_ref().unwrap(), window, cx);
}),
));
}
/// Use the given predicate to determine whether or not a drop event should be dispatched to this element.
/// The imperative API equivalent to [`InteractiveElement::can_drop`].
pub fn can_drop(
&mut self,
predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
) {
self.can_drop_predicate = Some(Box::new(predicate));
}
/// Bind the given callback to click events of this element.
/// The imperative API equivalent to [`StatefulInteractiveElement::on_click`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
#[inline(always)]
pub fn on_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
where
Self: Sized,
{
self.click_listeners.push(Rc::new(listener));
}
/// Bind the given callback to non-primary click events of this element.
/// The imperative API equivalent to [`StatefulInteractiveElement::on_aux_click`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_aux_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
where
Self: Sized,
{
self.aux_click_listeners.push(Rc::new(listener));
}
/// On drag initiation, this callback will be used to create a new view to render the dragged value for a
/// drag and drop operation. This API should also be used as the equivalent of 'on drag start' with
/// the [`Self::on_drag_move`] API.
/// The imperative API equivalent to [`StatefulInteractiveElement::on_drag`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_drag<T, W>(
&mut self,
value: T,
constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
) where
Self: Sized,
T: 'static,
W: 'static + Render,
{
debug_assert!(
self.drag_listener.is_none(),
"calling on_drag more than once on the same element is not supported"
);
self.drag_listener = Some(DragListener {
value: Arc::new(value),
render: Box::new(move |value, offset, window, cx| {
constructor(value.downcast_ref().unwrap(), offset, window, cx).into()
}),
external_payload: None,
});
}
/// Registers a callback resolving a payload to offer the platform if a drag started by this
/// element leaves the window. It is invoked at most once per drag gesture, when the pointer
/// exits the viewport. Must be called after [`Self::on_drag`], with the same dragged value
/// type `T`.
pub fn external_drag_payload<T>(
&mut self,
resolver: impl Fn(&T, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
) where
Self: Sized,
T: 'static,
{
let Some(drag_listener) = self.drag_listener.as_mut() else {
debug_assert!(false, "external_drag_payload must be called after on_drag");
return;
};
debug_assert!(
drag_listener.value.as_ref().type_id() == TypeId::of::<T>(),
"external_drag_payload must use the same dragged value type as on_drag"
);
debug_assert!(
drag_listener.external_payload.is_none(),
"calling external_drag_payload more than once on the same element is not supported"
);
drag_listener.external_payload = Some(Box::new(move |value, window, cx| {
resolver(value.downcast_ref::<T>()?, window, cx)
}));
}
/// Bind the given callback on the hover start and end events of this element. Note that the boolean
/// passed to the callback is true when the hover starts and false when it ends.
/// Transitions caused by layout changes under a stationary mouse also invoke the callback.
///
/// By default, keyboard input suppresses hover until the next mouse move, mouse down, or touch. Set
/// [`HoverListenerMode::InputModalityIndependent`] with [`Self::hover_listener_mode`] to
/// continue hit-testing hover after keyboard input.
/// The imperative API equivalent to [`StatefulInteractiveElement::on_hover`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
pub fn on_hover(&mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static)
where
Self: Sized,
{
debug_assert!(
self.hover_listener.is_none(),
"calling on_hover more than once on the same element is not supported"
);
self.hover_listener = Some(Box::new(listener));
}
/// Sets how [`Self::on_hover`] responds to key presses while the mouse is stationary.
/// This affects only the hover listener, not hover styles or tooltips. The imperative API
/// equivalent to [`StatefulInteractiveElement::hover_listener_mode`].
pub fn hover_listener_mode(&mut self, mode: HoverListenerMode)
where
Self: Sized,
{
self.hover_listener_mode = mode;
}
/// Constructs a tooltip when the element is hovered or long-pressed.
/// The imperative API equivalent to [`StatefulInteractiveElement::tooltip`].
pub fn tooltip(&mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static)
where
Self: Sized,
{
debug_assert!(
self.tooltip_builder.is_none(),
"calling tooltip more than once on the same element is not supported"
);
self.tooltip_builder = Some(TooltipBuilder {
build: Rc::new(build_tooltip),
hoverable: false,
});
}
/// Constructs a tooltip when the element is hovered or long-pressed.
/// The tooltip itself is also hoverable and won't disappear when the user moves the mouse into
/// the tooltip. The imperative API equivalent to [`StatefulInteractiveElement::hoverable_tooltip`].
pub fn hoverable_tooltip(
&mut self,
build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
) where
Self: Sized,
{
debug_assert!(
self.tooltip_builder.is_none(),
"calling tooltip more than once on the same element is not supported"
);
self.tooltip_builder = Some(TooltipBuilder {
build: Rc::new(build_tooltip),
hoverable: true,
});
}
/// Sets the delay before this element's tooltip is shown on hover.
///
/// Touch long presses show the tooltip immediately once the gesture is recognized.
/// The imperative API equivalent to [`StatefulInteractiveElement::tooltip_show_delay`].
pub fn tooltip_show_delay(&mut self, delay: Duration) {
self.tooltip_show_delay = Some(delay);
}
/// Block the mouse from all interactions with elements behind this element's hitbox. Typically
/// `block_mouse_except_scroll` should be preferred.
///
/// The imperative API equivalent to [`InteractiveElement::occlude`]
pub fn occlude_mouse(&mut self) {
self.hitbox_behavior = HitboxBehavior::BlockMouse;
}
/// Set the bounds of this element as a window control area for the platform window.
/// The imperative API equivalent to [`InteractiveElement::window_control_area`]
pub fn window_control_area(&mut self, area: WindowControlArea) {
self.window_control = Some(area);
}
/// Block non-scroll mouse interactions with elements behind this element's hitbox.
/// The imperative API equivalent to [`InteractiveElement::block_mouse_except_scroll`].
///
/// See [`Hitbox::is_hovered`] for details.
pub fn block_mouse_except_scroll(&mut self) {
self.hitbox_behavior = HitboxBehavior::BlockMouseExceptScroll;
}
fn has_pinch_listeners(&self) -> bool {
!self.pinch_listeners.is_empty()
}
}
/// A trait for elements that want to use the standard GPUI event handlers that don't
/// require any state.
pub trait InteractiveElement: Sized {
/// Retrieve the interactivity state associated with this element
fn interactivity(&mut self) -> &mut Interactivity;
/// Assign this element to a group of elements that can be styled together
fn group(mut self, group: impl Into<SharedString>) -> Self {
self.interactivity().group = Some(group.into());
self
}
/// Assign this element an ID, so that it can be used with interactivity
fn id(mut self, id: impl Into<ElementId>) -> Stateful<Self> {
self.interactivity().element_id = Some(id.into());
Stateful { element: self }
}
/// Track the focus state of the given focus handle on this element.
/// If the focus handle is focused by the application, this element will
/// apply its focused styles.
fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
self.interactivity().focusable = true;
self.interactivity().tracked_focus_handle = Some(focus_handle.clone());
self
}
/// Set whether this element is a tab stop.
///
/// When false, the element remains in tab-index order but cannot be reached via keyboard navigation.
/// Useful for container elements: focus the container, then call `window.focus_next(cx)` to focus
/// the first tab stop inside it while having the container element itself be unreachable via the keyboard.
/// Should only be used with `tab_index`.
fn tab_stop(mut self, tab_stop: bool) -> Self {
self.interactivity().tab_stop = tab_stop;
self
}
/// Set index of the tab stop order, and set this node as a tab stop.
/// This will default the element to being a tab stop. See [`Self::tab_stop`] for more information.
/// This should only be used in conjunction with `tab_group`
/// in order to not interfere with the tab index of other elements.
fn tab_index(mut self, index: isize) -> Self {
self.interactivity().focusable = true;
self.interactivity().tab_index = Some(index);
self.interactivity().tab_stop = true;
self
}
/// Designate this div as a "tab group". Tab groups have their own location in the tab-index order,
/// but for children of the tab group, the tab index is reset to 0. This can be useful for swapping
/// the order of tab stops within the group, without having to renumber all the tab stops in the whole
/// application.
fn tab_group(mut self) -> Self {
self.interactivity().tab_group = true;
if self.interactivity().tab_index.is_none() {
self.interactivity().tab_index = Some(0);
}
self
}
/// Set the keymap context for this element. This will be used to determine
/// which action to dispatch from the keymap.
fn key_context<C, E>(mut self, key_context: C) -> Self
where
C: TryInto<KeyContext, Error = E>,
E: std::fmt::Display,
{
if let Some(key_context) = key_context.try_into().log_err() {
self.interactivity().key_context = Some(key_context);
}
self
}
/// Apply the given style to this element when the mouse hovers over it
fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
debug_assert!(
self.interactivity().hover_style.is_none(),
"hover style already set"
);
self.interactivity().hover_style = Some(Box::new(f(StyleRefinement::default())));
self
}
/// Apply the given style to this element when the mouse hovers over a group member
fn group_hover(
mut self,
group_name: impl Into<SharedString>,
f: impl FnOnce(StyleRefinement) -> StyleRefinement,
) -> Self {
self.interactivity().group_hover_style = Some(GroupStyle {
group: group_name.into(),
style: Box::new(f(StyleRefinement::default())),
});
self
}
/// Bind the given callback to the mouse down event for the given mouse button.
/// The fluent API equivalent to [`Interactivity::on_mouse_down`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to the view state from this callback.
#[inline(always)]
fn on_mouse_down(
mut self,
button: MouseButton,
listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
) -> Self {
self.interactivity().on_mouse_down(button, listener);
self
}
#[cfg(any(test, feature = "test-support"))]
/// Set a key that can be used to look up this element's bounds
/// in the [`crate::VisualTestContext::debug_bounds`] map
/// This is a noop in release builds
fn debug_selector(mut self, f: impl FnOnce() -> String) -> Self {
self.interactivity().debug_selector = Some(f());
self
}
#[cfg(not(any(test, feature = "test-support")))]
/// Set a key that can be used to look up this element's bounds
/// in the [`crate::VisualTestContext::debug_bounds`] map
/// This is a noop in release builds
#[inline]
fn debug_selector(self, _: impl FnOnce() -> String) -> Self {
self
}
/// Bind the given callback to the mouse down event for any button, during the capture phase.
/// The fluent API equivalent to [`Interactivity::capture_any_mouse_down`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
fn capture_any_mouse_down(
mut self,
listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
) -> Self {
self.interactivity().capture_any_mouse_down(listener);
self
}
/// Bind the given callback to the mouse down event for any button, during the capture phase.
/// The fluent API equivalent to [`Interactivity::on_any_mouse_down`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
fn on_any_mouse_down(
mut self,
listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
) -> Self {
self.interactivity().on_any_mouse_down(listener);
self
}
/// Bind the given callback to the mouse up event for the given button, during the bubble phase.
/// The fluent API equivalent to [`Interactivity::on_mouse_up`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
fn on_mouse_up(
mut self,
button: MouseButton,
listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
) -> Self {
self.interactivity().on_mouse_up(button, listener);
self
}
/// Bind the given callback to the mouse up event for any button, during the capture phase.
/// The fluent API equivalent to [`Interactivity::capture_any_mouse_up`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
fn capture_any_mouse_up(
mut self,
listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
) -> Self {
self.interactivity().capture_any_mouse_up(listener);
self
}
/// Bind the given callback to the mouse pressure event, during the bubble phase
/// the fluent API equivalent to [`Interactivity::on_mouse_pressure`]
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
fn on_mouse_pressure(
mut self,
listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
) -> Self {
self.interactivity().on_mouse_pressure(listener);
self
}
/// Bind the given callback to the mouse pressure event, during the capture phase
/// the fluent API equivalent to [`Interactivity::on_mouse_pressure`]
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
fn capture_mouse_pressure(
mut self,
listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
) -> Self {
self.interactivity().capture_mouse_pressure(listener);
self
}
/// Bind the given callback to the mouse down event, on any button, during the capture phase,
/// when the mouse is outside of the bounds of this element.
/// The fluent API equivalent to [`Interactivity::on_mouse_down_out`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
fn on_mouse_down_out(
mut self,
listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
) -> Self {
self.interactivity().on_mouse_down_out(listener);
self
}
/// Bind the given callback to the mouse up event, for the given button, during the capture phase,
/// when the mouse is outside of the bounds of this element.
/// The fluent API equivalent to [`Interactivity::on_mouse_up_out`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
fn on_mouse_up_out(
mut self,
button: MouseButton,
listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
) -> Self {
self.interactivity().on_mouse_up_out(button, listener);
self
}
/// Bind the given callback to the mouse move event, during the bubble phase.
/// The fluent API equivalent to [`Interactivity::on_mouse_move`].
///
/// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
fn on_mouse_move(