use std::{borrow::Cow, path::Path};
pub(super) const IMAGE_REFERENCE_PREFIX: &str = "[View the image here: ";
pub(super) fn image_reference(path: &str) -> String {
format!("{IMAGE_REFERENCE_PREFIX}{path}]")
}
pub(super) fn image_filename(id: u64) -> String {
format!("clipboard-image-{id}-{}.png", uuid::Uuid::new_v4())
}
fn image_id(path: &str) -> Option<u64> {
let path = Path::new(path);
if !path.is_absolute() || path.parent()?.file_name()? != "tmp" {
return None;
}
let name = path.file_name()?.to_str()?;
let (id, uuid) = name
.strip_prefix("clipboard-image-")?
.strip_suffix(".png")?
.split_once('-')?;
uuid::Uuid::parse_str(uuid).ok()?;
id.parse().ok()
}
pub(super) fn display_image_references(text: &str) -> Cow<'_, str> {
if !text.contains(IMAGE_REFERENCE_PREFIX) {
return Cow::Borrowed(text);
}
let mut display = String::with_capacity(text.len());
let mut remaining = text;
while let Some(start) = remaining.find(IMAGE_REFERENCE_PREFIX) {
display.push_str(&remaining[..start]);
let reference = &remaining[start..];
let Some(end) = reference.find(']') else {
display.push_str(reference);
return Cow::Owned(display);
};
let path = &reference[IMAGE_REFERENCE_PREFIX.len()..end];
if let Some(id) = image_id(path) {
display.push_str(&format!("[Pasted Image #{id}]"));
} else {
display.push_str(&reference[..=end]);
}
remaining = &reference[end + 1..];
}
display.push_str(remaining);
Cow::Owned(display)
}