1use std::sync::Arc;
16
17pub use nsh_macros::HostProps;
18
19use crate::{EdgeInsets, EventKind, element::TsTypes, geometry::Points, style::Color};
20
21pub trait HostInput: Sized {
23 fn is_nullish(&self) -> bool;
25 fn is_object(&self) -> bool;
27 fn as_bool(&self) -> Option<bool>;
29 fn as_number(&self) -> Option<f64>;
31 fn as_string(&self) -> Option<String>;
33 fn field(&self, key: &str) -> Option<Self>;
35 fn items(&self) -> Vec<Self> {
37 match self.as_list() {
38 Some(list) => (0..list.len()).filter_map(|i| list.item(i)).collect(),
39 None => Vec::new(),
40 }
41 }
42 fn as_list(&self) -> Option<Self::List>;
44 type List: HostList<Item = Self>;
46 fn entries(&self) -> Vec<(String, Self)>;
48 fn truthy(&self) -> bool;
50 fn node(&self) -> Option<crate::NodeId> {
52 None
53 }
54 fn animated_node(&self) -> Option<crate::animation::NodeId> {
56 self.field("__av")
57 .and_then(|v| v.as_number())
58 .map(|n| n as crate::animation::NodeId)
59 }
60}
61
62pub trait HostList {
64 type Item;
66 fn len(&self) -> usize;
68 fn is_empty(&self) -> bool {
70 self.len() == 0
71 }
72 fn item(&self, index: usize) -> Option<Self::Item>;
74}
75
76#[derive(Debug, Default)]
79pub struct HostCx {
80 pub warnings: Vec<String>,
82 pub element: u32,
86}
87
88impl HostCx {
89 pub fn for_element(tag: crate::Tag) -> Self {
91 Self {
92 element: element_bits(tag),
93 ..Self::default()
94 }
95 }
96
97 pub fn warn(&mut self, message: impl Into<String>) {
99 self.warnings.push(message.into());
100 }
101
102 pub fn on_element(&self, on: u32) -> bool {
105 self.element == 0 || self.element & on != 0
106 }
107}
108
109pub fn element_bits(tag: crate::Tag) -> u32 {
111 use crate::Tag;
112 on::ALL
113 | match tag {
114 Tag::Text => on::TEXT,
115 Tag::Image => on::IMAGE,
116 Tag::Scroll => on::SCROLLING | on::SCROLL,
117 Tag::List => on::SCROLLING | on::LIST,
118 Tag::Input => on::INPUT,
119 Tag::Screen => on::SCREEN,
120 Tag::Modal => on::MODAL,
121 Tag::WebView => on::WEBVIEW,
122 Tag::Video => on::VIDEO,
123 Tag::InputAccessory => on::INPUT_ACCESSORY,
124 Tag::View => on::VIEW,
125 Tag::Shader => on::VIEW | on::SHADER,
126 Tag::ShaderEffect => on::VIEW | on::SHADER | on::EFFECT,
127 Tag::ShaderTransition => on::VIEW | on::SHADER | on::TRANSITION,
128 Tag::ScreenEffect => on::SHADER | on::EFFECT,
129 Tag::ScreenTransition => on::SHADER | on::TRANSITION,
130 Tag::Cell | Tag::Stack | Tag::HeaderItem | Tag::Canvas | Tag::Native | Tag::Overlay => {
131 0
132 }
133 }
134}
135
136pub type StylePatchProp = fn(Option<std::rc::Rc<crate::StylePatch>>) -> crate::Prop;
139
140#[inline]
145pub fn style_patch_prop(name: &str) -> Option<StylePatchProp> {
146 use crate::Prop;
147 Some(match name {
148 "activeStyle" => Prop::ActiveStyle,
149 "hoverStyle" => Prop::HoverStyle,
150 "focusStyle" => Prop::FocusStyle,
151 "disabledStyle" => Prop::DisabledStyle,
152 "selectedStyle" => Prop::SelectedStyle,
153 "checkedStyle" => Prop::CheckedStyle,
154 "indeterminateStyle" => Prop::IndeterminateStyle,
155 "expandedStyle" => Prop::ExpandedStyle,
156 "pressedStyle" => Prop::PressedStyle,
157 "focusWithinStyle" => Prop::FocusWithinStyle,
158 "focusVisibleStyle" => Prop::FocusVisibleStyle,
159 "headerStyle" => Prop::HeaderStyle,
160 _ => return None,
161 })
162}
163
164pub type PartClassProp = fn(Box<str>) -> crate::Prop;
167
168#[inline]
173pub fn part_class_prop(name: &str, tag: Option<crate::Tag>) -> Option<PartClassProp> {
174 use crate::{Prop, Tag};
175 match name {
176 "headerClass" => Some(Prop::HeaderClass),
177 "contentClass" if tag != Some(Tag::Scroll) => Some(Prop::ListContentClass),
178 _ => None,
179 }
180}
181
182pub trait HostValue: Sized {
186 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self>;
188 fn ts_type(types: &mut TsTypes) -> String;
190}
191
192#[doc(hidden)]
202pub fn decode_capture_keys<I: HostInput>(
203 input: &I,
204 cx: &mut HostCx,
205 apple: bool,
206) -> Option<crate::KeyCapture> {
207 use crate::{KeyCapture, keymap::Keystroke};
208 if let Some(text) = input.as_string() {
209 return match text.as_str() {
210 "none" => Some(KeyCapture::None),
211 "all" => Some(KeyCapture::All),
212 "text" => Some(KeyCapture::Text),
213 other => {
214 cx.warn(format!(
215 "captureKeys: expected \"none\", \"all\", \"text\" or keystrokes, got {other:?}"
216 ));
217 None
218 }
219 };
220 }
221 let list = input.as_list()?;
222 let mut keys = Vec::with_capacity(list.len());
223 for index in 0..list.len() {
224 let Some(item) = list.item(index) else {
225 continue;
226 };
227 let Some(text) = item.as_string() else {
228 cx.warn(format!("captureKeys[{index}]: expected a keystroke string"));
229 continue;
230 };
231 match Keystroke::parse_with(&text, apple) {
232 Ok(keystroke) => keys.push(keystroke),
233 Err(error) => cx.warn(format!("captureKeys: {error}")),
234 }
235 }
236 Some(KeyCapture::Keys(keys.into()))
237}
238
239pub mod on {
241 pub const ALL: u32 = 1;
243 pub const TEXT: u32 = 1 << 1;
245 pub const IMAGE: u32 = 1 << 2;
247 pub const SCROLLING: u32 = 1 << 3;
249 pub const SCROLL: u32 = 1 << 4;
251 pub const LIST: u32 = 1 << 5;
253 pub const INPUT: u32 = 1 << 6;
255 pub const SCREEN: u32 = 1 << 7;
257 pub const MODAL: u32 = 1 << 8;
259 pub const WEBVIEW: u32 = 1 << 9;
261 pub const VIDEO: u32 = 1 << 10;
263 pub const INPUT_ACCESSORY: u32 = 1 << 11;
265 pub const OVERLAY: u32 = 1 << 12;
267 pub const VIEW: u32 = 1 << 13;
269 pub const SHADER: u32 = 1 << 14;
271 pub const EFFECT: u32 = 1 << 15;
273 pub const TRANSITION: u32 = 1 << 16;
275 pub const INTERNAL: u32 = 1 << 31;
277}
278
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283pub enum Platform {
284 All,
286 Ios,
288 Android,
290 Macos,
292 Windows,
294 Desktop,
296 Web,
298}
299
300#[derive(Debug, Clone)]
302pub struct HostPropSpec {
303 pub name: &'static str,
305 pub ts: String,
307 pub doc: &'static str,
309 pub on: u32,
311 pub platform: Platform,
313}
314
315pub trait HostProps: Sized {
317 fn decode<I: HostInput>(name: &str, input: &I, cx: &mut HostCx) -> Option<Option<Self>>;
320 fn reset(&self) -> Option<Self>;
323 fn same_kind(&self, other: &Self) -> bool;
325 fn specs(types: &mut TsTypes, out: &mut Vec<HostPropSpec>);
327}
328
329pub trait Clamped {
331 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self;
333}
334
335impl Clamped for f32 {
336 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
337 let v = min.map_or(self, |m| self.max(m as f32));
338 max.map_or(v, |m| v.min(m as f32))
339 }
340}
341
342impl Clamped for Points {
343 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
344 Points(self.0.clamped(min, max))
345 }
346}
347
348impl Clamped for u32 {
349 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
350 let v = min.map_or(self, |m| self.max(m as u32));
351 max.map_or(v, |m| v.min(m as u32))
352 }
353}
354
355impl<T: Clamped> Clamped for Option<T> {
356 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
357 self.map(|v| v.clamped(min, max))
358 }
359}
360
361impl HostValue for bool {
362 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
363 input.as_bool()
364 }
365
366 fn ts_type(_: &mut TsTypes) -> String {
367 "boolean".into()
368 }
369}
370
371impl HostValue for f32 {
372 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
373 input.as_number().map(|n| n as f32)
374 }
375
376 fn ts_type(_: &mut TsTypes) -> String {
377 "number".into()
378 }
379}
380
381impl HostValue for Points {
383 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
384 f32::decode(input, cx).map(Points)
385 }
386
387 fn ts_type(_: &mut TsTypes) -> String {
388 "number".into()
389 }
390}
391
392impl HostValue for u32 {
393 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
395 input.as_number().map(|n| n.max(0.0) as u32)
396 }
397
398 fn ts_type(_: &mut TsTypes) -> String {
399 "number".into()
400 }
401}
402
403impl HostValue for u64 {
404 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
406 input.as_number().map(|n| n.max(0.0) as u64)
407 }
408
409 fn ts_type(_: &mut TsTypes) -> String {
410 "number".into()
411 }
412}
413
414impl HostValue for String {
415 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
417 input.as_string()
418 }
419
420 fn ts_type(_: &mut TsTypes) -> String {
421 "string".into()
422 }
423}
424
425impl HostValue for Arc<str> {
426 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
428 input.as_string().filter(|s| !s.is_empty()).map(Into::into)
429 }
430
431 fn ts_type(_: &mut TsTypes) -> String {
432 "string".into()
433 }
434}
435
436impl HostValue for Box<str> {
437 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
439 input.as_string().filter(|s| !s.is_empty()).map(Into::into)
440 }
441
442 fn ts_type(_: &mut TsTypes) -> String {
443 "string".into()
444 }
445}
446
447impl HostValue for Color {
448 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
450 input.as_string().and_then(|s| Color::parse(&s))
451 }
452
453 fn ts_type(_: &mut TsTypes) -> String {
454 "ColorValue".into()
455 }
456}
457
458impl<T: HostValue> HostValue for Option<T> {
460 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
461 Some(T::decode(input, cx))
462 }
463
464 fn ts_type(types: &mut TsTypes) -> String {
465 T::ts_type(types)
466 }
467}
468
469impl<T: HostValue> HostValue for Vec<T> {
471 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
472 Some(
473 input
474 .items()
475 .iter()
476 .filter_map(|i| T::decode(i, cx))
477 .collect(),
478 )
479 }
480
481 fn ts_type(types: &mut TsTypes) -> String {
482 format!("{}[]", T::ts_type(types))
483 }
484}
485
486impl HostValue for EdgeInsets {
488 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
489 let side = |key| Points(input.field(key).and_then(|v| v.as_number()).unwrap_or(0.0) as f32);
490 Some(EdgeInsets {
491 top: side("top"),
492 right: side("right"),
493 bottom: side("bottom"),
494 left: side("left"),
495 })
496 }
497
498 fn ts_type(_: &mut TsTypes) -> String {
499 "Partial<Edges>".into()
500 }
501}
502
503pub fn field<T: HostValue, I: HostInput>(input: &I, key: &str, cx: &mut HostCx) -> Option<T> {
505 input.field(key).and_then(|v| T::decode(&v, cx))
506}
507
508const EVENT_TYPES: &str = r#"/** A position, in points (`nsh_core::geometry::Point`). */
512export interface Point {
513 x: number;
514 y: number;
515}
516
517/** An extent, in points (`nsh_core::geometry::Size`). */
518export interface Size {
519 width: number;
520 height: number;
521}
522
523/** An image's or a video's own extent, in pixels as decoded
524 * (`nsh_core::geometry::Size<DevicePixels>`), not the points it is drawn at. */
525export interface PixelSize {
526 width: number;
527 height: number;
528}
529
530/** A position and an extent, in points (`nsh_core::geometry::Bounds`). */
531export interface Bounds {
532 /** The top left corner. */
533 origin: Point;
534 size: Size;
535}
536
537/** A length on each side, in points (`nsh_core::geometry::Edges`): insets, a safe area. */
538export interface Edges {
539 top: number;
540 right: number;
541 bottom: number;
542 left: number;
543}
544
545/** The modifier keys held (GPUI's `Modifiers`). */
546export interface Modifiers {
547 control: boolean;
548 /** Option on Apple platforms, Alt elsewhere. */
549 alt: boolean;
550 shift: boolean;
551 /** Command on Apple platforms, the Windows / Super key elsewhere. */
552 platform: boolean;
553 /** AltGr (the DOM's `getModifierState("AltGraph")`): the key's character came from the layout's AltGr level, so `control` and `alt` are held to type text, not for a shortcut. Set by key events on Windows; `false` elsewhere. */
554 altGraph: boolean;
555}
556
557/** A hardware key transition on the focused view: the payload of `onKeyDown` and `onKeyUp` (`nsh_core::KeyEvent`). */
558export interface KeyEvent {
559 /** The source's logical key: the DOM's spelling for named keys (`"Enter"`, `"ArrowLeft"`), else the character the key reports, in its case and layout. `"Unidentified"` when the source names none. */
560 key: string;
561 /** The key's physical identity as the DOM's `KeyboardEvent.code` spells it (`"KeyA"`, `"ArrowLeft"`, `"ShiftLeft"`); `""` when the source has none (GPUI, synthetic input), never guessed from `key`. */
562 code: string;
563 modifiers: Modifiers;
564 /** An auto-repeat of a held key (the press itself is not one). */
565 repeat: boolean;
566 /** The mounted `captureKeys` policy decided this transition: the platform runs no native default and types no text. It is this transition's decision, observed as the DOM's `defaultPrevented` is; a listener cannot veto handling after the fact. */
567 defaultPrevented: boolean;
568}
569
570/** Where the core placed an overlay: the payload of `onPosition`. */
571export interface OverlayPosition {
572 /** The side of the anchor it went on: the one asked for, or the other one when only that one has room. */
573 placement: "top" | "bottom" | "left" | "right";
574 /** Its frame in the root view (the surface, or the dialog it is in). */
575 bounds: Bounds;
576 /** The room on that side, inside the safe area less `margin`: what a menu may grow to. */
577 available: Size;
578}
579
580/** A drag: where it started, translation since then and velocity (points / second). */
581export interface PanEvent {
582 /** The system cancelled the drag rather than releasing it. */
583 cancelled: boolean;
584 /** Where the finger (or the pointer) went down, in the surface (as a touch's `pageX` / `pageY`). */
585 origin: Point;
586 /** How far the finger moved since the drag started. */
587 translation: Point;
588 /** How fast it moves, in points per second. */
589 velocity: Point;
590 /** The values `pan` binds now, those of the axes it binds (`pan.x`, `pan.y`). */
591 value?: Partial<Point>;
592}
593
594/** Where the pointer was at a press, the modifier keys held when it began and its click count: the payload of `onPress`, `onLongPress`, `onPressDown` and `onPressUp` on backends that know it. */
595export interface PressEvent {
596 /** Position in the pressed view (its transforms undone; a pressed span's text view). */
597 position: Point;
598 /** Position in the root view the view is in (the surface or its modal), as touches' `pageX` / `pageY`. */
599 pagePosition: Point;
600 modifiers: Modifiers;
601 /** Consecutive clicks at the same place: 1 for a click, 2 for a double click; 0 when not from a pointer (keyboard Enter / Space or an assistive technology's default action), as the DOM's `detail`. */
602 clickCount: number;
603}
604
605/** Where the mouse is over a view, or where a button was released over it: the payload of `onMouseEnter`, `onMouseMove`, `onMouseLeave` and `onMouseUp` (GPUI's `MouseMoveEvent`). */
606export interface MouseEvent {
607 /** Position in the view (its transforms undone). */
608 position: Point;
609 /** Position in the root view the view is in (the surface or its modal), as touches' `pageX` / `pageY`. */
610 pagePosition: Point;
611 modifiers: Modifiers;
612 /** The button held down (a drag), or `null`. */
613 pressedButton: MouseButton | null;
614 /** The button that changed at this event: the released one on `onMouseUp`, `null` on a move. */
615 button: MouseButton | null;
616 /** `"mouse"`, or `"pen"` for a pen over a tablet. */
617 pointerType: PointerType;
618 /** How hard it presses, 0 to 1 (`PointerEvent.pressure`): 0.5 with a button down and 0 without on a device without pressure. */
619 pressure: number;
620 /** A pen's tilt in degrees, -90 to 90 (`PointerEvent.tiltX` / `tiltY`); 0 when not reported. */
621 tiltX: number;
622 tiltY: number;
623}
624
625/** A wheel over a view: the payload of `onWheel` (GPUI's `ScrollWheelEvent`, the DOM's `WheelEvent`). */
626export interface WheelEvent {
627 /** Position in the view (its transforms undone). */
628 position: Point;
629 /** Position in the root view the view is in (the surface or its modal), as touches' `pageX` / `pageY`. */
630 pagePosition: Point;
631 /** How far it scrolled, in `deltaMode` units: positive `y` scrolls down (toward the end), positive `x` right, as the DOM's `deltaX` / `deltaY`. */
632 delta: Point;
633 /** `"points"`: a precise device (a touchpad); `"lines"`: mouse wheel notches. */
634 deltaMode: "points" | "lines";
635 modifiers: Modifiers;
636}
637
638/** A touchpad pinch over a view: the payload of `onPinch` (GPUI's `PinchEvent`). */
639export interface PinchEvent {
640 /** Position in the view (its transforms undone). */
641 position: Point;
642 /** Position in the root view the view is in (the surface or its modal), as touches' `pageX` / `pageY`. */
643 pagePosition: Point;
644 /** How much the scale changed since the last event, as a fraction: 0.1 is 10 % bigger, negative smaller. */
645 delta: number;
646 /** Where it is in the gesture, as a touch's phase. */
647 phase: "start" | "move" | "end";
648 modifiers: Modifiers;
649}
650
651/** A mouse button (GPUI's `MouseButton`). */
652export type MouseButton = "left" | "right" | "middle" | "back" | "forward";
653
654/** The kind of pointer behind an event (the DOM's `pointerType`). */
655export type PointerType = "mouse" | "pen" | "touch";
656
657/** Where a context menu was asked for: the payload of `onContextMenu`. */
658export interface ContextMenuEvent {
659 /** Position in the view (its transforms undone): the pointer's, or the view's bottom-start corner when no pointer asked. */
660 position: Point;
661 /** Position in the root view the view is in: where `Menu.popup` opens a menu (`Menu.popup(items, e.pagePosition)`). */
662 pagePosition: Point;
663 modifiers: Modifiers;
664 /** The pointer that asked for the menu, or `null` when the keyboard (Shift+F10, the Menu key) or an assistive technology's "show menu" action did: a menu opened then puts the keyboard focus on its first item. */
665 pointerType: PointerType | null;
666}
667
668/** Where a scroll view is: the payload of `onScroll`. */
669export interface ScrollEvent {
670 /** The content offset. */
671 offset: Point;
672 /** The content's size (zoomed). */
673 contentSize: Size;
674 /** The scroll view's size. */
675 size: Size;
676 /** The zoom scale (1 unless the scroll view zooms). */
677 zoomScale: number;
678}
679
680/** Where an input's caret is: the payload of `onCaretMove`. */
681export interface CaretEvent {
682 /** The caret in the input (its border box), the input's own scrolling applied: as wide as the platform draws it, as tall as its line. Empty until the input is laid out. */
683 bounds: Bounds;
684 /** The caret in the root view the input is in (the surface or its dialog), as of the event: an `Overlay`'s `anchor`. */
685 pageBounds: Bounds;
686}
687
688/** 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. */
689export interface PasteEvent {
690 /** The plain text, `""` when there was none. */
691 text: string;
692 /** 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. */
693 html: string;
694 /** Files with their bytes: images (a screenshot, an image copied from a page or an app), as `File`s an app can upload. */
695 files: File[];
696 /** Files larger than the input's `pasteMaxSize`, whose bytes were not read: their names, types and sizes, so the app can tell the user. */
697 tooLarge: UnreadFile[];
698 /** `file:` URLs of local files copied in a file manager (as `onFileDrop`'s). */
699 uris: string[];
700}
701
702/** A pasted file whose bytes were not read (`PasteEvent.tooLarge`). */
703export interface UnreadFile {
704 /** Its name. */
705 name: string;
706 /** Its media type (`application/pdf`; `application/octet-stream` when unknown). */
707 type: string;
708 /** Its size in bytes. */
709 size: number;
710}
711
712/** A line of a laid-out text (in the text's content box). */
713export interface TextLayoutLine {
714 text: string;
715 bounds: Bounds;
716 ascender: number;
717 descender: number;
718 capHeight: number;
719 xHeight: number;
720}
721
722/** Where a web view is: the payload of its navigation events. */
723export interface WebViewNavigation {
724 url: string;
725 title: string;
726 loading: boolean;
727 canGoBack: boolean;
728 canGoForward: boolean;
729}
730
731/** A web view's download (`onDownload`): where it is saved, in the app's data directory's `downloads`. */
732export interface WebViewDownload {
733 state: "started" | "finished" | "failed" | "cancelled";
734 id: string;
735 url: string;
736 filename: string;
737 path: string;
738 /** Who owns the bytes: the engine's transfer, a request NSH made, a page, or none (the response is gone). */
739 source: "transfer" | "request" | "page" | "none";
740 /** Once finished: the file's size in bytes. */
741 bytes?: number;
742 /** When it failed: why. */
743 message?: string;
744 /** A stable code on failure or cancellation. */
745 code?: string;
746 /** Why it was cancelled. */
747 reason?: "app" | "timeout" | "teardown" | "noListener";
748}
749"#;
750
751pub const EVENTS: &[(EventKind, u32, &str, &str)] = &[
756 (
757 EventKind::Press,
758 on::ALL,
759 "(e: PressEvent) => void",
760 "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).",
761 ),
762 (
763 EventKind::LongPress,
764 on::ALL,
765 "(e: PressEvent) => void",
766 "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).",
767 ),
768 (
769 EventKind::PressDown,
770 on::ALL,
771 "(e: PressEvent) => void",
772 "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).",
773 ),
774 (
775 EventKind::PressUp,
776 on::ALL,
777 "(e: PressEvent) => void",
778 "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).",
779 ),
780 (
781 EventKind::MouseEnter,
782 on::ALL,
783 "(e: MouseEvent) => void",
784 "The mouse came over the view or a view inside it (never on touches; the DOM's `mouseenter`).",
785 ),
786 (
787 EventKind::MouseLeave,
788 on::ALL,
789 "(e: MouseEvent) => void",
790 "The mouse left the view and the views inside it, or the window, from where `e` says (the DOM's `mouseleave`).",
791 ),
792 (
793 EventKind::MouseMove,
794 on::ALL,
795 "(e: MouseEvent) => void",
796 "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.",
797 ),
798 (
799 EventKind::Wheel,
800 on::ALL,
801 "(e: WheelEvent) => void",
802 "A mouse wheel or touchpad scrolled over the view (or a view inside it); desktops and the web. The nearest listener hears it. A listener nearer than any scroll view under the pointer takes the wheel: nothing scrolls or zooms natively (a canvas zooms on `e.modifiers.control` and pans otherwise); a scroll view listening, or a view around one, only observes it.",
803 ),
804 (
805 EventKind::Pinch,
806 on::ALL,
807 "(e: PinchEvent) => void",
808 "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.",
809 ),
810 (
811 EventKind::MouseUp,
812 on::ALL,
813 "(e: MouseEvent) => void",
814 "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.",
815 ),
816 (
817 EventKind::ContextMenu,
818 on::ALL,
819 "(e: ContextMenuEvent) => void",
820 "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.",
821 ),
822 (
823 EventKind::FileDragEnter,
824 on::ALL,
825 "(e: { uris: string[]; mimeTypes: string[] }) => void",
826 "A local file drag entered this destination (desktops, iOS and Android) with its offered file URLs and each one's MIME type by its name (`\"\"` when the name says none); no file is read. GTK waits for its file-list preload; iOS and Android read files only on drop, so they offer no URLs; the Web offers no URLs, only the types the browser shows.",
827 ),
828 (
829 EventKind::FileDragLeave,
830 on::ALL,
831 "() => void",
832 "A local file drag left this destination (desktops, iOS, Android and the Web).",
833 ),
834 (
835 EventKind::FileDrop,
836 on::ALL,
837 "(e: { uris: string[]; mimeTypes: string[]; pagePosition?: { x: number; y: number }; files: { file: File | null; name: string; type: string; size: number; status: \"read\" | \"tooLarge\" }[] }) => void",
838 "Local file URLs dropped on this destination (desktops, iOS, Android and the Web), with each one's MIME type by its name (`\"\"` when the name says none); `pagePosition`: where, in the window's coordinates, on backends that know it (Linux, iOS, Android, Web). On the Web `uris` is empty and `files` holds the dropped regular files with their contents (`status` `\"tooLarge\"` past 512 MiB a drop; at most 100); elsewhere `files` is empty.",
839 ),
840 (
841 EventKind::Layout,
842 on::ALL,
843 "(e: { bounds: Bounds }) => void",
844 "The frame changed: its bounds in the parent.",
845 ),
846 (EventKind::PanStart, on::ALL, "(e: PanEvent) => void", ""),
847 (
848 EventKind::PanEnd,
849 on::ALL,
850 "(e: PanEvent) => void",
851 "With the release velocity, e.g. to start a `decay`.",
852 ),
853 (
854 EventKind::PinchStart,
855 on::ALL,
856 "(e: { scale: number; velocity: number }) => void",
857 "",
858 ),
859 (
860 EventKind::PinchEnd,
861 on::ALL,
862 "(e: { scale: number; velocity: number }) => void",
863 "",
864 ),
865 (
866 EventKind::RotationStart,
867 on::ALL,
868 "(e: { rotation: number; velocity: number }) => void",
869 "",
870 ),
871 (
872 EventKind::RotationEnd,
873 on::ALL,
874 "(e: { rotation: number; velocity: number }) => void",
875 "",
876 ),
877 (
878 EventKind::AccessibilityAction,
879 on::ALL,
880 "(e: { actionName: string }) => void",
881 "",
882 ),
883 (
884 EventKind::TextLayout,
885 on::TEXT,
886 "(e: { lines: TextLayoutLine[] }) => void",
887 "The laid-out lines (in the text's content box), after each layout.",
888 ),
889 (
890 EventKind::LoadStart,
891 on::IMAGE | on::VIDEO,
892 "() => void",
893 "",
894 ),
895 (
896 EventKind::LoadStart,
897 on::WEBVIEW,
898 "(e: WebViewNavigation) => void",
899 "",
900 ),
901 (
902 EventKind::Progress,
903 on::IMAGE,
904 "(e: { loaded: number; total: number }) => void",
905 "Download progress in bytes (`total` 0 when unknown); at most every 100 ms.",
906 ),
907 (
908 EventKind::Progress,
909 on::VIDEO,
910 "(e: { currentTime: number; duration: number }) => void",
911 "",
912 ),
913 (
914 EventKind::Load,
915 on::IMAGE,
916 "(e: { size: PixelSize }) => void",
917 "The source image's size in pixels (not the decoded, downsampled one).",
918 ),
919 (
920 EventKind::Load,
921 on::WEBVIEW,
922 "(e: WebViewNavigation) => void",
923 "",
924 ),
925 (
926 EventKind::Load,
927 on::VIDEO,
928 "(e: { duration: number; size: PixelSize }) => void",
929 "",
930 ),
931 (
932 EventKind::Error,
933 on::IMAGE | on::WEBVIEW | on::VIDEO,
934 "(e: { message: string; code?: string }) => void",
935 "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).",
936 ),
937 (
938 EventKind::LoadEnd,
939 on::IMAGE,
940 "() => void",
941 "After `onLoad` or `onError`.",
942 ),
943 (
944 EventKind::Scroll,
945 on::SCROLLING,
946 "(e: ScrollEvent) => void",
947 "",
948 ),
949 (
950 EventKind::ScrollDragStart,
951 on::SCROLLING,
952 "(e: { offset: Point }) => void",
953 "",
954 ),
955 (
956 EventKind::ScrollDragEnd,
957 on::SCROLLING,
958 "(e: { offset: Point }) => void",
959 "",
960 ),
961 (
962 EventKind::MomentumStart,
963 on::SCROLLING,
964 "(e: { offset: Point }) => void",
965 "",
966 ),
967 (
968 EventKind::MomentumEnd,
969 on::SCROLLING,
970 "(e: { offset: Point }) => void",
971 "",
972 ),
973 (
974 EventKind::ScrollEnd,
975 on::SCROLL | on::LIST,
976 "(e: { offset: Point }) => void",
977 "",
978 ),
979 (EventKind::Refresh, on::SCROLL | on::LIST, "() => void", ""),
980 (EventKind::LoadMore, on::LIST, "() => void", ""),
981 (
982 EventKind::LoadMoreAtStart,
983 on::LIST,
984 "() => void",
985 "Within `loadMoreAtStartThreshold` viewports of the start, once the user or a scroll command moved the list: load what comes before the first item.",
986 ),
987 (
988 EventKind::ChangeText,
989 on::INPUT,
990 "(e: { value: string }) => void",
991 "The user edited the text: `value` is the text now.",
992 ),
993 (
994 EventKind::SubmitEditing,
995 on::INPUT,
996 "(e: { text: string }) => void",
997 "",
998 ),
999 (
1000 EventKind::Focus,
1001 on::ALL,
1002 "() => void",
1003 "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).",
1004 ),
1005 (
1006 EventKind::Blur,
1007 on::ALL,
1008 "() => void",
1009 "It lost the keyboard focus.",
1010 ),
1011 (
1012 EventKind::FocusIn,
1013 on::ALL,
1014 "() => void",
1015 "The keyboard focus came into it: onto it or a view inside it, from outside (it entered `focus-within`). Moving between the views inside it is no new coming in; the content of an overlay is inside the view the overlay is in. A panel notes where its focus is with it, to put it back later with `ref.focus()`.",
1016 ),
1017 (
1018 EventKind::FocusOut,
1019 on::ALL,
1020 "() => void",
1021 "The keyboard focus left it: from it or a view inside it to one outside, or to none (it left `focus-within`). A view removed with the focus inside it hears nothing.",
1022 ),
1023 (
1024 EventKind::SelectionChange,
1025 on::INPUT,
1026 "(e: { start: number; end: number }) => void",
1027 "",
1028 ),
1029 (
1030 EventKind::SelectionChange,
1031 on::VIEW,
1032 "(e: { text: string; start?: number; bounds?: Bounds; pageBounds?: Bounds }) => void",
1033 "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.",
1034 ),
1035 (
1036 EventKind::Paste,
1037 on::INPUT,
1038 "(e: PasteEvent) => void",
1039 "The user pasted (the keyboard's shortcut, a menu's Paste, a keyboard's image): the text, images as `File`s (files larger than `pasteMaxSize` in `tooLarge`, unread), local files' `file:` URLs. It comes before the `onChange` of the text it inserts; `pasteBehavior` decides whether the input inserts the text (images and files never are).",
1040 ),
1041 (
1042 EventKind::CaretMove,
1043 on::INPUT,
1044 "(e: CaretEvent) => void",
1045 "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.",
1046 ),
1047 (
1048 EventKind::KeyPress,
1049 on::INPUT,
1050 "(e: { key: string }) => void",
1051 "Before the text changes: `key` is the typed text, `Backspace` or `Enter`.",
1052 ),
1053 (
1054 EventKind::KeyDown,
1055 on::ALL,
1056 "(e: KeyEvent) => void",
1057 "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.",
1058 ),
1059 (
1060 EventKind::KeyUp,
1061 on::ALL,
1062 "(e: KeyEvent) => void",
1063 "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.",
1064 ),
1065 (
1066 EventKind::CompositionChange,
1067 on::INPUT,
1068 "(e: { composing: boolean; text: string }) => void",
1069 "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.",
1070 ),
1071 (
1072 EventKind::ContentSizeChange,
1073 on::INPUT,
1074 "(e: { size: Size }) => void",
1075 "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.",
1076 ),
1077 (
1078 EventKind::Message,
1079 on::WEBVIEW,
1080 "(e: { data: string }) => void",
1081 "The page called `window.nsh.postMessage(data)`.",
1082 ),
1083 (
1084 EventKind::NavigationStateChange,
1085 on::WEBVIEW,
1086 "(e: WebViewNavigation) => void",
1087 "",
1088 ),
1089 (
1090 EventKind::Download,
1091 on::WEBVIEW,
1092 "(e: WebViewDownload) => void",
1093 "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.",
1094 ),
1095 (EventKind::End, on::VIDEO, "() => void", ""),
1096 (
1097 EventKind::Buffer,
1098 on::VIDEO,
1099 "(e: { isBuffering: boolean }) => void",
1100 "",
1101 ),
1102 (
1103 EventKind::PressOutside,
1104 on::OVERLAY,
1105 "(e: { pagePosition: Point }) => void",
1106 "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.",
1107 ),
1108 (
1109 EventKind::Cancel,
1110 on::OVERLAY,
1111 "() => void",
1112 "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.",
1113 ),
1114 (
1115 EventKind::DetentChange,
1116 on::MODAL,
1117 "(e: { detent: SheetDetent }) => void",
1118 "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.",
1119 ),
1120 (
1121 EventKind::Position,
1122 on::OVERLAY,
1123 "(e: OverlayPosition) => void",
1124 "The core placed the overlay (again: the anchor moved, the overlay changed size, it went to the other side).",
1125 ),
1126];
1127
1128pub const INTERNAL_EVENTS: &[EventKind] = &[
1133 EventKind::Touch,
1134 EventKind::Insets,
1135 EventKind::NativeEvent,
1136 EventKind::Dialog,
1137 EventKind::BackPress,
1138 EventKind::BackProgress,
1139 EventKind::ImageInfo,
1140 EventKind::WebEvaluation,
1141 EventKind::WebViewReply,
1142 EventKind::DownloadPending,
1143 EventKind::DownloadOffer,
1144 EventKind::DownloadProgress,
1145 EventKind::DownloadEnd,
1146 EventKind::Clipboard,
1147 EventKind::Host,
1148 EventKind::Pick,
1149 EventKind::OpenUrl,
1150 EventKind::OpenAppSettings,
1151 EventKind::ClipboardWrite,
1152 EventKind::ScreenColor,
1153 EventKind::Share,
1154 EventKind::AuthSession,
1155 EventKind::CanvasImage,
1156 EventKind::FileRequest,
1157 EventKind::Notification,
1158 EventKind::UrlScheme,
1159 EventKind::SecondInstance,
1160 EventKind::Audio,
1161 EventKind::Window,
1162 EventKind::EditAction,
1163 EventKind::KeyCommand,
1164 EventKind::Menu,
1165 EventKind::ViewableItemsChange,
1166 EventKind::TextDrop,
1168 EventKind::BackRequest,
1172 EventKind::Dismiss,
1173 EventKind::RequestClose,
1174 EventKind::Show,
1175];
1176
1177const GROUPS: &[(u32, &str, &str)] = &[
1180 (on::ALL, "", "every element"),
1181 (on::VIEW, "View", "`<View>`"),
1182 (on::TEXT, "Text", "`<Text>`"),
1183 (on::IMAGE, "Image", "`<Image>`"),
1184 (
1185 on::SCROLLING,
1186 "Scrolling",
1187 "scroll views and lists (how they scroll)",
1188 ),
1189 (on::SCROLL, "Scroll", "`<Scroll>`"),
1190 (on::LIST, "List", "lists"),
1191 (on::INPUT, "Input", "`<Input>`"),
1192 (on::SCREEN, "NavPage", "the pages of a `NavStack`"),
1193 (on::MODAL, "Dialog", "dialogs"),
1194 (on::WEBVIEW, "WebView", "web views"),
1195 (on::VIDEO, "Video", "videos"),
1196 (on::SHADER, "Shader", "shaders"),
1197 (on::EFFECT, "ShaderEffect", "shader effects"),
1198 (on::TRANSITION, "ShaderTransition", "shader transitions"),
1199 (on::INPUT_ACCESSORY, "InputAccessory", "input accessories"),
1200 (on::OVERLAY, "Overlay", "`<Overlay>`"),
1201];
1202
1203pub fn declarations() -> String {
1209 use std::fmt::Write as _;
1210 let mut types = TsTypes::default();
1211 let mut specs = Vec::new();
1212 <crate::Prop as HostProps>::specs(&mut types, &mut specs);
1213 <crate::RevealOptions as HostValue>::ts_type(&mut types);
1214 let mut out = String::from(EVENT_TYPES);
1215 for declaration in types.declarations() {
1216 let _ = write!(out, "\n{declaration}\n");
1217 }
1218 for (bit, group, what) in GROUPS {
1219 for (platform, prefix, inside) in [
1220 (Platform::All, "", ""),
1221 (Platform::Ios, "IOS", " inside `ios={{…}}`"),
1222 (Platform::Android, "Android", " inside `android={{…}}`"),
1223 (Platform::Macos, "MacOS", " inside `macos={{…}}`"),
1224 (Platform::Windows, "Windows", " inside `windows={{…}}`"),
1225 (Platform::Desktop, "Desktop", " inside `desktop={{…}}`"),
1226 (Platform::Web, "Web", " inside `web={{…}}`"),
1227 ] {
1228 let props: Vec<&HostPropSpec> = specs
1229 .iter()
1230 .filter(|s| s.on & bit != 0 && s.platform == platform)
1231 .collect();
1232 let events: Vec<_> = EVENTS
1234 .iter()
1235 .filter(|e| e.1 & bit != 0 && platform == Platform::All)
1236 .collect();
1237 if props.is_empty() && events.is_empty() {
1238 continue;
1239 }
1240 let _ = write!(
1241 out,
1242 "\n/** The props of {what}{inside}. */\nexport interface {prefix}{group}HostProps {{\n"
1243 );
1244 for p in props {
1245 if !p.doc.is_empty() {
1246 let _ = writeln!(out, " /** {} */", p.doc);
1247 }
1248 let _ = writeln!(out, " {}?: {};", p.name, p.ts);
1249 }
1250 for (kind, _, handler, doc) in events {
1251 if !doc.is_empty() {
1252 let _ = writeln!(out, " /** {doc} */");
1253 }
1254 let _ = writeln!(out, " {}?: {handler};", kind.handler_name());
1255 }
1256 out.push_str("}\n");
1257 }
1258 }
1259 out
1260}