From 5e493e7ce066ec096688297fce481fed8d6201e6 Mon Sep 17 00:00:00 2001 From: Ildar Akhmetgaleev Date: Tue, 5 May 2020 02:46:28 +0700 Subject: [PATCH] Set element keys for code blocks --- crate/src/page/guide.rs | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/crate/src/page/guide.rs b/crate/src/page/guide.rs index 6ae9acd..26369f7 100644 --- a/crate/src/page/guide.rs +++ b/crate/src/page/guide.rs @@ -6,7 +6,11 @@ use crate::{ page::partial::{content_control_panel, guide_list, intro}, Guide, Model, Msg, }; -use seed::{a, attrs, div, img, prelude::*, raw, C}; +use seed::{prelude::*, *}; +use std::{ + collections::hash_map::DefaultHasher, + hash::{Hash, Hasher}, +}; pub fn view(guide: &Guide, model: &Model, show_intro: bool) -> Node { div![ @@ -54,7 +58,7 @@ fn view_guide_html(content: &str) -> Node { // it has to be "markdown-body" so it's content is styled by Github CSS C.markdown_body, ], - raw!(content) + set_keys_to_code_blocks(raw!(content)) ] } @@ -78,3 +82,22 @@ fn view_netlify_logo() -> Node { ], ] } + +/// Add element key to each code block to force reinitialization if code changed. +fn set_keys_to_code_blocks(nodes: Vec>) -> Vec> { + nodes + .into_iter() + .map(|node| match node { + Node::Element(el) => { + if el.is_custom() && el.tag.as_str() == "code-block" { + let mut hasher = DefaultHasher::new(); + el.get_text().hash(&mut hasher); + custom![el.tag, el_key(&hasher.finish()), el.children] + } else { + Node::Element(el) + } + }, + _ => node, + }) + .collect() +}