use std::{
any::{Any, TypeId},
fmt,
sync::Arc,
};
use rustc_hash::FxHashMap;
use super::{
Children, IntoElement, PropError, Slot, TsType, TsTypes,
builder::{ComponentElement, ElNode},
call::{AnyValue, JsResult, MethodCall},
class::{Class, ClassDef, ClassSpec, MemberKind, Thrown},
js::{JsHost, JsIn, JsOwned},
module::{FunctionSpec, Module, ModuleSpec},
};
pub trait Component: 'static {
type Props: Props;
type Event: Event;
const METHODS: Methods = Methods::NONE;
const DOC: &'static str = "";
fn view(props: Self::Props, cx: super::Scope<Self::Event>) -> impl IntoElement;
fn element(props: Self::Props) -> ComponentElement<Self>
where
Self: Sized,
{
ComponentElement::new(props)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComponentError {
pub component: &'static str,
pub message: String,
}
impl fmt::Display for ComponentError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} failed: {}", self.component, self.message)
}
}
pub(crate) fn caught<R>(f: impl FnOnce() -> R) -> Result<R, String> {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(panic_message)
}
pub(crate) fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
match payload.downcast::<String>() {
Ok(s) => *s,
Err(payload) => match payload.downcast::<&'static str>() {
Ok(s) => (*s).to_owned(),
Err(_) => "a panic".to_owned(),
},
}
}
pub struct Method {
pub name: &'static str,
pub doc: &'static str,
pub params: &'static [Param],
pub returns: Option<TsType>,
pub refs: super::ClassRefs,
pub call: fn(&dyn JsHost) -> Result<MethodCall, Thrown>,
}
pub trait Api: Sized + 'static {
const METHODS: &'static [Method];
}
#[derive(Clone, Copy)]
pub struct Methods {
specs: fn(&mut TsTypes) -> Vec<MethodSpec>,
refs: super::ClassRefs,
}
impl Methods {
pub const NONE: Self = Self {
specs: |_| Vec::new(),
refs: |_| {},
};
pub const fn of<A: Api>() -> Self {
Self {
specs: specs_of::<A>,
refs: |out| {
for m in A::METHODS {
(m.refs)(out);
}
},
}
}
}
fn specs_of<A: Api>(types: &mut TsTypes) -> Vec<MethodSpec> {
A::METHODS
.iter()
.map(|m| MethodSpec {
name: m.name,
doc: m.doc,
params: m
.params
.iter()
.map(|(n, ts, optional)| (*n, ts(types), *optional))
.collect(),
returns: m.returns.map(|ts| ts(types)),
call: m.call,
})
.collect()
}
pub type Param = (&'static str, TsType, bool);
#[derive(Debug, Clone)]
pub struct MethodSpec {
pub name: &'static str,
pub doc: &'static str,
pub params: Vec<(&'static str, String, bool)>,
pub returns: Option<String>,
pub call: fn(&dyn JsHost) -> Result<MethodCall, Thrown>,
}
impl MethodSpec {
pub fn promises(&self) -> bool {
self.returns.is_some()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PropKind {
Value,
Renderer,
Slot,
Children,
Items,
}
pub type PropDecode = fn(JsIn<'_>) -> Result<AnyValue, PropError>;
#[derive(Debug, Clone)]
pub struct PropSpec {
pub name: &'static str,
pub ts: String,
pub optional: bool,
pub doc: &'static str,
pub kind: PropKind,
pub decode: Option<PropDecode>,
}
#[derive(Debug, Clone)]
pub struct EventSpec {
pub name: &'static str,
pub arg: &'static str,
pub data: String,
pub doc: &'static str,
}
pub trait Props: Clone + PartialEq + 'static {
#[doc(hidden)]
const ITEMS: Option<&'static str> = None;
#[doc(hidden)]
const LAZY_CHILDREN: bool = false;
#[doc(hidden)]
const GENERIC: bool = false;
fn spec(types: &mut TsTypes) -> Vec<PropSpec>;
fn initial() -> Self;
fn set(&mut self, name: &str, value: Option<AnyValue>) -> Result<bool, PropError>;
fn set_slot(&mut self, name: &str, slot: Option<Slot>) -> bool;
fn set_children(&mut self, children: Children) -> bool;
#[doc(hidden)]
fn held(&self) -> Self {
self.clone()
}
#[doc(hidden)]
fn update_from(&mut self, new: &Self) -> bool {
if self == new {
return false;
}
*self = new.clone();
true
}
}
impl Props for () {
fn spec(_: &mut TsTypes) -> Vec<PropSpec> {
Vec::new()
}
fn initial() -> Self {}
fn set(&mut self, name: &str, _: Option<AnyValue>) -> Result<bool, PropError> {
Err(PropError(format!("unknown prop `{name}`")))
}
fn set_slot(&mut self, _: &str, _: Option<Slot>) -> bool {
false
}
fn set_children(&mut self, _: Children) -> bool {
false
}
}
pub trait Event: 'static {
fn spec(types: &mut TsTypes) -> Vec<EventSpec>;
fn name(&self) -> &'static str;
fn data_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NoEvent {}
impl Event for NoEvent {
fn spec(_types: &mut TsTypes) -> Vec<EventSpec> {
Vec::new()
}
fn name(&self) -> &'static str {
match *self {}
}
fn data_js<'a>(&self, _host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
match *self {}
}
}
#[derive(Debug, Clone)]
pub struct ComponentSpec {
pub name: &'static str,
pub export: String,
pub doc: &'static str,
pub props: Vec<PropSpec>,
pub events: Vec<EventSpec>,
pub methods: Vec<MethodSpec>,
pub types: TsTypes,
pub lazy_children: bool,
pub generic: bool,
}
pub const HOST_PROPS: &[&str] = &[
"class",
"classList",
"style",
"activeStyle",
"hoverStyle",
"focusStyle",
"focusWithinStyle",
"focusVisibleStyle",
"disabledStyle",
"testID",
"accessible",
"accessibilityLabel",
"accessibilityHint",
"accessibilityDescription",
"role",
"accessibilityState",
"accessibilityValue",
"accessibilityElementsHidden",
"importantForAccessibility",
"accessibilityLiveRegion",
"accessibilityActions",
"accessibilityLevel",
"accessibilityActiveDescendant",
"accessibilityControls",
"accessibilityDescribedBy",
"tooltip",
"focusable",
"onLayout",
"onFileDragEnter",
"onFileDragLeave",
"onFileDrop",
"onMouseEnter",
"onMouseMove",
"onMouseLeave",
"onMouseUp",
"onContextMenu",
"onAccessibilityAction",
];
type Specs = (
fn(&mut TsTypes) -> Vec<PropSpec>,
fn(&mut TsTypes) -> Vec<EventSpec>,
fn(&mut TsTypes) -> Vec<MethodSpec>,
);
impl ComponentSpec {
pub fn host_props(&self) -> impl Iterator<Item = &'static str> + '_ {
HOST_PROPS.iter().copied().filter(|&name| {
!self.props.iter().any(|p| p.name == name)
&& !self.events.iter().any(|e| handler_name(e.name) == name)
})
}
pub(crate) fn of<C: Component>() -> Self {
Self::build(
name_of::<C>(),
C::DOC,
(C::Props::spec, C::Event::spec, C::METHODS.specs),
C::Props::LAZY_CHILDREN,
C::Props::GENERIC,
)
}
#[inline(never)]
fn build(
name: &'static str,
doc: &'static str,
(props, events, methods): Specs,
lazy_children: bool,
generic: bool,
) -> Self {
let mut types = TsTypes::default();
let props = props(&mut types);
let events = events(&mut types);
let methods = methods(&mut types);
Self {
name,
export: export_name(name).to_owned(),
doc,
props,
events,
methods,
types,
lazy_children,
generic,
}
}
pub fn slots(&self) -> impl Iterator<Item = &'static str> + '_ {
self.props
.iter()
.filter(|p| p.kind == PropKind::Slot)
.map(|p| p.name)
}
pub fn renderers(&self) -> impl Iterator<Item = &'static str> + '_ {
self.props
.iter()
.filter(|p| p.kind == PropKind::Renderer)
.map(|p| p.name)
}
pub fn takes_children(&self) -> bool {
self.props.iter().any(|p| p.kind == PropKind::Children)
}
pub fn items(&self) -> Option<&'static str> {
self.props
.iter()
.find(|p| p.kind == PropKind::Items)
.map(|p| p.name)
}
pub(crate) fn holder(&self, name: &str) -> Option<&'static str> {
self.props
.iter()
.find(|p| matches!(p.kind, PropKind::Slot | PropKind::Items) && p.name == name)
.map(|p| p.name)
}
}
pub(crate) fn name_of<C: Component>() -> &'static str {
std::any::type_name::<C>()
}
pub(crate) fn export_name(type_name: &str) -> &str {
let path = type_name.split('<').next().unwrap_or(type_name);
path.rsplit("::").next().unwrap_or(path)
}
pub(crate) trait AnyInstance {
fn set_prop(&mut self, name: &str, value: Option<AnyValue>) -> Result<bool, PropError>;
fn set_props(&mut self, props: &dyn Any);
fn set_slot(&mut self, name: &'static str, filled: bool);
fn set_children(&mut self, present: bool);
fn cleanup(&mut self);
fn view(&mut self) -> ElNode;
fn name(&self) -> &'static str;
fn call(&mut self, call: MethodCall) -> Option<JsResult>;
fn owner(&self) -> Option<super::Owner>;
fn failure_owner(&self) -> super::Owner;
fn adopt(&mut self, parent: super::Owner);
fn place(&mut self, host: crate::NodeId, parent: super::Owner);
}
#[derive(Clone)]
pub struct Root {
make: Arc<dyn Fn() -> super::AnyElement + Send + Sync>,
tokens: Option<Arc<super::Tokens>>,
fonts: Vec<Arc<[u8]>>,
appearance: Option<crate::platform::Appearance>,
app_id: Option<String>,
links: crate::url_scheme::AppLinks,
capabilities: Option<crate::access::Capabilities>,
status_bar: Option<crate::StatusBarSetting>,
main_window: Option<crate::desktop::MainWindowOptions>,
application: Option<crate::desktop::ApplicationOptions>,
translations: Option<crate::i18n::Translations>,
app_info: Option<crate::platform::AppInfo>,
}
impl Root {
pub fn new<C: Component>(props: impl Fn() -> C::Props + Send + Sync + 'static) -> Self {
Self {
make: Arc::new(move || super::IntoElement::into_element(C::element(props()))),
tokens: None,
fonts: Vec::new(),
appearance: None,
app_id: None,
links: crate::url_scheme::AppLinks::default(),
capabilities: None,
status_bar: None,
main_window: None,
application: None,
translations: None,
app_info: None,
}
}
pub fn translations(mut self, translations: crate::i18n::Translations) -> Self {
self.translations = Some(translations);
self
}
#[doc(hidden)]
pub fn translations_json(self, json: &str) -> Self {
match crate::i18n::Translations::from_json(json) {
Ok(translations) => self.translations(translations),
Err(e) => {
log::warn!("locales: {e}");
self
}
}
}
pub fn translations_ref(&self) -> Option<&crate::i18n::Translations> {
self.translations.as_ref()
}
pub fn app_id(mut self, id: impl Into<String>) -> Self {
self.app_id = Some(id.into());
self
}
pub fn app_id_ref(&self) -> Option<&str> {
self.app_id.as_deref()
}
pub fn app_info(mut self, info: crate::platform::AppInfo) -> Self {
self.app_info = Some(info);
self
}
#[doc(hidden)]
pub fn app_info_json(self, json: &str) -> Self {
let info = match serde_json::from_str(json) {
Ok(value) => crate::platform::AppInfo::from_json(&value),
Err(e) => {
log::warn!("appInfo: {e}, ignored");
crate::platform::AppInfo::default()
}
};
self.app_info(info)
}
#[doc(hidden)]
pub fn app_info_ref(&self) -> Option<&crate::platform::AppInfo> {
self.app_info.as_ref()
}
pub fn url_schemes(mut self, schemes: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.links.set_schemes(schemes);
self
}
pub fn url_schemes_ref(&self) -> &[String] {
self.links.schemes()
}
pub fn links(mut self, links: crate::url_scheme::AppLinks) -> Self {
self.links = links;
self
}
#[doc(hidden)]
pub fn links_json(self, json: &str) -> Self {
let links = match serde_json::from_str::<serde_json::Value>(json) {
Ok(config) => {
let (links, ignored) = crate::url_scheme::AppLinks::from_json_lenient(&config);
for what in ignored {
log::warn!("nsh.json: {what}, ignored");
}
links
}
Err(e) => {
log::warn!("nsh.json: links: {e}; none claimed");
crate::url_scheme::AppLinks::default()
}
};
self.links(links)
}
pub fn links_ref(&self) -> &crate::url_scheme::AppLinks {
&self.links
}
pub fn capabilities(mut self, capabilities: crate::access::Capabilities) -> Self {
self.capabilities = Some(capabilities);
self
}
#[doc(hidden)]
pub fn capabilities_json(self, json: &str) -> Self {
let read = serde_json::from_str::<serde_json::Value>(json)
.map_err(|e| e.to_string())
.and_then(|v| crate::access::Capabilities::from_json_lenient(&v));
let capabilities = match read {
Ok((capabilities, dropped)) => {
for what in dropped {
log::warn!("nsh.json: {what}, not granted");
}
capabilities
}
Err(e) => {
log::warn!("nsh.json: capabilities: {e}; nothing granted");
crate::access::Capabilities::default()
}
};
self.capabilities(capabilities)
}
pub fn capabilities_ref(&self) -> Option<&crate::access::Capabilities> {
self.capabilities.as_ref()
}
pub fn tokens(mut self, tokens: super::Tokens) -> Self {
self.tokens = Some(Arc::new(tokens));
self
}
pub fn font(mut self, data: impl Into<Arc<[u8]>>) -> Self {
self.fonts.push(data.into());
self
}
pub fn appearance(mut self, appearance: crate::platform::Appearance) -> Self {
self.appearance = Some(appearance);
self
}
pub fn status_bar(mut self, setting: crate::StatusBarSetting) -> Self {
self.status_bar = Some(setting);
self
}
pub fn main_window(mut self, options: crate::desktop::MainWindowOptions) -> Self {
self.main_window = Some(options);
self
}
#[doc(hidden)]
pub fn main_window_json(self, json: &str) -> Self {
let options = serde_json::from_str::<serde_json::Value>(json)
.map_err(|e| e.to_string())
.and_then(|v| {
crate::desktop::MainWindowOptions::from_json(&v).map_err(|e| e.to_string())
});
match options {
Ok(options) => self.main_window(options),
Err(e) => {
log::warn!("nsh.json: window: {e}");
self
}
}
}
pub fn main_window_ref(&self) -> Option<&crate::desktop::MainWindowOptions> {
self.main_window.as_ref()
}
pub fn application(mut self, options: crate::desktop::ApplicationOptions) -> Self {
self.application = Some(options);
self
}
#[doc(hidden)]
pub fn application_json(self, json: &str) -> Self {
let options = serde_json::from_str::<serde_json::Value>(json)
.map_err(|e| e.to_string())
.and_then(|v| {
crate::desktop::ApplicationOptions::from_json(&v).map_err(|e| e.to_string())
});
match options {
Ok(options) => self.application(options),
Err(e) => {
log::warn!("nsh.json: application: {e}");
self
}
}
}
pub fn application_ref(&self) -> Option<&crate::desktop::ApplicationOptions> {
self.application.as_ref()
}
pub fn status_bar_ref(&self) -> Option<crate::StatusBarSetting> {
self.status_bar
}
pub fn appearance_ref(&self) -> Option<crate::platform::Appearance> {
self.appearance
}
pub fn tokens_ref(&self) -> Option<&super::Tokens> {
self.tokens.as_deref()
}
pub fn fonts(&self) -> &[Arc<[u8]>] {
&self.fonts
}
pub fn of<C: Component>() -> Self
where
C::Props: Default,
{
Self::new::<C>(C::Props::default)
}
pub(crate) fn element(&self) -> super::AnyElement {
(self.make)()
}
}
impl fmt::Debug for Root {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Root")
}
}
pub const BY_NAME_MARKER: &str = "missing_instance";
#[inline(never)]
pub(crate) fn missing_instance() -> Box<dyn AnyInstance> {
unreachable!("a component made by name is made by its registry")
}
pub(crate) fn missing_spec() -> ComponentSpec {
unreachable!("a component made by name is made by its registry")
}
pub(crate) fn make_instance<C: Component>() -> Box<dyn AnyInstance> {
Box::new(super::once::OnceInstance::<C>::new())
}
#[derive(Clone)]
struct ComponentType {
spec: Arc<ComponentSpec>,
make: fn() -> Box<dyn AnyInstance>,
id: TypeId,
}
#[derive(Clone)]
struct ModuleType {
spec: Arc<ModuleSpec>,
type_name: &'static str,
}
#[derive(Clone)]
struct ClassType {
spec: Arc<ClassSpec>,
type_name: &'static str,
}
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct BuiltInScrollbar {
pub target: crate::NodeId,
pub horizontal: bool,
pub theme: Option<Arc<crate::JsonValue>>,
pub theme_value: Option<super::AnyValue>,
pub app_theme: Option<super::AnyValue>,
}
pub type ScrollbarSource = fn(&BuiltInScrollbar) -> Option<super::AnyElement>;
#[derive(Clone)]
pub struct ScrollbarThemeValue {
source: ScrollbarSource,
theme: super::AnyValue,
}
impl ScrollbarThemeValue {
pub fn new(source: ScrollbarSource, theme: super::AnyValue) -> Self {
Self { source, theme }
}
pub fn source(&self) -> ScrollbarSource {
self.source
}
pub fn theme(&self) -> &super::AnyValue {
&self.theme
}
}
impl PartialEq for ScrollbarThemeValue {
fn eq(&self, other: &Self) -> bool {
self.theme == other.theme
}
}
impl std::fmt::Debug for ScrollbarThemeValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("ScrollbarThemeValue")
.field(&self.theme)
.finish()
}
}
#[derive(Clone, Default)]
pub struct Registry {
types: Arc<FxHashMap<&'static str, ComponentType>>,
modules: Arc<FxHashMap<&'static str, ModuleType>>,
classes: Arc<FxHashMap<(Option<&'static str>, &'static str), ClassType>>,
reexports: Arc<(Vec<&'static str>, Vec<&'static str>)>,
native_values: Arc<Vec<&'static str>>,
namespace: Option<&'static str>,
ui_set: Option<&'static str>,
assets: Arc<Vec<(&'static [crate::platform::Os], &'static [super::AssetFile])>>,
tokens: Option<super::TokenSource>,
scrollbars: Option<ScrollbarSource>,
submodules: Arc<Vec<Registry>>,
setups: Arc<Vec<Setup>>,
fakes: Arc<Vec<(&'static str, Arc<dyn crate::fake::Fake>)>>,
gpu_renderers: Arc<Vec<(&'static str, crate::gpu::GpuSource)>>,
}
type Setup = Arc<dyn Fn() + Send + Sync>;
impl fmt::Debug for Registry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_set().entries(self.types.keys()).finish()
}
}
impl Registry {
pub fn new() -> Self {
Self::default()
}
#[track_caller]
pub fn register<C: Component>(&mut self) -> &mut Self {
let spec = ComponentSpec::of::<C>();
let mut refs = Vec::new();
(C::METHODS.refs)(&mut refs);
self.register_erased(spec, make_instance::<C>, TypeId::of::<C>(), refs)
}
#[track_caller]
#[inline(never)]
fn register_erased(
&mut self,
spec: ComponentSpec,
make: fn() -> Box<dyn AnyInstance>,
id: TypeId,
refs: Vec<&'static ClassDef>,
) -> &mut Self {
let types = Arc::make_mut(&mut self.types);
if let Some(old) = types.get(spec.name) {
let set = self.ui_set.or(self.namespace);
panic!("{}", same_name(spec.name, old.id, id, set));
}
if self.classes.keys().any(|(_, name)| *name == spec.export) {
panic!(
"component `{}` is exported as `{}` like a class{}: rename one",
spec.name,
spec.export,
of_set(self.ui_set.or(self.namespace)),
);
}
if let Some(other) = types.values().find(|t| t.spec.export == spec.export) {
panic!(
"components `{}` and `{}` are both exported as `{}`{}: rename one",
other.spec.name,
spec.name,
spec.export,
of_set(self.ui_set.or(self.namespace)),
);
}
types.insert(
spec.name,
ComponentType {
spec: Arc::new(spec),
make,
id,
},
);
self.classes_named(refs)
}
#[track_caller]
pub fn module<M: Module>(&mut self) -> &mut Self {
let type_name = std::any::type_name::<M>();
if self.classes.keys().any(|(_, name)| *name == M::NAME) {
panic!(
"module `{type_name}` is named `{}` like a class{}: rename one",
M::NAME,
of_set(self.ui_set.or(self.namespace))
);
}
let modules = Arc::make_mut(&mut self.modules);
if let Some(old) = modules.get(M::NAME) {
panic!(
"{}",
same_module(
M::NAME,
old.type_name,
type_name,
self.ui_set.or(self.namespace)
)
);
}
modules.insert(
M::NAME,
ModuleType {
spec: Arc::new(ModuleSpec::of::<M>()),
type_name,
},
);
let mut refs = Vec::new();
for f in M::FUNCTIONS {
(f.refs)(&mut refs);
}
self.classes_named(refs)
}
#[track_caller]
pub fn class<C: Class>(&mut self) -> &mut Self {
self.class_def(C::DEF)
}
#[track_caller]
fn classes_named(&mut self, refs: Vec<&'static ClassDef>) -> &mut Self {
for def in refs {
self.class_def(def);
}
self
}
#[track_caller]
fn class_def(&mut self, def: &'static ClassDef) -> &mut Self {
let type_name = (def.type_name)();
let set = self.ui_set.or(self.namespace);
if let Some(old) = self.classes.get(&(set, def.name)) {
if (old.spec.def.type_id)() == (def.type_id)() {
return self;
}
panic!("{}", same_class(def.name, old.type_name, type_name, set));
}
if self.modules.contains_key(def.name)
|| self.types.values().any(|t| t.spec.export == def.name)
{
panic!(
"class `{type_name}` is named `{}` like a module or a component{}: rename one",
def.name,
of_set(set)
);
}
Arc::make_mut(&mut self.classes).insert(
(set, def.name),
ClassType {
spec: Arc::new(ClassSpec::of(def)),
type_name,
},
);
let mut refs = Vec::new();
for m in def.members {
(m.refs)(&mut refs);
}
self.classes_named(refs)
}
pub fn reexport(&mut self, values: &[&'static str], types: &[&'static str]) -> &mut Self {
let r = Arc::make_mut(&mut self.reexports);
r.0.extend_from_slice(values);
r.1.extend_from_slice(types);
self
}
#[track_caller]
pub fn merged(sets: &[Registry]) -> Self {
let mut out = Self::default();
for set in sets.iter().flat_map(Registry::sets) {
out.tokens = out.tokens.or(set.tokens);
out.scrollbars = out.scrollbars.or(set.scrollbars);
Arc::make_mut(&mut out.setups).extend(set.setups.iter().cloned());
let fakes = Arc::make_mut(&mut out.fakes);
for (name, fake) in set.fakes.iter() {
assert!(
fakes.iter().all(|(n, _)| n != name),
"two fakes are named `{name}`, by two UI sets"
);
fakes.push((name, fake.clone()));
}
let renderers = Arc::make_mut(&mut out.gpu_renderers);
for (name, source) in set.gpu_renderers.iter() {
assert!(
renderers.iter().all(|(n, _)| n != name),
"two GPU renderers are named `{name}`, by two UI sets"
);
renderers.push((name, source.clone()));
}
let types = Arc::make_mut(&mut out.types);
for (name, ty) in set.types.iter() {
if let Some(old) = types.insert(name, ty.clone()) {
panic!("{}, by two UI sets", same_name(name, old.id, ty.id, None));
}
}
}
out
}
pub fn ui_set(specifier: &'static str) -> Self {
Self {
ui_set: Some(specifier),
..Self::default()
}
}
pub fn specifier(&self) -> Option<&'static str> {
self.ui_set.or(self.namespace)
}
pub fn reexports(&self) -> (&[&'static str], &[&'static str]) {
(&self.reexports.0, &self.reexports.1)
}
#[track_caller]
pub fn submodule(&mut self, set: Registry) -> &mut Self {
let under = match (self.ui_set, set.ui_set) {
(Some(parent), Some(child)) => child
.strip_prefix(parent)
.is_some_and(|rest| rest.len() > 1 && rest.starts_with('/')),
_ => false,
};
assert!(
under,
"a submodule is a UI set under a path of its set's specifier: {:?} under {:?}",
set.ui_set, self.ui_set
);
Arc::make_mut(&mut self.submodules).push(set);
self
}
pub fn sets(&self) -> Vec<&Registry> {
let mut out = vec![self];
for sub in self.submodules.iter() {
out.extend(sub.sets());
}
out
}
pub fn native_values(&mut self, values: &[&'static str]) -> &mut Self {
Arc::make_mut(&mut self.native_values).extend_from_slice(values);
self
}
pub fn assets(&mut self, files: &'static [super::AssetFile]) -> &mut Self {
self.assets_for(&[], files)
}
pub fn assets_for(
&mut self,
targets: &'static [crate::platform::Os],
files: &'static [super::AssetFile],
) -> &mut Self {
Arc::make_mut(&mut self.assets).push((targets, files));
self
}
pub fn tokens_from(&mut self, source: super::TokenSource) -> &mut Self {
self.tokens = Some(source);
self
}
pub fn scrollbars_from(&mut self, source: ScrollbarSource) -> &mut Self {
self.scrollbars = Some(source);
self
}
pub(crate) fn scrollbar_source(&self) -> Option<ScrollbarSource> {
self.scrollbars
}
pub fn setup(&mut self, f: impl Fn() + Send + Sync + 'static) -> &mut Self {
Arc::make_mut(&mut self.setups).push(Arc::new(f));
self
}
pub fn gpu_renderer_source(
&mut self,
name: &'static str,
source: crate::gpu::GpuSource,
) -> &mut Self {
let renderers = Arc::make_mut(&mut self.gpu_renderers);
renderers.retain(|(n, _)| *n != name);
renderers.push((name, source));
self
}
pub fn registered_gpu_renderer(&self, name: &str) -> Option<&crate::gpu::GpuSource> {
self.gpu_renderers
.iter()
.find(|(n, _)| *n == name)
.map(|(_, s)| s)
}
#[track_caller]
pub fn fake(&mut self, name: &'static str, fake: Arc<dyn crate::fake::Fake>) -> &mut Self {
assert!(
self.fakes.iter().all(|(n, _)| *n != name),
"two fakes are named `{name}`{}",
of_set(self.ui_set.or(self.namespace))
);
Arc::make_mut(&mut self.fakes).push((name, fake));
self
}
#[doc(hidden)]
pub fn fakes(&self) -> Vec<(&'static str, Arc<dyn crate::fake::Fake>)> {
self.sets()
.into_iter()
.flat_map(|set| set.fakes.iter().cloned())
.collect()
}
pub(crate) fn run_setups(&self) {
for setup in self.setups.iter() {
setup();
}
}
pub(crate) fn run_setups_not_in(&self, old: &Registry) {
for setup in self.setups.iter() {
let known = old
.setups
.iter()
.any(|o| std::ptr::addr_eq(Arc::as_ptr(o), Arc::as_ptr(setup)));
if !known {
setup();
}
}
}
pub fn tokens(
&self,
json: Option<&str>,
) -> Option<Result<(super::Tokens, Vec<String>), String>> {
self.tokens.map(|source| source(json))
}
pub(crate) fn token_source(&self) -> Option<super::TokenSource> {
self.tokens
}
pub fn asset_files(&self) -> impl Iterator<Item = &'static super::AssetFile> + '_ {
self.assets.iter().flat_map(|(_, files)| files.iter())
}
pub fn scoped_asset_files(
&self,
) -> impl Iterator<Item = (&'static [crate::platform::Os], &'static super::AssetFile)> + '_
{
self.assets
.iter()
.flat_map(|&(targets, files)| files.iter().map(move |file| (targets, file)))
}
pub fn native_value_names(&self) -> &[&'static str] {
&self.native_values
}
pub(crate) fn runtime(namespace: &'static str) -> Self {
Self {
namespace: Some(namespace),
..Self::default()
}
}
pub fn namespace(&self) -> Option<&'static str> {
self.namespace
}
pub fn class_specs(&self) -> Vec<Arc<ClassSpec>> {
let mut specs: Vec<_> = self.classes.values().map(|c| c.spec.clone()).collect();
specs.sort_by_key(|s| s.name);
specs
}
pub fn module_specs(&self) -> Vec<Arc<ModuleSpec>> {
let mut specs: Vec<_> = self.modules.values().map(|m| m.spec.clone()).collect();
specs.sort_by_key(|s| s.name);
specs
}
pub fn function_members(&self, function: &str) -> Option<Arc<ModuleSpec>> {
let exported = self.modules.values().any(|m| {
m.spec.flat
&& m.spec
.functions
.iter()
.any(|f| !f.getter && f.name == function)
});
exported
.then(|| {
self.modules
.values()
.find(|m| !m.spec.flat && m.spec.name == function)
.map(|m| m.spec.clone())
})
.flatten()
}
pub fn specs(&self) -> Vec<Arc<ComponentSpec>> {
let mut specs: Vec<_> = self.types.values().map(|t| t.spec.clone()).collect();
specs.sort_by(|a, b| a.export.cmp(&b.export).then(a.name.cmp(b.name)));
specs
}
pub fn undocumented(&self) -> Vec<String> {
let mut out = Vec::new();
let specs = self.specs();
for c in &specs {
if c.doc.is_empty() {
out.push(c.export.clone());
}
for p in c.props.iter().filter(|p| p.doc.is_empty()) {
out.push(format!("{}.{}", c.export, p.name));
}
for e in c.events.iter().filter(|e| e.doc.is_empty()) {
out.push(format!("{}.{}", c.export, handler_name(e.name)));
}
for m in c.methods.iter().filter(|m| m.doc.is_empty()) {
out.push(format!("{}.{}", c.export, m.name));
}
}
for m in self.module_specs() {
let merged = specs.iter().any(|c| c.export == m.name)
|| (!m.flat && self.function_members(m.name).is_some());
if m.doc.is_empty() && !merged && !m.flat {
out.push(m.name.to_owned());
}
for f in m.functions.iter().filter(|f| f.doc.is_empty()) {
out.push(if m.flat {
f.name.to_owned()
} else {
format!("{}.{}", m.name, f.name)
});
}
}
for c in self.class_specs() {
if c.doc.is_empty() {
out.push(c.name.to_owned());
}
let documented_getter = |name: &str| {
c.members
.iter()
.any(|m| m.kind == MemberKind::Getter && m.name == name && !m.doc.is_empty())
};
for m in c.members.iter().filter(|m| m.doc.is_empty()) {
match m.kind {
MemberKind::Constructor => out.push(format!("new {}", c.name)),
MemberKind::Setter if documented_getter(m.name) => {}
_ => out.push(format!("{}.{}", c.name, m.name)),
}
}
}
out
}
pub(crate) fn make_type(
&self,
id: TypeId,
) -> Option<(Arc<ComponentSpec>, Box<dyn AnyInstance>)> {
self.types
.values()
.find(|t| t.id == id)
.map(|t| (t.spec.clone(), (t.make)()))
}
pub(crate) fn make(&self, name: &str) -> Option<(Arc<ComponentSpec>, Box<dyn AnyInstance>)> {
self.types.get(name).map(|t| (t.spec.clone(), (t.make)()))
}
}
fn same_name(name: &str, old: TypeId, new: TypeId, set: Option<&str>) -> String {
if old == new {
format!("component `{name}` is registered twice{}", of_set(set))
} else {
format!(
"two different types named `{name}` are registered{} (two versions of one crate?)",
of_set(set)
)
}
}
fn same_module(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
if old == new {
format!("module `{old}` is registered twice{}", of_set(set))
} else {
format!(
"modules `{old}` and `{new}` are both named `{name}`{}: rename one",
of_set(set)
)
}
}
fn same_class(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
if old == new {
format!("class `{old}` is registered twice{}", of_set(set))
} else {
format!(
"classes `{old}` and `{new}` are both named `{name}`{}: rename one",
of_set(set)
)
}
}
fn of_set(set: Option<&str>) -> String {
set.map(|s| format!(" in `{s}`")).unwrap_or_default()
}
pub fn declarations(registry: &Registry, omit: &[&str]) -> String {
let specs = registry.specs();
let modules = registry.module_specs();
let classes = registry.class_specs();
use std::fmt::Write as _;
let mut out = String::new();
let doc = |out: &mut String, indent: &str, doc: &str| {
if !doc.is_empty() {
let _ = writeln!(out, "{indent}/** {doc} */");
}
};
let mut types = TsTypes::default();
for spec in &specs {
types.merge(&spec.types);
}
for m in &modules {
types.merge(&m.types);
}
for c in &classes {
types.merge(&c.types);
}
for declaration in types.declarations() {
let _ = write!(out, "{declaration}\n\n");
}
let module_of = |name: &str| modules.iter().find(|m| m.name == name);
let signatures = |f: &FunctionSpec| {
let one = |params: &[(&str, String, bool)], returns: &Option<String>| {
let params = params
.iter()
.map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
.collect::<Vec<_>>()
.join(", ");
let value = returns.clone().unwrap_or_else(|| "void".to_owned());
let returns = if f.promises() {
format!("Promise<{value}>")
} else {
value
};
(params, returns)
};
if f.overloads.is_empty() {
vec![one(&f.params, &f.returns)]
} else {
f.overloads
.iter()
.map(|(params, returns)| one(params, returns))
.collect()
}
};
let module_object = |out: &mut String, m: &ModuleSpec| {
out.push_str("{\n");
for f in &m.functions {
for (params, returns) in signatures(f) {
doc(out, " ", f.doc);
if f.getter {
let _ = writeln!(out, " readonly {}: {returns};", f.name);
continue;
}
let _ = writeln!(out, " {}({params}): {returns};", f.name);
}
}
for constant in &m.constants {
doc(out, " ", constant.doc);
let _ = writeln!(
out,
" readonly {}: {};",
constant.name,
constant.value.ts_type()
);
}
out.push('}');
};
for spec in &specs {
let (generic, params, extends) = match spec.items() {
Some(_) => ("<T>", "<T>", ", ListItemsProps<T>"),
None if spec.generic => ("<T>", "<T = any>", ""),
None => ("", "", ""),
};
let mut omit: Vec<&str> = HOST_PROPS
.iter()
.copied()
.filter(|&h| !spec.host_props().any(|p| p == h))
.collect();
if !spec.methods.is_empty() {
omit.insert(0, "ref");
}
let host = if omit.is_empty() {
"ComponentHostProps".to_owned()
} else {
let names = omit.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>();
format!("Omit<ComponentHostProps, {}>", names.join(" | "))
};
if !spec.methods.is_empty() {
let _ = write!(
out,
"/** The ref of `{0}`: its methods. */\nexport interface {0}Ref {{\n /** The component's host node. */\n readonly node: ViewRef;\n",
spec.export
);
for m in &spec.methods {
doc(&mut out, " ", m.doc);
let params = m
.params
.iter()
.map(|(n, ts, optional)| {
format!("{n}{}: {ts}", if *optional { "?" } else { "" })
})
.collect::<Vec<_>>()
.join(", ");
let returns = match &m.returns {
Some(ts) => format!("Promise<{ts}>"),
None => "void".to_owned(),
};
let _ = writeln!(out, " {}({params}): {returns};", m.name);
}
out.push_str("}\n\n");
}
let _ = writeln!(
out,
"export interface {}Props{params} extends {host}{extends} {{",
spec.export
);
if !spec.methods.is_empty() {
let _ = writeln!(
out,
" ref?: {0}Ref | ((ref: {0}Ref) => void);",
spec.export
);
}
for p in spec.props.iter().filter(|p| p.kind != PropKind::Items) {
doc(&mut out, " ", p.doc);
let optional = if p.optional { "?" } else { "" };
let _ = writeln!(out, " {}{optional}: {};", p.name, p.ts);
}
for e in &spec.events {
doc(&mut out, " ", e.doc);
let handler = handler_name(e.name);
let arg = if e.data == "void" {
String::new()
} else {
format!("{}: {}", e.arg, e.data)
};
let _ = writeln!(out, " {handler}?: ({arg}) => void;");
}
out.push_str("}\n\n");
if omit.contains(&spec.export.as_str()) {
continue;
}
doc(&mut out, "", spec.doc);
let mut with = String::new();
if let Some(m) = module_of(&spec.export) {
with.push_str(" & ");
module_object(&mut with, m);
}
let _ = write!(
out,
"export declare const {}: ({params}(props: {}Props{generic}) => JSX.Element){with};\n\n",
spec.export, spec.export,
);
}
for m in &modules {
if specs.iter().any(|s| s.export == m.name)
|| (!m.flat && registry.function_members(m.name).is_some())
{
continue;
}
if m.flat {
for f in m
.functions
.iter()
.filter(|f| !f.getter && !omit.contains(&f.name))
{
for (params, returns) in signatures(f) {
doc(&mut out, "", f.doc);
let _ = writeln!(
out,
"export declare function {}({params}): {returns};",
f.name
);
}
if let Some(members) = registry.function_members(f.name) {
let _ = writeln!(out, "export declare namespace {} {{", f.name);
for member in &members.functions {
for (params, returns) in signatures(member) {
doc(&mut out, " ", member.doc);
let _ = if member.getter {
writeln!(out, " const {}: {returns};", member.name)
} else {
writeln!(out, " function {}({params}): {returns};", member.name)
};
}
}
for constant in &members.constants {
doc(&mut out, " ", constant.doc);
let _ = writeln!(
out,
" const {}: {};",
constant.name,
constant.value.ts_type()
);
}
out.push_str("}\n");
}
out.push('\n');
}
for constant in &m.constants {
if !omit.contains(&constant.name) {
doc(&mut out, "", constant.doc);
let _ = writeln!(
out,
"export declare const {}: {};\n",
constant.name,
constant.value.ts_type()
);
}
}
if m.default && !omit.contains(&"default") {
let _ = write!(out, "declare const defaultExport: ");
module_object(&mut out, m);
for native in registry.native_value_names() {
let _ = write!(out, " & {{ {native}: typeof {native} }}");
}
out.push_str(";\nexport default defaultExport;\n\n");
}
continue;
}
doc(&mut out, "", m.doc);
let _ = write!(out, "export interface {}Module ", m.name);
module_object(&mut out, m);
out.push_str("\n\n");
if !omit.contains(&m.name) {
doc(&mut out, "", m.doc);
let _ = write!(out, "export declare const {0}: {0}Module;\n\n", m.name);
}
if m.default && !omit.contains(&"default") {
let _ = write!(
out,
"declare const defaultExport: {}Module;\nexport default defaultExport;\n\n",
m.name
);
}
}
for c in classes.iter().filter(|c| !omit.contains(&c.name)) {
class_declaration(&mut out, c);
}
out
}
fn class_declaration(out: &mut String, c: &ClassSpec) {
use std::fmt::Write as _;
let doc = |out: &mut String, indent: &str, doc: &str| {
if !doc.is_empty() {
let _ = writeln!(out, "{indent}/** {doc} */");
}
};
doc(out, "", c.doc);
if c.def.interface {
let _ = writeln!(out, "export interface {} {{", c.name);
for m in &c.members {
let params = m
.params
.iter()
.map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
.collect::<Vec<_>>()
.join(", ");
let value = m.returns.clone().unwrap_or_else(|| "void".to_owned());
let returns = if m.is_async {
format!("Promise<{value}>")
} else {
value
};
doc(out, " ", m.doc);
let has_setter = |name| {
c.members
.iter()
.any(|s| s.kind == MemberKind::Setter && s.name == name)
};
let _ = match m.kind {
MemberKind::Method => writeln!(out, " {}({params}): {returns};", m.name),
MemberKind::Getter if has_setter(m.name) => {
writeln!(out, " {}: {returns};", m.name)
}
MemberKind::Getter => writeln!(out, " readonly {}: {returns};", m.name),
_ => Ok(()),
};
}
out.push_str("}\n\n");
return;
}
let _ = writeln!(out, "export declare class {} {{", c.name);
if !c.members.iter().any(|m| m.kind == MemberKind::Constructor) {
out.push_str(" /** Made by the class's members only. */\n private constructor();\n");
}
let one = |m: &super::MemberSpec, params: &[(&str, String, bool)], returns: &Option<String>| {
let params = params
.iter()
.map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
.collect::<Vec<_>>()
.join(", ");
let value = returns.clone().unwrap_or_else(|| "void".to_owned());
let returns = if m.is_async {
format!("Promise<{value}>")
} else {
value
};
(params, returns)
};
for m in &c.members {
if !m.overloads.is_empty() {
for (params, returns) in &m.overloads {
doc(out, " ", m.doc);
let (params, returns) = one(m, params, returns);
let _ = match m.kind {
MemberKind::Static => {
writeln!(out, " static {}({params}): {returns};", m.name)
}
_ => writeln!(out, " {}({params}): {returns};", m.name),
};
}
continue;
}
doc(out, " ", m.doc);
let (params, returns) = one(m, &m.params, &m.returns);
let _ = match m.kind {
MemberKind::Constructor => writeln!(out, " constructor({params});"),
MemberKind::Method => writeln!(out, " {}({params}): {returns};", m.name),
MemberKind::Getter => writeln!(out, " get {}(): {returns};", m.name),
MemberKind::Setter => writeln!(out, " set {}({params});", m.name),
MemberKind::Static => writeln!(out, " static {}({params}): {returns};", m.name),
};
}
out.push_str(
" /** Frees the Rust value now (else when the object is collected); the object throws after. */\n dispose(): void;\n [Symbol.dispose](): void;\n}\n\n",
);
}
fn handler_name(event: &str) -> String {
let mut chars = event.chars();
match chars.next() {
Some(first) => format!("on{}{}", first.to_ascii_uppercase(), chars.as_str()),
None => "on".to_owned(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::prelude::*;
#[test]
fn by_name_marker_names_the_stand_in_make() {
let name = std::any::type_name_of_val(&missing_instance);
assert!(
name.ends_with(&format!("::{BY_NAME_MARKER}")),
"{name} is not {BY_NAME_MARKER}: update nsh-cli's by-name detection"
);
}
#[component]
fn ByName() -> impl IntoElement {
text("by name")
}
#[test]
fn a_component_made_by_name_has_the_marked_make() {
let mut element = crate::element::ComponentElement::<ByName>::named(());
let crate::element::ElKind::Component(c) = &element.node().kind else {
panic!("not a component element");
};
assert!(std::ptr::fn_addr_eq(
c.make,
missing_instance as fn() -> Box<dyn AnyInstance>
));
}
#[derive(Default)]
struct Stepper;
#[derive(Clone, PartialEq, Props)]
struct StepperProps {
value: f64,
#[prop(default)]
size: StepperSize,
max_value: Option<f64>,
label: Option<Slot>,
children: Children,
}
#[derive(Clone, Copy, PartialEq, Default, PropEnum)]
enum StepperSize {
#[default]
Regular,
ExtraLarge,
}
#[derive(Event)]
enum StepperEvent {
Change {
new_value: f64,
},
#[args(limit)]
Limit(u32),
Reset,
}
struct StepperApi;
#[methods]
impl StepperApi {
pub(crate) fn jump_to(&self, value: f64) {
let _ = value;
}
pub(crate) fn value(&self) -> f64 {
0.0
}
#[allow(dead_code)]
fn clamp(&self, value: f64) -> f64 {
value
}
}
impl Component for Stepper {
type Props = StepperProps;
type Event = StepperEvent;
const METHODS: Methods = Methods::of::<StepperApi>();
const DOC: &'static str = "Picks a number.";
fn view(_: StepperProps, _: super::super::Scope<StepperEvent>) -> impl IntoElement {
view()
}
}
#[test]
fn the_declarations_come_from_the_types() {
let mut registry = Registry::new();
registry.register::<Stepper>();
let ts = declarations(®istry, &[]);
for line in [
" /** The value. */\n value: number;",
"export type StepperSize = \"regular\" | \"extraLarge\";",
" size?: StepperSize;",
" maxValue?: number | null;",
" /** Above the control. */\n label?: JSX.Element;",
" children?: JSX.Element;",
" /** The value changed. */\n onChange?: (event: { newValue: number }) => void;",
" onLimit?: (event: { limit: number }) => void;",
" onReset?: () => void;",
"/** Picks a number. */",
"export interface StepperRef {",
" /** Jumps to `value`. */\n jumpTo(value: number): void;",
" value(): Promise<number>;",
"export interface StepperProps extends Omit<ComponentHostProps, \"ref\"> {\n ref?: StepperRef | ((ref: StepperRef) => void);",
"export declare const Stepper: ((props: StepperProps) => JSX.Element);",
] {
assert!(ts.contains(line), "missing {line:?} in\n{ts}");
}
assert!(!ts.contains("clamp"), "a helper is not a method:\n{ts}");
assert_eq!(StepperApi::METHODS.len(), 2);
let mut props = StepperProps::initial();
let size = |json| {
let specs = StepperProps::spec(&mut TsTypes::default());
let decode = specs
.iter()
.find(|p| p.name == "size")
.unwrap()
.decode
.unwrap();
super::super::json_host::decode(decode, json)
};
assert!(
props
.set("size", Some(size(serde_json::json!("extraLarge")).unwrap()))
.unwrap()
);
assert!(props.size == StepperSize::ExtraLarge);
assert!(size(serde_json::json!("huge")).is_err());
assert!(props.set("size", Some(AnyValue::new(1.0f64))).is_err());
assert!(props.set("size", None).unwrap());
assert!(props.size == StepperSize::Regular);
let data = |e: &StepperEvent| super::super::json_host::event_data(e);
assert_eq!(
data(&StepperEvent::Change { new_value: 2.5 }),
Some(serde_json::json!({ "newValue": 2.5 }))
);
assert_eq!(
data(&StepperEvent::Limit(3)),
Some(serde_json::json!({ "limit": 3 }))
);
assert_eq!(data(&StepperEvent::Reset), None);
assert_eq!(StepperEvent::Reset.name(), "reset");
}
#[test]
fn exports_without_docs_are_listed() {
let mut registry = Registry::new();
registry.register::<Stepper>();
assert_eq!(
registry.undocumented(),
[
"Stepper.size",
"Stepper.maxValue",
"Stepper.children",
"Stepper.onLimit",
"Stepper.onReset",
"Stepper.value",
]
);
let mut r = Registry::ui_set("test/maker");
r.module::<Maker>();
assert_eq!(r.undocumented(), ["Maker.make", "new Lonely"]);
}
#[crate::element::class]
struct Lonely;
#[crate::element::class]
impl Lonely {
pub(crate) fn new() -> Self {
Lonely
}
}
#[crate::element::module]
struct Maker;
#[crate::element::module]
impl Maker {
pub(crate) fn make() -> Instance<Lonely> {
Instance::new(Lonely)
}
}
#[test]
fn the_classes_a_signature_names_are_registered_with_it() {
let mut r = Registry::ui_set("test/maker");
r.module::<Maker>();
let names: Vec<_> = r.class_specs().iter().map(|c| c.name).collect();
assert_eq!(names, ["Lonely"]);
let ts = declarations(&r, &[]);
assert!(ts.contains("export declare class Lonely"), "{ts}");
assert!(ts.contains("make(): Lonely;"), "{ts}");
r.class::<Lonely>();
assert_eq!(r.class_specs().len(), 1);
let _ = Registry::merged(&[r]);
}
#[crate::element::module]
struct Checks;
#[crate::element::module(flat)]
impl Checks {
pub(crate) fn check(name: String) {
let _ = name;
}
}
#[crate::element::module]
struct CheckVariants;
#[crate::element::module(name = "check")]
impl CheckVariants {
pub(crate) const COUNT: u32 = 2;
pub(crate) fn skip(name: String) {
let _ = name;
}
pub(crate) fn todo(name: String) {
let _ = name;
}
}
#[crate::element::module]
struct Loose;
#[crate::element::module(name = "loose")]
impl Loose {
pub(crate) fn nothing() {}
}
#[test]
fn a_module_named_like_a_function_puts_its_functions_on_it() {
let mut r = Registry::ui_set("test/checks");
r.module::<Checks>()
.module::<CheckVariants>()
.module::<Loose>();
assert_eq!(r.function_members("check").unwrap().name, "check");
assert!(r.function_members("loose").is_none());
let ts = declarations(&r, &[]);
assert!(
ts.contains(
"/** Declares a check. */\n\
export declare function check(name: string): void;\n\
export declare namespace check {\n \
/** Declares a check that does not run. */\n \
function skip(name: string): void;\n \
function todo(name: string): void;\n \
/** How many variants there are. */\n \
const COUNT: number;\n}\n"
),
"{ts}"
);
assert!(
!ts.contains("CheckVariants") && !ts.contains("checkModule"),
"{ts}"
);
assert!(
ts.contains("export declare const loose: looseModule;"),
"{ts}"
);
assert_eq!(r.undocumented(), ["check.todo"]);
let described = super::super::description::SetDescription::of(&r).unwrap();
let exports: Vec<_> = described
.exports
.iter()
.map(|e| (e.name.as_str(), e.kind))
.collect();
assert_eq!(
exports,
[
("check", super::super::description::ExportKind::Function),
("loose", super::super::description::ExportKind::Module)
]
);
}
mod clash {
#[crate::element::class]
pub(super) struct Lonely;
#[crate::element::class]
impl Lonely {
pub(super) fn new() -> Self {
Lonely
}
}
}
#[test]
fn a_clash_through_a_signature_names_both_types() {
let mut r = Registry::ui_set("test/maker");
r.class::<clash::Lonely>();
let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
r.module::<Maker>();
}))
.unwrap_err();
let message = failed.downcast_ref::<String>().unwrap();
assert!(
message.contains("`nsh_core::element::component::tests::clash::Lonely`")
&& message.contains("`nsh_core::element::component::tests::Lonely`"),
"{message}"
);
}
#[test]
fn components_are_named_after_their_types() {
let mut registry = Registry::ui_set("test/ui");
registry.register::<Stepper>();
let specs = registry.specs();
assert_eq!(
specs[0].name,
"nsh_core::element::component::tests::Stepper"
);
assert_eq!(specs[0].export, "Stepper");
assert_eq!(export_name("app::picker::Picker<app::Fruit>"), "Picker");
assert_eq!(export_name("Bare"), "Bare");
}
mod other {
use crate::prelude::*;
#[derive(Default)]
pub(super) struct Stepper;
impl Component for Stepper {
type Props = ();
type Event = NoEvent;
fn view(_: (), _: crate::element::Scope<NoEvent>) -> impl IntoElement {
view()
}
}
}
#[test]
#[should_panic(
expected = "components `nsh_core::element::component::tests::Stepper` and `nsh_core::element::component::tests::other::Stepper` are both exported as `Stepper` in `test/ui`"
)]
fn two_components_of_one_set_cannot_share_an_export() {
Registry::ui_set("test/ui")
.register::<Stepper>()
.register::<other::Stepper>();
}
#[test]
#[should_panic(
expected = "component `nsh_core::element::component::tests::Stepper` is registered twice"
)]
fn a_component_is_registered_once() {
Registry::new().register::<Stepper>().register::<Stepper>();
}
#[test]
fn a_sets_submodules_come_with_it() {
let mut sub = Registry::ui_set("test/set/sub");
sub.register::<Stepper>();
let mut set = Registry::ui_set("test/set");
set.submodule(sub);
let specifiers: Vec<_> = set.sets().iter().map(|s| s.specifier()).collect();
assert_eq!(specifiers, [Some("test/set"), Some("test/set/sub")]);
assert_eq!(Registry::merged(&[set]).specs().len(), 1);
let elsewhere = std::panic::catch_unwind(|| {
Registry::ui_set("test/set").submodule(Registry::ui_set("test/settings"));
});
assert!(elsewhere.is_err());
}
#[test]
fn sets_may_share_exports_but_not_components() {
let mut a = Registry::ui_set("test/a");
a.register::<Stepper>();
let mut b = Registry::ui_set("test/b");
b.register::<other::Stepper>();
let merged = Registry::merged(&[a.clone(), b]);
assert_eq!(merged.specs().len(), 2);
let twice = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
Registry::merged(&[a.clone(), a])
}));
let message = *twice.unwrap_err().downcast::<String>().unwrap();
assert_eq!(
message,
"component `nsh_core::element::component::tests::Stepper` is registered twice, by two UI sets"
);
}
struct NoFake;
impl crate::fake::Fake for NoFake {
fn install(&self) {}
fn call(&self, _: &str, _: &[crate::JsonValue]) -> Result<crate::JsonValue, String> {
Ok(crate::JsonValue::Null)
}
}
#[test]
fn fake_names_are_unique_across_sets() {
let mut a = Registry::ui_set("test/a");
a.fake("test/mic", Arc::new(NoFake));
let mut b = Registry::ui_set("test/b");
b.fake("test/camera", Arc::new(NoFake));
let names: Vec<_> = Registry::merged(&[a.clone(), b])
.fakes()
.into_iter()
.map(|(name, _)| name)
.collect();
assert_eq!(names, ["test/mic", "test/camera"]);
let mut c = Registry::ui_set("test/c");
c.fake("test/mic", Arc::new(NoFake));
let twice =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Registry::merged(&[a, c])));
let message = *twice.unwrap_err().downcast::<String>().unwrap();
assert_eq!(message, "two fakes are named `test/mic`, by two UI sets");
}
}
#[cfg(test)]
mod root_tests {
use super::Root;
use crate::{access::Capabilities, prelude::*};
#[component]
fn Empty() -> impl IntoElement {
view()
}
#[test]
fn a_root_reads_its_declared_capabilities_as_packages_are_read() {
assert_eq!(Root::of::<Empty>().capabilities_ref(), None);
let root = Root::of::<Empty>().capabilities_json(r#"{"clipboard":true,"bluetooth":true}"#);
let expected = Capabilities {
clipboard: true,
..Capabilities::default()
};
assert_eq!(root.capabilities_ref(), Some(&expected));
let root = Root::of::<Empty>().capabilities_json("not json");
assert_eq!(root.capabilities_ref(), Some(&Capabilities::default()));
}
}