#![allow(missing_docs, clippy::unwrap_used, clippy::expect_used)] use std::sync::Arc;
use oxblade::{
Shape, View,
attributes::{AttributeBag, AttributeValue},
engine::{Environment, Limits, Options},
error::ErrorKind,
loader::{Loader, Source, missing_view},
render::components::{ComponentContext, Output, Slots},
value::{Value, ValueMap},
};
use serde::{Deserialize, Serialize};
struct Views(&'static [(&'static str, &'static str)]);
impl Loader for Views {
fn load(&self, name: &str) -> oxblade::error::Result<Source> {
self.0
.iter()
.find(|(view, _)| *view == name)
.map(|&(_, source)| Source::new(name, source))
.ok_or_else(|| missing_view(name))
}
}
#[derive(Clone, Default)]
struct Theme(&'static str);
#[derive(Deserialize, Shape)]
struct Card {
level: u8,
#[serde(default = "Card::default_title")]
title: String,
#[serde(default)]
hidden: bool,
#[serde(skip)]
#[inject]
theme: Arc<Theme>,
}
#[derive(Serialize)]
struct CardView {
heading_text: String,
}
#[oxblade::component("card", except = [hidden, secret])]
impl Card {
fn default_title() -> String {
"Default".into()
}
fn should_render(&self) -> bool {
!self.hidden
}
fn with_attributes(&self, attrs: &mut AttributeBag) {
attrs.offset_set("data-theme", AttributeValue::Text(self.theme.0.into()));
}
#[expose]
fn label(&self, suffix: &str) -> String {
format!("{}{}", self.title, suffix)
}
#[expose]
#[allow(dead_code)]
fn secret(&self) -> &'static str {
"secret"
}
fn view(&self, slots: &Slots<'_, '_>, theme: &Arc<Theme>) -> CardView {
CardView {
heading_text: format!("{} {}", theme.0, slots.text("heading")),
}
}
fn template() -> &'static str {
"<h{{ level }} {{ attributes }}>{{ heading_text }}:{{ label('?') }} [{{ hidden ?? 'excluded' }}|{{ secret ?? 'excluded' }}|{{ slot }}]</h{{ level }}>"
}
}
#[derive(Deserialize, Shape)]
struct Icon {
size: u8,
}
#[oxblade::component("icon")]
impl Icon {
fn render(
&self,
cx: &ComponentContext<'_, '_>,
out: &mut Output,
) -> oxblade::error::Result<()> {
out.raw("<svg data-size=\"")?;
out.escaped(&self.size.to_string())?;
out.raw("\" ")?;
out.raw(&cx.attributes().to_html().unwrap())?;
out.raw("></svg>")
}
}
#[derive(Deserialize, Shape)]
struct Closure {
value: String,
}
#[oxblade::component("closure")]
impl Closure {
fn render(&self, _data: &ValueMap<'_>) -> impl FnOnce(&ValueMap<'_>) -> String + '_ {
|data| format!("<b>{}{}</b>", self.value, data["slot"].display().unwrap())
}
}
#[oxblade::component("struct-only", except = [ignored])]
#[derive(Deserialize, Shape)]
struct StructOnly {
value: u8,
#[serde(default)]
ignored: bool,
}
#[test]
fn class_lifecycle_and_slots_are_run_in_the_caller() {
let environment = Environment::builder(Views(&[(
"main",
concat!(
"@let(component = 'original')",
"<x-card level=\"8\" :hidden=\"true\">@push('s')hidden @endpush</x-card>",
"<x-card level=\"3\" id=\"hello\">",
"<x-slot:heading>@let(after = component.title){{ component.label('!') }}</x-slot:heading>",
"Hi</x-card>{{ after }}:{{ component }}@stack('s')"
),
)]))
.component(Card::OXBLADE_COMPONENT)
.component_service(Arc::new(Theme("dark")))
.build();
assert_eq!(
environment.render("main", ValueMap::new()).unwrap(),
"<h3 id=\"hello\" data-theme=\"dark\">dark Default!:Default? [excluded|excluded|Hi]</h3>Default:original",
);
}
#[test]
fn class_registration_and_direct_rendering_precede_anonymous_loading() {
let env = Environment::builder(Views(&[
("main", r#"<x-dynamic-component component="pkg::icon" size="15" class="i" /><x:renamed value="4"/><x-closure value="start">end</x-closure>"#),
("components.struct-only", "{{ value + 1 }}:{{ ignored ?? 'excluded' }}"),
("pkg::icon", "anonymous"),
]))
.component_namespace("pkg", [Icon::OXBLADE_COMPONENT])
.components([StructOnly::OXBLADE_COMPONENT, Closure::OXBLADE_COMPONENT])
.alias_component("struct-only", "renamed")
.build();
assert_eq!(
env.render("main", ValueMap::new()).unwrap(),
r#"<svg data-size="15" class="i"></svg>5:excluded<b>startend</b>"#,
);
}
#[test]
fn direct_render_obeys_the_output_limit_and_reports_the_call_site() {
let env = Environment::builder(Views(&[("main", "<x-icon size=\"15\"/>")]))
.component(Icon::OXBLADE_COMPONENT)
.options(Options {
limits: Limits {
output: 8,
..Limits::default()
},
..Options::default()
})
.build();
let error = env.render("main", ValueMap::new()).unwrap_err();
assert_eq!(error.kind, ErrorKind::Limit);
assert_eq!(error.chain.last().unwrap().name, "icon");
assert!(error.message.contains("main:1:1"));
}
#[test]
fn literal_props_are_coerced_and_bound_strings_are_not() {
let env = Environment::builder(Views(&[
("main", "<x-icon :size=\"'15'\"/>"),
("anonymous", "<x-item level=\"3\" />"),
("overflow", "<x-item level=\"256\" />"),
("components.item", "@props(level: u8){{ level + 1 }}"),
]))
.component(Icon::OXBLADE_COMPONENT)
.build();
assert!(env.render("main", ValueMap::new()).is_err());
assert_eq!(env.render("anonymous", ValueMap::new()).unwrap(), "4");
assert!(env.render("overflow", ValueMap::new()).is_err());
}
#[derive(Deserialize, Serialize, Shape)]
struct Destination {
name: String,
}
#[oxblade::methods]
impl Destination {
pub fn format(&self, suffix: &str) -> String {
format!("{}{}", self.name, suffix)
}
}
#[derive(Deserialize)]
struct Venue {
name: String,
}
#[oxblade::methods]
impl Venue {
pub fn format(&self, suffix: &str) -> String {
format!("venue {}{}", self.name, suffix)
}
}
#[derive(Serialize, Shape, View)]
#[view("model")]
struct Trip {
city: Destination,
stops: Vec<Destination>,
}
#[test]
fn receivers_dispatch_by_declared_type_or_unique_method() {
let row = serde_json::json!({"name": "Lisbon"});
let input = ValueMap::from([("city".into(), Value::Json(&row))]);
let views = Views(&[
("typed", "@props(city: Destination){{ city.format('!') }}"),
("untyped", "{{ city.format('?') }}{{ city.format('!') }}"),
("model", "{{ city.format('!') }}{{ stops[0].format('?') }}"),
]);
let env = Environment::builder(views)
.methods([Destination::OXBLADE_METHODS, Venue::OXBLADE_METHODS])
.build();
assert_eq!(env.render("typed", input.clone()).unwrap(), "Lisbon!");
assert!(
env.render("untyped", input.clone())
.unwrap_err()
.message
.contains("ambiguous")
);
let trip = Trip {
city: Destination {
name: "Lisbon".into(),
},
stops: vec![Destination {
name: "Porto".into(),
}],
};
assert_eq!(env.render_model(&trip).unwrap(), "Lisbon!Porto?");
let env = Environment::builder(Views(&[(
"untyped",
"{{ city.format('?') }}{{ city.format('!') }}",
)]))
.methods([Destination::OXBLADE_METHODS])
.build();
assert_eq!(env.render("untyped", input).unwrap(), "Lisbon?Lisbon!");
}
#[test]
fn disabling_component_tags_keeps_markup_and_compiles_echoes() {
let env = Environment::builder(Views(&[("main", "<x-card>{{ 'text' }}</x-card>")]))
.without_component_tags()
.build();
assert_eq!(
env.render("main", ValueMap::new()).unwrap(),
"<x-card>text</x-card>"
);
}
#[test]
fn the_component_attribute_echo_escapes_once() {
let env = Environment::builder(Views(&[
(
"main",
r#"<x-item name="{{ label }}" title="{{ label }}"/>"#,
),
(
"components.item",
"@props(name: String)<b {{ attributes }}>{{ name }}</b>",
),
]))
.build();
let data = ValueMap::from([("label".into(), Value::string("Tom & Jerry"))]);
assert_eq!(
env.render("main", data).unwrap(),
r#"<b title="Tom & Jerry">Tom & Jerry</b>"#,
);
}
#[test]
fn anonymous_path_and_namespace_resolve_index_components() {
let views = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../conformance/cases/components/lookup-and-dynamic-slots/views");
let env = Environment::builder(oxblade::loader::FilesystemLoader::new(&views))
.anonymous_component_path(views.join("packages"), "pkg")
.anonymous_component_namespace("packages", "logical")
.build();
for name in ["pkg::group", "logical::group"] {
assert_eq!(
env.render_component(name, ValueMap::new()).unwrap(),
"<b></b>"
);
}
}