use std::sync::Arc;
use crate::{
app::{component::Component, ctx::Ctx},
node::{Element, text_highlight::TextHighlight},
ui::CodeBlock,
};
#[derive(Clone, PartialEq)]
pub(super) struct MountedCodeProps {
pub(super) code: Arc<str>,
pub(super) language: Option<Arc<str>>,
pub(super) fit: bool,
pub(super) selectable: bool,
pub(super) highlights: Arc<[TextHighlight]>,
}
impl crate::app::component::DevtoolsInspectable for MountedCodeProps {}
pub(super) trait MountCode {
fn mount_code(&self, key: &str, props: MountedCodeProps) -> Element;
}
impl MountCode for std::cell::RefCell<&mut Ctx> {
fn mount_code(&self, key: &str, props: MountedCodeProps) -> Element {
self.borrow_mut().mount_keyed::<MountedCode>(key, props)
}
}
pub(super) struct MountedCode {
lines: Arc<std::sync::Mutex<crate::code::LineCache>>,
}
impl Component for MountedCode {
type Props = MountedCodeProps;
fn create(_ctx: &mut Ctx) -> Self {
Self { lines: Arc::default() }
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let props = ctx.props::<MountedCodeProps>().clone();
let mut block = CodeBlock::new(&props.code)
.selectable(false)
.kept_lines(self.lines.clone());
if let Some(language) = &props.language {
block = block.language(language);
}
if props.code.bytes().filter(|byte| *byte == b'\n').count() >= crate::ui::CODE_BLOCK_WINDOWED_LINES {
return block.selectable(props.selectable).mount(ctx);
}
let mut element = block.build(ctx.theme());
if !props.highlights.is_empty()
&& let Some(node) = super::code_text(&mut element.node, &props.code)
{
node.set_text_highlights(props.highlights.clone());
}
if props.fit {
super::fit(&mut element.node, 3);
}
if props.selectable {
element.node.selectable_recursive(true);
}
element
}
}