Skip to main content

nsh_core/js/
host.rs

1//! The props of host elements as JS sets them: how each one is decoded
2//! from the JS value and what its TypeScript type is, from one definition.
3//! `#[derive(HostProps)]` on [`crate::Prop`] (and the enums it nests) maps
4//! JS names to variants, decodes their payloads with [`HostValue`] and
5//! writes the [`HostPropSpec`]s the element types are generated from. The
6//! decoders read JS values through [`HostInput`], which `nsh-js` implements
7//! for QuickJS values: no JSON in between.
8//!
9//! A few props are not [`HostProps`]: the state styles and a page's header
10//! style, whose values each renderer decodes with its own style decoder, and
11//! the class lists of an element's parts. [`style_patch_prop`] and
12//! [`part_class_prop`] name them for both renderers (QuickJS' and the
13//! browser runtime's).
14
15use std::sync::Arc;
16
17pub use nsh_macros::HostProps;
18
19use crate::{EdgeInsets, EventKind, element::TsTypes, geometry::Points, style::Color};
20
21/// A JS value as host props read it.
22pub trait HostInput: Sized {
23    /// `null` or `undefined`.
24    fn is_nullish(&self) -> bool;
25    /// An object (arrays and functions are objects too).
26    fn is_object(&self) -> bool;
27    /// A boolean.
28    fn as_bool(&self) -> Option<bool>;
29    /// A number.
30    fn as_number(&self) -> Option<f64>;
31    /// A string.
32    fn as_string(&self) -> Option<String>;
33    /// Field `key` of an object (`None`: not an object, or no such field).
34    fn field(&self, key: &str) -> Option<Self>;
35    /// The items of an array (empty for anything else).
36    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    /// An array, to read by index (checked once, not per item).
43    fn as_list(&self) -> Option<Self::List>;
44    /// What [`HostInput::as_list`] gives.
45    type List: HostList<Item = Self>;
46    /// The fields of an object (empty for anything else).
47    fn entries(&self) -> Vec<(String, Self)>;
48    /// Truthy, as JS sees it.
49    fn truthy(&self) -> bool;
50    /// The host element this value is (the node object a `ref` holds).
51    fn node(&self) -> Option<crate::NodeId> {
52        None
53    }
54    /// The native animation node this value is (`AnimatedNode.__av`).
55    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
62/// A JS array, read by index.
63pub trait HostList {
64    /// Its items.
65    type Item;
66    /// Its length.
67    fn len(&self) -> usize;
68    /// Whether it is empty.
69    fn is_empty(&self) -> bool {
70        self.len() == 0
71    }
72    /// Item `index`.
73    fn item(&self, index: usize) -> Option<Self::Item>;
74}
75
76/// Where decoding reports what it could not take, and the element it
77/// decodes for.
78#[derive(Debug, Default)]
79pub struct HostCx {
80    /// Warnings for the app's console (`unknown role`).
81    pub warnings: Vec<String>,
82    /// The [`on`] bits of the element the props are set on
83    /// ([`element_bits`]); 0 when unknown, which decodes a name several
84    /// elements share as the first prop of that name.
85    pub element: u32,
86}
87
88impl HostCx {
89    /// The context of props set on an element `tag`.
90    pub fn for_element(tag: crate::Tag) -> Self {
91        Self {
92            element: element_bits(tag),
93            ..Self::default()
94        }
95    }
96
97    /// Reports `message`.
98    pub fn warn(&mut self, message: impl Into<String>) {
99        self.warnings.push(message.into());
100    }
101
102    /// Whether a prop of the elements `on` applies to the element decoded
103    /// for (always, when it is unknown).
104    pub fn on_element(&self, on: u32) -> bool {
105        self.element == 0 || self.element & on != 0
106    }
107}
108
109/// The [`on`] bits of the props element `tag` takes.
110pub 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
136/// A prop whose value is a style over the element's own: the style patch
137/// the renderer decodes from it as from a `style` (`None` when empty).
138pub type StylePatchProp = fn(Option<std::rc::Rc<crate::StylePatch>>) -> crate::Prop;
139
140/// The prop a state style or a page's header style sets (`activeStyle`,
141/// `hoverStyle`, ..., `headerStyle`). They are not [`HostProps`]: each
142/// renderer decodes their style with its own style decoder, then makes the
143/// prop with this, so QuickJS' and the browser's take the same names.
144#[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
163/// A prop whose value is a class list of a part of an element: the class
164/// names as the renderer reads them from the JS string.
165pub type PartClassProp = fn(Box<str>) -> crate::Prop;
166
167/// The prop a class list of a part of element `tag` sets: a page's header
168/// (`headerClass`) or a list's content (`contentClass`). A scroll view's
169/// `contentClass` is not one: it styles the scroll view's content container,
170/// which a renderer makes itself rather than the core.
171#[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
181/// A prop's value: how it comes out of a JS value and its TypeScript type.
182/// `decode` gives `None` for a value it does not take (`undefined`, another
183/// type): the prop then gets its default.
184pub trait HostValue: Sized {
185    /// The value in `input`.
186    fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self>;
187    /// Its TypeScript type, declaring the named types it uses.
188    fn ts_type(types: &mut TsTypes) -> String;
189}
190
191/// Where a host prop applies, for the generated element types.
192pub mod on {
193    /// Every element.
194    pub const ALL: u32 = 1;
195    /// `<text>`.
196    pub const TEXT: u32 = 1 << 1;
197    /// `<image>`.
198    pub const IMAGE: u32 = 1 << 2;
199    /// Scroll views and lists (their scrolling behavior).
200    pub const SCROLLING: u32 = 1 << 3;
201    /// `<scroll>` only.
202    pub const SCROLL: u32 = 1 << 4;
203    /// Lists (`List`).
204    pub const LIST: u32 = 1 << 5;
205    /// `<input>`.
206    pub const INPUT: u32 = 1 << 6;
207    /// Screens of a stack.
208    pub const SCREEN: u32 = 1 << 7;
209    /// `<modal>`.
210    pub const MODAL: u32 = 1 << 8;
211    /// `<webview>`.
212    pub const WEBVIEW: u32 = 1 << 9;
213    /// `<video>`.
214    pub const VIDEO: u32 = 1 << 10;
215    /// Input accessories (iOS).
216    pub const INPUT_ACCESSORY: u32 = 1 << 11;
217    /// `<overlay>`.
218    pub const OVERLAY: u32 = 1 << 12;
219    /// `<view>`.
220    pub const VIEW: u32 = 1 << 13;
221    /// `<shader>` and the shader effects and transitions.
222    pub const SHADER: u32 = 1 << 14;
223    /// Shader effects (`ShaderEffect`, `ScreenEffect`).
224    pub const EFFECT: u32 = 1 << 15;
225    /// Shader transitions (`ShaderTransition`, `ScreenTransition`).
226    pub const TRANSITION: u32 = 1 << 16;
227    /// Set by the runtime itself, not part of the elements' types.
228    pub const INTERNAL: u32 = 1 << 31;
229}
230
231/// The platform a prop is for: everywhere, or inside `ios={{…}}` /
232/// `android={{…}}` / `desktop={{…}}` / `web={{…}}`.
233#[derive(Debug, Clone, Copy, PartialEq, Eq)]
234pub enum Platform {
235    /// Every platform.
236    All,
237    /// `ios={{…}}`.
238    Ios,
239    /// `android={{…}}`.
240    Android,
241    /// `desktop={{…}}` (macOS, Windows, Linux, desktop browsers).
242    Desktop,
243    /// `web={{…}}`.
244    Web,
245}
246
247/// One host prop, for the generated TypeScript.
248#[derive(Debug, Clone)]
249pub struct HostPropSpec {
250    /// Its JS name.
251    pub name: &'static str,
252    /// Its TypeScript type.
253    pub ts: String,
254    /// Documentation.
255    pub doc: &'static str,
256    /// The elements it applies to ([`on`] bits).
257    pub on: u32,
258    /// The platform it is for.
259    pub platform: Platform,
260}
261
262/// An enum of host props (`#[derive(HostProps)]`).
263pub trait HostProps: Sized {
264    /// The prop JS name `name` sets with `input`: `None` for a name that is
265    /// not one of these props, `Some(None)` when nothing is to be set.
266    fn decode<I: HostInput>(name: &str, input: &I, cx: &mut HostCx) -> Option<Option<Self>>;
267    /// This prop at its default (what clearing it from JS sets); `None` for
268    /// the props the runtime sets once.
269    fn reset(&self) -> Option<Self>;
270    /// Whether `self` and `other` set the same property.
271    fn same_kind(&self, other: &Self) -> bool;
272    /// The props, for the generated TypeScript.
273    fn specs(types: &mut TsTypes, out: &mut Vec<HostPropSpec>);
274}
275
276/// Numbers held to a range after decoding (`#[prop(min = …, max = …)]`).
277pub trait Clamped {
278    /// `self` within `min..=max` (either bound left out).
279    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
328/// A number of points.
329impl 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    /// Negative numbers are 0, fractions are cut.
341    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    /// Anything but a string is the empty string's default.
352    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    /// The empty string is no value.
363    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    /// The empty string is no value.
374    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    /// A CSS color string; anything else, or an invalid color, is none.
385    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
394/// `None` when there is no value: the prop is cleared.
395impl<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
405/// The items `T` takes, the others skipped.
406impl<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
422/// `{ top, right, bottom, left }` (each 0 when left out).
423impl 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
439/// Field `key` of `input` as `T`.
440pub 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
444/// The payloads of the host elements' events, and the shapes they are made
445/// of: `nsh_core::geometry`'s `Point`, `Size`, `Bounds` and `Edges` (in
446/// points) and `keymap::Modifiers`, with GPUI's field names.
447const 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
612/// The events of the host elements, as their handler props: the event, the
613/// elements whose props declare it ([`on`] bits), the handler's type and
614/// its documentation. An event whose payload differs between elements has
615/// a row per payload.
616pub 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
935/// The events no element's props declare: the root's (`BackHandler`,
936/// `nsh/keymap`, dialogs, `Image.getSize`, clipboard reads, menus, `nsh/host`'s replies and events), the runtime's own (touches, insets, native
937/// components' events) and those whose payload a module makes
938/// (`List`'s viewable items, with the app's items).
939pub 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    // `NavPage`'s `onDismiss` / `onBackPress` and `Dialog`'s `onClose` /
957    // `onCancel` / `onOpenChange` / `onOpen`: the navigation's handlers
958    // (`nsh-js` `navigation.rs`), declared with its components.
959    EventKind::BackRequest,
960    EventKind::Dismiss,
961    EventKind::RequestClose,
962    EventKind::Show,
963];
964
965/// The interfaces of the host props, by the elements their props apply
966/// to: `HostProps` for every element, `TextHostProps` for `<text>`, ...
967const 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
991/// The declarations of the host elements' props: the named types they use
992/// and one interface per element group and platform (`InputHostProps`,
993/// `IOSInputHostProps`, ...), which the element types and the components
994/// of `nsh` (`WebView`, `Video`, ...) extend.
995pub 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            // Events are for every platform.
1017            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}