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