1use std::sync::Arc;
10
11pub use nsh_macros::HostProps;
12
13use crate::{EdgeInsets, EventKind, geometry::Points, style::Color, ui::TsTypes};
14
15pub trait HostInput: Sized {
17 fn is_nullish(&self) -> bool;
19 fn is_object(&self) -> bool;
21 fn as_bool(&self) -> Option<bool>;
23 fn as_number(&self) -> Option<f64>;
25 fn as_string(&self) -> Option<String>;
27 fn field(&self, key: &str) -> Option<Self>;
29 fn items(&self) -> Vec<Self> {
31 match self.as_list() {
32 Some(list) => (0..list.len()).filter_map(|i| list.item(i)).collect(),
33 None => Vec::new(),
34 }
35 }
36 fn as_list(&self) -> Option<Self::List>;
38 type List: HostList<Item = Self>;
40 fn entries(&self) -> Vec<(String, Self)>;
42 fn truthy(&self) -> bool;
44 fn node(&self) -> Option<crate::NodeId> {
46 None
47 }
48 fn animated_node(&self) -> Option<crate::animation::NodeId> {
50 self.field("__av")
51 .and_then(|v| v.as_number())
52 .map(|n| n as crate::animation::NodeId)
53 }
54}
55
56pub trait HostList {
58 type Item;
60 fn len(&self) -> usize;
62 fn is_empty(&self) -> bool {
64 self.len() == 0
65 }
66 fn item(&self, index: usize) -> Option<Self::Item>;
68}
69
70#[derive(Debug, Default)]
73pub struct HostCx {
74 pub warnings: Vec<String>,
76 pub element: u32,
80}
81
82impl HostCx {
83 pub fn for_element(tag: crate::Tag) -> Self {
85 Self {
86 element: element_bits(tag),
87 ..Self::default()
88 }
89 }
90
91 pub fn warn(&mut self, message: impl Into<String>) {
93 self.warnings.push(message.into());
94 }
95
96 pub fn on_element(&self, on: u32) -> bool {
99 self.element == 0 || self.element & on != 0
100 }
101}
102
103pub fn element_bits(tag: crate::Tag) -> u32 {
105 use crate::Tag;
106 on::ALL
107 | match tag {
108 Tag::Text => on::TEXT,
109 Tag::Image => on::IMAGE,
110 Tag::Scroll => on::SCROLLING | on::SCROLL,
111 Tag::List => on::SCROLLING | on::LIST,
112 Tag::Input => on::INPUT,
113 Tag::Screen => on::SCREEN,
114 Tag::Modal => on::MODAL,
115 Tag::WebView => on::WEBVIEW,
116 Tag::Video => on::VIDEO,
117 Tag::InputAccessory => on::INPUT_ACCESSORY,
118 Tag::View
119 | Tag::Cell
120 | Tag::Stack
121 | Tag::HeaderItem
122 | Tag::Canvas
123 | Tag::Native
124 | Tag::Overlay => 0,
125 }
126}
127
128pub trait HostValue: Sized {
132 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self>;
134 fn ts_type(types: &mut TsTypes) -> String;
136}
137
138pub mod on {
140 pub const ALL: u32 = 1;
142 pub const TEXT: u32 = 1 << 1;
144 pub const IMAGE: u32 = 1 << 2;
146 pub const SCROLLING: u32 = 1 << 3;
148 pub const SCROLL: u32 = 1 << 4;
150 pub const LIST: u32 = 1 << 5;
152 pub const INPUT: u32 = 1 << 6;
154 pub const SCREEN: u32 = 1 << 7;
156 pub const MODAL: u32 = 1 << 8;
158 pub const WEBVIEW: u32 = 1 << 9;
160 pub const VIDEO: u32 = 1 << 10;
162 pub const INPUT_ACCESSORY: u32 = 1 << 11;
164 pub const OVERLAY: u32 = 1 << 12;
166 pub const INTERNAL: u32 = 1 << 31;
168}
169
170#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub enum Platform {
174 All,
176 Ios,
178 Android,
180 Desktop,
182 Web,
184}
185
186#[derive(Debug, Clone)]
188pub struct HostPropSpec {
189 pub name: &'static str,
191 pub ts: String,
193 pub doc: &'static str,
195 pub on: u32,
197 pub platform: Platform,
199}
200
201pub trait HostProps: Sized {
203 fn decode<I: HostInput>(name: &str, input: &I, cx: &mut HostCx) -> Option<Option<Self>>;
206 fn reset(&self) -> Option<Self>;
209 fn same_kind(&self, other: &Self) -> bool;
211 fn specs(types: &mut TsTypes, out: &mut Vec<HostPropSpec>);
213}
214
215pub trait Clamped {
217 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self;
219}
220
221impl Clamped for f32 {
222 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
223 let v = min.map_or(self, |m| self.max(m as f32));
224 max.map_or(v, |m| v.min(m as f32))
225 }
226}
227
228impl Clamped for Points {
229 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
230 Points(self.0.clamped(min, max))
231 }
232}
233
234impl Clamped for u32 {
235 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
236 let v = min.map_or(self, |m| self.max(m as u32));
237 max.map_or(v, |m| v.min(m as u32))
238 }
239}
240
241impl<T: Clamped> Clamped for Option<T> {
242 fn clamped(self, min: Option<f64>, max: Option<f64>) -> Self {
243 self.map(|v| v.clamped(min, max))
244 }
245}
246
247impl HostValue for bool {
248 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
249 input.as_bool()
250 }
251
252 fn ts_type(_: &mut TsTypes) -> String {
253 "boolean".into()
254 }
255}
256
257impl HostValue for f32 {
258 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
259 input.as_number().map(|n| n as f32)
260 }
261
262 fn ts_type(_: &mut TsTypes) -> String {
263 "number".into()
264 }
265}
266
267impl HostValue for Points {
269 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
270 f32::decode(input, cx).map(Points)
271 }
272
273 fn ts_type(_: &mut TsTypes) -> String {
274 "number".into()
275 }
276}
277
278impl HostValue for u32 {
279 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
281 input.as_number().map(|n| n.max(0.0) as u32)
282 }
283
284 fn ts_type(_: &mut TsTypes) -> String {
285 "number".into()
286 }
287}
288
289impl HostValue for String {
290 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
292 input.as_string()
293 }
294
295 fn ts_type(_: &mut TsTypes) -> String {
296 "string".into()
297 }
298}
299
300impl HostValue for Arc<str> {
301 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
303 input.as_string().filter(|s| !s.is_empty()).map(Into::into)
304 }
305
306 fn ts_type(_: &mut TsTypes) -> String {
307 "string".into()
308 }
309}
310
311impl HostValue for Box<str> {
312 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
314 input.as_string().filter(|s| !s.is_empty()).map(Into::into)
315 }
316
317 fn ts_type(_: &mut TsTypes) -> String {
318 "string".into()
319 }
320}
321
322impl HostValue for Color {
323 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
325 input.as_string().and_then(|s| Color::parse(&s))
326 }
327
328 fn ts_type(_: &mut TsTypes) -> String {
329 "ColorValue".into()
330 }
331}
332
333impl<T: HostValue> HostValue for Option<T> {
335 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
336 Some(T::decode(input, cx))
337 }
338
339 fn ts_type(types: &mut TsTypes) -> String {
340 T::ts_type(types)
341 }
342}
343
344impl<T: HostValue> HostValue for Vec<T> {
346 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
347 Some(
348 input
349 .items()
350 .iter()
351 .filter_map(|i| T::decode(i, cx))
352 .collect(),
353 )
354 }
355
356 fn ts_type(types: &mut TsTypes) -> String {
357 format!("{}[]", T::ts_type(types))
358 }
359}
360
361impl HostValue for EdgeInsets {
363 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
364 let side = |key| Points(input.field(key).and_then(|v| v.as_number()).unwrap_or(0.0) as f32);
365 Some(EdgeInsets {
366 top: side("top"),
367 right: side("right"),
368 bottom: side("bottom"),
369 left: side("left"),
370 })
371 }
372
373 fn ts_type(_: &mut TsTypes) -> String {
374 "Partial<Edges>".into()
375 }
376}
377
378pub fn field<T: HostValue, I: HostInput>(input: &I, key: &str, cx: &mut HostCx) -> Option<T> {
380 input.field(key).and_then(|v| T::decode(&v, cx))
381}
382
383const EVENT_TYPES: &str = r#"/** A position, in points (`nsh_core::geometry::Point`). */
387export interface Point {
388 x: number;
389 y: number;
390}
391
392/** An extent, in points (`nsh_core::geometry::Size`). */
393export interface Size {
394 width: number;
395 height: number;
396}
397
398/** A position and an extent, in points (`nsh_core::geometry::Bounds`). */
399export interface Bounds {
400 /** The top left corner. */
401 origin: Point;
402 size: Size;
403}
404
405/** A length on each side, in points (`nsh_core::geometry::Edges`): insets, a safe area. */
406export interface Edges {
407 top: number;
408 right: number;
409 bottom: number;
410 left: number;
411}
412
413/** The modifier keys held (GPUI's `Modifiers`). */
414export interface Modifiers {
415 control: boolean;
416 /** Option on Apple platforms, Alt elsewhere. */
417 alt: boolean;
418 shift: boolean;
419 /** Command on Apple platforms, the Windows / Super key elsewhere. */
420 platform: boolean;
421}
422
423/** Where the core placed an overlay: the payload of `onPosition`. */
424export interface OverlayPosition {
425 /** The side of the anchor it went on: the one asked for, or the other one when only that one has room. */
426 placement: "top" | "bottom" | "left" | "right";
427 /** Its frame in the root view (the surface, or the dialog it is in). */
428 bounds: Bounds;
429 /** The room on that side, inside the safe area less `margin`: what a menu may grow to. */
430 available: Size;
431}
432
433/** A drag: translation since the start and velocity (points / second). */
434export interface PanEvent {
435 translationX: number;
436 translationY: number;
437 velocityX: number;
438 velocityY: number;
439 /** The `pan.x` value now (with one). */
440 valueX?: number;
441 /** The `pan.y` value now (with one). */
442 valueY?: number;
443}
444
445/** Where the mouse is over a hovered view: the payload of `onHoverMove` (GPUI's `MouseMoveEvent`). */
446export interface HoverEvent {
447 /** Position in the view (its transforms undone). */
448 position: Point;
449 /** Position in the root view the view is in (the surface or its modal), as touches' `pageX` / `pageY`. */
450 pagePosition: Point;
451 modifiers: Modifiers;
452}
453
454/** Where a context menu was asked for: the payload of `onContextMenu`. */
455export interface ContextMenuEvent {
456 /** Position in the view (its transforms undone). */
457 position: Point;
458 /** Position in the root view the view is in: where `Menu.popup` opens a menu (`Menu.popup(items, e.pagePosition)`). */
459 pagePosition: Point;
460 modifiers: Modifiers;
461}
462
463/** Where a scroll view is: the payload of `onScroll`. */
464export interface ScrollEvent {
465 /** The content offset. */
466 offset: Point;
467 /** The content's size (zoomed). */
468 contentSize: Size;
469 /** The scroll view's size. */
470 size: Size;
471 /** The zoom scale (1 unless the scroll view zooms). */
472 zoomScale: number;
473}
474
475/** A line of a laid-out text (in the text's content box). */
476export interface TextLayoutLine {
477 text: string;
478 bounds: Bounds;
479 ascender: number;
480 descender: number;
481 capHeight: number;
482 xHeight: number;
483}
484
485/** Where a web view is: the payload of its navigation events. */
486export interface WebViewNavigation {
487 url: string;
488 title: string;
489 loading: boolean;
490 canGoBack: boolean;
491 canGoForward: boolean;
492}
493"#;
494
495pub const EVENTS: &[(EventKind, u32, &str, &str)] = &[
500 (EventKind::Press, on::ALL, "() => void", ""),
501 (EventKind::LongPress, on::ALL, "() => void", ""),
502 (EventKind::PressDown, on::ALL, "() => void", ""),
503 (EventKind::PressUp, on::ALL, "() => void", ""),
504 (
505 EventKind::HoverIn,
506 on::ALL,
507 "() => void",
508 "The mouse came over the view or a view inside it (never on touches).",
509 ),
510 (
511 EventKind::HoverOut,
512 on::ALL,
513 "() => void",
514 "The mouse left the view and the views inside it, or the window.",
515 ),
516 (
517 EventKind::HoverMove,
518 on::ALL,
519 "(e: HoverEvent) => void",
520 "The mouse moved over the view (or a view inside it) with no button down, at most once per frame.",
521 ),
522 (
523 EventKind::ContextMenu,
524 on::ALL,
525 "(e: ContextMenuEvent) => void",
526 "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.",
527 ),
528 (
529 EventKind::MouseMove,
530 on::ALL,
531 "(e: Point) => void",
532 "The mouse moved inside the view, including with a button down (desktops and web); `x`/`y` are local coordinates in points, delivered at most once per frame.",
533 ),
534 (
535 EventKind::FileDragEnter,
536 on::ALL,
537 "() => void",
538 "A local file drag entered this desktop destination.",
539 ),
540 (
541 EventKind::FileDragLeave,
542 on::ALL,
543 "() => void",
544 "A local file drag left this desktop destination.",
545 ),
546 (
547 EventKind::FileDrop,
548 on::ALL,
549 "(e: { uris: string[] }) => void",
550 "Local file URLs dropped on this desktop destination.",
551 ),
552 (
553 EventKind::Layout,
554 on::ALL,
555 "(bounds: Bounds) => void",
556 "The frame changed: its bounds in the parent.",
557 ),
558 (EventKind::PanStart, on::ALL, "(e: PanEvent) => void", ""),
559 (
560 EventKind::PanEnd,
561 on::ALL,
562 "(e: PanEvent) => void",
563 "With the release velocity, e.g. to start a `decay`.",
564 ),
565 (
566 EventKind::PinchStart,
567 on::ALL,
568 "(e: { scale: number; velocity: number }) => void",
569 "",
570 ),
571 (
572 EventKind::PinchEnd,
573 on::ALL,
574 "(e: { scale: number; velocity: number }) => void",
575 "",
576 ),
577 (
578 EventKind::RotationStart,
579 on::ALL,
580 "(e: { rotation: number; velocity: number }) => void",
581 "",
582 ),
583 (
584 EventKind::RotationEnd,
585 on::ALL,
586 "(e: { rotation: number; velocity: number }) => void",
587 "",
588 ),
589 (
590 EventKind::AccessibilityAction,
591 on::ALL,
592 "(e: { actionName: string }) => void",
593 "",
594 ),
595 (
596 EventKind::TextLayout,
597 on::TEXT,
598 "(e: { lines: TextLayoutLine[] }) => void",
599 "The laid-out lines (in the text's content box), after each layout.",
600 ),
601 (
602 EventKind::LoadStart,
603 on::IMAGE | on::VIDEO,
604 "() => void",
605 "",
606 ),
607 (
608 EventKind::LoadStart,
609 on::WEBVIEW,
610 "(e: WebViewNavigation) => void",
611 "",
612 ),
613 (
614 EventKind::Progress,
615 on::IMAGE,
616 "(e: { loaded: number; total: number }) => void",
617 "Download progress in bytes (`total` 0 when unknown); at most every 100 ms.",
618 ),
619 (
620 EventKind::Progress,
621 on::VIDEO,
622 "(e: { currentTime: number; duration: number }) => void",
623 "",
624 ),
625 (
626 EventKind::Load,
627 on::IMAGE,
628 "(e: Size) => void",
629 "The source image's size in pixels (not the decoded, downsampled one).",
630 ),
631 (
632 EventKind::Load,
633 on::WEBVIEW,
634 "(e: WebViewNavigation) => void",
635 "",
636 ),
637 (
638 EventKind::Load,
639 on::VIDEO,
640 "(e: { duration: number; size: Size }) => void",
641 "",
642 ),
643 (
644 EventKind::Error,
645 on::IMAGE | on::WEBVIEW | on::VIDEO,
646 "(e: { message: string }) => void",
647 "",
648 ),
649 (
650 EventKind::LoadEnd,
651 on::IMAGE,
652 "() => void",
653 "After `onLoad` or `onError`.",
654 ),
655 (
656 EventKind::Scroll,
657 on::SCROLLING,
658 "(e: ScrollEvent) => void",
659 "",
660 ),
661 (
662 EventKind::ScrollDragStart,
663 on::SCROLLING,
664 "(e: Point) => void",
665 "",
666 ),
667 (
668 EventKind::ScrollDragEnd,
669 on::SCROLLING,
670 "(e: Point) => void",
671 "",
672 ),
673 (
674 EventKind::MomentumStart,
675 on::SCROLLING,
676 "(e: Point) => void",
677 "",
678 ),
679 (
680 EventKind::MomentumEnd,
681 on::SCROLLING,
682 "(e: Point) => void",
683 "",
684 ),
685 (
686 EventKind::ScrollEnd,
687 on::SCROLL | on::LIST,
688 "(e: Point) => void",
689 "",
690 ),
691 (EventKind::Refresh, on::SCROLL | on::LIST, "() => void", ""),
692 (EventKind::LoadMore, on::LIST, "() => void", ""),
693 (
694 EventKind::ChangeText,
695 on::INPUT,
696 "(text: string) => void",
697 "",
698 ),
699 (
700 EventKind::SubmitEditing,
701 on::INPUT,
702 "(e: { text: string }) => void",
703 "",
704 ),
705 (EventKind::Focus, on::INPUT, "() => void", ""),
706 (EventKind::Blur, on::INPUT, "() => void", ""),
707 (
708 EventKind::SelectionChange,
709 on::INPUT,
710 "(e: { start: number; end: number }) => void",
711 "",
712 ),
713 (
714 EventKind::KeyPress,
715 on::INPUT,
716 "(e: { key: string }) => void",
717 "Before the text changes: `key` is the typed text, `Backspace` or `Enter`.",
718 ),
719 (
720 EventKind::CompositionChange,
721 on::INPUT,
722 "(e: { composing: boolean; text: string }) => void",
723 "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.",
724 ),
725 (
726 EventKind::ContentSizeChange,
727 on::INPUT,
728 "(e: Size) => void",
729 "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.",
730 ),
731 (
732 EventKind::Message,
733 on::WEBVIEW,
734 "(e: { data: string }) => void",
735 "The page called `window.nsh.postMessage(data)`.",
736 ),
737 (
738 EventKind::NavigationStateChange,
739 on::WEBVIEW,
740 "(e: WebViewNavigation) => void",
741 "",
742 ),
743 (EventKind::End, on::VIDEO, "() => void", ""),
744 (
745 EventKind::Buffer,
746 on::VIDEO,
747 "(e: { isBuffering: boolean }) => void",
748 "",
749 ),
750 (
751 EventKind::PressOutside,
752 on::OVERLAY,
753 "(e: { pagePosition: Point }) => void",
754 "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.",
755 ),
756 (
757 EventKind::Cancel,
758 on::OVERLAY,
759 "() => void",
760 "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.",
761 ),
762 (
763 EventKind::Position,
764 on::OVERLAY,
765 "(e: OverlayPosition) => void",
766 "The core placed the overlay (again: the anchor moved, the overlay changed size, it went to the other side).",
767 ),
768];
769
770pub const INTERNAL_EVENTS: &[EventKind] = &[
775 EventKind::Touch,
776 EventKind::Insets,
777 EventKind::NativeEvent,
778 EventKind::Dialog,
779 EventKind::BackPress,
780 EventKind::ImageInfo,
781 EventKind::Clipboard,
782 EventKind::KeyCommand,
783 EventKind::Menu,
784 EventKind::ViewableItemsChange,
785 EventKind::BackRequest,
789 EventKind::Dismiss,
790 EventKind::RequestClose,
791 EventKind::Show,
792];
793
794const GROUPS: &[(u32, &str, &str)] = &[
797 (on::ALL, "", "every element"),
798 (on::TEXT, "Text", "`<Text>`"),
799 (on::IMAGE, "Image", "`<Image>`"),
800 (
801 on::SCROLLING,
802 "Scrolling",
803 "scroll views and lists (how they scroll)",
804 ),
805 (on::SCROLL, "Scroll", "`<Scroll>`"),
806 (on::LIST, "List", "lists"),
807 (on::INPUT, "Input", "`<Input>`"),
808 (on::SCREEN, "NavPage", "the pages of a `NavStack`"),
809 (on::MODAL, "Dialog", "dialogs"),
810 (on::WEBVIEW, "WebView", "web views"),
811 (on::VIDEO, "Video", "videos"),
812 (on::INPUT_ACCESSORY, "InputAccessory", "input accessories"),
813 (on::OVERLAY, "Overlay", "`<Overlay>`"),
814];
815
816pub fn declarations() -> String {
821 use std::fmt::Write as _;
822 let mut types = TsTypes::default();
823 let mut specs = Vec::new();
824 <crate::Prop as HostProps>::specs(&mut types, &mut specs);
825 let mut out = String::from(EVENT_TYPES);
826 for declaration in types.declarations() {
827 let _ = write!(out, "\n{declaration}\n");
828 }
829 for (bit, group, what) in GROUPS {
830 for (platform, prefix, inside) in [
831 (Platform::All, "", ""),
832 (Platform::Ios, "IOS", " inside `ios={{…}}`"),
833 (Platform::Android, "Android", " inside `android={{…}}`"),
834 (Platform::Desktop, "Desktop", " inside `desktop={{…}}`"),
835 (Platform::Web, "Web", " inside `web={{…}}`"),
836 ] {
837 let props: Vec<&HostPropSpec> = specs
838 .iter()
839 .filter(|s| s.on & bit != 0 && s.platform == platform)
840 .collect();
841 let events: Vec<_> = EVENTS
843 .iter()
844 .filter(|e| e.1 & bit != 0 && platform == Platform::All)
845 .collect();
846 if props.is_empty() && events.is_empty() {
847 continue;
848 }
849 let _ = write!(
850 out,
851 "\n/** The props of {what}{inside}. */\nexport interface {prefix}{group}HostProps {{\n"
852 );
853 for p in props {
854 if !p.doc.is_empty() {
855 let _ = writeln!(out, " /** {} */", p.doc);
856 }
857 let _ = writeln!(out, " {}?: {};", p.name, p.ts);
858 }
859 for (kind, _, handler, doc) in events {
860 if !doc.is_empty() {
861 let _ = writeln!(out, " /** {doc} */");
862 }
863 let _ = writeln!(out, " {}?: {handler};", kind.handler_name());
864 }
865 out.push_str("}\n");
866 }
867 }
868 out
869}