use std::{borrow::Cow, fmt, ops::Index};
use indexmap::IndexMap;
use crate::encode::{ArrayKey, Entries, JsonKind, JsonValue, e};
pub type Attributes = IndexMap<String, AttributeValue>;
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub enum AttributeValue {
#[default]
Null,
Bool(bool),
Integer(i64),
Float(f64),
Text(String),
Html(String),
Stringable(String),
Escapable {
text: String,
escape: bool,
},
Array(Attributes),
Prepended(Box<AttributeValue>),
}
impl From<&str> for AttributeValue {
fn from(value: &str) -> Self {
Self::Text(value.to_owned())
}
}
impl From<String> for AttributeValue {
fn from(value: String) -> Self {
Self::Text(value)
}
}
impl AttributeValue {
pub(crate) fn depth_within(&self, remaining: usize) -> bool {
match self {
Self::Array(values) => {
remaining > 0
&& values
.values()
.all(|value| value.depth_within(remaining - 1))
}
Self::Prepended(value) => remaining > 0 && value.depth_within(remaining - 1),
_ => true,
}
}
fn php_string(&self) -> Result<Cow<'_, str>, AttributeError> {
Ok(match self {
Self::Text(text) | Self::Html(text) | Self::Stringable(text) => Cow::Borrowed(text),
Self::Escapable { text, escape: true } => Cow::Owned(e(text)),
Self::Escapable {
text,
escape: false,
} => Cow::Borrowed(text),
Self::Null | Self::Bool(false) => Cow::Borrowed(""),
Self::Bool(true) => Cow::Borrowed("1"),
Self::Integer(number) => Cow::Owned(number.to_string()),
Self::Float(number) => Cow::Owned(php_float(*number)),
Self::Prepended(value) => value.php_string()?,
Self::Array(_) => return Err(AttributeError::ArrayAsText),
})
}
fn truthy(&self) -> bool {
match self {
Self::Null | Self::Bool(false) | Self::Integer(0) => false,
Self::Float(value) => *value != 0.0,
Self::Text(value) => !matches!(value.as_str(), "" | "0"),
Self::Array(values) => !values.is_empty(),
_ => true,
}
}
fn escape_default(&self, escape: bool) -> Result<Self, AttributeError> {
Ok(match self {
Self::Text(_) | Self::Integer(_) | Self::Float(_) | Self::Array(_) if escape => {
Self::Text(e(&self.php_string()?))
}
value => value.clone(),
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum AttributeError {
ArrayAsText,
InvalidName,
OutputLimit,
}
impl fmt::Display for AttributeError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::ArrayAsText => "an array cannot be printed as an HTML attribute",
Self::InvalidName => "invalid attribute name",
Self::OutputLimit => "render output limit exceeded while writing attributes",
})
}
}
impl std::error::Error for AttributeError {}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub enum CssEntry<'a> {
Always(&'a str),
If(&'a str, bool),
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AttributeBag {
attributes: Attributes,
}
impl AttributeBag {
pub(crate) fn check_data_depth(&mut self) -> crate::error::Result<()> {
if self
.attributes
.values()
.all(|value| value.depth_within(crate::value::MAX_OWNED_DATA_DEPTH))
{
return Ok(());
}
let mut pending = std::mem::take(&mut self.attributes)
.into_values()
.collect::<Vec<_>>();
while let Some(value) = pending.pop() {
match value {
AttributeValue::Array(values) => pending.extend(values.into_values()),
AttributeValue::Prepended(value) => pending.push(*value),
_ => {}
}
}
Err(crate::library::data_depth_error())
}
pub fn new(attributes: Attributes) -> Self {
Self { attributes }
}
pub fn all(&self) -> &Attributes {
&self.attributes
}
pub fn all_for(&self, keys: &[&str]) -> Attributes {
self.only(keys).attributes
}
pub fn first(&self) -> Option<&AttributeValue> {
self.attributes
.first()
.map(|(_, value)| value)
.filter(|value| !matches!(value, AttributeValue::Null))
}
pub fn get(&self, key: &str) -> Option<&AttributeValue> {
self.attributes
.get(key)
.filter(|value| !matches!(value, AttributeValue::Null))
}
pub fn get_or_else(
&self,
key: &str,
default: impl FnOnce() -> AttributeValue,
) -> AttributeValue {
self.get(key).cloned().unwrap_or_else(default)
}
pub fn first_or_else(&self, default: impl FnOnce() -> AttributeValue) -> AttributeValue {
self.first().cloned().unwrap_or_else(default)
}
pub fn only(&self, keys: &[&str]) -> Self {
self.filter(|_, key| keys.contains(&key))
}
pub fn except(&self, keys: &[&str]) -> Self {
let mut attributes = self.attributes.clone();
for key in keys {
remove_path(&mut attributes, key);
}
Self::new(attributes)
}
pub fn filter(&self, mut predicate: impl FnMut(&AttributeValue, &str) -> bool) -> Self {
Self::new(
self.attributes
.iter()
.filter(|(key, value)| predicate(value, key))
.map(|(key, value)| (key.clone(), value.clone()))
.collect(),
)
}
pub fn where_starts_with(&self, prefixes: &[&str]) -> Self {
self.filter(|_, key| starts_with(key, prefixes))
}
pub fn where_doesnt_start_with(&self, prefixes: &[&str]) -> Self {
self.filter(|_, key| !starts_with(key, prefixes))
}
pub fn that_start_with(&self, prefixes: &[&str]) -> Self {
self.where_starts_with(prefixes)
}
pub fn extract_prop_names(names: &[&str]) -> Vec<String> {
names
.iter()
.flat_map(|name| [(*name).to_owned(), kebab(name)])
.collect()
}
pub fn only_props(&self, names: &[&str]) -> Self {
let props = Self::extract_prop_names(names);
self.filter(|_, key| props.iter().any(|prop| prop == key))
}
pub fn except_props(&self, names: &[&str]) -> Self {
let props = Self::extract_prop_names(names);
self.except(&props.iter().map(String::as_str).collect::<Vec<_>>())
}
pub fn has(&self, keys: &[&str]) -> bool {
keys.iter().all(|key| has_path(&self.attributes, key))
}
pub fn has_any(&self, keys: &[&str]) -> bool {
keys.iter().any(|key| has_path(&self.attributes, key))
}
pub fn missing(&self, keys: &[&str]) -> bool {
!self.has(keys)
}
pub fn when<T: From<Self>>(
&self,
condition: bool,
callback: impl FnOnce(&Self, bool) -> Option<T>,
) -> T {
self.when_else(condition, callback, |_, _| None)
}
pub fn unless<T: From<Self>>(
&self,
condition: bool,
callback: impl FnOnce(&Self, bool) -> Option<T>,
) -> T {
self.unless_else(condition, callback, |_, _| None)
}
pub fn when_else<T: From<Self>>(
&self,
condition: bool,
callback: impl FnOnce(&Self, bool) -> Option<T>,
default: impl FnOnce(&Self, bool) -> Option<T>,
) -> T {
let result = if condition {
callback(self, condition)
} else {
default(self, condition)
};
result.unwrap_or_else(|| self.clone().into())
}
pub fn unless_else<T: From<Self>>(
&self,
condition: bool,
callback: impl FnOnce(&Self, bool) -> Option<T>,
default: impl FnOnce(&Self, bool) -> Option<T>,
) -> T {
self.when_else(condition, default, callback)
}
pub fn prepends(&self, value: impl Into<AttributeValue>) -> AttributeValue {
match value.into() {
value @ AttributeValue::Prepended(_) => value,
value => AttributeValue::Prepended(Box::new(value)),
}
}
pub fn class(&self, entries: &[CssEntry<'_>]) -> Result<Self, AttributeError> {
self.merge_css("class", entries)
}
pub fn style(&self, entries: &[CssEntry<'_>]) -> Result<Self, AttributeError> {
self.merge_css("style", entries)
}
fn merge_css(&self, key: &str, entries: &[CssEntry<'_>]) -> Result<Self, AttributeError> {
let parts: Vec<_> = entries
.iter()
.filter_map(|entry| match entry {
CssEntry::If(_, false) => None,
CssEntry::Always(text) | CssEntry::If(text, true) if key == "style" => {
Some(finish_style(text))
}
CssEntry::Always(text) | CssEntry::If(text, true) => Some(Cow::Borrowed(*text)),
})
.collect();
self.merge(&[(key.to_owned(), parts.join(" ").into())].into(), true)
}
pub fn merge(&self, defaults: &Attributes, escape: bool) -> Result<Self, AttributeError> {
let defaults: Attributes = defaults
.iter()
.map(|(key, value)| {
validate_name(key)?;
let value = match value {
AttributeValue::Prepended(value) => {
AttributeValue::Prepended(Box::new(value.escape_default(escape)?))
}
value => value.escape_default(escape)?,
};
Ok((key.clone(), value))
})
.collect::<Result<_, AttributeError>>()?;
let (appendable, ordinary): (Vec<_>, Vec<_>) =
self.attributes.iter().partition(|(key, _)| {
matches!(key.as_str(), "class" | "style")
|| matches!(defaults.get(*key), Some(AttributeValue::Prepended(_)))
});
let mut result = Attributes::with_capacity(defaults.len() + self.attributes.len());
let mut next_index = 0;
for (key, value) in &defaults {
insert_merged(&mut result, key, value.clone(), &mut next_index);
}
for (key, value) in appendable {
let default = match defaults.get(key) {
Some(AttributeValue::Prepended(value)) => value.as_ref().clone(),
Some(value) => value.clone(),
None => AttributeValue::Null,
};
let merged = append_attribute(key, &default, value)?;
insert_merged(&mut result, key, merged.into(), &mut next_index);
}
for (key, value) in ordinary {
insert_merged(&mut result, key, value.clone(), &mut next_index);
}
Ok(Self::new(result))
}
pub fn insert_literal(&mut self, name: impl Into<String>, value: impl Into<String>) {
self.attributes
.insert(name.into(), AttributeValue::Text(value.into()));
}
pub fn insert_bound(&mut self, name: impl Into<String>, value: impl Into<AttributeValue>) {
self.attributes
.insert(name.into(), sanitize_component_attribute(value.into()));
}
pub fn forward(&self, parent: &Self) -> Result<Self, AttributeError> {
parent.merge(&self.attributes, false)
}
pub fn get_attributes(&self) -> &Attributes {
self.all()
}
pub fn set_attributes(&mut self, attributes: Attributes) {
self.attributes = attributes;
}
pub fn offset_exists(&self, key: &str) -> bool {
self.get(key).is_some()
}
pub fn offset_get(&self, key: &str) -> Option<&AttributeValue> {
self.get(key)
}
pub fn offset_set(&mut self, key: impl Into<String>, value: impl Into<AttributeValue>) {
self.attributes.insert(key.into(), value.into());
}
pub fn offset_unset(&mut self, key: &str) {
self.attributes.shift_remove(key);
}
pub fn get_iterator(&self) -> indexmap::map::Iter<'_, String, AttributeValue> {
self.attributes.iter()
}
pub fn json_serialize(&self) -> &Attributes {
self.all()
}
pub fn to_array(&self) -> Attributes {
self.attributes.clone()
}
pub fn invoke(&self, defaults: &Attributes) -> Result<String, AttributeError> {
self.merge(defaults, true)?.to_html()
}
pub fn is_empty(&self) -> Result<bool, AttributeError> {
Ok(self.to_html()?.is_empty())
}
pub fn is_not_empty(&self) -> Result<bool, AttributeError> {
Ok(!self.is_empty()?)
}
pub fn to_html(&self) -> Result<String, AttributeError> {
self.to_html_bounded(usize::MAX)
}
pub(crate) fn to_html_bounded(&self, max_bytes: usize) -> Result<String, AttributeError> {
let mut html = String::new();
let mut first = true;
let mut push = |text: &str| {
if text.len() > max_bytes.saturating_sub(html.len()) {
return Err(AttributeError::OutputLimit);
}
html.push_str(text);
Ok(())
};
for (key, value) in &self.attributes {
validate_name(key)?;
let text = match value {
AttributeValue::Null | AttributeValue::Bool(false) => continue,
AttributeValue::Bool(true) if key == "x-data" || key.starts_with("wire:") => {
Cow::Borrowed("")
}
AttributeValue::Bool(true) => Cow::Borrowed(key.as_str()),
value => value.php_string()?,
};
if !first {
push(" ")?;
}
first = false;
push(key)?;
push("=\"")?;
crate::encode::escape_attribute_parts(php_trim(&text), &mut push)?;
push("\"")?;
}
Ok(html)
}
}
impl Index<&str> for AttributeBag {
type Output = AttributeValue;
fn index(&self, key: &str) -> &Self::Output {
self.get(key).unwrap_or(&AttributeValue::Null)
}
}
impl<'a> IntoIterator for &'a AttributeBag {
type Item = (&'a String, &'a AttributeValue);
type IntoIter = indexmap::map::Iter<'a, String, AttributeValue>;
fn into_iter(self) -> Self::IntoIter {
self.get_iterator()
}
}
impl JsonValue for AttributeValue {
fn json_kind(&self) -> JsonKind<'_> {
match self {
Self::Null => JsonKind::Null,
Self::Bool(value) => JsonKind::Bool(*value),
Self::Integer(value) => JsonKind::Integer(*value),
Self::Float(value) => JsonKind::Float(*value),
Self::Text(value) => JsonKind::String(value.as_bytes()),
Self::Html(_) | Self::Stringable(_) | Self::Escapable { .. } => {
JsonKind::Object(Box::new(std::iter::empty()))
}
Self::Array(values) => JsonKind::Array(json_entries(values)),
Self::Prepended(value) => JsonKind::Object(Box::new(std::iter::once((
ArrayKey::from("value"),
value.as_ref() as &dyn JsonValue,
)))),
}
}
}
impl JsonValue for AttributeBag {
fn json_kind(&self) -> JsonKind<'_> {
JsonKind::Array(json_entries(&self.attributes))
}
}
fn json_entries(values: &Attributes) -> Entries<'_> {
Box::new(values.iter().map(|(key, value)| {
let key = integer_key(key).map_or_else(|| ArrayKey::from(key.as_str()), ArrayKey::Integer);
(key, value as &dyn JsonValue)
}))
}
pub fn sanitize_component_attribute(value: AttributeValue) -> AttributeValue {
match value {
AttributeValue::Text(text) | AttributeValue::Stringable(text) => {
AttributeValue::Text(e(&text))
}
AttributeValue::Html(text) => AttributeValue::Text(text),
AttributeValue::Escapable { text, .. } => AttributeValue::Escapable { text, escape: true },
AttributeValue::Prepended(value) => {
AttributeValue::Prepended(Box::new(sanitize_component_attribute(*value)))
}
value => value,
}
}
pub(crate) fn validate_name(name: &str) -> Result<(), AttributeError> {
if name.is_empty()
|| name.bytes().any(|byte| {
byte.is_ascii_control() || byte.is_ascii_whitespace() || b"/=\"'<>".contains(&byte)
})
{
return Err(AttributeError::InvalidName);
}
Ok(())
}
fn append_attribute(
key: &str,
default: &AttributeValue,
value: &AttributeValue,
) -> Result<String, AttributeError> {
let default = match default {
AttributeValue::Text(text) if key == "style" && !text.is_empty() => {
Some(finish_style(text))
}
value if value.truthy() => Some(value.php_string()?),
_ => None,
};
let value = if key == "style" {
Some(Cow::Owned(finish_style(&value.php_string()?).into_owned()))
} else if value.truthy() {
Some(value.php_string()?)
} else {
None
};
Ok(match (default, value) {
(Some(default), Some(value)) if default != value => format!("{default} {value}"),
(Some(text), _) | (_, Some(text)) => text.into_owned(),
(None, None) => String::new(),
})
}
fn finish_style(value: &str) -> Cow<'_, str> {
if value.ends_with(';') && !value.ends_with(";;") {
Cow::Borrowed(value)
} else {
Cow::Owned(format!("{};", value.trim_end_matches(';')))
}
}
fn php_trim(value: &str) -> &str {
value.trim_matches([' ', '\t', '\n', '\r', '\0', '\u{b}'])
}
fn starts_with(key: &str, prefixes: &[&str]) -> bool {
prefixes
.iter()
.any(|prefix| !prefix.is_empty() && key.starts_with(prefix))
}
fn has_path(attributes: &Attributes, key: &str) -> bool {
if attributes.contains_key(key) {
return true;
}
let mut segments = key.split('.').peekable();
let mut current = attributes;
while let Some(segment) = segments.next() {
match current.get(segment) {
Some(_) if segments.peek().is_none() => return true,
Some(AttributeValue::Array(values)) => current = values,
_ => return false,
}
}
false
}
fn remove_path(attributes: &mut Attributes, key: &str) {
if attributes.shift_remove(key).is_some() {
return;
}
let mut segments = key.split('.').peekable();
let mut current = attributes;
while let Some(segment) = segments.next() {
if segments.peek().is_none() {
current.shift_remove(segment);
return;
}
match current.get_mut(segment) {
Some(AttributeValue::Array(values)) => current = values,
_ => return,
}
}
}
fn insert_merged(
attributes: &mut Attributes,
key: &str,
value: AttributeValue,
next_index: &mut usize,
) {
let key = if key
.parse::<i64>()
.is_ok_and(|index| index.to_string() == key)
{
let key = next_index.to_string();
*next_index += 1;
key
} else {
key.to_owned()
};
attributes.insert(key, value);
}
fn integer_key(key: &str) -> Option<i64> {
let index = key.parse::<i64>().ok()?;
(index.to_string() == key).then_some(index)
}
fn kebab(value: &str) -> String {
let mut result = String::new();
let mut word_start = true;
for ch in value.chars() {
if ch.is_whitespace() {
word_start |= matches!(ch, ' ' | '\t' | '\r' | '\n' | '\u{b}' | '\u{c}');
continue;
}
let ch = if word_start {
ch.to_ascii_uppercase()
} else {
ch
};
if !result.is_empty() && ch.is_ascii_uppercase() {
result.push('-');
}
result.push(ch);
word_start = false;
}
result.to_lowercase()
}
fn php_float(number: f64) -> String {
if number.is_nan() {
return "NAN".to_owned();
}
if !number.is_finite() {
return if number.is_sign_negative() {
"-INF"
} else {
"INF"
}
.to_owned();
}
let scientific = format!("{number:.13e}");
let (mantissa, exponent) = scientific.split_once('e').unwrap_or((&scientific, "0"));
let exponent = exponent.parse::<i32>().unwrap_or(0);
if (-4..14).contains(&exponent) {
let decimal = format!("{number:.precision$}", precision = (13 - exponent) as usize);
decimal
.trim_end_matches('0')
.trim_end_matches('.')
.to_owned()
} else {
let truncated = mantissa.trim_end_matches('0').trim_end_matches('.');
let fraction = if truncated.contains('.') { "" } else { ".0" };
format!("{truncated}{fraction}E{exponent:+}")
}
}