use askama::Template;
use super::system::{
External, ExternalContent, ExternalSlot, Instruction, InstructionSlot, SystemRegion,
TextChange, boundary,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LiveContent {
subject: &'static str,
tag: &'static str,
}
impl LiveContent {
pub const COMMANDS: Self = Self::new("The table of terminal commands", "commands_diff");
#[must_use]
pub const fn new(subject: &'static str, tag: &'static str) -> Self {
Self { subject, tag }
}
}
pub struct LiveUpdate<'a> {
instructions: &'a mut SystemRegion<Instruction>,
external: &'a mut SystemRegion<External>,
warm: bool,
changes: Vec<TextChange>,
}
impl std::fmt::Debug for LiveUpdate<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LiveUpdate")
.field("warm", &self.warm)
.field("changes", &self.changes.len())
.finish_non_exhaustive()
}
}
impl<'a> LiveUpdate<'a> {
pub(crate) const fn new(
instructions: &'a mut SystemRegion<Instruction>,
external: &'a mut SystemRegion<External>,
warm: bool,
) -> Self {
Self {
instructions,
external,
warm,
changes: Vec::new(),
}
}
pub fn instruction(&mut self, slot: &InstructionSlot, desired: Option<String>) -> &mut Self {
let change = self.instructions.change(slot, desired, self.warm);
self.changes.extend(change);
self
}
pub fn external(&mut self, slot: &ExternalSlot, desired: Option<ExternalContent>) -> &mut Self {
let change = self.external.change(slot, desired, self.warm);
self.changes.extend(change);
self
}
pub(crate) fn into_alert(self, content: &LiveContent) -> Option<String> {
if self.changes.is_empty() {
return None;
}
let diff: String = self
.changes
.iter()
.map(|change| unified_diff(&change.before, &change.after))
.collect();
Some(
LiveContentChangedTemplate {
subject: content.subject,
tag: content.tag,
boundary: boundary(&[&diff]),
diff: &diff,
}
.render()
.expect("live content alert template must render"),
)
}
}
pub(crate) fn unified_diff(before: &str, after: &str) -> String {
similar::TextDiff::from_lines(before, after)
.unified_diff()
.context_radius(2)
.to_string()
}
#[derive(Template)]
#[template(path = "live_content_changed.txt", escape = "none")]
struct LiveContentChangedTemplate<'a> {
subject: &'a str,
tag: &'a str,
boundary: String,
diff: &'a str,
}