Skip to content

Commit

Permalink
feat: impl IntoClass for Cow<'_, str> (#3420)
Browse files Browse the repository at this point in the history
I also thought about making the implementation more generic, for example over
T: AsRef<str>, but that would change the associated types and be a breaking change
it would also conflict with the `Option` impl due to the orphan rules.

Maybe there is something to be done with Borrow or Deref in a future release?
  • Loading branch information
sgued authored Jan 3, 2025
1 parent 34ecd2d commit a1f5d6f
Showing 1 changed file with 58 additions and 1 deletion.
59 changes: 58 additions & 1 deletion tachys/src/html/class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::{
renderer::Rndr,
view::{Position, ToTemplate},
};
use std::{future::Future, sync::Arc};
use std::{borrow::Cow, future::Future, sync::Arc};

/// Adds a CSS class.
#[inline(always)]
Expand Down Expand Up @@ -324,6 +324,63 @@ impl IntoClass for &str {
}
}

impl IntoClass for Cow<'_, str> {
type AsyncOutput = Self;
type State = (crate::renderer::types::Element, Self);
type Cloneable = Arc<str>;
type CloneableOwned = Arc<str>;

fn html_len(&self) -> usize {
self.len()
}

fn to_html(self, class: &mut String) {
IntoClass::to_html(&*self, class);
}

fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
if !FROM_SERVER {
Rndr::set_attribute(el, "class", &self);
}
(el.clone(), self)
}

fn build(self, el: &crate::renderer::types::Element) -> Self::State {
Rndr::set_attribute(el, "class", &self);
(el.clone(), self)
}

fn rebuild(self, state: &mut Self::State) {
let (el, prev) = state;
if self != *prev {
Rndr::set_attribute(el, "class", &self);
}
*prev = self;
}

fn into_cloneable(self) -> Self::Cloneable {
self.into()
}

fn into_cloneable_owned(self) -> Self::CloneableOwned {
self.into()
}

fn dry_resolve(&mut self) {}

async fn resolve(self) -> Self::AsyncOutput {
self
}

fn reset(state: &mut Self::State) {
let (el, _prev) = state;
Rndr::remove_attribute(el, "class");
}
}

impl IntoClass for String {
type AsyncOutput = Self;
type State = (crate::renderer::types::Element, Self);
Expand Down

0 comments on commit a1f5d6f

Please sign in to comment.