Skip to main content

nsh_core/js/
mod.rs

1//! What the JS side is decoded with and typed from, so the two cannot
2//! drift apart: the animation graph's codes ([`protocol`]), the canvas
3//! operations and their decoding ([`canvas`], with [`ops`]'
4//! `#[derive(JsOps)]`), the style types ([`style`]), the host elements'
5//! props ([`host`]: their decoding and types, from `#[derive(HostProps)]`
6//! on [`crate::Prop`]) and the easings and layout animations ([`animation`]).
7//! The decoders in `nsh-js` match on the same constants and call the
8//! derived decoders, and their declarations go into the ones apps are
9//! checked against (`nsh-js` `declarations.rs`).
10
11use std::time::Duration;
12
13/// nsh's own native ES modules, which bundles compiled with nsh's JSX
14/// compiler import (served by `nsh-js`, left as imports by the bundler):
15/// `nsh`, the API apps write against; `nsh:rt`, the renderer compiled JSX
16/// calls; `nsh/device` and `nsh/accessibility`, the environment; the
17/// platforms' and host elements' modules. Registries add theirs
18/// (`Registry::specifier`: `nsh/ui/mobile`, ...) or the functions of
19/// nsh's own (`nsh/image`, `nsh/android`).
20pub const NATIVE_MODULES: &[&str] = &[
21    "nsh",
22    "nsh:rt",
23    "nsh/device",
24    "nsh/accessibility",
25    "nsh/android",
26    "nsh/ios",
27    "nsh/desktop",
28    "nsh/webview",
29    "nsh/video",
30    "nsh/native",
31    "nsh/gesture",
32    "nsh/animated",
33    "nsh/canvas",
34    "nsh/list",
35    "nsh/image",
36    "nsh/keymap",
37];
38
39/// Resource limits of one VM.
40#[derive(Debug, Clone, Copy, PartialEq)]
41pub struct Limits {
42    /// QuickJS heap, in bytes (0: no limit). Running out stops the VM.
43    pub memory_bytes: usize,
44    /// Interpreter stack, in bytes: deep recursion becomes a `RangeError`
45    /// rather than a native stack overflow. Must stay below the engine
46    /// thread's stack.
47    pub stack_bytes: usize,
48    /// Evaluating the bundle.
49    pub load_budget: Duration,
50    /// Any other call into JS: one event (with the rendering it causes), one
51    /// list bind, one timer, one frame's callbacks, the microtask drain.
52    pub call_budget: Duration,
53    /// Changes JS may make at once (the op queue's length): they are held in
54    /// Rust memory, which the heap limit does not cover.
55    pub max_op_values: usize,
56    /// Operations one canvas drawing may record.
57    pub max_canvas_ops: usize,
58    /// Nodes the core keeps (each may have a native view, whose memory the
59    /// heap limit does not cover either).
60    pub max_nodes: usize,
61}
62
63impl Default for Limits {
64    fn default() -> Self {
65        Self {
66            memory_bytes: 256 << 20,
67            stack_bytes: 4 << 20,
68            load_budget: Duration::from_secs(10),
69            call_budget: Duration::from_secs(2),
70            max_op_values: 8_000_000,
71            max_canvas_ops: 1_000_000,
72            max_nodes: 200_000,
73        }
74    }
75}
76
77/// Constants of encoded operations and a table of them for the generators.
78macro_rules! codes {
79    ($table:ident: $($(#[doc = $doc:literal])* $name:ident = $value:literal),* $(,)?) => {
80        $(
81            #[doc = concat!("`", stringify!($name), "`.")]
82            $(#[doc = $doc])*
83            pub const $name: i32 = $value;
84        )*
85
86        /// The codes by name, with their documentation (the operands).
87        pub const $table: &[(&str, i32, &str)] = &[$((stringify!($name), $value, concat!($($doc),*))),*];
88    };
89}
90
91pub mod animation;
92pub mod canvas;
93pub mod host;
94pub(crate) mod host_values;
95pub mod ops;
96pub mod protocol;
97pub mod style;
98
99#[cfg(test)]
100mod tests {
101    #[test]
102    fn the_declarations_match_the_tables() {
103        let canvas = super::canvas::declarations();
104        assert!(
105            canvas.contains("  moveTo(x: CanvasNumber, y: CanvasNumber): void;"),
106            "{canvas}"
107        );
108        assert!(canvas.contains("counterclockwise?: boolean): void;"));
109        assert!(canvas.contains("  lineCap: LineCap;"));
110        assert!(canvas.contains("export type LineCap = \"butt\" | \"round\" | \"square\";"));
111        let style = super::style::declarations();
112        // Every property the core parses has a type, in its interface.
113        for (name, ts) in [
114            ("boxShadow", "string"),
115            ("gridTemplateColumns", "string"),
116            ("transform", "TransformStep[]"),
117            ("tintColor", "ColorValue"),
118            ("display", "\"flex\" | \"grid\" | \"block\" | \"none\""),
119        ] {
120            assert!(style.contains(&format!("  {name}?: {ts};")), "{name}");
121        }
122        let text = style.find("export interface TextStyle").unwrap();
123        assert!(style[text..].contains("  textDecorationStyle?:"));
124        // Each host prop and event in the interface of the elements it is for.
125        let elements = super::host::declarations();
126        for (interface, prop) in [
127            ("HostProps", "  pointerEvents?: PointerEvents;"),
128            ("HostProps", "  onPress?: () => void;"),
129            ("HostProps", "  onLayout?: (e: LayoutEvent) => void;"),
130            ("AndroidHostProps", "  elevation?: number;"),
131            ("InputHostProps", "  keyboardType?: KeyboardType;"),
132            ("InputHostProps", "  onChangeText?: (text: string) => void;"),
133            ("IOSInputHostProps", "  inputAccessoryViewID?: string;"),
134            (
135                "IOSInputHostProps",
136                "  keyboardAppearance?: KeyboardAppearance;",
137            ),
138            ("TextHostProps", "  selectionColor?: ColorValue;"),
139            ("InputHostProps", "  selectionColor?: ColorValue;"),
140            (
141                "ImageHostProps",
142                "  onLoad?: (e: { width: number; height: number }) => void;",
143            ),
144            (
145                "VideoHostProps",
146                "  onLoad?: (e: { duration: number; width: number; height: number }) => void;",
147            ),
148            (
149                "ScrollingHostProps",
150                "  decelerationRate?: \"normal\" | \"fast\" | number;",
151            ),
152            (
153                "ScrollingHostProps",
154                "  onScroll?: (e: ScrollEvent) => void;",
155            ),
156            (
157                "ListHostProps",
158                "  contentContainerStyle?: ListContentStyle;",
159            ),
160            (
161                "IOSModalHostProps",
162                "  presentationStyle?: ModalPresentation;",
163            ),
164            (
165                "DesktopModalHostProps",
166                "  presentationStyle?: ModalPresentation;",
167            ),
168            ("DesktopScreenHostProps", "  headerBackTitle?: string;"),
169            (
170                "DesktopWebViewHostProps",
171                "  allowsBackForwardNavigationGestures?: boolean;",
172            ),
173            ("ModalHostProps", "  onRequestClose?: () => void;"),
174        ] {
175            let at = elements
176                .find(&format!("export interface {interface} {{"))
177                .unwrap_or_else(|| panic!("{interface}"));
178            let end = at + elements[at..].find("\n}").unwrap();
179            assert!(elements[at..end].contains(prop), "{interface}: {prop}");
180        }
181        assert!(elements.contains(
182            "export type KeyboardType = \"default\" | \"number-pad\" | \"decimal-pad\" | \"numeric\" | \"numbers-and-punctuation\""
183        ));
184        assert!(
185            elements
186                .contains("export type KeyboardAppearance = \"default\" | \"light\" | \"dark\";")
187        );
188        let animation = super::animation::declarations();
189        assert!(animation.contains("  back(s?: number): EasingCurve;"));
190        assert!(
191            animation.contains("export type LayoutAnimationType = \"easeInEaseOut\" | \"spring\"")
192        );
193        assert!(animation.contains("  readonly scaleXY: \"scaleXY\";"));
194        // What the runtime sets itself is not part of the types.
195        for internal in ["splice?", "cellIndex?", "tailwindTheme?", "headerSlot?"] {
196            assert!(!elements.contains(internal), "{internal}");
197        }
198    }
199
200    #[test]
201    fn every_event_is_typed_or_internal() {
202        use super::host::{EVENTS, INTERNAL_EVENTS};
203        for kind in crate::EventKind::ALL {
204            let typed = EVENTS.iter().any(|e| e.0 == *kind);
205            let internal = INTERNAL_EVENTS.contains(kind);
206            assert!(
207                typed != internal,
208                "{}: give it a handler type in `EVENTS` or list it in `INTERNAL_EVENTS`",
209                kind.prop_name()
210            );
211        }
212    }
213}