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 | Tag::GpuView => 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        "focusVisibleStyle" => Prop::FocusVisibleStyle,
159        "headerStyle" => Prop::HeaderStyle,
160        _ => return None,
161    })
162}
163
164/// A prop whose value is a class list of a part of an element: the class
165/// names as the renderer reads them from the JS string.
166pub type PartClassProp = fn(Box<str>) -> crate::Prop;
167
168/// The prop a class list of a part of element `tag` sets: a page's header
169/// (`headerClass`) or a list's content (`contentClass`). A scroll view's
170/// `contentClass` is not one: it styles the scroll view's content container,
171/// which a renderer makes itself rather than the core.
172#[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
182/// A prop's value: how it comes out of a JS value and its TypeScript type.
183/// `decode` gives `None` for a value it does not take (`undefined`, another
184/// type): the prop then gets its default.
185pub trait HostValue: Sized {
186    /// The value in `input`.
187    fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self>;
188    /// Its TypeScript type, declaring the named types it uses.
189    fn ts_type(types: &mut TsTypes) -> String;
190}
191
192/// Decodes a view's `captureKeys` (`"none"`, `"all"`, `"text"`, or an array of
193/// keystroke strings) with the platform's `mod` convention: `apple` says
194/// `mod` is Command ([`crate::keymap::apple_keys`]).
195///
196/// [`HostValue`]'s decoder for [`crate::KeyCapture`] reads the convention
197/// from the engine's ambient environment. A JS host decodes outside one (the
198/// native JS runtime while it renders, the browser's bridge), so it resolves
199/// the convention from the environment it has and calls this. Backend-only
200/// (`#[doc(hidden)]`), never an app-facing key conversion API.
201#[doc(hidden)]
202pub fn decode_capture_keys<I: HostInput>(
203    input: &I,
204    cx: &mut HostCx,
205    apple: bool,
206) -> Option<crate::KeyCapture> {
207    use crate::{KeyCapture, keymap::Keystroke};
208    if let Some(text) = input.as_string() {
209        return match text.as_str() {
210            "none" => Some(KeyCapture::None),
211            "all" => Some(KeyCapture::All),
212            "text" => Some(KeyCapture::Text),
213            other => {
214                cx.warn(format!(
215                    "captureKeys: expected \"none\", \"all\", \"text\" or keystrokes, got {other:?}"
216                ));
217                None
218            }
219        };
220    }
221    let list = input.as_list()?;
222    let mut keys = Vec::with_capacity(list.len());
223    for index in 0..list.len() {
224        let Some(item) = list.item(index) else {
225            continue;
226        };
227        let Some(text) = item.as_string() else {
228            cx.warn(format!("captureKeys[{index}]: expected a keystroke string"));
229            continue;
230        };
231        match Keystroke::parse_with(&text, apple) {
232            Ok(keystroke) => keys.push(keystroke),
233            Err(error) => cx.warn(format!("captureKeys: {error}")),
234        }
235    }
236    Some(KeyCapture::Keys(keys.into()))
237}
238
239/// Where a host prop applies, for the generated element types.
240pub mod on {
241    /// Every element.
242    pub const ALL: u32 = 1;
243    /// `<text>`.
244    pub const TEXT: u32 = 1 << 1;
245    /// `<image>`.
246    pub const IMAGE: u32 = 1 << 2;
247    /// Scroll views and lists (their scrolling behavior).
248    pub const SCROLLING: u32 = 1 << 3;
249    /// `<scroll>` only.
250    pub const SCROLL: u32 = 1 << 4;
251    /// Lists (`List`).
252    pub const LIST: u32 = 1 << 5;
253    /// `<input>`.
254    pub const INPUT: u32 = 1 << 6;
255    /// Screens of a stack.
256    pub const SCREEN: u32 = 1 << 7;
257    /// `<modal>`.
258    pub const MODAL: u32 = 1 << 8;
259    /// `<webview>`.
260    pub const WEBVIEW: u32 = 1 << 9;
261    /// `<video>`.
262    pub const VIDEO: u32 = 1 << 10;
263    /// Input accessories (iOS).
264    pub const INPUT_ACCESSORY: u32 = 1 << 11;
265    /// `<overlay>`.
266    pub const OVERLAY: u32 = 1 << 12;
267    /// `<view>`.
268    pub const VIEW: u32 = 1 << 13;
269    /// `<shader>` and the shader effects and transitions.
270    pub const SHADER: u32 = 1 << 14;
271    /// Shader effects (`ShaderEffect`, `ScreenEffect`).
272    pub const EFFECT: u32 = 1 << 15;
273    /// Shader transitions (`ShaderTransition`, `ScreenTransition`).
274    pub const TRANSITION: u32 = 1 << 16;
275    /// Set by the runtime itself, not part of the elements' types.
276    pub const INTERNAL: u32 = 1 << 31;
277}
278
279/// The platform a prop is for: everywhere, or inside `ios={{…}}` /
280/// `android={{…}}` / `macos={{…}}` / `windows={{…}}` / `desktop={{…}}` /
281/// `web={{…}}`.
282#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283pub enum Platform {
284    /// Every platform.
285    All,
286    /// `ios={{…}}`.
287    Ios,
288    /// `android={{…}}`.
289    Android,
290    /// `macos={{…}}`.
291    Macos,
292    /// `windows={{…}}`.
293    Windows,
294    /// `desktop={{…}}` (macOS, Windows, Linux, desktop browsers).
295    Desktop,
296    /// `web={{…}}`.
297    Web,
298}
299
300/// One host prop, for the generated TypeScript.
301#[derive(Debug, Clone)]
302pub struct HostPropSpec {
303    /// Its JS name.
304    pub name: &'static str,
305    /// Its TypeScript type.
306    pub ts: String,
307    /// Documentation.
308    pub doc: &'static str,
309    /// The elements it applies to ([`on`] bits).
310    pub on: u32,
311    /// The platform it is for.
312    pub platform: Platform,
313}
314
315/// An enum of host props (`#[derive(HostProps)]`).
316pub trait HostProps: Sized {
317    /// The prop JS name `name` sets with `input`: `None` for a name that is
318    /// not one of these props, `Some(None)` when nothing is to be set.
319    fn decode<I: HostInput>(name: &str, input: &I, cx: &mut HostCx) -> Option<Option<Self>>;
320    /// This prop at its default (what clearing it from JS sets); `None` for
321    /// the props the runtime sets once.
322    fn reset(&self) -> Option<Self>;
323    /// Whether `self` and `other` set the same property.
324    fn same_kind(&self, other: &Self) -> bool;
325    /// The props, for the generated TypeScript.
326    fn specs(types: &mut TsTypes, out: &mut Vec<HostPropSpec>);
327}
328
329/// Numbers held to a range after decoding (`#[prop(min = …, max = …)]`).
330pub trait Clamped {
331    /// `self` within `min..=max` (either bound left out).
332    fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self;
333}
334
335impl Clamped for f32 {
336    fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
337        let v = min.map_or(self, |m| self.max(m as f32));
338        max.map_or(v, |m| v.min(m as f32))
339    }
340}
341
342impl Clamped for Points {
343    fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
344        Points(self.0.clamped(min, max))
345    }
346}
347
348impl Clamped for u32 {
349    fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
350        let v = min.map_or(self, |m| self.max(m as u32));
351        max.map_or(v, |m| v.min(m as u32))
352    }
353}
354
355impl<T: Clamped> Clamped for Option<T> {
356    fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
357        self.map(|v| v.clamped(min, max))
358    }
359}
360
361impl HostValue for bool {
362    fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
363        input.as_bool()
364    }
365
366    fn ts_type(_: &mut TsTypes) -> String {
367        "boolean".into()
368    }
369}
370
371impl HostValue for f32 {
372    fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
373        input.as_number().map(|n| n as f32)
374    }
375
376    fn ts_type(_: &mut TsTypes) -> String {
377        "number".into()
378    }
379}
380
381/// A number of points.
382impl HostValue for Points {
383    fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
384        f32::decode(input, cx).map(Points)
385    }
386
387    fn ts_type(_: &mut TsTypes) -> String {
388        "number".into()
389    }
390}
391
392impl HostValue for u32 {
393    /// Negative numbers are 0, fractions are cut.
394    fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
395        input.as_number().map(|n| n.max(0.0) as u32)
396    }
397
398    fn ts_type(_: &mut TsTypes) -> String {
399        "number".into()
400    }
401}
402
403impl HostValue for u64 {
404    /// Negative numbers are 0, fractions are cut (a size in bytes).
405    fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
406        input.as_number().map(|n| n.max(0.0) as u64)
407    }
408
409    fn ts_type(_: &mut TsTypes) -> String {
410        "number".into()
411    }
412}
413
414impl HostValue for String {
415    /// Anything but a string is the empty string's default.
416    fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
417        input.as_string()
418    }
419
420    fn ts_type(_: &mut TsTypes) -> String {
421        "string".into()
422    }
423}
424
425impl HostValue for Arc<str> {
426    /// The empty string is no value.
427    fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
428        input.as_string().filter(|s| !s.is_empty()).map(Into::into)
429    }
430
431    fn ts_type(_: &mut TsTypes) -> String {
432        "string".into()
433    }
434}
435
436impl HostValue for Box<str> {
437    /// The empty string is no value.
438    fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
439        input.as_string().filter(|s| !s.is_empty()).map(Into::into)
440    }
441
442    fn ts_type(_: &mut TsTypes) -> String {
443        "string".into()
444    }
445}
446
447impl HostValue for Color {
448    /// A CSS color string; anything else, or an invalid color, is none.
449    fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
450        input.as_string().and_then(|s| Color::parse(&s))
451    }
452
453    fn ts_type(_: &mut TsTypes) -> String {
454        "ColorValue".into()
455    }
456}
457
458/// `None` when there is no value: the prop is cleared.
459impl<T: HostValue> HostValue for Option<T> {
460    fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
461        Some(T::decode(input, cx))
462    }
463
464    fn ts_type(types: &mut TsTypes) -> String {
465        T::ts_type(types)
466    }
467}
468
469/// The items `T` takes, the others skipped.
470impl<T: HostValue> HostValue for Vec<T> {
471    fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
472        Some(
473            input
474                .items()
475                .iter()
476                .filter_map(|i| T::decode(i, cx))
477                .collect(),
478        )
479    }
480
481    fn ts_type(types: &mut TsTypes) -> String {
482        format!("{}[]", T::ts_type(types))
483    }
484}
485
486/// `{ top, right, bottom, left }` (each 0 when left out).
487impl HostValue for EdgeInsets {
488    fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
489        let side = |key| Points(input.field(key).and_then(|v| v.as_number()).unwrap_or(0.0) as f32);
490        Some(EdgeInsets {
491            top: side("top"),
492            right: side("right"),
493            bottom: side("bottom"),
494            left: side("left"),
495        })
496    }
497
498    fn ts_type(_: &mut TsTypes) -> String {
499        "Partial<Edges>".into()
500    }
501}
502
503/// Field `key` of `input` as `T`.
504pub fn field<T: HostValue, I: HostInput>(input: &I, key: &str, cx: &mut HostCx) -> Option<T> {
505    input.field(key).and_then(|v| T::decode(&v, cx))
506}
507
508/// The payloads of the host elements' events, and the shapes they are made
509/// of: `nsh_core::geometry`'s `Point`, `Size`, `Bounds` and `Edges` (in
510/// points) and `keymap::Modifiers`, with GPUI's field names.
511const EVENT_TYPES: &str = r#"/** A position, in points (`nsh_core::geometry::Point`). */
512export interface Point {
513  x: number;
514  y: number;
515}
516
517/** An extent, in points (`nsh_core::geometry::Size`). */
518export interface Size {
519  width: number;
520  height: number;
521}
522
523/** An image's or a video's own extent, in pixels as decoded
524 * (`nsh_core::geometry::Size<DevicePixels>`), not the points it is drawn at. */
525export interface PixelSize {
526  width: number;
527  height: number;
528}
529
530/** A position and an extent, in points (`nsh_core::geometry::Bounds`). */
531export interface Bounds {
532  /** The top left corner. */
533  origin: Point;
534  size: Size;
535}
536
537/** A length on each side, in points (`nsh_core::geometry::Edges`): insets, a safe area. */
538export interface Edges {
539  top: number;
540  right: number;
541  bottom: number;
542  left: number;
543}
544
545/** The modifier keys held (GPUI's `Modifiers`). */
546export interface Modifiers {
547  control: boolean;
548  /** Option on Apple platforms, Alt elsewhere. */
549  alt: boolean;
550  shift: boolean;
551  /** Command on Apple platforms, the Windows / Super key elsewhere. */
552  platform: boolean;
553  /** AltGr (the DOM's `getModifierState("AltGraph")`): the key's character came from the layout's AltGr level, so `control` and `alt` are held to type text, not for a shortcut. Set by key events on Windows; `false` elsewhere. */
554  altGraph: boolean;
555}
556
557/** A hardware key transition on the focused view: the payload of `onKeyDown` and `onKeyUp` (`nsh_core::KeyEvent`). */
558export interface KeyEvent {
559  /** The source's logical key: the DOM's spelling for named keys (`"Enter"`, `"ArrowLeft"`), else the character the key reports, in its case and layout. `"Unidentified"` when the source names none. */
560  key: string;
561  /** The key's physical identity as the DOM's `KeyboardEvent.code` spells it (`"KeyA"`, `"ArrowLeft"`, `"ShiftLeft"`); `""` when the source has none (GPUI, synthetic input), never guessed from `key`. */
562  code: string;
563  modifiers: Modifiers;
564  /** An auto-repeat of a held key (the press itself is not one). */
565  repeat: boolean;
566  /** The mounted `captureKeys` policy decided this transition: the platform runs no native default and types no text. It is this transition's decision, observed as the DOM's `defaultPrevented` is; a listener cannot veto handling after the fact. */
567  defaultPrevented: boolean;
568}
569
570/** Where the core placed an overlay: the payload of `onPosition`. */
571export interface OverlayPosition {
572  /** The side of the anchor it went on: the one asked for, or the other one when only that one has room. */
573  placement: "top" | "bottom" | "left" | "right";
574  /** Its frame in the root view (the surface, or the dialog it is in). */
575  bounds: Bounds;
576  /** The room on that side, inside the safe area less `margin`: what a menu may grow to. */
577  available: Size;
578}
579
580/** A drag: where it started, translation since then and velocity (points / second). */
581export interface PanEvent {
582  /** The system cancelled the drag rather than releasing it. */
583  cancelled: boolean;
584  /** Where the finger (or the pointer) went down, in the surface (as a touch's `pageX` / `pageY`). */
585  origin: Point;
586  /** How far the finger moved since the drag started. */
587  translation: Point;
588  /** How fast it moves, in points per second. */
589  velocity: Point;
590  /** The values `pan` binds now, those of the axes it binds (`pan.x`, `pan.y`). */
591  value?: Partial<Point>;
592}
593
594/** 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. */
595export interface PressEvent {
596  /** Position in the pressed view (its transforms undone; a pressed span's text view). */
597  position: Point;
598  /** Position in the root view the view is in (the surface or its modal), as touches' `pageX` / `pageY`. */
599  pagePosition: Point;
600  modifiers: Modifiers;
601  /** Consecutive clicks at the same place: 1 for a click, 2 for a double click; 0 when not from a pointer (keyboard Enter / Space or an assistive technology's default action), as the DOM's `detail`. */
602  clickCount: number;
603}
604
605/** 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`). */
606export interface MouseEvent {
607  /** Position in the view (its transforms undone). */
608  position: Point;
609  /** Position in the root view the view is in (the surface or its modal), as touches' `pageX` / `pageY`. */
610  pagePosition: Point;
611  modifiers: Modifiers;
612  /** The button held down (a drag), or `null`. */
613  pressedButton: MouseButton | null;
614  /** The button that changed at this event: the released one on `onMouseUp`, `null` on a move. */
615  button: MouseButton | null;
616  /** `"mouse"`, or `"pen"` for a pen over a tablet. */
617  pointerType: PointerType;
618  /** How hard it presses, 0 to 1 (`PointerEvent.pressure`): 0.5 with a button down and 0 without on a device without pressure. */
619  pressure: number;
620  /** A pen's tilt in degrees, -90 to 90 (`PointerEvent.tiltX` / `tiltY`); 0 when not reported. */
621  tiltX: number;
622  tiltY: number;
623}
624
625/** A wheel over a view: the payload of `onWheel` (GPUI's `ScrollWheelEvent`, the DOM's `WheelEvent`). */
626export interface WheelEvent {
627  /** Position in the view (its transforms undone). */
628  position: Point;
629  /** Position in the root view the view is in (the surface or its modal), as touches' `pageX` / `pageY`. */
630  pagePosition: Point;
631  /** How far it scrolled, in `deltaMode` units: positive `y` scrolls down (toward the end), positive `x` right, as the DOM's `deltaX` / `deltaY`. */
632  delta: Point;
633  /** `"points"`: a precise device (a touchpad); `"lines"`: mouse wheel notches. */
634  deltaMode: "points" | "lines";
635  modifiers: Modifiers;
636}
637
638/** A touchpad pinch over a view: the payload of `onPinch` (GPUI's `PinchEvent`). */
639export interface PinchEvent {
640  /** Position in the view (its transforms undone). */
641  position: Point;
642  /** Position in the root view the view is in (the surface or its modal), as touches' `pageX` / `pageY`. */
643  pagePosition: Point;
644  /** How much the scale changed since the last event, as a fraction: 0.1 is 10 % bigger, negative smaller. */
645  delta: number;
646  /** Where it is in the gesture, as a touch's phase. */
647  phase: "start" | "move" | "end";
648  modifiers: Modifiers;
649}
650
651/** A mouse button (GPUI's `MouseButton`). */
652export type MouseButton = "left" | "right" | "middle" | "back" | "forward";
653
654/** The kind of pointer behind an event (the DOM's `pointerType`). */
655export type PointerType = "mouse" | "pen" | "touch";
656
657/** Where a context menu was asked for: the payload of `onContextMenu`. */
658export interface ContextMenuEvent {
659  /** Position in the view (its transforms undone): the pointer's, or the view's bottom-start corner when no pointer asked. */
660  position: Point;
661  /** Position in the root view the view is in: where `Menu.popup` opens a menu (`Menu.popup(items, e.pagePosition)`). */
662  pagePosition: Point;
663  modifiers: Modifiers;
664  /** 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. */
665  pointerType: PointerType | null;
666}
667
668/** Where a scroll view is: the payload of `onScroll`. */
669export interface ScrollEvent {
670  /** The content offset. */
671  offset: Point;
672  /** The content's size (zoomed). */
673  contentSize: Size;
674  /** The scroll view's size. */
675  size: Size;
676  /** The zoom scale (1 unless the scroll view zooms). */
677  zoomScale: number;
678}
679
680/** Where an input's caret is: the payload of `onCaretMove`. */
681export interface CaretEvent {
682  /** 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. */
683  bounds: Bounds;
684  /** The caret in the root view the input is in (the surface or its dialog), as of the event: an `Overlay`'s `anchor`. */
685  pageBounds: Bounds;
686}
687
688/** One end of a selection across a list's items: `onSelectionChange`'s `anchor` and `focus`. */
689export interface TextSelectionEndpoint {
690  /** The item's key, as the list names it (`keyExtractor`, else the item's `key` or `id`, else its index). */
691  key: string;
692  /** Where the end is in the item's text, as a copy of the whole item gives it (UTF-16 units). */
693  offset: number;
694}
695
696/** 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. */
697export interface PasteEvent {
698  /** The plain text, `""` when there was none. */
699  text: string;
700  /** 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. */
701  html: string;
702  /** Files with their bytes: images (a screenshot, an image copied from a page or an app), as `File`s an app can upload. */
703  files: File[];
704  /** Files larger than the input's `pasteMaxSize`, whose bytes were not read: their names, types and sizes, so the app can tell the user. */
705  tooLarge: UnreadFile[];
706  /** `file:` URLs of local files copied in a file manager (as `onFileDrop`'s). */
707  uris: string[];
708}
709
710/** A pasted file whose bytes were not read (`PasteEvent.tooLarge`). */
711export interface UnreadFile {
712  /** Its name. */
713  name: string;
714  /** Its media type (`application/pdf`; `application/octet-stream` when unknown). */
715  type: string;
716  /** Its size in bytes. */
717  size: number;
718}
719
720/** A line of a laid-out text (in the text's content box). */
721export interface TextLayoutLine {
722  text: string;
723  bounds: Bounds;
724  ascender: number;
725  descender: number;
726  capHeight: number;
727  xHeight: number;
728}
729
730/** Where a web view is: the payload of its navigation events. */
731export interface WebViewNavigation {
732  url: string;
733  title: string;
734  loading: boolean;
735  canGoBack: boolean;
736  canGoForward: boolean;
737}
738
739/** A web view's download (`onDownload`): where it is saved, in the app's data directory's `downloads`. */
740export interface WebViewDownload {
741  state: "started" | "finished" | "failed" | "cancelled";
742  id: string;
743  url: string;
744  filename: string;
745  path: string;
746  /** Who owns the bytes: the engine's transfer, a request NSH made, a page, or none (the response is gone). */
747  source: "transfer" | "request" | "page" | "none";
748  /** Once finished: the file's size in bytes. */
749  bytes?: number;
750  /** When it failed: why. */
751  message?: string;
752  /** A stable code on failure or cancellation. */
753  code?: string;
754  /** Why it was cancelled. */
755  reason?: "app" | "timeout" | "teardown" | "noListener";
756}
757"#;
758
759/// The events of the host elements, as their handler props: the event, the
760/// elements whose props declare it ([`on`] bits), the handler's type and
761/// its documentation. An event whose payload differs between elements has
762/// a row per payload.
763pub const EVENTS: &[(EventKind, u32, &str, &str)] = &[
764    (
765        EventKind::Press,
766        on::ALL,
767        "(e: PressEvent) => void",
768        "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).",
769    ),
770    (
771        EventKind::LongPress,
772        on::ALL,
773        "(e: PressEvent) => void",
774        "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).",
775    ),
776    (
777        EventKind::PressDown,
778        on::ALL,
779        "(e: PressEvent) => void",
780        "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).",
781    ),
782    (
783        EventKind::PressUp,
784        on::ALL,
785        "(e: PressEvent) => void",
786        "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).",
787    ),
788    (
789        EventKind::MouseEnter,
790        on::ALL,
791        "(e: MouseEvent) => void",
792        "The mouse came over the view or a view inside it (never on touches; the DOM's `mouseenter`).",
793    ),
794    (
795        EventKind::MouseLeave,
796        on::ALL,
797        "(e: MouseEvent) => void",
798        "The mouse left the view and the views inside it, or the window, from where `e` says (the DOM's `mouseleave`).",
799    ),
800    (
801        EventKind::MouseMove,
802        on::ALL,
803        "(e: MouseEvent) => void",
804        "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.",
805    ),
806    (
807        EventKind::Wheel,
808        on::ALL,
809        "(e: WheelEvent) => void",
810        "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.control` and pans otherwise); a scroll view listening, or a view around one, only observes it.",
811    ),
812    (
813        EventKind::Pinch,
814        on::ALL,
815        "(e: PinchEvent) => void",
816        "A touchpad pinch over the view (or a view inside it); macOS, Linux, the GPUI backend and Safari (Windows and the other browsers report a touchpad pinch as Control + wheel: `onWheel`). The nearest listener hears it; a listener nearer than any view that pinches natively takes it, and nothing zooms natively. A pinch stays on the view its start went to. Fingers pinching a touchscreen are `onPinchStart`'s.",
817    ),
818    (
819        EventKind::MouseUp,
820        on::ALL,
821        "(e: MouseEvent) => void",
822        "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.",
823    ),
824    (
825        EventKind::ContextMenu,
826        on::ALL,
827        "(e: ContextMenuEvent) => void",
828        "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.",
829    ),
830    (
831        EventKind::FileDragEnter,
832        on::ALL,
833        "(e: { uris: string[]; mimeTypes: string[] }) => void",
834        "A local file drag entered this destination (desktops, iOS and Android) 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; iOS and Android read files only on drop, so they offer no URLs; the Web offers no URLs, only the types the browser shows.",
835    ),
836    (
837        EventKind::FileDragLeave,
838        on::ALL,
839        "() => void",
840        "A local file drag left this destination (desktops, iOS, Android and the Web).",
841    ),
842    (
843        EventKind::FileDrop,
844        on::ALL,
845        "(e: { uris: string[]; mimeTypes: string[]; pagePosition?: { x: number; y: number }; files: { file: File | null; name: string; type: string; size: number; status: \"read\" | \"tooLarge\" }[] }) => void",
846        "Local file URLs dropped on this destination (desktops, iOS, Android and the Web), with each one's MIME type by its name (`\"\"` when the name says none); `pagePosition`: where, in the window's coordinates as a mouse event's (macOS, Windows, Linux, iOS, Android and the Web; absent on the GPUI backend). On the Web `uris` is empty and `files` holds the dropped regular files with their contents (`status` `\"tooLarge\"` past 512 MiB a drop; at most 100); elsewhere `files` is empty.",
847    ),
848    (
849        EventKind::Layout,
850        on::ALL,
851        "(e: { bounds: Bounds }) => void",
852        "The frame changed: its bounds in the parent.",
853    ),
854    (EventKind::PanStart, on::ALL, "(e: PanEvent) => void", ""),
855    (
856        EventKind::PanEnd,
857        on::ALL,
858        "(e: PanEvent) => void",
859        "With the release velocity, e.g. to start a `decay`.",
860    ),
861    (
862        EventKind::PinchStart,
863        on::ALL,
864        "(e: { scale: number; velocity: number }) => void",
865        "",
866    ),
867    (
868        EventKind::PinchEnd,
869        on::ALL,
870        "(e: { scale: number; velocity: number }) => void",
871        "",
872    ),
873    (
874        EventKind::RotationStart,
875        on::ALL,
876        "(e: { rotation: number; velocity: number }) => void",
877        "",
878    ),
879    (
880        EventKind::RotationEnd,
881        on::ALL,
882        "(e: { rotation: number; velocity: number }) => void",
883        "",
884    ),
885    (
886        EventKind::AccessibilityAction,
887        on::ALL,
888        "(e: { actionName: string }) => void",
889        "",
890    ),
891    (
892        EventKind::TextLayout,
893        on::TEXT,
894        "(e: { lines: TextLayoutLine[] }) => void",
895        "The laid-out lines (in the text's content box), after each layout.",
896    ),
897    (
898        EventKind::LoadStart,
899        on::IMAGE | on::VIDEO,
900        "() => void",
901        "",
902    ),
903    (
904        EventKind::LoadStart,
905        on::WEBVIEW,
906        "(e: WebViewNavigation) => void",
907        "",
908    ),
909    (
910        EventKind::Progress,
911        on::IMAGE,
912        "(e: { loaded: number; total: number }) => void",
913        "Download progress in bytes (`total` 0 when unknown); at most every 100 ms.",
914    ),
915    (
916        EventKind::Progress,
917        on::VIDEO,
918        "(e: { currentTime: number; duration: number }) => void",
919        "",
920    ),
921    (
922        EventKind::Load,
923        on::IMAGE,
924        "(e: { size: PixelSize }) => void",
925        "The source image's size in pixels (not the decoded, downsampled one).",
926    ),
927    (
928        EventKind::Load,
929        on::WEBVIEW,
930        "(e: WebViewNavigation) => void",
931        "",
932    ),
933    (
934        EventKind::Load,
935        on::VIDEO,
936        "(e: { duration: number; size: PixelSize }) => void",
937        "",
938    ),
939    (
940        EventKind::Error,
941        on::IMAGE | on::WEBVIEW | on::VIDEO,
942        "(e: { message: string; code?: string }) => void",
943        "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`), `\"ERR_FEATURE_UNAVAILABLE_ON_PLATFORM\"` for a web view where the platform shows none (`WebView.available()`), and `\"ERR_NSH_WEBVIEW_TERMINATED\"` when a web view's web content process ended (it shows no page until `reload()`, `load()` or a new source).",
944    ),
945    (
946        EventKind::LoadEnd,
947        on::IMAGE,
948        "() => void",
949        "After `onLoad` or `onError`.",
950    ),
951    (
952        EventKind::Scroll,
953        on::SCROLLING,
954        "(e: ScrollEvent) => void",
955        "",
956    ),
957    (
958        EventKind::ScrollDragStart,
959        on::SCROLLING,
960        "(e: { offset: Point }) => void",
961        "",
962    ),
963    (
964        EventKind::ScrollDragEnd,
965        on::SCROLLING,
966        "(e: { offset: Point }) => void",
967        "",
968    ),
969    (
970        EventKind::MomentumStart,
971        on::SCROLLING,
972        "(e: { offset: Point }) => void",
973        "",
974    ),
975    (
976        EventKind::MomentumEnd,
977        on::SCROLLING,
978        "(e: { offset: Point }) => void",
979        "",
980    ),
981    (
982        EventKind::ScrollEnd,
983        on::SCROLL | on::LIST,
984        "(e: { offset: Point }) => void",
985        "",
986    ),
987    (EventKind::Refresh, on::SCROLL | on::LIST, "() => void", ""),
988    (EventKind::LoadMore, on::LIST, "() => void", ""),
989    (
990        EventKind::LoadMoreAtStart,
991        on::LIST,
992        "() => void",
993        "Within `loadMoreAtStartThreshold` viewports of the start, once the user or a scroll command moved the list: load what comes before the first item.",
994    ),
995    (
996        EventKind::ChangeText,
997        on::INPUT,
998        "(e: { value: string }) => void",
999        "The user edited the text: `value` is the text now.",
1000    ),
1001    (
1002        EventKind::SubmitEditing,
1003        on::INPUT,
1004        "(e: { text: string }) => void",
1005        "",
1006    ),
1007    (
1008        EventKind::Focus,
1009        on::ALL,
1010        "() => void",
1011        "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).",
1012    ),
1013    (
1014        EventKind::Blur,
1015        on::ALL,
1016        "() => void",
1017        "It lost the keyboard focus.",
1018    ),
1019    (
1020        EventKind::FocusIn,
1021        on::ALL,
1022        "() => void",
1023        "The keyboard focus came into it: onto it or a view inside it, from outside (it entered `focus-within`). Moving between the views inside it is no new coming in; the content of an overlay is inside the view the overlay is in. A panel notes where its focus is with it, to put it back later with `ref.focus()`.",
1024    ),
1025    (
1026        EventKind::FocusOut,
1027        on::ALL,
1028        "() => void",
1029        "The keyboard focus left it: from it or a view inside it to one outside, or to none (it left `focus-within`). A view removed with the focus inside it hears nothing.",
1030    ),
1031    (
1032        EventKind::SelectionChange,
1033        on::INPUT,
1034        "(e: { start: number; end: number }) => void",
1035        "",
1036    ),
1037    (
1038        EventKind::SelectionChange,
1039        on::VIEW,
1040        "(e: { text: string; start?: number; bounds?: Bounds; pageBounds?: Bounds; anchor?: TextSelectionEndpoint; focus?: TextSelectionEndpoint }) => void",
1041        "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. `anchor` (where the selection started) and `focus` (where it goes now, before `anchor` when the user selected backward) name the `List` item each end is in by its key, with the offset in that item's text, while something is selected and the end is in a list item. Only the outermost selectable view of an area reports it.",
1042    ),
1043    (
1044        EventKind::Paste,
1045        on::INPUT,
1046        "(e: PasteEvent) => void",
1047        "The user pasted (the keyboard's shortcut, a menu's Paste, a keyboard's image): the text, images as `File`s (files larger than `pasteMaxSize` in `tooLarge`, unread), 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).",
1048    ),
1049    (
1050        EventKind::CaretMove,
1051        on::INPUT,
1052        "(e: CaretEvent) => void",
1053        "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.",
1054    ),
1055    (
1056        EventKind::KeyPress,
1057        on::INPUT,
1058        "(e: { key: string }) => void",
1059        "Before the text changes: `key` is the typed text, `Backspace` or `Enter`.",
1060    ),
1061    (
1062        EventKind::KeyDown,
1063        on::ALL,
1064        "(e: KeyEvent) => void",
1065        "A hardware key went down on the focused view or a view inside it on desktop and Web. It bubbles to enabled listening ancestors within the same native window. `defaultPrevented` is the mounted `captureKeys` decision for this transition.",
1066    ),
1067    (
1068        EventKind::KeyUp,
1069        on::ALL,
1070        "(e: KeyEvent) => void",
1071        "A hardware key came up on the focused view, with this transition's `defaultPrevented` decision; it bubbles as `onKeyDown` does. A window that loses the focus invents no releases.",
1072    ),
1073    (
1074        EventKind::CompositionChange,
1075        on::INPUT,
1076        "(e: { composing: boolean; text: string }) => void",
1077        "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.",
1078    ),
1079    (
1080        EventKind::ContentSizeChange,
1081        on::INPUT,
1082        "(e: { size: Size }) => void",
1083        "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.",
1084    ),
1085    (
1086        EventKind::Message,
1087        on::WEBVIEW,
1088        "(e: { data: string }) => void",
1089        "The page called `window.nsh.postMessage(data)`.",
1090    ),
1091    (
1092        EventKind::NavigationStateChange,
1093        on::WEBVIEW,
1094        "(e: WebViewNavigation) => void",
1095        "",
1096    ),
1097    (
1098        EventKind::Download,
1099        on::WEBVIEW,
1100        "(e: WebViewDownload) => void",
1101        "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.",
1102    ),
1103    (EventKind::End, on::VIDEO, "() => void", ""),
1104    (
1105        EventKind::Buffer,
1106        on::VIDEO,
1107        "(e: { isBuffering: boolean }) => void",
1108        "",
1109    ),
1110    (
1111        EventKind::PressOutside,
1112        on::OVERLAY,
1113        "(e: { pagePosition: Point }) => void",
1114        "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.",
1115    ),
1116    (
1117        EventKind::Cancel,
1118        on::OVERLAY,
1119        "() => void",
1120        "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.",
1121    ),
1122    (
1123        EventKind::DetentChange,
1124        on::MODAL,
1125        "(e: { detent: SheetDetent }) => void",
1126        "The user moved an iOS sheet to another of its `detents` (dragging it, its grabber, a scroll at its edge, a screen reader): set `detent` to it to keep the app's value in step.",
1127    ),
1128    (
1129        EventKind::Position,
1130        on::OVERLAY,
1131        "(e: OverlayPosition) => void",
1132        "The core placed the overlay (again: the anchor moved, the overlay changed size, it went to the other side).",
1133    ),
1134];
1135
1136/// The events no element's props declare: the root's (`BackHandler`'s,
1137/// `nsh/keymap`, dialogs, `Image.getSize`, clipboard reads, menus, `nsh/host`'s replies and events, links), the runtime's own (touches, insets, native
1138/// components' events) and those whose payload a module makes
1139/// (`List`'s viewable items, with the app's items).
1140pub const INTERNAL_EVENTS: &[EventKind] = &[
1141    EventKind::Touch,
1142    EventKind::Insets,
1143    EventKind::NativeEvent,
1144    EventKind::Dialog,
1145    EventKind::BackPress,
1146    EventKind::BackProgress,
1147    EventKind::ImageInfo,
1148    EventKind::WebEvaluation,
1149    EventKind::WebViewReply,
1150    EventKind::DownloadPending,
1151    EventKind::DownloadOffer,
1152    EventKind::DownloadProgress,
1153    EventKind::DownloadEnd,
1154    EventKind::Clipboard,
1155    EventKind::Host,
1156    EventKind::Pick,
1157    EventKind::OpenUrl,
1158    EventKind::OpenAppSettings,
1159    EventKind::ClipboardWrite,
1160    EventKind::ScreenColor,
1161    EventKind::CanvasImage,
1162    EventKind::FileRequest,
1163    EventKind::Notification,
1164    EventKind::UrlScheme,
1165    EventKind::SecondInstance,
1166    EventKind::Audio,
1167    EventKind::Window,
1168    EventKind::EditAction,
1169    EventKind::KeyCommand,
1170    EventKind::Menu,
1171    EventKind::ViewableItemsChange,
1172    // Text dropped on a Rust component (`RichEditor` inserts it).
1173    EventKind::TextDrop,
1174    // `NavPage`'s `onDismiss` / `onBackPress` and `Dialog`'s `onClose` /
1175    // `onCancel` / `onOpenChange` / `onOpen`: the navigation's handlers
1176    // (`nsh-js` `navigation.rs`), declared with its components.
1177    EventKind::BackRequest,
1178    EventKind::Dismiss,
1179    EventKind::RequestClose,
1180    EventKind::Show,
1181];
1182
1183/// The interfaces of the host props, by the elements their props apply
1184/// to: `HostProps` for every element, `TextHostProps` for `<text>`, ...
1185const GROUPS: &[(u32, &str, &str)] = &[
1186    (on::ALL, "", "every element"),
1187    (on::VIEW, "View", "`<View>`"),
1188    (on::TEXT, "Text", "`<Text>`"),
1189    (on::IMAGE, "Image", "`<Image>`"),
1190    (
1191        on::SCROLLING,
1192        "Scrolling",
1193        "scroll views and lists (how they scroll)",
1194    ),
1195    (on::SCROLL, "Scroll", "`<Scroll>`"),
1196    (on::LIST, "List", "lists"),
1197    (on::INPUT, "Input", "`<Input>`"),
1198    (on::SCREEN, "NavPage", "the pages of a `NavStack`"),
1199    (on::MODAL, "Dialog", "dialogs"),
1200    (on::WEBVIEW, "WebView", "web views"),
1201    (on::VIDEO, "Video", "videos"),
1202    (on::SHADER, "Shader", "shaders"),
1203    (on::EFFECT, "ShaderEffect", "shader effects"),
1204    (on::TRANSITION, "ShaderTransition", "shader transitions"),
1205    (on::INPUT_ACCESSORY, "InputAccessory", "input accessories"),
1206    (on::OVERLAY, "Overlay", "`<Overlay>`"),
1207];
1208
1209/// The declarations of the host elements' props: the named types they use
1210/// and one interface per element group and platform (`InputHostProps`,
1211/// `IOSInputHostProps`, ...), which the element types and the components
1212/// of `nsh` (`WebView`, `Video`, ...) extend, and the options the refs'
1213/// methods take (`RevealOptions`).
1214pub fn declarations() -> String {
1215    use std::fmt::Write as _;
1216    let mut types = TsTypes::default();
1217    let mut specs = Vec::new();
1218    <crate::Prop as HostProps>::specs(&mut types, &mut specs);
1219    <crate::RevealOptions as HostValue>::ts_type(&mut types);
1220    let mut out = String::from(EVENT_TYPES);
1221    for declaration in types.declarations() {
1222        let _ = write!(out, "\n{declaration}\n");
1223    }
1224    for (bit, group, what) in GROUPS {
1225        for (platform, prefix, inside) in [
1226            (Platform::All, "", ""),
1227            (Platform::Ios, "IOS", " inside `ios={{…}}`"),
1228            (Platform::Android, "Android", " inside `android={{…}}`"),
1229            (Platform::Macos, "MacOS", " inside `macos={{…}}`"),
1230            (Platform::Windows, "Windows", " inside `windows={{…}}`"),
1231            (Platform::Desktop, "Desktop", " inside `desktop={{…}}`"),
1232            (Platform::Web, "Web", " inside `web={{…}}`"),
1233        ] {
1234            let props: Vec<&HostPropSpec> = specs
1235                .iter()
1236                .filter(|s| s.on & bit != 0 && s.platform == platform)
1237                .collect();
1238            // Events are for every platform.
1239            let events: Vec<_> = EVENTS
1240                .iter()
1241                .filter(|e| e.1 & bit != 0 && platform == Platform::All)
1242                .collect();
1243            if props.is_empty() && events.is_empty() {
1244                continue;
1245            }
1246            let _ = write!(
1247                out,
1248                "\n/** The props of {what}{inside}. */\nexport interface {prefix}{group}HostProps {{\n"
1249            );
1250            for p in props {
1251                if !p.doc.is_empty() {
1252                    let _ = writeln!(out, "  /** {} */", p.doc);
1253                }
1254                let _ = writeln!(out, "  {}?: {};", p.name, p.ts);
1255            }
1256            for (kind, _, handler, doc) in events {
1257                if !doc.is_empty() {
1258                    let _ = writeln!(out, "  /** {doc} */");
1259                }
1260                let _ = writeln!(out, "  {}?: {handler};", kind.handler_name());
1261            }
1262            out.push_str("}\n");
1263        }
1264    }
1265    out
1266}