Skip to main content

nativeview_codegen/targets/
export_common.rs

1//! Shared helpers for exporting `#[nv_hybrid_view]` specs across all 6 target frameworks.
2
3use crate::error::CodegenError;
4use crate::naming::{
5    kotlin_package_segment, strip_on_prefix, to_camel_case, to_pascal_case, to_snake_case,
6};
7
8/// Crate-level snake_case library stem shared by all views in `file` (`lib<stem>.so`,
9/// `<stem>_web.js`), ensuring multi-view specs load from one compiled crate binary while
10/// differentiating views by `vtable_symbol` / `componentName`.
11pub fn export_lib_stem(file: &HybridFileSpec) -> String {
12    file.stem_snake()
13}
14
15/// Canonical React Native `codegenConfig.name` and `<react/renderer/components/<name>/*.h>`
16/// header directory shared across `package.json` and generated ObjC++ Fabric ComponentViews.
17pub fn rn_codegen_spec_name(file: &HybridFileSpec) -> String {
18    format!("{}Spec", file.stem_pascal())
19}
20
21/// C anchor function exported by `<Mod>Anchor`'s `NvExportAnchor.m` in `nitro-ui-pkg` that
22/// resolves each view's `<vtable_symbol>` from its isolated `<Mod>Core.framework` via
23/// `dlopen(RTLD_LOCAL)` + `dlsym`.
24pub fn nitro_ios_anchor_fn(view_name: &str) -> String {
25    format!("nv_export_interface_{}", to_snake_case(view_name))
26}
27
28/// Default Apple module name derived from `file.stem_pascal()`, avoiding double `NvNv` prefixes.
29pub(crate) fn default_ios_module_name(file: &HybridFileSpec) -> String {
30    let stem_pascal = file.stem_pascal();
31    if stem_pascal.is_empty() {
32        "NvComponent".to_owned()
33    } else if stem_pascal.starts_with("Nv") {
34        stem_pascal
35    } else {
36        format!("Nv{stem_pascal}")
37    }
38}
39
40/// Dynamic iOS `.framework` / `.xcframework` bundle name for an exported component (`<Mod>Core`),
41/// keeping the dynamic Rust binary distinct from the CocoaPods/SwiftPM wrapper module `<Mod>`.
42pub fn ios_core_framework_name(ios_module_name: &str) -> String {
43    format!("{ios_module_name}Core")
44}
45
46/// Kotlin-safe `package` header name preserving segment underscores/casing while backtick-escaping
47/// reserved Kotlin keywords.
48pub(crate) fn android_package_kotlin(file: &HybridFileSpec) -> String {
49    file.android_package()
50        .split('.')
51        .map(kotlin_package_segment)
52        .collect::<Vec<_>>()
53        .join(".")
54}
55use crate::schema::hybrid::{HybridFileSpec, HybridType, HybridViewSpec};
56
57/// Validates a spec file for single-view export.
58pub(crate) fn validate_export_view(
59    file: &HybridFileSpec,
60    view: &HybridViewSpec,
61) -> Result<(), CodegenError> {
62    file.validate()?;
63    if view.name.trim().is_empty() {
64        return Err(CodegenError::validation("HybridViewSpec.name must not be empty"));
65    }
66    Ok(())
67}
68
69/// Idiomatic camelCase callback name for a view event (`on_count_change` / `count_change` ->
70/// `onCountChange`, `select` -> `onSelect`).
71pub(crate) fn event_handler_name(raw: &str) -> String {
72    let stripped = strip_on_prefix(raw);
73    if stripped.is_empty() {
74        return to_camel_case(raw);
75    }
76    format!("on{}", to_pascal_case(&stripped))
77}
78
79/// PascalCase stem of an event name without a leading `on` (`on_count_change` -> `CountChange`).
80pub(crate) fn event_stem_pascal(raw: &str) -> String {
81    let stripped = strip_on_prefix(raw);
82    if stripped.is_empty() {
83        to_pascal_case(raw)
84    } else {
85        to_pascal_case(&stripped)
86    }
87}
88
89/// Deduplicated wire names an event dispatcher matches against `nv.custom` event names:
90/// the declared spec name, the `on`-stripped form, and the camelCase handler name.
91pub(crate) fn event_wire_aliases(raw: &str) -> Vec<String> {
92    let mut out = Vec::with_capacity(3);
93    let mut push = |candidate: String| {
94        if !candidate.is_empty() && !out.contains(&candidate) {
95            out.push(candidate);
96        }
97    };
98    push(raw.to_owned());
99    push(strip_on_prefix(raw));
100    push(event_handler_name(raw));
101    out
102}
103
104/// Resolves the integer discriminant of `EnumName::Variant` in `file`.
105pub(crate) fn resolve_enum_discriminant(
106    file: &HybridFileSpec,
107    enum_name: &str,
108    variant: &str,
109) -> Option<i64> {
110    file.find_enum(enum_name)?
111        .variants
112        .iter()
113        .find(|v| v.name == variant)
114        .map(|v| v.value)
115}
116
117/// Recursively tests whether `pred` holds for `ty` or any nested container/option type.
118pub(crate) fn type_matches(ty: &HybridType, pred: fn(&HybridType) -> bool) -> bool {
119    if pred(ty) {
120        return true;
121    }
122    match ty {
123        HybridType::Optional(inner)
124        | HybridType::Vec(inner)
125        | HybridType::FixedArray { elem: inner, .. } => type_matches(inner, pred),
126        HybridType::Result { ok, .. } => type_matches(ok, pred),
127        _ => false,
128    }
129}
130
131/// Tests whether `pred` matches any prop, event param, method param, or transitive struct field
132/// of `view`.
133pub(crate) fn view_type_matches(
134    file: &HybridFileSpec,
135    view: &HybridViewSpec,
136    pred: fn(&HybridType) -> bool,
137) -> bool {
138    let (_enums, structs) = view.referenced_types(file);
139    view.props.iter().any(|p| type_matches(&p.ty, pred))
140        || view
141            .events
142            .iter()
143            .any(|e| e.params.iter().any(|p| type_matches(&p.ty, pred)))
144        || view
145            .methods
146            .iter()
147            .any(|m| m.params.iter().any(|p| type_matches(&p.ty, pred)))
148        || structs
149            .iter()
150            .any(|s| s.fields.iter().any(|f| type_matches(&f.ty, pred)))
151}