1use std::sync::Arc;
16
17pub use nsh_macros::HostProps;
18
19use crate::{EdgeInsets, EventKind, element::TsTypes, geometry::Points, style::Color};
20
21pub trait HostInput: Sized {
23 fn is_nullish(&self) -> bool;
25 fn is_object(&self) -> bool;
27 fn as_bool(&self) -> Option<bool>;
29 fn as_number(&self) -> Option<f64>;
31 fn as_string(&self) -> Option<String>;
33 fn field(&self, key: &str) -> Option<Self>;
35 fn items(&self) -> Vec<Self> {
37 match self.as_list() {
38 Some(list) => (0..list.len()).filter_map(|i| list.item(i)).collect(),
39 None => Vec::new(),
40 }
41 }
42 fn as_list(&self) -> Option<Self::List>;
44 type List: HostList<Item = Self>;
46 fn entries(&self) -> Vec<(String, Self)>;
48 fn truthy(&self) -> bool;
50 fn node(&self) -> Option<crate::NodeId> {
52 None
53 }
54 fn animated_node(&self) -> Option<crate::animation::NodeId> {
56 self.field("__av")
57 .and_then(|v| v.as_number())
58 .map(|n| n as crate::animation::NodeId)
59 }
60}
61
62pub trait HostList {
64 type Item;
66 fn len(&self) -> usize;
68 fn is_empty(&self) -> bool {
70 self.len() == 0
71 }
72 fn item(&self, index: usize) -> Option<Self::Item>;
74}
75
76#[derive(Debug, Default)]
79pub struct HostCx {
80 pub warnings: Vec<String>,
82 pub element: u32,
86}
87
88impl HostCx {
89 pub fn for_element(tag: crate::Tag) -> Self {
91 Self {
92 element: element_bits(tag),
93 ..Self::default()
94 }
95 }
96
97 pub fn warn(&mut self, message: impl Into<String>) {
99 self.warnings.push(message.into());
100 }
101
102 pub fn on_element(&self, on: u32) -> bool {
105 self.element == 0 || self.element & on != 0
106 }
107}
108
109pub fn element_bits(tag: crate::Tag) -> u32 {
111 use crate::Tag;
112 on::ALL
113 | match tag {
114 Tag::Text => on::TEXT,
115 Tag::Image => on::IMAGE,
116 Tag::Scroll => on::SCROLLING | on::SCROLL,
117 Tag::List => on::SCROLLING | on::LIST,
118 Tag::Input => on::INPUT,
119 Tag::Screen => on::SCREEN,
120 Tag::Modal => on::MODAL,
121 Tag::WebView => on::WEBVIEW,
122 Tag::Video => on::VIDEO,
123 Tag::InputAccessory => on::INPUT_ACCESSORY,
124 Tag::View => on::VIEW,
125 Tag::Shader => on::VIEW | on::SHADER,
126 Tag::ShaderEffect => on::VIEW | on::SHADER | on::EFFECT,
127 Tag::ShaderTransition => on::VIEW | on::SHADER | on::TRANSITION,
128 Tag::ScreenEffect => on::SHADER | on::EFFECT,
129 Tag::ScreenTransition => on::SHADER | on::TRANSITION,
130 Tag::Cell | Tag::Stack | Tag::HeaderItem | Tag::Canvas | Tag::Native | Tag::Overlay => {
131 0
132 }
133 }
134}
135
136pub type StylePatchProp = fn(Option<std::rc::Rc<crate::StylePatch>>) -> crate::Prop;
139
140#[inline]
145pub fn style_patch_prop(name: &str) -> Option<StylePatchProp> {
146 use crate::Prop;
147 Some(match name {
148 "activeStyle" => Prop::ActiveStyle,
149 "hoverStyle" => Prop::HoverStyle,
150 "focusStyle" => Prop::FocusStyle,
151 "disabledStyle" => Prop::DisabledStyle,
152 "selectedStyle" => Prop::SelectedStyle,
153 "checkedStyle" => Prop::CheckedStyle,
154 "indeterminateStyle" => Prop::IndeterminateStyle,
155 "expandedStyle" => Prop::ExpandedStyle,
156 "pressedStyle" => Prop::PressedStyle,
157 "focusWithinStyle" => Prop::FocusWithinStyle,
158 "headerStyle" => Prop::HeaderStyle,
159 _ => return None,
160 })
161}
162
163pub type PartClassProp = fn(Box<str>) -> crate::Prop;
166
167#[inline]
172pub fn part_class_prop(name: &str, tag: Option<crate::Tag>) -> Option<PartClassProp> {
173 use crate::{Prop, Tag};
174 match name {
175 "headerClass" => Some(Prop::HeaderClass),
176 "contentClass" if tag != Some(Tag::Scroll) => Some(Prop::ListContentClass),
177 _ => None,
178 }
179}
180
181pub trait HostValue: Sized {
185 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self>;
187 fn ts_type(types: &mut TsTypes) -> String;
189}
190
191pub mod on {
193 pub const ALL: u32 = 1;
195 pub const TEXT: u32 = 1 << 1;
197 pub const IMAGE: u32 = 1 << 2;
199 pub const SCROLLING: u32 = 1 << 3;
201 pub const SCROLL: u32 = 1 << 4;
203 pub const LIST: u32 = 1 << 5;
205 pub const INPUT: u32 = 1 << 6;
207 pub const SCREEN: u32 = 1 << 7;
209 pub const MODAL: u32 = 1 << 8;
211 pub const WEBVIEW: u32 = 1 << 9;
213 pub const VIDEO: u32 = 1 << 10;
215 pub const INPUT_ACCESSORY: u32 = 1 << 11;
217 pub const OVERLAY: u32 = 1 << 12;
219 pub const VIEW: u32 = 1 << 13;
221 pub const SHADER: u32 = 1 << 14;
223 pub const EFFECT: u32 = 1 << 15;
225 pub const TRANSITION: u32 = 1 << 16;
227 pub const INTERNAL: u32 = 1 << 31;
229}
230
231#[derive(Debug, Clone, Copy, PartialEq, Eq)]
234pub enum Platform {
235 All,
237 Ios,
239 Android,
241 Desktop,
243 Web,
245}
246
247#[derive(Debug, Clone)]
249pub struct HostPropSpec {
250 pub name: &'static str,
252 pub ts: String,
254 pub doc: &'static str,
256 pub on: u32,
258 pub platform: Platform,
260}
261
262pub trait HostProps: Sized {
264 fn decode<I: HostInput>(name: &str, input: &I, cx: &mut HostCx) -> Option<Option<Self>>;
267 fn reset(&self) -> Option<Self>;
270 fn same_kind(&self, other: &Self) -> bool;
272 fn specs(types: &mut TsTypes, out: &mut Vec<HostPropSpec>);
274}
275
276pub trait Clamped {
278 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self;
280}
281
282impl Clamped for f32 {
283 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
284 let v = min.map_or(self, |m| self.max(m as f32));
285 max.map_or(v, |m| v.min(m as f32))
286 }
287}
288
289impl Clamped for Points {
290 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
291 Points(self.0.clamped(min, max))
292 }
293}
294
295impl Clamped for u32 {
296 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
297 let v = min.map_or(self, |m| self.max(m as u32));
298 max.map_or(v, |m| v.min(m as u32))
299 }
300}
301
302impl<T: Clamped> Clamped for Option<T> {
303 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
304 self.map(|v| v.clamped(min, max))
305 }
306}
307
308impl HostValue for bool {
309 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
310 input.as_bool()
311 }
312
313 fn ts_type(_: &mut TsTypes) -> String {
314 "boolean".into()
315 }
316}
317
318impl HostValue for f32 {
319 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
320 input.as_number().map(|n| n as f32)
321 }
322
323 fn ts_type(_: &mut TsTypes) -> String {
324 "number".into()
325 }
326}
327
328impl HostValue for Points {
330 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
331 f32::decode(input, cx).map(Points)
332 }
333
334 fn ts_type(_: &mut TsTypes) -> String {
335 "number".into()
336 }
337}
338
339impl HostValue for u32 {
340 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
342 input.as_number().map(|n| n.max(0.0) as u32)
343 }
344
345 fn ts_type(_: &mut TsTypes) -> String {
346 "number".into()
347 }
348}
349
350impl HostValue for String {
351 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
353 input.as_string()
354 }
355
356 fn ts_type(_: &mut TsTypes) -> String {
357 "string".into()
358 }
359}
360
361impl HostValue for Arc<str> {
362 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
364 input.as_string().filter(|s| !s.is_empty()).map(Into::into)
365 }
366
367 fn ts_type(_: &mut TsTypes) -> String {
368 "string".into()
369 }
370}
371
372impl HostValue for Box<str> {
373 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
375 input.as_string().filter(|s| !s.is_empty()).map(Into::into)
376 }
377
378 fn ts_type(_: &mut TsTypes) -> String {
379 "string".into()
380 }
381}
382
383impl HostValue for Color {
384 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
386 input.as_string().and_then(|s| Color::parse(&s))
387 }
388
389 fn ts_type(_: &mut TsTypes) -> String {
390 "ColorValue".into()
391 }
392}
393
394impl<T: HostValue> HostValue for Option<T> {
396 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
397 Some(T::decode(input, cx))
398 }
399
400 fn ts_type(types: &mut TsTypes) -> String {
401 T::ts_type(types)
402 }
403}
404
405impl<T: HostValue> HostValue for Vec<T> {
407 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
408 Some(
409 input
410 .items()
411 .iter()
412 .filter_map(|i| T::decode(i, cx))
413 .collect(),
414 )
415 }
416
417 fn ts_type(types: &mut TsTypes) -> String {
418 format!("{}[]", T::ts_type(types))
419 }
420}
421
422impl HostValue for EdgeInsets {
424 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
425 let side = |key| Points(input.field(key).and_then(|v| v.as_number()).unwrap_or(0.0) as f32);
426 Some(EdgeInsets {
427 top: side("top"),
428 right: side("right"),
429 bottom: side("bottom"),
430 left: side("left"),
431 })
432 }
433
434 fn ts_type(_: &mut TsTypes) -> String {
435 "Partial<Edges>".into()
436 }
437}
438
439pub fn field<T: HostValue, I: HostInput>(input: &I, key: &str, cx: &mut HostCx) -> Option<T> {
441 input.field(key).and_then(|v| T::decode(&v, cx))
442}
443
444const EVENT_TYPES: &str = r#"/** A position, in points (`nsh_core::geometry::Point`). */
448export interface Point {
449 x: number;
450 y: number;
451}
452
453/** An extent, in points (`nsh_core::geometry::Size`). */
454export interface Size {
455 width: number;
456 height: number;
457}
458
459/** An image's or a video's own extent, in pixels as decoded
460 * (`nsh_core::geometry::Size<DevicePixels>`), not the points it is drawn at. */
461export interface PixelSize {
462 width: number;
463 height: number;
464}
465
466/** A position and an extent, in points (`nsh_core::geometry::Bounds`). */
467export interface Bounds {
468 /** The top left corner. */
469 origin: Point;
470 size: Size;
471}
472
473/** A length on each side, in points (`nsh_core::geometry::Edges`): insets, a safe area. */
474export interface Edges {
475 top: number;
476 right: number;
477 bottom: number;
478 left: number;
479}
480
481/** The modifier keys held (GPUI's `Modifiers`). */
482export interface Modifiers {
483 control: boolean;
484 /** Option on Apple platforms, Alt elsewhere. */
485 alt: boolean;
486 shift: boolean;
487 /** Command on Apple platforms, the Windows / Super key elsewhere. */
488 platform: boolean;
489}
490
491/** Where the core placed an overlay: the payload of `onPosition`. */
492export interface OverlayPosition {
493 /** The side of the anchor it went on: the one asked for, or the other one when only that one has room. */
494 placement: "top" | "bottom" | "left" | "right";
495 /** Its frame in the root view (the surface, or the dialog it is in). */
496 bounds: Bounds;
497 /** The room on that side, inside the safe area less `margin`: what a menu may grow to. */
498 available: Size;
499}
500
501/** A drag: translation since the start and velocity (points / second). */
502export interface PanEvent {
503 /** The system cancelled the drag rather than releasing it. */
504 cancelled: boolean;
505 /** How far the finger moved since the drag started. */
506 translation: Point;
507 /** How fast it moves, in points per second. */
508 velocity: Point;
509 /** The values `pan` binds now, those of the axes it binds (`pan.x`, `pan.y`). */
510 value?: Partial<Point>;
511}
512
513/** 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. */
514export interface PressEvent {
515 /** Position in the pressed view (its transforms undone; a pressed span's text view). */
516 position: Point;
517 /** Position in the root view the view is in (the surface or its modal), as touches' `pageX` / `pageY`. */
518 pagePosition: Point;
519 modifiers: Modifiers;
520 /** Consecutive clicks at the same place: 1 for a click, 2 for a double click. */
521 clickCount: number;
522}
523
524/** Where the mouse is over a view: the payload of `onMouseEnter`, `onMouseMove` and `onMouseLeave` (GPUI's `MouseMoveEvent`). */
525export interface MouseEvent {
526 /** Position in the view (its transforms undone). */
527 position: Point;
528 /** Position in the root view the view is in (the surface or its modal), as touches' `pageX` / `pageY`. */
529 pagePosition: Point;
530 modifiers: Modifiers;
531 /** The button held down (a drag), or `null`. */
532 pressedButton: MouseButton | null;
533}
534
535/** A mouse button (GPUI's `MouseButton`). */
536export type MouseButton = "left" | "right" | "middle" | "back" | "forward";
537
538/** Where a context menu was asked for: the payload of `onContextMenu`. */
539export interface ContextMenuEvent {
540 /** Position in the view (its transforms undone). */
541 position: Point;
542 /** Position in the root view the view is in: where `Menu.popup` opens a menu (`Menu.popup(items, e.pagePosition)`). */
543 pagePosition: Point;
544 modifiers: Modifiers;
545}
546
547/** Where a scroll view is: the payload of `onScroll`. */
548export interface ScrollEvent {
549 /** The content offset. */
550 offset: Point;
551 /** The content's size (zoomed). */
552 contentSize: Size;
553 /** The scroll view's size. */
554 size: Size;
555 /** The zoom scale (1 unless the scroll view zooms). */
556 zoomScale: number;
557}
558
559/** Where an input's caret is: the payload of `onCaretMove`. */
560export interface CaretEvent {
561 /** 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. */
562 bounds: Bounds;
563 /** The caret in the root view the input is in (the surface or its dialog), as of the event: an `Overlay`'s `anchor`. */
564 pageBounds: Bounds;
565}
566
567/** 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. */
568export interface PasteEvent {
569 /** The plain text, `""` when there was none. */
570 text: string;
571 /** The same content as HTML (`text/html`), with its formatting: what a browser, an office suite or a rich text editor copied; `""` when there was none. */
572 html: string;
573 /** Files with their bytes: images (a screenshot, an image copied from a page or an app), as `File`s an app can upload. */
574 files: File[];
575 /** `file:` URLs of local files copied in a file manager (as `onFileDrop`'s). */
576 uris: string[];
577}
578
579/** A line of a laid-out text (in the text's content box). */
580export interface TextLayoutLine {
581 text: string;
582 bounds: Bounds;
583 ascender: number;
584 descender: number;
585 capHeight: number;
586 xHeight: number;
587}
588
589/** Where a web view is: the payload of its navigation events. */
590export interface WebViewNavigation {
591 url: string;
592 title: string;
593 loading: boolean;
594 canGoBack: boolean;
595 canGoForward: boolean;
596}
597
598/** A web view's download (`onDownload`): where it is saved, in the app's data directory's `downloads`. */
599export interface WebViewDownload {
600 state: "started" | "finished" | "failed";
601 id: string;
602 url: string;
603 filename: string;
604 path: string;
605 /** Once finished: the file's size in bytes. */
606 bytes?: number;
607 /** When it failed: why. */
608 message?: string;
609}
610"#;
611
612pub const EVENTS: &[(EventKind, u32, &str, &str)] = &[
617 (
618 EventKind::Press,
619 on::ALL,
620 "(e: PressEvent) => void",
621 "A tap. `e` is where the pointer was, with the modifier keys and the click count (at the view's origin, with no keys and one click, on backends that do not know the pointer).",
622 ),
623 (
624 EventKind::LongPress,
625 on::ALL,
626 "(e: PressEvent) => void",
627 "A press held for about half a second. `e` is where the pointer was, with the modifier keys and the click count (at the view's origin, with no keys and one click, on backends that do not know the pointer).",
628 ),
629 (
630 EventKind::PressDown,
631 on::ALL,
632 "(e: PressEvent) => void",
633 "A press went down. `e` is where the pointer was, with the modifier keys and the click count (at the view's origin, with no keys and one click, on backends that do not know the pointer).",
634 ),
635 (
636 EventKind::PressUp,
637 on::ALL,
638 "(e: PressEvent) => void",
639 "The press ended. `e` is where the pointer was, with the modifier keys and the click count (at the view's origin, with no keys and one click, on backends that do not know the pointer).",
640 ),
641 (
642 EventKind::MouseEnter,
643 on::ALL,
644 "(e: MouseEvent) => void",
645 "The mouse came over the view or a view inside it (never on touches; the DOM's `mouseenter`).",
646 ),
647 (
648 EventKind::MouseLeave,
649 on::ALL,
650 "(e: MouseEvent) => void",
651 "The mouse left the view and the views inside it, or the window, from where `e` says (the DOM's `mouseleave`).",
652 ),
653 (
654 EventKind::MouseMove,
655 on::ALL,
656 "(e: MouseEvent) => void",
657 "The mouse moved over the view (or a view inside it), with or without a button down (`e.pressedButton`), or a modifier key changed while it rests there with none down; at most once per frame.",
658 ),
659 (
660 EventKind::ContextMenu,
661 on::ALL,
662 "(e: ContextMenuEvent) => void",
663 "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.",
664 ),
665 (
666 EventKind::FileDragEnter,
667 on::ALL,
668 "() => void",
669 "A local file drag entered this desktop destination.",
670 ),
671 (
672 EventKind::FileDragLeave,
673 on::ALL,
674 "() => void",
675 "A local file drag left this desktop destination.",
676 ),
677 (
678 EventKind::FileDrop,
679 on::ALL,
680 "(e: { uris: string[]; pagePosition?: { x: number; y: number } }) => void",
681 "Local file URLs dropped on this desktop destination; `pagePosition`: where, in the window's coordinates, on backends that know it (Linux).",
682 ),
683 (
684 EventKind::Layout,
685 on::ALL,
686 "(e: { bounds: Bounds }) => void",
687 "The frame changed: its bounds in the parent.",
688 ),
689 (EventKind::PanStart, on::ALL, "(e: PanEvent) => void", ""),
690 (
691 EventKind::PanEnd,
692 on::ALL,
693 "(e: PanEvent) => void",
694 "With the release velocity, e.g. to start a `decay`.",
695 ),
696 (
697 EventKind::PinchStart,
698 on::ALL,
699 "(e: { scale: number; velocity: number }) => void",
700 "",
701 ),
702 (
703 EventKind::PinchEnd,
704 on::ALL,
705 "(e: { scale: number; velocity: number }) => void",
706 "",
707 ),
708 (
709 EventKind::RotationStart,
710 on::ALL,
711 "(e: { rotation: number; velocity: number }) => void",
712 "",
713 ),
714 (
715 EventKind::RotationEnd,
716 on::ALL,
717 "(e: { rotation: number; velocity: number }) => void",
718 "",
719 ),
720 (
721 EventKind::AccessibilityAction,
722 on::ALL,
723 "(e: { actionName: string }) => void",
724 "",
725 ),
726 (
727 EventKind::TextLayout,
728 on::TEXT,
729 "(e: { lines: TextLayoutLine[] }) => void",
730 "The laid-out lines (in the text's content box), after each layout.",
731 ),
732 (
733 EventKind::LoadStart,
734 on::IMAGE | on::VIDEO,
735 "() => void",
736 "",
737 ),
738 (
739 EventKind::LoadStart,
740 on::WEBVIEW,
741 "(e: WebViewNavigation) => void",
742 "",
743 ),
744 (
745 EventKind::Progress,
746 on::IMAGE,
747 "(e: { loaded: number; total: number }) => void",
748 "Download progress in bytes (`total` 0 when unknown); at most every 100 ms.",
749 ),
750 (
751 EventKind::Progress,
752 on::VIDEO,
753 "(e: { currentTime: number; duration: number }) => void",
754 "",
755 ),
756 (
757 EventKind::Load,
758 on::IMAGE,
759 "(e: { size: PixelSize }) => void",
760 "The source image's size in pixels (not the decoded, downsampled one).",
761 ),
762 (
763 EventKind::Load,
764 on::WEBVIEW,
765 "(e: WebViewNavigation) => void",
766 "",
767 ),
768 (
769 EventKind::Load,
770 on::VIDEO,
771 "(e: { duration: number; size: PixelSize }) => void",
772 "",
773 ),
774 (
775 EventKind::Error,
776 on::IMAGE | on::WEBVIEW | on::VIDEO,
777 "(e: { message: string; code?: string }) => void",
778 "The source failed to load. `code` is `\"ERR_ACCESS_DENIED\"` when the app's capabilities do not grant it (an image's or video's URL: `network`; a web view's page or `html`: `webview`).",
779 ),
780 (
781 EventKind::LoadEnd,
782 on::IMAGE,
783 "() => void",
784 "After `onLoad` or `onError`.",
785 ),
786 (
787 EventKind::Scroll,
788 on::SCROLLING,
789 "(e: ScrollEvent) => void",
790 "",
791 ),
792 (
793 EventKind::ScrollDragStart,
794 on::SCROLLING,
795 "(e: { offset: Point }) => void",
796 "",
797 ),
798 (
799 EventKind::ScrollDragEnd,
800 on::SCROLLING,
801 "(e: { offset: Point }) => void",
802 "",
803 ),
804 (
805 EventKind::MomentumStart,
806 on::SCROLLING,
807 "(e: { offset: Point }) => void",
808 "",
809 ),
810 (
811 EventKind::MomentumEnd,
812 on::SCROLLING,
813 "(e: { offset: Point }) => void",
814 "",
815 ),
816 (
817 EventKind::ScrollEnd,
818 on::SCROLL | on::LIST,
819 "(e: { offset: Point }) => void",
820 "",
821 ),
822 (EventKind::Refresh, on::SCROLL | on::LIST, "() => void", ""),
823 (EventKind::LoadMore, on::LIST, "() => void", ""),
824 (
825 EventKind::LoadMoreAtStart,
826 on::LIST,
827 "() => void",
828 "Within `loadMoreAtStartThreshold` viewports of the start, once the user or a scroll command moved the list: load what comes before the first item.",
829 ),
830 (
831 EventKind::ChangeText,
832 on::INPUT,
833 "(e: { value: string }) => void",
834 "The user edited the text: `value` is the text now.",
835 ),
836 (
837 EventKind::SubmitEditing,
838 on::INPUT,
839 "(e: { text: string }) => void",
840 "",
841 ),
842 (
843 EventKind::Focus,
844 on::ALL,
845 "() => void",
846 "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).",
847 ),
848 (
849 EventKind::Blur,
850 on::ALL,
851 "() => void",
852 "It lost the keyboard focus.",
853 ),
854 (
855 EventKind::SelectionChange,
856 on::INPUT,
857 "(e: { start: number; end: number }) => void",
858 "",
859 ),
860 (
861 EventKind::Paste,
862 on::INPUT,
863 "(e: PasteEvent) => void",
864 "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).",
865 ),
866 (
867 EventKind::CaretMove,
868 on::INPUT,
869 "(e: CaretEvent) => void",
870 "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.",
871 ),
872 (
873 EventKind::KeyPress,
874 on::INPUT,
875 "(e: { key: string }) => void",
876 "Before the text changes: `key` is the typed text, `Backspace` or `Enter`.",
877 ),
878 (
879 EventKind::CompositionChange,
880 on::INPUT,
881 "(e: { composing: boolean; text: string }) => void",
882 "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.",
883 ),
884 (
885 EventKind::ContentSizeChange,
886 on::INPUT,
887 "(e: { size: Size }) => void",
888 "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.",
889 ),
890 (
891 EventKind::Message,
892 on::WEBVIEW,
893 "(e: { data: string }) => void",
894 "The page called `window.nsh.postMessage(data)`.",
895 ),
896 (
897 EventKind::NavigationStateChange,
898 on::WEBVIEW,
899 "(e: WebViewNavigation) => void",
900 "",
901 ),
902 (
903 EventKind::Download,
904 on::WEBVIEW,
905 "(e: WebViewDownload) => void",
906 "With a listener, what the page downloads (an attachment, a type the web view cannot show, a `download` link) is saved as a file in the app's data directory, `downloads/<id>/<filename>`: reported as it starts, finishes and fails. Without one, those navigations behave as before.",
907 ),
908 (EventKind::End, on::VIDEO, "() => void", ""),
909 (
910 EventKind::Buffer,
911 on::VIDEO,
912 "(e: { isBuffering: boolean }) => void",
913 "",
914 ),
915 (
916 EventKind::PressOutside,
917 on::OVERLAY,
918 "(e: { pagePosition: Point }) => void",
919 "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.",
920 ),
921 (
922 EventKind::Cancel,
923 on::OVERLAY,
924 "() => void",
925 "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.",
926 ),
927 (
928 EventKind::Position,
929 on::OVERLAY,
930 "(e: OverlayPosition) => void",
931 "The core placed the overlay (again: the anchor moved, the overlay changed size, it went to the other side).",
932 ),
933];
934
935pub const INTERNAL_EVENTS: &[EventKind] = &[
940 EventKind::Touch,
941 EventKind::Insets,
942 EventKind::NativeEvent,
943 EventKind::Dialog,
944 EventKind::BackPress,
945 EventKind::ImageInfo,
946 EventKind::Clipboard,
947 EventKind::Host,
948 EventKind::Pick,
949 EventKind::OpenUrl,
950 EventKind::ScreenColor,
951 EventKind::FileRequest,
952 EventKind::Speech,
953 EventKind::KeyCommand,
954 EventKind::Menu,
955 EventKind::ViewableItemsChange,
956 EventKind::BackRequest,
960 EventKind::Dismiss,
961 EventKind::RequestClose,
962 EventKind::Show,
963];
964
965const GROUPS: &[(u32, &str, &str)] = &[
968 (on::ALL, "", "every element"),
969 (on::VIEW, "View", "`<View>`"),
970 (on::TEXT, "Text", "`<Text>`"),
971 (on::IMAGE, "Image", "`<Image>`"),
972 (
973 on::SCROLLING,
974 "Scrolling",
975 "scroll views and lists (how they scroll)",
976 ),
977 (on::SCROLL, "Scroll", "`<Scroll>`"),
978 (on::LIST, "List", "lists"),
979 (on::INPUT, "Input", "`<Input>`"),
980 (on::SCREEN, "NavPage", "the pages of a `NavStack`"),
981 (on::MODAL, "Dialog", "dialogs"),
982 (on::WEBVIEW, "WebView", "web views"),
983 (on::VIDEO, "Video", "videos"),
984 (on::SHADER, "Shader", "shaders"),
985 (on::EFFECT, "ShaderEffect", "shader effects"),
986 (on::TRANSITION, "ShaderTransition", "shader transitions"),
987 (on::INPUT_ACCESSORY, "InputAccessory", "input accessories"),
988 (on::OVERLAY, "Overlay", "`<Overlay>`"),
989];
990
991pub fn declarations() -> String {
996 use std::fmt::Write as _;
997 let mut types = TsTypes::default();
998 let mut specs = Vec::new();
999 <crate::Prop as HostProps>::specs(&mut types, &mut specs);
1000 let mut out = String::from(EVENT_TYPES);
1001 for declaration in types.declarations() {
1002 let _ = write!(out, "\n{declaration}\n");
1003 }
1004 for (bit, group, what) in GROUPS {
1005 for (platform, prefix, inside) in [
1006 (Platform::All, "", ""),
1007 (Platform::Ios, "IOS", " inside `ios={{…}}`"),
1008 (Platform::Android, "Android", " inside `android={{…}}`"),
1009 (Platform::Desktop, "Desktop", " inside `desktop={{…}}`"),
1010 (Platform::Web, "Web", " inside `web={{…}}`"),
1011 ] {
1012 let props: Vec<&HostPropSpec> = specs
1013 .iter()
1014 .filter(|s| s.on & bit != 0 && s.platform == platform)
1015 .collect();
1016 let events: Vec<_> = EVENTS
1018 .iter()
1019 .filter(|e| e.1 & bit != 0 && platform == Platform::All)
1020 .collect();
1021 if props.is_empty() && events.is_empty() {
1022 continue;
1023 }
1024 let _ = write!(
1025 out,
1026 "\n/** The props of {what}{inside}. */\nexport interface {prefix}{group}HostProps {{\n"
1027 );
1028 for p in props {
1029 if !p.doc.is_empty() {
1030 let _ = writeln!(out, " /** {} */", p.doc);
1031 }
1032 let _ = writeln!(out, " {}?: {};", p.name, p.ts);
1033 }
1034 for (kind, _, handler, doc) in events {
1035 if !doc.is_empty() {
1036 let _ = writeln!(out, " /** {doc} */");
1037 }
1038 let _ = writeln!(out, " {}?: {handler};", kind.handler_name());
1039 }
1040 out.push_str("}\n");
1041 }
1042 }
1043 out
1044}