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