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 "focusVisibleStyle" => Prop::FocusVisibleStyle,
159 "headerStyle" => Prop::HeaderStyle,
160 _ => return None,
161 })
162}
163
164pub type PartClassProp = fn(Box<str>) -> crate::Prop;
167
168#[inline]
173pub fn part_class_prop(name: &str, tag: Option<crate::Tag>) -> Option<PartClassProp> {
174 use crate::{Prop, Tag};
175 match name {
176 "headerClass" => Some(Prop::HeaderClass),
177 "contentClass" if tag != Some(Tag::Scroll) => Some(Prop::ListContentClass),
178 _ => None,
179 }
180}
181
182pub trait HostValue: Sized {
186 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self>;
188 fn ts_type(types: &mut TsTypes) -> String;
190}
191
192pub mod on {
194 pub const ALL: u32 = 1;
196 pub const TEXT: u32 = 1 << 1;
198 pub const IMAGE: u32 = 1 << 2;
200 pub const SCROLLING: u32 = 1 << 3;
202 pub const SCROLL: u32 = 1 << 4;
204 pub const LIST: u32 = 1 << 5;
206 pub const INPUT: u32 = 1 << 6;
208 pub const SCREEN: u32 = 1 << 7;
210 pub const MODAL: u32 = 1 << 8;
212 pub const WEBVIEW: u32 = 1 << 9;
214 pub const VIDEO: u32 = 1 << 10;
216 pub const INPUT_ACCESSORY: u32 = 1 << 11;
218 pub const OVERLAY: u32 = 1 << 12;
220 pub const VIEW: u32 = 1 << 13;
222 pub const SHADER: u32 = 1 << 14;
224 pub const EFFECT: u32 = 1 << 15;
226 pub const TRANSITION: u32 = 1 << 16;
228 pub const INTERNAL: u32 = 1 << 31;
230}
231
232#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub enum Platform {
236 All,
238 Ios,
240 Android,
242 Macos,
244 Desktop,
246 Web,
248}
249
250#[derive(Debug, Clone)]
252pub struct HostPropSpec {
253 pub name: &'static str,
255 pub ts: String,
257 pub doc: &'static str,
259 pub on: u32,
261 pub platform: Platform,
263}
264
265pub trait HostProps: Sized {
267 fn decode<I: HostInput>(name: &str, input: &I, cx: &mut HostCx) -> Option<Option<Self>>;
270 fn reset(&self) -> Option<Self>;
273 fn same_kind(&self, other: &Self) -> bool;
275 fn specs(types: &mut TsTypes, out: &mut Vec<HostPropSpec>);
277}
278
279pub trait Clamped {
281 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self;
283}
284
285impl Clamped for f32 {
286 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
287 let v = min.map_or(self, |m| self.max(m as f32));
288 max.map_or(v, |m| v.min(m as f32))
289 }
290}
291
292impl Clamped for Points {
293 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
294 Points(self.0.clamped(min, max))
295 }
296}
297
298impl Clamped for u32 {
299 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
300 let v = min.map_or(self, |m| self.max(m as u32));
301 max.map_or(v, |m| v.min(m as u32))
302 }
303}
304
305impl<T: Clamped> Clamped for Option<T> {
306 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
307 self.map(|v| v.clamped(min, max))
308 }
309}
310
311impl HostValue for bool {
312 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
313 input.as_bool()
314 }
315
316 fn ts_type(_: &mut TsTypes) -> String {
317 "boolean".into()
318 }
319}
320
321impl HostValue for f32 {
322 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
323 input.as_number().map(|n| n as f32)
324 }
325
326 fn ts_type(_: &mut TsTypes) -> String {
327 "number".into()
328 }
329}
330
331impl HostValue for Points {
333 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
334 f32::decode(input, cx).map(Points)
335 }
336
337 fn ts_type(_: &mut TsTypes) -> String {
338 "number".into()
339 }
340}
341
342impl HostValue for u32 {
343 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
345 input.as_number().map(|n| n.max(0.0) as u32)
346 }
347
348 fn ts_type(_: &mut TsTypes) -> String {
349 "number".into()
350 }
351}
352
353impl HostValue for String {
354 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
356 input.as_string()
357 }
358
359 fn ts_type(_: &mut TsTypes) -> String {
360 "string".into()
361 }
362}
363
364impl HostValue for Arc<str> {
365 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
367 input.as_string().filter(|s| !s.is_empty()).map(Into::into)
368 }
369
370 fn ts_type(_: &mut TsTypes) -> String {
371 "string".into()
372 }
373}
374
375impl HostValue for Box<str> {
376 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
378 input.as_string().filter(|s| !s.is_empty()).map(Into::into)
379 }
380
381 fn ts_type(_: &mut TsTypes) -> String {
382 "string".into()
383 }
384}
385
386impl HostValue for Color {
387 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
389 input.as_string().and_then(|s| Color::parse(&s))
390 }
391
392 fn ts_type(_: &mut TsTypes) -> String {
393 "ColorValue".into()
394 }
395}
396
397impl<T: HostValue> HostValue for Option<T> {
399 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
400 Some(T::decode(input, cx))
401 }
402
403 fn ts_type(types: &mut TsTypes) -> String {
404 T::ts_type(types)
405 }
406}
407
408impl<T: HostValue> HostValue for Vec<T> {
410 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
411 Some(
412 input
413 .items()
414 .iter()
415 .filter_map(|i| T::decode(i, cx))
416 .collect(),
417 )
418 }
419
420 fn ts_type(types: &mut TsTypes) -> String {
421 format!("{}[]", T::ts_type(types))
422 }
423}
424
425impl HostValue for EdgeInsets {
427 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
428 let side = |key| Points(input.field(key).and_then(|v| v.as_number()).unwrap_or(0.0) as f32);
429 Some(EdgeInsets {
430 top: side("top"),
431 right: side("right"),
432 bottom: side("bottom"),
433 left: side("left"),
434 })
435 }
436
437 fn ts_type(_: &mut TsTypes) -> String {
438 "Partial<Edges>".into()
439 }
440}
441
442pub fn field<T: HostValue, I: HostInput>(input: &I, key: &str, cx: &mut HostCx) -> Option<T> {
444 input.field(key).and_then(|v| T::decode(&v, cx))
445}
446
447const EVENT_TYPES: &str = r#"/** A position, in points (`nsh_core::geometry::Point`). */
451export interface Point {
452 x: number;
453 y: number;
454}
455
456/** An extent, in points (`nsh_core::geometry::Size`). */
457export interface Size {
458 width: number;
459 height: number;
460}
461
462/** An image's or a video's own extent, in pixels as decoded
463 * (`nsh_core::geometry::Size<DevicePixels>`), not the points it is drawn at. */
464export interface PixelSize {
465 width: number;
466 height: number;
467}
468
469/** A position and an extent, in points (`nsh_core::geometry::Bounds`). */
470export interface Bounds {
471 /** The top left corner. */
472 origin: Point;
473 size: Size;
474}
475
476/** A length on each side, in points (`nsh_core::geometry::Edges`): insets, a safe area. */
477export interface Edges {
478 top: number;
479 right: number;
480 bottom: number;
481 left: number;
482}
483
484/** The modifier keys held (GPUI's `Modifiers`). */
485export interface Modifiers {
486 control: boolean;
487 /** Option on Apple platforms, Alt elsewhere. */
488 alt: boolean;
489 shift: boolean;
490 /** Command on Apple platforms, the Windows / Super key elsewhere. */
491 platform: boolean;
492}
493
494/** Where the core placed an overlay: the payload of `onPosition`. */
495export interface OverlayPosition {
496 /** The side of the anchor it went on: the one asked for, or the other one when only that one has room. */
497 placement: "top" | "bottom" | "left" | "right";
498 /** Its frame in the root view (the surface, or the dialog it is in). */
499 bounds: Bounds;
500 /** The room on that side, inside the safe area less `margin`: what a menu may grow to. */
501 available: Size;
502}
503
504/** A drag: translation since the start and velocity (points / second). */
505export interface PanEvent {
506 /** The system cancelled the drag rather than releasing it. */
507 cancelled: boolean;
508 /** How far the finger moved since the drag started. */
509 translation: Point;
510 /** How fast it moves, in points per second. */
511 velocity: Point;
512 /** The values `pan` binds now, those of the axes it binds (`pan.x`, `pan.y`). */
513 value?: Partial<Point>;
514}
515
516/** 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. */
517export interface PressEvent {
518 /** Position in the pressed view (its transforms undone; a pressed span's text view). */
519 position: Point;
520 /** Position in the root view the view is in (the surface or its modal), as touches' `pageX` / `pageY`. */
521 pagePosition: Point;
522 modifiers: Modifiers;
523 /** Consecutive clicks at the same place: 1 for a click, 2 for a double click. */
524 clickCount: number;
525}
526
527/** Where the mouse is over a view, or where a button was released over it: the payload of `onMouseEnter`, `onMouseMove`, `onMouseLeave` and `onMouseUp` (GPUI's `MouseMoveEvent`). */
528export interface MouseEvent {
529 /** Position in the view (its transforms undone). */
530 position: Point;
531 /** Position in the root view the view is in (the surface or its modal), as touches' `pageX` / `pageY`. */
532 pagePosition: Point;
533 modifiers: Modifiers;
534 /** The button held down (a drag), or `null`. */
535 pressedButton: MouseButton | null;
536 /** The button that changed at this event: the released one on `onMouseUp`, `null` on a move. */
537 button: MouseButton | null;
538}
539
540/** A wheel over a view: the payload of `onWheel` (GPUI's `ScrollWheelEvent`, the DOM's `WheelEvent`). */
541export interface WheelEvent {
542 /** Position in the view (its transforms undone). */
543 position: Point;
544 /** Position in the root view the view is in (the surface or its modal), as touches' `pageX` / `pageY`. */
545 pagePosition: Point;
546 /** How far it scrolled, in `deltaMode` units: positive `y` scrolls down (toward the end), positive `x` right, as the DOM's `deltaX` / `deltaY`. */
547 delta: Point;
548 /** `"points"`: a precise device (a touchpad); `"lines"`: mouse wheel notches. */
549 deltaMode: "points" | "lines";
550 modifiers: Modifiers;
551}
552
553/** A mouse button (GPUI's `MouseButton`). */
554export type MouseButton = "left" | "right" | "middle" | "back" | "forward";
555
556/** The kind of pointer behind an event (the DOM's `pointerType`). */
557export type PointerType = "mouse" | "pen" | "touch";
558
559/** Where a context menu was asked for: the payload of `onContextMenu`. */
560export interface ContextMenuEvent {
561 /** Position in the view (its transforms undone): the pointer's, or the view's bottom-start corner when no pointer asked. */
562 position: Point;
563 /** Position in the root view the view is in: where `Menu.popup` opens a menu (`Menu.popup(items, e.pagePosition)`). */
564 pagePosition: Point;
565 modifiers: Modifiers;
566 /** The pointer that asked for the menu, or `null` when the keyboard (Shift+F10, the Menu key) or an assistive technology's "show menu" action did: a menu opened then puts the keyboard focus on its first item. */
567 pointerType: PointerType | null;
568}
569
570/** Where a scroll view is: the payload of `onScroll`. */
571export interface ScrollEvent {
572 /** The content offset. */
573 offset: Point;
574 /** The content's size (zoomed). */
575 contentSize: Size;
576 /** The scroll view's size. */
577 size: Size;
578 /** The zoom scale (1 unless the scroll view zooms). */
579 zoomScale: number;
580}
581
582/** Where an input's caret is: the payload of `onCaretMove`. */
583export interface CaretEvent {
584 /** 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. */
585 bounds: Bounds;
586 /** The caret in the root view the input is in (the surface or its dialog), as of the event: an `Overlay`'s `anchor`. */
587 pageBounds: Bounds;
588}
589
590/** 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. */
591export interface PasteEvent {
592 /** The plain text, `""` when there was none. */
593 text: string;
594 /** 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. */
595 html: string;
596 /** Files with their bytes: images (a screenshot, an image copied from a page or an app), as `File`s an app can upload. */
597 files: File[];
598 /** `file:` URLs of local files copied in a file manager (as `onFileDrop`'s). */
599 uris: string[];
600}
601
602/** A line of a laid-out text (in the text's content box). */
603export interface TextLayoutLine {
604 text: string;
605 bounds: Bounds;
606 ascender: number;
607 descender: number;
608 capHeight: number;
609 xHeight: number;
610}
611
612/** Where a web view is: the payload of its navigation events. */
613export interface WebViewNavigation {
614 url: string;
615 title: string;
616 loading: boolean;
617 canGoBack: boolean;
618 canGoForward: boolean;
619}
620
621/** A web view's download (`onDownload`): where it is saved, in the app's data directory's `downloads`. */
622export interface WebViewDownload {
623 state: "started" | "finished" | "failed";
624 id: string;
625 url: string;
626 filename: string;
627 path: string;
628 /** Once finished: the file's size in bytes. */
629 bytes?: number;
630 /** When it failed: why. */
631 message?: string;
632}
633"#;
634
635pub const EVENTS: &[(EventKind, u32, &str, &str)] = &[
640 (
641 EventKind::Press,
642 on::ALL,
643 "(e: PressEvent) => void",
644 "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).",
645 ),
646 (
647 EventKind::LongPress,
648 on::ALL,
649 "(e: PressEvent) => void",
650 "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).",
651 ),
652 (
653 EventKind::PressDown,
654 on::ALL,
655 "(e: PressEvent) => void",
656 "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).",
657 ),
658 (
659 EventKind::PressUp,
660 on::ALL,
661 "(e: PressEvent) => void",
662 "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).",
663 ),
664 (
665 EventKind::MouseEnter,
666 on::ALL,
667 "(e: MouseEvent) => void",
668 "The mouse came over the view or a view inside it (never on touches; the DOM's `mouseenter`).",
669 ),
670 (
671 EventKind::MouseLeave,
672 on::ALL,
673 "(e: MouseEvent) => void",
674 "The mouse left the view and the views inside it, or the window, from where `e` says (the DOM's `mouseleave`).",
675 ),
676 (
677 EventKind::MouseMove,
678 on::ALL,
679 "(e: MouseEvent) => void",
680 "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.",
681 ),
682 (
683 EventKind::Wheel,
684 on::ALL,
685 "(e: WheelEvent) => void",
686 "A mouse wheel or touchpad scrolled over the view (or a view inside it); desktops and the web. The nearest listener hears it. A listener nearer than any scroll view under the pointer takes the wheel: nothing scrolls or zooms natively (a canvas zooms on `e.modifiers.ctrl` and pans otherwise); a scroll view listening, or a view around one, only observes it.",
687 ),
688 (
689 EventKind::MouseUp,
690 on::ALL,
691 "(e: MouseEvent) => void",
692 "A mouse button was released over the view (or a view inside it): which button (`e.button`), where, and with the modifiers. The primary button's release also reports `onPressUp`. Desktops, the terminal and the web; a release outside the view is not reported.",
693 ),
694 (
695 EventKind::ContextMenu,
696 on::ALL,
697 "(e: ContextMenuEvent) => void",
698 "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.",
699 ),
700 (
701 EventKind::FileDragEnter,
702 on::ALL,
703 "(e: { uris: string[]; mimeTypes: string[] }) => void",
704 "A local file drag entered this desktop destination with its offered file URLs and each one's MIME type by its name (`\"\"` when the name says none); no file is read. GTK waits for its file-list preload.",
705 ),
706 (
707 EventKind::FileDragLeave,
708 on::ALL,
709 "() => void",
710 "A local file drag left this desktop destination.",
711 ),
712 (
713 EventKind::FileDrop,
714 on::ALL,
715 "(e: { uris: string[]; mimeTypes: string[]; pagePosition?: { x: number; y: number } }) => void",
716 "Local file URLs dropped on this desktop destination, with each one's MIME type by its name (`\"\"` when the name says none); `pagePosition`: where, in the window's coordinates, on backends that know it (Linux).",
717 ),
718 (
719 EventKind::Layout,
720 on::ALL,
721 "(e: { bounds: Bounds }) => void",
722 "The frame changed: its bounds in the parent.",
723 ),
724 (EventKind::PanStart, on::ALL, "(e: PanEvent) => void", ""),
725 (
726 EventKind::PanEnd,
727 on::ALL,
728 "(e: PanEvent) => void",
729 "With the release velocity, e.g. to start a `decay`.",
730 ),
731 (
732 EventKind::PinchStart,
733 on::ALL,
734 "(e: { scale: number; velocity: number }) => void",
735 "",
736 ),
737 (
738 EventKind::PinchEnd,
739 on::ALL,
740 "(e: { scale: number; velocity: number }) => void",
741 "",
742 ),
743 (
744 EventKind::RotationStart,
745 on::ALL,
746 "(e: { rotation: number; velocity: number }) => void",
747 "",
748 ),
749 (
750 EventKind::RotationEnd,
751 on::ALL,
752 "(e: { rotation: number; velocity: number }) => void",
753 "",
754 ),
755 (
756 EventKind::AccessibilityAction,
757 on::ALL,
758 "(e: { actionName: string }) => void",
759 "",
760 ),
761 (
762 EventKind::TextLayout,
763 on::TEXT,
764 "(e: { lines: TextLayoutLine[] }) => void",
765 "The laid-out lines (in the text's content box), after each layout.",
766 ),
767 (
768 EventKind::LoadStart,
769 on::IMAGE | on::VIDEO,
770 "() => void",
771 "",
772 ),
773 (
774 EventKind::LoadStart,
775 on::WEBVIEW,
776 "(e: WebViewNavigation) => void",
777 "",
778 ),
779 (
780 EventKind::Progress,
781 on::IMAGE,
782 "(e: { loaded: number; total: number }) => void",
783 "Download progress in bytes (`total` 0 when unknown); at most every 100 ms.",
784 ),
785 (
786 EventKind::Progress,
787 on::VIDEO,
788 "(e: { currentTime: number; duration: number }) => void",
789 "",
790 ),
791 (
792 EventKind::Load,
793 on::IMAGE,
794 "(e: { size: PixelSize }) => void",
795 "The source image's size in pixels (not the decoded, downsampled one).",
796 ),
797 (
798 EventKind::Load,
799 on::WEBVIEW,
800 "(e: WebViewNavigation) => void",
801 "",
802 ),
803 (
804 EventKind::Load,
805 on::VIDEO,
806 "(e: { duration: number; size: PixelSize }) => void",
807 "",
808 ),
809 (
810 EventKind::Error,
811 on::IMAGE | on::WEBVIEW | on::VIDEO,
812 "(e: { message: string; code?: string }) => void",
813 "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`), and `\"ERR_FEATURE_UNAVAILABLE_ON_PLATFORM\"` for a web view where the platform shows none (`WebView.available()`).",
814 ),
815 (
816 EventKind::LoadEnd,
817 on::IMAGE,
818 "() => void",
819 "After `onLoad` or `onError`.",
820 ),
821 (
822 EventKind::Scroll,
823 on::SCROLLING,
824 "(e: ScrollEvent) => void",
825 "",
826 ),
827 (
828 EventKind::ScrollDragStart,
829 on::SCROLLING,
830 "(e: { offset: Point }) => void",
831 "",
832 ),
833 (
834 EventKind::ScrollDragEnd,
835 on::SCROLLING,
836 "(e: { offset: Point }) => void",
837 "",
838 ),
839 (
840 EventKind::MomentumStart,
841 on::SCROLLING,
842 "(e: { offset: Point }) => void",
843 "",
844 ),
845 (
846 EventKind::MomentumEnd,
847 on::SCROLLING,
848 "(e: { offset: Point }) => void",
849 "",
850 ),
851 (
852 EventKind::ScrollEnd,
853 on::SCROLL | on::LIST,
854 "(e: { offset: Point }) => void",
855 "",
856 ),
857 (EventKind::Refresh, on::SCROLL | on::LIST, "() => void", ""),
858 (EventKind::LoadMore, on::LIST, "() => void", ""),
859 (
860 EventKind::LoadMoreAtStart,
861 on::LIST,
862 "() => void",
863 "Within `loadMoreAtStartThreshold` viewports of the start, once the user or a scroll command moved the list: load what comes before the first item.",
864 ),
865 (
866 EventKind::ChangeText,
867 on::INPUT,
868 "(e: { value: string }) => void",
869 "The user edited the text: `value` is the text now.",
870 ),
871 (
872 EventKind::SubmitEditing,
873 on::INPUT,
874 "(e: { text: string }) => void",
875 "",
876 ),
877 (
878 EventKind::Focus,
879 on::ALL,
880 "() => void",
881 "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).",
882 ),
883 (
884 EventKind::Blur,
885 on::ALL,
886 "() => void",
887 "It lost the keyboard focus.",
888 ),
889 (
890 EventKind::SelectionChange,
891 on::INPUT,
892 "(e: { start: number; end: number }) => void",
893 "",
894 ),
895 (
896 EventKind::SelectionChange,
897 on::VIEW,
898 "(e: { text: string; start?: number; bounds?: Bounds; pageBounds?: Bounds }) => void",
899 "The selection across the texts of a `selectable` view changed: `text` is what a copy would give, empty once nothing is selected; `start` is where it starts in the view's whole text (UTF-16 units) when the platform knows it; `bounds` is the box around the selected text in the view and `pageBounds` in the root view it is in, as of the event (an `Overlay`'s `anchor`: a bar of actions on the selection), while something is selected and the platform knows them. Only the outermost selectable view of an area reports it.",
900 ),
901 (
902 EventKind::Paste,
903 on::INPUT,
904 "(e: PasteEvent) => void",
905 "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).",
906 ),
907 (
908 EventKind::CaretMove,
909 on::INPUT,
910 "(e: CaretEvent) => void",
911 "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.",
912 ),
913 (
914 EventKind::KeyPress,
915 on::INPUT,
916 "(e: { key: string }) => void",
917 "Before the text changes: `key` is the typed text, `Backspace` or `Enter`.",
918 ),
919 (
920 EventKind::CompositionChange,
921 on::INPUT,
922 "(e: { composing: boolean; text: string }) => void",
923 "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.",
924 ),
925 (
926 EventKind::ContentSizeChange,
927 on::INPUT,
928 "(e: { size: Size }) => void",
929 "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.",
930 ),
931 (
932 EventKind::Message,
933 on::WEBVIEW,
934 "(e: { data: string }) => void",
935 "The page called `window.nsh.postMessage(data)`.",
936 ),
937 (
938 EventKind::NavigationStateChange,
939 on::WEBVIEW,
940 "(e: WebViewNavigation) => void",
941 "",
942 ),
943 (
944 EventKind::Download,
945 on::WEBVIEW,
946 "(e: WebViewDownload) => void",
947 "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.",
948 ),
949 (EventKind::End, on::VIDEO, "() => void", ""),
950 (
951 EventKind::Buffer,
952 on::VIDEO,
953 "(e: { isBuffering: boolean }) => void",
954 "",
955 ),
956 (
957 EventKind::PressOutside,
958 on::OVERLAY,
959 "(e: { pagePosition: Point }) => void",
960 "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.",
961 ),
962 (
963 EventKind::Cancel,
964 on::OVERLAY,
965 "() => void",
966 "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.",
967 ),
968 (
969 EventKind::Position,
970 on::OVERLAY,
971 "(e: OverlayPosition) => void",
972 "The core placed the overlay (again: the anchor moved, the overlay changed size, it went to the other side).",
973 ),
974];
975
976pub const INTERNAL_EVENTS: &[EventKind] = &[
981 EventKind::Touch,
982 EventKind::Insets,
983 EventKind::NativeEvent,
984 EventKind::Dialog,
985 EventKind::BackPress,
986 EventKind::ImageInfo,
987 EventKind::WebEvaluation,
988 EventKind::Clipboard,
989 EventKind::Host,
990 EventKind::Pick,
991 EventKind::OpenUrl,
992 EventKind::ScreenColor,
993 EventKind::FileRequest,
994 EventKind::Speech,
995 EventKind::Notification,
996 EventKind::UrlScheme,
997 EventKind::SecondInstance,
998 EventKind::Audio,
999 EventKind::Window,
1000 EventKind::EditAction,
1001 EventKind::KeyCommand,
1002 EventKind::Menu,
1003 EventKind::ViewableItemsChange,
1004 EventKind::BackRequest,
1008 EventKind::Dismiss,
1009 EventKind::RequestClose,
1010 EventKind::Show,
1011];
1012
1013const GROUPS: &[(u32, &str, &str)] = &[
1016 (on::ALL, "", "every element"),
1017 (on::VIEW, "View", "`<View>`"),
1018 (on::TEXT, "Text", "`<Text>`"),
1019 (on::IMAGE, "Image", "`<Image>`"),
1020 (
1021 on::SCROLLING,
1022 "Scrolling",
1023 "scroll views and lists (how they scroll)",
1024 ),
1025 (on::SCROLL, "Scroll", "`<Scroll>`"),
1026 (on::LIST, "List", "lists"),
1027 (on::INPUT, "Input", "`<Input>`"),
1028 (on::SCREEN, "NavPage", "the pages of a `NavStack`"),
1029 (on::MODAL, "Dialog", "dialogs"),
1030 (on::WEBVIEW, "WebView", "web views"),
1031 (on::VIDEO, "Video", "videos"),
1032 (on::SHADER, "Shader", "shaders"),
1033 (on::EFFECT, "ShaderEffect", "shader effects"),
1034 (on::TRANSITION, "ShaderTransition", "shader transitions"),
1035 (on::INPUT_ACCESSORY, "InputAccessory", "input accessories"),
1036 (on::OVERLAY, "Overlay", "`<Overlay>`"),
1037];
1038
1039pub fn declarations() -> String {
1045 use std::fmt::Write as _;
1046 let mut types = TsTypes::default();
1047 let mut specs = Vec::new();
1048 <crate::Prop as HostProps>::specs(&mut types, &mut specs);
1049 <crate::RevealOptions as HostValue>::ts_type(&mut types);
1050 let mut out = String::from(EVENT_TYPES);
1051 for declaration in types.declarations() {
1052 let _ = write!(out, "\n{declaration}\n");
1053 }
1054 for (bit, group, what) in GROUPS {
1055 for (platform, prefix, inside) in [
1056 (Platform::All, "", ""),
1057 (Platform::Ios, "IOS", " inside `ios={{…}}`"),
1058 (Platform::Android, "Android", " inside `android={{…}}`"),
1059 (Platform::Macos, "MacOS", " inside `macos={{…}}`"),
1060 (Platform::Desktop, "Desktop", " inside `desktop={{…}}`"),
1061 (Platform::Web, "Web", " inside `web={{…}}`"),
1062 ] {
1063 let props: Vec<&HostPropSpec> = specs
1064 .iter()
1065 .filter(|s| s.on & bit != 0 && s.platform == platform)
1066 .collect();
1067 let events: Vec<_> = EVENTS
1069 .iter()
1070 .filter(|e| e.1 & bit != 0 && platform == Platform::All)
1071 .collect();
1072 if props.is_empty() && events.is_empty() {
1073 continue;
1074 }
1075 let _ = write!(
1076 out,
1077 "\n/** The props of {what}{inside}. */\nexport interface {prefix}{group}HostProps {{\n"
1078 );
1079 for p in props {
1080 if !p.doc.is_empty() {
1081 let _ = writeln!(out, " /** {} */", p.doc);
1082 }
1083 let _ = writeln!(out, " {}?: {};", p.name, p.ts);
1084 }
1085 for (kind, _, handler, doc) in events {
1086 if !doc.is_empty() {
1087 let _ = writeln!(out, " /** {doc} */");
1088 }
1089 let _ = writeln!(out, " {}?: {handler};", kind.handler_name());
1090 }
1091 out.push_str("}\n");
1092 }
1093 }
1094 out
1095}