use super::*;
#[component]
pub(crate) fn docs_code_block(node: VirtualNode<DocsCodeBlockProps>) -> VirtualNode {
let DocsCodeBlockProps { lang, code }: DocsCodeBlockProps =
node.try_get_props().unwrap_or_default();
let clipboard: UseClipboard = use_clipboard();
let copy: Option<Rc<dyn Fn(Event)>> = Some(Rc::new(move |event: Event| {
let started: bool = clipboard.copy(code);
if let Some(button) = event_button(&event) {
set_copy_label(&button, if started { COPY_STATE } else { FAILED_STATE });
let button: Element = button.clone();
schedule_after(COPY_FEEDBACK_MILLIS, move || {
set_copy_label(&button, RESTING_STATE);
});
}
}));
let html: String = highlighted_html(lang, code);
html! {
figure {
class: c_docs_code()
div {
class: c_docs_code_header()
span {
class: c_docs_code_lang()
{
lang
}
}
button {
class: c_docs_code_copy()
aria-label: COPY_BUTTON_LABEL
onclick: copy
span {
class: c_docs_code_label()
{
COPY_LABEL
}
}
span {
class: c_docs_code_label_hidden()
{
COPIED_LABEL
}
}
span {
class: c_docs_code_label_hidden()
{
FAILED_LABEL
}
}
}
}
pre {
class: c_docs_code_pre()
code {
class: c_docs_code_content()
inner_html: html
}
}
}
}
}
fn event_button(event: &Event) -> Option<Element> {
let target: EventTarget = event.target()?;
let target: Element = target.dyn_into::<Element>().ok()?;
target.closest(COPY_BUTTON_SELECTOR).ok().flatten()
}
fn set_copy_label(button: &Element, state: u8) {
let Ok(labels) = button.query_selector_all(LABEL_SELECTOR) else {
return;
};
let count: u32 = labels.length();
for index in 0..count {
let Some(label) = labels.item(index) else {
continue;
};
let Ok(label) = label.dyn_into::<Element>() else {
continue;
};
let class: &str = if index as u8 == state {
COPY_LABEL_CLASS
} else {
HIDDEN_LABEL_CLASS
};
let _ = label.set_attribute("class", class);
}
}
fn schedule_after<F>(delay_ms: u32, callback: F)
where
F: FnOnce() + 'static,
{
#[cfg(target_arch = "wasm32")]
{
let Some(window) = window() else {
return;
};
let function: JsValue = Closure::once_into_js(move || {
callback();
});
let Ok(function) = function.dyn_into::<Function>() else {
return;
};
let _: Result<i32, JsValue> = window.set_timeout_with_callback_and_timeout_and_arguments_0(
function.as_ref(),
delay_ms as i32,
);
}
#[cfg(not(target_arch = "wasm32"))]
{
let _: u32 = delay_ms;
let _: F = callback;
}
}