use std::cell::RefCell;
use super::element::Node;
use microformats_types::{DebugContext, PropertyValue};
#[cfg(feature = "debug_flow")]
thread_local! {
pub(super) static DEBUG_CONTEXT: RefCell<Option<DebugContext>> = const { RefCell::new(None) };
}
pub fn with_debug_context<F, R>(ctx: DebugContext, f: F) -> (R, DebugContext)
where
F: FnOnce() -> R,
{
DEBUG_CONTEXT.with(|cell| {
*cell.borrow_mut() = Some(ctx.clone());
let result = f();
let ctx_out = cell.borrow_mut().take().unwrap();
(result, ctx_out)
})
}
pub fn get_debug_context() -> Option<DebugContext> {
DEBUG_CONTEXT.with(|cell| cell.borrow().clone())
}
pub struct DebugHook;
impl super::ParserHook for DebugHook {
fn on_property_matched(&self, node: &Node, name: &str, _value: &PropertyValue) {
if let Some(mut ctx) = get_debug_context() {
if let Some(mf2_id) = node.attr("data-mf2-id") {
ctx.property_sources
.push(microformats_types::PropertySourceRecord {
path: format!("properties.{}", name),
element_id: mf2_id.to_string(),
property_name: name.to_string(),
});
}
}
}
fn on_item_matched(&self, node: &Node, _item_type: &str) {
if let Some(mut ctx) = get_debug_context() {
let debug_info = node.capture_debug_info();
let mf2_id = debug_info
.mf2_id
.clone()
.unwrap_or_else(|| format!("anon-{}", ctx.elements.len()));
ctx.elements.insert(mf2_id.clone(), debug_info);
}
}
}