Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: rebuilding of InertElement (closes #3368) #3370

Merged
merged 1 commit into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 36 additions & 6 deletions tachys/src/html/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ use self::attribute::Attribute;
use crate::{
hydration::Cursor,
no_attrs,
prelude::AddAnyAttr,
renderer::{CastFrom, Rndr},
prelude::{AddAnyAttr, Mountable},
renderer::{
dom::{Element, Node},
CastFrom, Rndr,
},
view::{Position, PositionState, Render, RenderHtml},
};
use std::borrow::Cow;
Expand Down Expand Up @@ -90,14 +93,41 @@ impl InertElement {
}
}

/// Retained view state for [`InertElement`].
pub struct InertElementState(Cow<'static, str>, Element);

impl Mountable for InertElementState {
fn unmount(&mut self) {
self.1.unmount();
}

fn mount(&mut self, parent: &Element, marker: Option<&Node>) {
self.1.mount(parent, marker)
}

fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
self.1.insert_before_this(child)
}
}

impl Render for InertElement {
type State = crate::renderer::types::Element;
type State = InertElementState;

fn build(self) -> Self::State {
Rndr::create_element_from_html(&self.html)
let el = Rndr::create_element_from_html(&self.html);
InertElementState(self.html, el)
}

fn rebuild(self, _state: &mut Self::State) {}
fn rebuild(self, state: &mut Self::State) {
let InertElementState(prev, el) = state;
if &self.html != prev {
let mut new_el = Rndr::create_element_from_html(&self.html);
el.insert_before_this(&mut new_el);
el.unmount();
*el = new_el;
*prev = self.html;
}
}
}

impl AddAnyAttr for InertElement {
Expand Down Expand Up @@ -157,6 +187,6 @@ impl RenderHtml for InertElement {
let el = crate::renderer::types::Element::cast_from(cursor.current())
.unwrap();
position.set(Position::NextChild);
el
InertElementState(self.html, el)
}
}
3 changes: 2 additions & 1 deletion tachys/src/renderer/dom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -444,7 +444,8 @@ impl Dom {
// TODO can be optimized to cache HTML strings or cache <template>?
let tpl = document().create_element("template").unwrap();
tpl.set_inner_html(html);
Self::clone_template(tpl.unchecked_ref())
let tpl = Self::clone_template(tpl.unchecked_ref());
tpl.first_element_child().unwrap_or(tpl)
}
}

Expand Down
Loading