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 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
238pub mod on {
240 pub const ALL: u32 = 1;
242 pub const TEXT: u32 = 1 << 1;
244 pub const IMAGE: u32 = 1 << 2;
246 pub const SCROLLING: u32 = 1 << 3;
248 pub const SCROLL: u32 = 1 << 4;
250 pub const LIST: u32 = 1 << 5;
252 pub const INPUT: u32 = 1 << 6;
254 pub const SCREEN: u32 = 1 << 7;
256 pub const MODAL: u32 = 1 << 8;
258 pub const WEBVIEW: u32 = 1 << 9;
260 pub const VIDEO: u32 = 1 << 10;
262 pub const INPUT_ACCESSORY: u32 = 1 << 11;
264 pub const OVERLAY: u32 = 1 << 12;
266 pub const VIEW: u32 = 1 << 13;
268 pub const SHADER: u32 = 1 << 14;
270 pub const EFFECT: u32 = 1 << 15;
272 pub const TRANSITION: u32 = 1 << 16;
274 pub const INTERNAL: u32 = 1 << 31;
276}
277
278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
281pub enum Platform {
282 All,
284 Ios,
286 Android,
288 Macos,
290 Desktop,
292 Web,
294}
295
296#[derive(Debug, Clone)]
298pub struct HostPropSpec {
299 pub name: &'static str,
301 pub ts: String,
303 pub doc: &'static str,
305 pub on: u32,
307 pub platform: Platform,
309}
310
311pub trait HostProps: Sized {
313 fn decode<I: HostInput>(name: &str, input: &I, cx: &mut HostCx) -> Option<Option<Self>>;
316 fn reset(&self) -> Option<Self>;
319 fn same_kind(&self, other: &Self) -> bool;
321 fn specs(types: &mut TsTypes, out: &mut Vec<HostPropSpec>);
323}
324
325pub trait Clamped {
327 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
377impl 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 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 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 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 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 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
443impl<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
454impl<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
471impl 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
488pub 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
493const 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
720pub 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
1085pub 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 EventKind::BackRequest,
1125 EventKind::Dismiss,
1126 EventKind::RequestClose,
1127 EventKind::Show,
1128];
1129
1130const 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
1156pub 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 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}