1use std::sync::Arc;
10
11pub use nsh_macros::HostProps;
12
13use crate::{EdgeInsets, EventKind, element::TsTypes, geometry::Points, style::Color};
14
15pub trait HostInput: Sized {
17 fn is_nullish(&self) -> bool;
19 fn is_object(&self) -> bool;
21 fn as_bool(&self) -> Option<bool>;
23 fn as_number(&self) -> Option<f64>;
25 fn as_string(&self) -> Option<String>;
27 fn field(&self, key: &str) -> Option<Self>;
29 fn items(&self) -> Vec<Self> {
31 match self.as_list() {
32 Some(list) => (0..list.len()).filter_map(|i| list.item(i)).collect(),
33 None => Vec::new(),
34 }
35 }
36 fn as_list(&self) -> Option<Self::List>;
38 type List: HostList<Item = Self>;
40 fn entries(&self) -> Vec<(String, Self)>;
42 fn truthy(&self) -> bool;
44 fn node(&self) -> Option<crate::NodeId> {
46 None
47 }
48 fn animated_node(&self) -> Option<crate::animation::NodeId> {
50 self.field("__av")
51 .and_then(|v| v.as_number())
52 .map(|n| n as crate::animation::NodeId)
53 }
54}
55
56pub trait HostList {
58 type Item;
60 fn len(&self) -> usize;
62 fn is_empty(&self) -> bool {
64 self.len() == 0
65 }
66 fn item(&self, index: usize) -> Option<Self::Item>;
68}
69
70#[derive(Debug, Default)]
73pub struct HostCx {
74 pub warnings: Vec<String>,
76 pub element: u32,
80}
81
82impl HostCx {
83 pub fn for_element(tag: crate::Tag) -> Self {
85 Self {
86 element: element_bits(tag),
87 ..Self::default()
88 }
89 }
90
91 pub fn warn(&mut self, message: impl Into<String>) {
93 self.warnings.push(message.into());
94 }
95
96 pub fn on_element(&self, on: u32) -> bool {
99 self.element == 0 || self.element & on != 0
100 }
101}
102
103pub fn element_bits(tag: crate::Tag) -> u32 {
105 use crate::Tag;
106 on::ALL
107 | match tag {
108 Tag::Text => on::TEXT,
109 Tag::Image => on::IMAGE,
110 Tag::Scroll => on::SCROLLING | on::SCROLL,
111 Tag::List => on::SCROLLING | on::LIST,
112 Tag::Input => on::INPUT,
113 Tag::Screen => on::SCREEN,
114 Tag::Modal => on::MODAL,
115 Tag::WebView => on::WEBVIEW,
116 Tag::Video => on::VIDEO,
117 Tag::InputAccessory => on::INPUT_ACCESSORY,
118 Tag::View => on::VIEW,
119 Tag::Cell | Tag::Stack | Tag::HeaderItem | Tag::Canvas | Tag::Native | Tag::Overlay => {
120 0
121 }
122 }
123}
124
125pub trait HostValue: Sized {
129 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self>;
131 fn ts_type(types: &mut TsTypes) -> String;
133}
134
135pub mod on {
137 pub const ALL: u32 = 1;
139 pub const TEXT: u32 = 1 << 1;
141 pub const IMAGE: u32 = 1 << 2;
143 pub const SCROLLING: u32 = 1 << 3;
145 pub const SCROLL: u32 = 1 << 4;
147 pub const LIST: u32 = 1 << 5;
149 pub const INPUT: u32 = 1 << 6;
151 pub const SCREEN: u32 = 1 << 7;
153 pub const MODAL: u32 = 1 << 8;
155 pub const WEBVIEW: u32 = 1 << 9;
157 pub const VIDEO: u32 = 1 << 10;
159 pub const INPUT_ACCESSORY: u32 = 1 << 11;
161 pub const OVERLAY: u32 = 1 << 12;
163 pub const VIEW: u32 = 1 << 13;
165 pub const INTERNAL: u32 = 1 << 31;
167}
168
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172pub enum Platform {
173 All,
175 Ios,
177 Android,
179 Desktop,
181 Web,
183}
184
185#[derive(Debug, Clone)]
187pub struct HostPropSpec {
188 pub name: &'static str,
190 pub ts: String,
192 pub doc: &'static str,
194 pub on: u32,
196 pub platform: Platform,
198}
199
200pub trait HostProps: Sized {
202 fn decode<I: HostInput>(name: &str, input: &I, cx: &mut HostCx) -> Option<Option<Self>>;
205 fn reset(&self) -> Option<Self>;
208 fn same_kind(&self, other: &Self) -> bool;
210 fn specs(types: &mut TsTypes, out: &mut Vec<HostPropSpec>);
212}
213
214pub trait Clamped {
216 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self;
218}
219
220impl Clamped for f32 {
221 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
222 let v = min.map_or(self, |m| self.max(m as f32));
223 max.map_or(v, |m| v.min(m as f32))
224 }
225}
226
227impl Clamped for Points {
228 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
229 Points(self.0.clamped(min, max))
230 }
231}
232
233impl Clamped for u32 {
234 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
235 let v = min.map_or(self, |m| self.max(m as u32));
236 max.map_or(v, |m| v.min(m as u32))
237 }
238}
239
240impl<T: Clamped> Clamped for Option<T> {
241 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
242 self.map(|v| v.clamped(min, max))
243 }
244}
245
246impl HostValue for bool {
247 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
248 input.as_bool()
249 }
250
251 fn ts_type(_: &mut TsTypes) -> String {
252 "boolean".into()
253 }
254}
255
256impl HostValue for f32 {
257 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
258 input.as_number().map(|n| n as f32)
259 }
260
261 fn ts_type(_: &mut TsTypes) -> String {
262 "number".into()
263 }
264}
265
266impl HostValue for Points {
268 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
269 f32::decode(input, cx).map(Points)
270 }
271
272 fn ts_type(_: &mut TsTypes) -> String {
273 "number".into()
274 }
275}
276
277impl HostValue for u32 {
278 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
280 input.as_number().map(|n| n.max(0.0) as u32)
281 }
282
283 fn ts_type(_: &mut TsTypes) -> String {
284 "number".into()
285 }
286}
287
288impl HostValue for String {
289 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
291 input.as_string()
292 }
293
294 fn ts_type(_: &mut TsTypes) -> String {
295 "string".into()
296 }
297}
298
299impl HostValue for Arc<str> {
300 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
302 input.as_string().filter(|s| !s.is_empty()).map(Into::into)
303 }
304
305 fn ts_type(_: &mut TsTypes) -> String {
306 "string".into()
307 }
308}
309
310impl HostValue for Box<str> {
311 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
313 input.as_string().filter(|s| !s.is_empty()).map(Into::into)
314 }
315
316 fn ts_type(_: &mut TsTypes) -> String {
317 "string".into()
318 }
319}
320
321impl HostValue for Color {
322 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
324 input.as_string().and_then(|s| Color::parse(&s))
325 }
326
327 fn ts_type(_: &mut TsTypes) -> String {
328 "ColorValue".into()
329 }
330}
331
332impl<T: HostValue> HostValue for Option<T> {
334 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
335 Some(T::decode(input, cx))
336 }
337
338 fn ts_type(types: &mut TsTypes) -> String {
339 T::ts_type(types)
340 }
341}
342
343impl<T: HostValue> HostValue for Vec<T> {
345 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
346 Some(
347 input
348 .items()
349 .iter()
350 .filter_map(|i| T::decode(i, cx))
351 .collect(),
352 )
353 }
354
355 fn ts_type(types: &mut TsTypes) -> String {
356 format!("{}[]", T::ts_type(types))
357 }
358}
359
360impl HostValue for EdgeInsets {
362 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
363 let side = |key| Points(input.field(key).and_then(|v| v.as_number()).unwrap_or(0.0) as f32);
364 Some(EdgeInsets {
365 top: side("top"),
366 right: side("right"),
367 bottom: side("bottom"),
368 left: side("left"),
369 })
370 }
371
372 fn ts_type(_: &mut TsTypes) -> String {
373 "Partial<Edges>".into()
374 }
375}
376
377pub fn field<T: HostValue, I: HostInput>(input: &I, key: &str, cx: &mut HostCx) -> Option<T> {
379 input.field(key).and_then(|v| T::decode(&v, cx))
380}
381
382const EVENT_TYPES: &str = r#"/** A position, in points (`nsh_core::geometry::Point`). */
386export interface Point {
387 x: number;
388 y: number;
389}
390
391/** An extent, in points (`nsh_core::geometry::Size`). */
392export interface Size {
393 width: number;
394 height: number;
395}
396
397/** A position and an extent, in points (`nsh_core::geometry::Bounds`). */
398export interface Bounds {
399 /** The top left corner. */
400 origin: Point;
401 size: Size;
402}
403
404/** A length on each side, in points (`nsh_core::geometry::Edges`): insets, a safe area. */
405export interface Edges {
406 top: number;
407 right: number;
408 bottom: number;
409 left: number;
410}
411
412/** The modifier keys held (GPUI's `Modifiers`). */
413export interface Modifiers {
414 control: boolean;
415 /** Option on Apple platforms, Alt elsewhere. */
416 alt: boolean;
417 shift: boolean;
418 /** Command on Apple platforms, the Windows / Super key elsewhere. */
419 platform: boolean;
420}
421
422/** Where the core placed an overlay: the payload of `onPosition`. */
423export interface OverlayPosition {
424 /** The side of the anchor it went on: the one asked for, or the other one when only that one has room. */
425 placement: "top" | "bottom" | "left" | "right";
426 /** Its frame in the root view (the surface, or the dialog it is in). */
427 bounds: Bounds;
428 /** The room on that side, inside the safe area less `margin`: what a menu may grow to. */
429 available: Size;
430}
431
432/** A drag: translation since the start and velocity (points / second). */
433export interface PanEvent {
434 /** The system cancelled the drag rather than releasing it. */
435 cancelled: boolean;
436 translationX: number;
437 translationY: number;
438 velocityX: number;
439 velocityY: number;
440 /** The `pan.x` value now (with one). */
441 valueX?: number;
442 /** The `pan.y` value now (with one). */
443 valueY?: number;
444}
445
446/** Where the pointer was at a press, the modifier keys held when it began and its click count: the payload of `onPress`, `onLongPress`, `onPressDown` and `onPressUp` on backends that know it. */
447export interface PressEvent {
448 /** Position in the pressed view (its transforms undone; a pressed span's text view). */
449 position: Point;
450 /** Position in the root view the view is in (the surface or its modal), as touches' `pageX` / `pageY`. */
451 pagePosition: Point;
452 modifiers: Modifiers;
453 /** Consecutive clicks at the same place: 1 for a click, 2 for a double click. */
454 clickCount: number;
455}
456
457/** Where the mouse is over a hovered view: the payload of `onHoverMove` (GPUI's `MouseMoveEvent`). */
458export interface HoverEvent {
459 /** Position in the view (its transforms undone). */
460 position: Point;
461 /** Position in the root view the view is in (the surface or its modal), as touches' `pageX` / `pageY`. */
462 pagePosition: Point;
463 modifiers: Modifiers;
464}
465
466/** Where a context menu was asked for: the payload of `onContextMenu`. */
467export interface ContextMenuEvent {
468 /** Position in the view (its transforms undone). */
469 position: Point;
470 /** Position in the root view the view is in: where `Menu.popup` opens a menu (`Menu.popup(items, e.pagePosition)`). */
471 pagePosition: Point;
472 modifiers: Modifiers;
473}
474
475/** Where a scroll view is: the payload of `onScroll`. */
476export interface ScrollEvent {
477 /** The content offset. */
478 offset: Point;
479 /** The content's size (zoomed). */
480 contentSize: Size;
481 /** The scroll view's size. */
482 size: Size;
483 /** The zoom scale (1 unless the scroll view zooms). */
484 zoomScale: number;
485}
486
487/** Where an input's caret is: the payload of `onCaretMove`. */
488export interface CaretEvent {
489 /** The caret in the input (its border box), the input's own scrolling applied: as wide as the platform draws it, as tall as its line. Empty until the input is laid out. */
490 bounds: Bounds;
491 /** The caret in the root view the input is in (the surface or its dialog), as of the event: an `Overlay`'s `anchor`. */
492 pageBounds: Bounds;
493}
494
495/** What the user pasted into an input: the payload of `onPaste`. The platform read the clipboard as the user pasted; the app never reads it for this. */
496export interface PasteEvent {
497 /** The plain text, `""` when there was none. */
498 text: string;
499 /** Files with their bytes: images (a screenshot, an image copied from a page or an app), as `File`s an app can upload. */
500 files: File[];
501 /** `file:` URLs of local files copied in a file manager (as `onFileDrop`'s). */
502 uris: string[];
503}
504
505/** A line of a laid-out text (in the text's content box). */
506export interface TextLayoutLine {
507 text: string;
508 bounds: Bounds;
509 ascender: number;
510 descender: number;
511 capHeight: number;
512 xHeight: number;
513}
514
515/** Where a web view is: the payload of its navigation events. */
516export interface WebViewNavigation {
517 url: string;
518 title: string;
519 loading: boolean;
520 canGoBack: boolean;
521 canGoForward: boolean;
522}
523"#;
524
525pub const EVENTS: &[(EventKind, u32, &str, &str)] = &[
530 (
531 EventKind::Press,
532 on::ALL,
533 "(e?: PressEvent) => void",
534 "A tap. `e` is where the pointer was, with the modifier keys and the click count, on backends that know it.",
535 ),
536 (
537 EventKind::LongPress,
538 on::ALL,
539 "(e?: PressEvent) => void",
540 "A press held for about half a second. `e` is where the pointer was, with the modifier keys and the click count, on backends that know it.",
541 ),
542 (
543 EventKind::PressDown,
544 on::ALL,
545 "(e?: PressEvent) => void",
546 "A press went down. `e` is where the pointer was, with the modifier keys and the click count, on backends that know it.",
547 ),
548 (
549 EventKind::PressUp,
550 on::ALL,
551 "(e?: PressEvent) => void",
552 "The press ended. `e` is where the pointer was, with the modifier keys and the click count, on backends that know it.",
553 ),
554 (
555 EventKind::HoverIn,
556 on::ALL,
557 "() => void",
558 "The mouse came over the view or a view inside it (never on touches).",
559 ),
560 (
561 EventKind::HoverOut,
562 on::ALL,
563 "() => void",
564 "The mouse left the view and the views inside it, or the window.",
565 ),
566 (
567 EventKind::HoverMove,
568 on::ALL,
569 "(e: HoverEvent) => void",
570 "The mouse moved over the view (or a view inside it) with no button down, at most once per frame.",
571 ),
572 (
573 EventKind::ContextMenu,
574 on::ALL,
575 "(e: ContextMenuEvent) => void",
576 "The secondary button (a right click, Control-click on Apple platforms) was pressed over the view: open a menu with `Menu.popup(items, e.pagePosition)`. The nearest listener hears it; a text input or selectable text nearer shows its own menu instead.",
577 ),
578 (
579 EventKind::MouseMove,
580 on::ALL,
581 "(e: Point) => void",
582 "The mouse moved inside the view, including with a button down (desktops and web); `x`/`y` are local coordinates in points, delivered at most once per frame.",
583 ),
584 (
585 EventKind::FileDragEnter,
586 on::ALL,
587 "() => void",
588 "A local file drag entered this desktop destination.",
589 ),
590 (
591 EventKind::FileDragLeave,
592 on::ALL,
593 "() => void",
594 "A local file drag left this desktop destination.",
595 ),
596 (
597 EventKind::FileDrop,
598 on::ALL,
599 "(e: { uris: string[] }) => void",
600 "Local file URLs dropped on this desktop destination.",
601 ),
602 (
603 EventKind::Layout,
604 on::ALL,
605 "(bounds: Bounds) => void",
606 "The frame changed: its bounds in the parent.",
607 ),
608 (EventKind::PanStart, on::ALL, "(e: PanEvent) => void", ""),
609 (
610 EventKind::PanEnd,
611 on::ALL,
612 "(e: PanEvent) => void",
613 "With the release velocity, e.g. to start a `decay`.",
614 ),
615 (
616 EventKind::PinchStart,
617 on::ALL,
618 "(e: { scale: number; velocity: number }) => void",
619 "",
620 ),
621 (
622 EventKind::PinchEnd,
623 on::ALL,
624 "(e: { scale: number; velocity: number }) => void",
625 "",
626 ),
627 (
628 EventKind::RotationStart,
629 on::ALL,
630 "(e: { rotation: number; velocity: number }) => void",
631 "",
632 ),
633 (
634 EventKind::RotationEnd,
635 on::ALL,
636 "(e: { rotation: number; velocity: number }) => void",
637 "",
638 ),
639 (
640 EventKind::AccessibilityAction,
641 on::ALL,
642 "(e: { actionName: string }) => void",
643 "",
644 ),
645 (
646 EventKind::TextLayout,
647 on::TEXT,
648 "(e: { lines: TextLayoutLine[] }) => void",
649 "The laid-out lines (in the text's content box), after each layout.",
650 ),
651 (
652 EventKind::LoadStart,
653 on::IMAGE | on::VIDEO,
654 "() => void",
655 "",
656 ),
657 (
658 EventKind::LoadStart,
659 on::WEBVIEW,
660 "(e: WebViewNavigation) => void",
661 "",
662 ),
663 (
664 EventKind::Progress,
665 on::IMAGE,
666 "(e: { loaded: number; total: number }) => void",
667 "Download progress in bytes (`total` 0 when unknown); at most every 100 ms.",
668 ),
669 (
670 EventKind::Progress,
671 on::VIDEO,
672 "(e: { currentTime: number; duration: number }) => void",
673 "",
674 ),
675 (
676 EventKind::Load,
677 on::IMAGE,
678 "(e: Size) => void",
679 "The source image's size in pixels (not the decoded, downsampled one).",
680 ),
681 (
682 EventKind::Load,
683 on::WEBVIEW,
684 "(e: WebViewNavigation) => void",
685 "",
686 ),
687 (
688 EventKind::Load,
689 on::VIDEO,
690 "(e: { duration: number; size: Size }) => void",
691 "",
692 ),
693 (
694 EventKind::Error,
695 on::IMAGE | on::WEBVIEW | on::VIDEO,
696 "(e: { message: string }) => void",
697 "",
698 ),
699 (
700 EventKind::LoadEnd,
701 on::IMAGE,
702 "() => void",
703 "After `onLoad` or `onError`.",
704 ),
705 (
706 EventKind::Scroll,
707 on::SCROLLING,
708 "(e: ScrollEvent) => void",
709 "",
710 ),
711 (
712 EventKind::ScrollDragStart,
713 on::SCROLLING,
714 "(e: Point) => void",
715 "",
716 ),
717 (
718 EventKind::ScrollDragEnd,
719 on::SCROLLING,
720 "(e: Point) => void",
721 "",
722 ),
723 (
724 EventKind::MomentumStart,
725 on::SCROLLING,
726 "(e: Point) => void",
727 "",
728 ),
729 (
730 EventKind::MomentumEnd,
731 on::SCROLLING,
732 "(e: Point) => void",
733 "",
734 ),
735 (
736 EventKind::ScrollEnd,
737 on::SCROLL | on::LIST,
738 "(e: Point) => void",
739 "",
740 ),
741 (EventKind::Refresh, on::SCROLL | on::LIST, "() => void", ""),
742 (EventKind::LoadMore, on::LIST, "() => void", ""),
743 (
744 EventKind::LoadMoreAtStart,
745 on::LIST,
746 "() => void",
747 "Within `loadMoreAtStartThreshold` viewports of the start, once the user or a scroll command moved the list: load what comes before the first item.",
748 ),
749 (
750 EventKind::ChangeText,
751 on::INPUT,
752 "(text: string) => void",
753 "",
754 ),
755 (
756 EventKind::SubmitEditing,
757 on::INPUT,
758 "(e: { text: string }) => void",
759 "",
760 ),
761 (
762 EventKind::Focus,
763 on::ALL,
764 "() => void",
765 "It took the keyboard focus: an input, or a view that takes presses reached by Tab on the platforms that move the focus between pressables (macOS, the web).",
766 ),
767 (
768 EventKind::Blur,
769 on::ALL,
770 "() => void",
771 "It lost the keyboard focus.",
772 ),
773 (
774 EventKind::SelectionChange,
775 on::INPUT,
776 "(e: { start: number; end: number }) => void",
777 "",
778 ),
779 (
780 EventKind::Paste,
781 on::INPUT,
782 "(e: PasteEvent) => void",
783 "The user pasted (the keyboard's shortcut, a menu's Paste, a keyboard's image): the text, images as `File`s, local files' `file:` URLs. It comes before the `onChange` of the text it inserts; `pasteBehavior` decides whether the input inserts the text (images and files never are).",
784 ),
785 (
786 EventKind::CaretMove,
787 on::INPUT,
788 "(e: CaretEvent) => void",
789 "The caret moved: with the selection, or as the text scrolled or wrapped again. `bounds` is where it is in the input, `pageBounds` in the root view (an `Overlay`'s `anchor`): an `@` mention's suggestions open there.",
790 ),
791 (
792 EventKind::KeyPress,
793 on::INPUT,
794 "(e: { key: string }) => void",
795 "Before the text changes: `key` is the typed text, `Backspace` or `Enter`.",
796 ),
797 (
798 EventKind::CompositionChange,
799 on::INPUT,
800 "(e: { composing: boolean; text: string }) => void",
801 "An input method's composition started, changed or ended: `text` is what is being composed (pinyin before a character is chosen), empty once it ends. The committed text reaches `onChange` before the composition's end; while composing, the platform holds the `value` the app sets and shows it once the composition ends.",
802 ),
803 (
804 EventKind::ContentSizeChange,
805 on::INPUT,
806 "(e: Size) => void",
807 "The size of the text (at the input's width when `multiline`; one empty line's while it is empty, whatever its placeholder): grow a multiline input with it.",
808 ),
809 (
810 EventKind::Message,
811 on::WEBVIEW,
812 "(e: { data: string }) => void",
813 "The page called `window.nsh.postMessage(data)`.",
814 ),
815 (
816 EventKind::NavigationStateChange,
817 on::WEBVIEW,
818 "(e: WebViewNavigation) => void",
819 "",
820 ),
821 (EventKind::End, on::VIDEO, "() => void", ""),
822 (
823 EventKind::Buffer,
824 on::VIDEO,
825 "(e: { isBuffering: boolean }) => void",
826 "",
827 ),
828 (
829 EventKind::PressOutside,
830 on::OVERLAY,
831 "(e: { pagePosition: Point }) => void",
832 "A press went down outside the overlay, its anchor and the overlays inside it (where, in the root view). Closing is the app's: leave the overlay out.",
833 ),
834 (
835 EventKind::Cancel,
836 on::OVERLAY,
837 "() => void",
838 "Escape or the Android back button, while this is the top overlay listening to it (it takes the key from the overlays below, the pages and `BackHandler`). Closing is the app's.",
839 ),
840 (
841 EventKind::Position,
842 on::OVERLAY,
843 "(e: OverlayPosition) => void",
844 "The core placed the overlay (again: the anchor moved, the overlay changed size, it went to the other side).",
845 ),
846];
847
848pub const INTERNAL_EVENTS: &[EventKind] = &[
853 EventKind::Touch,
854 EventKind::Insets,
855 EventKind::NativeEvent,
856 EventKind::Dialog,
857 EventKind::BackPress,
858 EventKind::ImageInfo,
859 EventKind::Clipboard,
860 EventKind::Host,
861 EventKind::Pick,
862 EventKind::OpenUrl,
863 EventKind::KeyCommand,
864 EventKind::Menu,
865 EventKind::ViewableItemsChange,
866 EventKind::BackRequest,
870 EventKind::Dismiss,
871 EventKind::RequestClose,
872 EventKind::Show,
873];
874
875const GROUPS: &[(u32, &str, &str)] = &[
878 (on::ALL, "", "every element"),
879 (on::VIEW, "View", "`<View>`"),
880 (on::TEXT, "Text", "`<Text>`"),
881 (on::IMAGE, "Image", "`<Image>`"),
882 (
883 on::SCROLLING,
884 "Scrolling",
885 "scroll views and lists (how they scroll)",
886 ),
887 (on::SCROLL, "Scroll", "`<Scroll>`"),
888 (on::LIST, "List", "lists"),
889 (on::INPUT, "Input", "`<Input>`"),
890 (on::SCREEN, "NavPage", "the pages of a `NavStack`"),
891 (on::MODAL, "Dialog", "dialogs"),
892 (on::WEBVIEW, "WebView", "web views"),
893 (on::VIDEO, "Video", "videos"),
894 (on::INPUT_ACCESSORY, "InputAccessory", "input accessories"),
895 (on::OVERLAY, "Overlay", "`<Overlay>`"),
896];
897
898pub fn declarations() -> String {
903 use std::fmt::Write as _;
904 let mut types = TsTypes::default();
905 let mut specs = Vec::new();
906 <crate::Prop as HostProps>::specs(&mut types, &mut specs);
907 let mut out = String::from(EVENT_TYPES);
908 for declaration in types.declarations() {
909 let _ = write!(out, "\n{declaration}\n");
910 }
911 for (bit, group, what) in GROUPS {
912 for (platform, prefix, inside) in [
913 (Platform::All, "", ""),
914 (Platform::Ios, "IOS", " inside `ios={{…}}`"),
915 (Platform::Android, "Android", " inside `android={{…}}`"),
916 (Platform::Desktop, "Desktop", " inside `desktop={{…}}`"),
917 (Platform::Web, "Web", " inside `web={{…}}`"),
918 ] {
919 let props: Vec<&HostPropSpec> = specs
920 .iter()
921 .filter(|s| s.on & bit != 0 && s.platform == platform)
922 .collect();
923 let events: Vec<_> = EVENTS
925 .iter()
926 .filter(|e| e.1 & bit != 0 && platform == Platform::All)
927 .collect();
928 if props.is_empty() && events.is_empty() {
929 continue;
930 }
931 let _ = write!(
932 out,
933 "\n/** The props of {what}{inside}. */\nexport interface {prefix}{group}HostProps {{\n"
934 );
935 for p in props {
936 if !p.doc.is_empty() {
937 let _ = writeln!(out, " /** {} */", p.doc);
938 }
939 let _ = writeln!(out, " {}?: {};", p.name, p.ts);
940 }
941 for (kind, _, handler, doc) in events {
942 if !doc.is_empty() {
943 let _ = writeln!(out, " /** {doc} */");
944 }
945 let _ = writeln!(out, " {}?: {handler};", kind.handler_name());
946 }
947 out.push_str("}\n");
948 }
949 }
950 out
951}