use std::{
cell::{Cell, RefCell},
collections::HashMap,
ops::Range,
sync::Arc,
};
use super::{
bidi_paragraphs::link_directions,
link_block::LinkBlock,
links::{MarkdownLink, MarkdownLinkPresentation},
tooltip::{LinkTooltip, TooltipHover, TooltipKey},
};
use crate::{
app::{
events::{MouseButton, MouseEvent},
theme::ThemeMarkdown,
},
core::ElementRef,
layout::{quad::RichTextSpan, text_style::TextStyle},
markdown::{
Direction, FIRST_STRONG_ISOLATE, MarkdownInline, POP_DIRECTIONAL_ISOLATE, is_invisible, markdown_inline_rich_text,
paragraph_breaks_as_line_feeds, paragraph_breaks_as_spaces, strip_bidi_controls,
},
node::{CursorIcon, EventHandler, Node, NodeUpdate, inline_link::InlineLink, text_highlight::TextHighlight},
};
const ROOM: char = '\u{2060}';
const BREAK: char = '\u{200b}';
const SPACE_EM: f32 = if cfg!(target_vendor = "apple") { 0.205 } else { 0.27 };
struct Room {
index: usize,
before: bool,
extra: f32,
}
pub(super) const FOOTNOTE_ANCHOR: &str = "#fn:";
pub(super) const REFERENCE_ANCHOR: &str = "#fnref:";
pub(super) type MarkdownJump = Arc<dyn Fn(&str) + Send + Sync>;
pub(super) type MarkdownLinkCallback = Arc<dyn Fn(&MarkdownLink) + Send + Sync>;
pub(super) type MarkdownLinkActivator = Arc<dyn Fn(&MarkdownLink, &MouseEvent) + Send + Sync>;
pub(super) type MarkdownLinkPresenter = Arc<dyn Fn(&MarkdownLink) -> MarkdownLinkPresentation + Send + Sync>;
pub(super) struct LinkSession {
next_index: Cell<usize>,
occurrences: RefCell<HashMap<Arc<str>, usize>>,
presenter: Option<MarkdownLinkPresenter>,
on_link_select: Option<MarkdownLinkCallback>,
on_link_activate: Option<MarkdownLinkActivator>,
#[cfg(feature = "router")]
navigator: Option<crate::router::Navigator>,
hover: TooltipHover,
tooltips: RefCell<Vec<LinkTooltip>>,
footnotes: RefCell<HashMap<String, usize>>,
anchors: RefCell<HashMap<Arc<str>, ElementRef>>,
jump: Option<MarkdownJump>,
code_fill: Option<TextHighlight>,
kbd_fill: Option<TextHighlight>,
}
pub(super) struct LinkCheckpoint {
next_index: usize,
occurrences: HashMap<Arc<str>, usize>,
tooltips: usize,
}
impl LinkSession {
pub(super) fn new(
presenter: Option<MarkdownLinkPresenter>,
on_link_select: Option<MarkdownLinkCallback>,
on_link_activate: Option<MarkdownLinkActivator>,
#[cfg(feature = "router")] navigator: Option<crate::router::Navigator>,
hover: TooltipHover,
) -> Self {
Self {
next_index: Cell::new(0),
occurrences: RefCell::new(HashMap::new()),
presenter,
on_link_select,
on_link_activate,
#[cfg(feature = "router")]
navigator,
hover,
tooltips: RefCell::new(Vec::new()),
footnotes: RefCell::new(HashMap::new()),
anchors: RefCell::new(HashMap::new()),
jump: None,
code_fill: None,
kbd_fill: None,
}
}
pub(super) fn set_footnotes(&self, footnotes: HashMap<String, usize>) {
*self.footnotes.borrow_mut() = footnotes;
}
pub(super) fn footnote_number(&self, label: &str) -> Option<usize> {
self.footnotes.borrow().get(label).copied()
}
pub(super) fn with_jump(mut self, jump: MarkdownJump) -> Self {
self.jump = Some(jump);
self
}
pub(super) fn with_fills(mut self, code: Option<TextHighlight>, kbd: Option<TextHighlight>) -> Self {
self.code_fill = code;
self.kbd_fill = kbd;
self
}
pub(super) fn anchor(&self, key: &str) -> ElementRef {
self
.anchors
.borrow_mut()
.entry(Arc::from(key))
.or_insert_with(ElementRef::new)
.clone()
}
pub(super) fn anchor_of(&self, key: &str) -> Option<ElementRef> {
self.anchors.borrow().get(key).cloned()
}
pub(super) fn jump(&self) -> Option<MarkdownJump> {
self.jump.clone()
}
pub(super) fn take_tooltips(&self) -> Vec<LinkTooltip> {
let tooltips = self.tooltips.take();
self.hover.keep_anchors(&tooltips);
tooltips
}
pub(super) fn checkpoint(&self) -> LinkCheckpoint {
LinkCheckpoint {
next_index: self.next_index.get(),
occurrences: self.occurrences.borrow().clone(),
tooltips: self.tooltips.borrow().len(),
}
}
pub(super) fn restore(&self, checkpoint: LinkCheckpoint) {
self.next_index.set(checkpoint.next_index);
*self.occurrences.borrow_mut() = checkpoint.occurrences;
self.tooltips.borrow_mut().truncate(checkpoint.tooltips);
}
fn next_link(&self, destination: &str, title: &str, words: String) -> (MarkdownLink, TooltipKey) {
let index = self.next_index.get();
self.next_index.set(index + 1);
let destination: Arc<str> = Arc::from(destination);
let occurrence = {
let mut occurrences = self.occurrences.borrow_mut();
let count = occurrences.entry(destination.clone()).or_default();
*count += 1;
*count - 1
};
let link = MarkdownLink {
destination: destination.clone(),
title: Arc::from(title),
text: Arc::from(words),
index,
};
(link, TooltipKey::new(destination, occurrence))
}
fn present(&self, link: &MarkdownLink) -> MarkdownLinkPresentation {
self
.presenter
.as_ref()
.map_or_else(MarkdownLinkPresentation::link, |present| present(link))
}
fn activation_handler(&self, link: MarkdownLink) -> EventHandler<MouseEvent> {
let on_link_activate = self.on_link_activate.clone();
let on_link_select = self.on_link_select.clone();
let jump = self.jump.clone();
#[cfg(feature = "router")]
let navigator = self.navigator.clone();
EventHandler::new(move |event: &MouseEvent| {
if let Some(on_link_activate) = &on_link_activate {
on_link_activate(&link, event);
}
if event.button != MouseButton::Left {
return;
}
if let Some(jump) = &jump
&& link.destination().starts_with(FOOTNOTE_ANCHOR)
{
jump(link.destination());
return;
}
if let Some(on_link_select) = &on_link_select {
on_link_select(&link);
return;
}
#[cfg(feature = "router")]
if on_link_activate.is_none()
&& let Some(navigator) = &navigator
&& is_router_link(link.destination())
{
navigator.push(link.destination().to_owned());
}
})
}
fn follows(&self, node: Node, link: MarkdownLink) -> Node {
let activate = self.activation_handler(link);
let node = node.on_click(activate.clone());
if self.on_link_activate.is_none() {
return node;
}
node
.on_mouse_down(hold_middle_press)
.on_mouse_click(MouseButton::Middle, activate)
}
fn with_tooltip(&self, node: Node, key: TooltipKey, text: Option<Arc<str>>) -> Node {
let Some(text) = text else {
return node;
};
let anchor = self.hover.anchor(&key);
self
.tooltips
.borrow_mut()
.push(LinkTooltip::new(key.clone(), anchor.clone(), text));
let (enter, leave) = (self.hover.clone(), self.hover.clone());
let enter_key = key.clone();
node
.ref_element(anchor)
.on_mouse_enter(move || enter.enter(&enter_key))
.on_mouse_leave(move || leave.leave(&key))
}
}
fn hold_middle_press(event: MouseEvent) {
if event.button == MouseButton::Middle {
event.prevent_default();
}
}
#[cfg(feature = "router")]
fn is_router_link(destination: &str) -> bool {
destination.starts_with('/') || destination.starts_with('#') || destination.starts_with('?')
}
pub(super) enum FlowItem<'i> {
Text(Box<Node>),
Image(&'i MarkdownInline, TextStyle),
}
pub(super) struct Paragraph<'a> {
spans: Vec<RichTextSpan>,
sealed: usize,
generated: Vec<Range<usize>>,
strip_controls: bool,
directions: std::vec::IntoIter<Direction>,
links: Vec<Node>,
theme: &'a ThemeMarkdown,
session: &'a LinkSession,
fills: Vec<TextHighlight>,
references: Vec<String>,
rooms: Vec<Room>,
}
impl<'a> Paragraph<'a> {
pub(super) fn new(
inlines: &[MarkdownInline],
flow: bool,
theme: &'a ThemeMarkdown,
session: &'a LinkSession,
) -> Self {
let strip_controls = has_link(inlines);
let directions = if strip_controls {
link_directions(inlines, flow, theme)
} else {
Vec::new()
};
Self {
spans: Vec::new(),
sealed: 0,
generated: Vec::new(),
strip_controls,
directions: directions.into_iter(),
links: Vec::new(),
theme,
session,
fills: Vec::new(),
references: Vec::new(),
rooms: Vec::new(),
}
}
fn text_len(&self) -> usize {
self.spans.iter().map(|span| span.text.len()).sum()
}
fn fill_from(&mut self, start: usize, fill: Option<&TextHighlight>, height: f32) {
let end = self.text_len();
let line = self
.spans
.first()
.map_or(height, |span| span.style.font_size * span.style.line_height);
if let Some(fill) = fill
&& end > start
{
self.fills.push(TextHighlight {
range: start..end,
padding: (fill.padding.0, (height - line) / 2.0),
..fill.clone()
});
}
}
pub(super) fn is_empty(&self) -> bool {
self.spans.is_empty()
}
pub(super) fn take_node(&mut self) -> Node {
self.widen_rooms();
self.sealed = 0;
let mut node = Node::rich_text_with_links(
std::mem::take(&mut self.spans),
std::mem::take(&mut self.links),
std::mem::take(&mut self.generated),
);
let fills = std::mem::take(&mut self.fills);
if !fills.is_empty() {
node.set_text_highlights(fills);
}
let references = std::mem::take(&mut self.references);
let fresh: Vec<String> = references
.into_iter()
.filter(|label| self.session.anchor_of(&format!("{REFERENCE_ANCHOR}{label}")).is_none())
.collect();
if let Some(first) = fresh.first() {
let anchor = self.session.anchor(&format!("{REFERENCE_ANCHOR}{first}"));
for label in &fresh[1..] {
self
.session
.anchors
.borrow_mut()
.insert(Arc::from(format!("{REFERENCE_ANCHOR}{label}")), anchor.clone());
}
NodeUpdate::ref_element(&mut node, anchor);
}
node
}
pub(super) fn push_inlines<'i>(
&mut self,
inlines: &'i [MarkdownInline],
style: &TextStyle,
flow: &mut Option<&mut Vec<FlowItem<'i>>>,
) {
for inline in inlines {
match inline {
MarkdownInline::Link {
destination,
title,
children,
} => self.push_link(destination, title, children, style),
MarkdownInline::Image { .. } if flow.is_some() => {
if let Some(flow) = flow.as_mut() {
if !self.is_empty() {
flow.push(FlowItem::Text(Box::new(self.take_node())));
}
flow.push(FlowItem::Image(inline, style.clone()));
}
}
MarkdownInline::Emphasis(children) => {
self.push_inlines(children, &self.theme.emphasis.apply(style), flow);
}
MarkdownInline::Strong(children) => {
self.push_inlines(children, &self.theme.strong.apply(style), flow);
}
MarkdownInline::Strikethrough(children) => {
self.push_inlines(children, &self.theme.strikethrough.apply(style), flow);
}
MarkdownInline::Code(_) => {
let fill = self.session.code_fill.clone();
let code_style = self.theme.inline_code.apply(style);
self.push_room(fill.as_ref(), &code_style, style, true);
let start = self.text_len();
for span in markdown_inline_rich_text(std::slice::from_ref(inline), style, self.theme) {
self.push_span(span);
}
let height = code_style.font_size * 1.25 + 2.0 * fill.as_ref().map_or(0.0, |fill| fill.padding.1);
self.fill_from(start, fill.as_ref(), height);
self.push_room(fill.as_ref(), &code_style, style, false);
}
MarkdownInline::Kbd(words) => {
let fill = self.session.kbd_fill.clone();
let key_style = self.theme.kbd.apply(style);
self.push_room(fill.as_ref(), &key_style, style, true);
let start = self.text_len();
self.push_span(RichTextSpan {
text: words.clone(),
style: key_style.clone(),
});
let height = fill.as_ref().map_or(20.0, |fill| fill.padding.1);
self.fill_from(start, fill.as_ref(), height);
self.push_room(fill.as_ref(), &key_style, style, false);
}
MarkdownInline::FootnoteReference(label) => match self.session.footnote_number(label) {
Some(number) => {
self.references.push(label.clone());
let children = [MarkdownInline::Text(number.to_string())];
let reference_style = self.theme.footnote_reference.apply(style);
self.push_link(&format!("{FOOTNOTE_ANCHOR}{label}"), "", &children, &reference_style);
}
None => {
for span in markdown_inline_rich_text(std::slice::from_ref(inline), style, self.theme) {
self.push_span(span);
}
}
},
_ => {
for span in markdown_inline_rich_text(std::slice::from_ref(inline), style, self.theme) {
self.push_span(span);
}
}
}
}
}
fn push_link(&mut self, destination: &str, title: &str, children: &[MarkdownInline], style: &TextStyle) {
let direction = self.directions.next().unwrap_or(Direction::LeftToRight);
let (link, key) = self
.session
.next_link(destination, title, link_words(children, self.theme));
if is_invisible(link.text()) {
self.push_invisible_words(children, style);
return;
}
let presentation = self.session.present(&link);
let words_style = if presentation.as_text {
style.clone()
} else {
presentation.style.as_ref().unwrap_or(&self.theme.link).apply(style)
};
let words = self.words(children, &words_style);
let runs = presentation
.trailing
.iter()
.map(|run| RichTextSpan {
text: paragraph_breaks_as_spaces(&strip_bidi_controls(&run.text)).into_owned(),
style: run.style.apply(style),
})
.collect();
let block = self.push_block(LinkBlock::new(direction, words, runs, style));
if presentation.as_text || block.label.is_empty() {
return;
}
let inline_link = InlineLink {
label: block.label,
trailing: block.trailing,
target: block.target,
look: presentation.look(self.theme),
};
let node = Node::inline_link(inline_link, link.text()).cursor(CursorIcon::Pointer);
let node = if presentation.pointer_only {
node.focusable(false)
} else {
node.tab_index(0)
};
let node = self.session.follows(node, link);
self
.links
.push(self.session.with_tooltip(node, key, presentation.tooltip));
}
fn words(&mut self, children: &[MarkdownInline], style: &TextStyle) -> Vec<RichTextSpan> {
let start = self.seal();
self.push_inlines(children, style, &mut None);
let mut words = self.spans.split_off(start);
self.seal();
for span in &mut words {
span.text = paragraph_breaks_as_spaces(&span.text).into_owned();
}
words
}
fn push_invisible_words(&mut self, children: &[MarkdownInline], style: &TextStyle) {
let words = self.words(children, style);
self.push_mark(FIRST_STRONG_ISOLATE, style);
for span in words {
self.push_span(span);
}
self.push_mark(POP_DIRECTIONAL_ISOLATE, style);
}
fn push_block(&mut self, block: LinkBlock) -> PlacedLink {
let offset = self.seal();
let shift = |range: Range<usize>| range.start + offset..range.end + offset;
self.spans.extend(block.spans);
self.generated.extend(block.generated.into_iter().map(shift));
self.seal();
PlacedLink {
label: shift(block.label),
trailing: shift(block.trailing),
target: shift(block.target),
}
}
fn push_room(&mut self, fill: Option<&TextHighlight>, style: &TextStyle, around: &TextStyle, before: bool) {
let Some(width) = fill.map(|fill| fill.padding.0).filter(|width| *width > 0.0) else {
return;
};
let extra = (self.theme.box_gap - SPACE_EM * around.font_size).max(0.0);
if before {
let index = self.seal();
self.spans.push(RichTextSpan {
text: BREAK.to_string(),
style: style.clone(),
});
self.generated.push(index..index + 1);
}
let index = self.seal();
self.spans.push(RichTextSpan {
text: ROOM.to_string(),
style: TextStyle {
letter_spacing: width,
..style.clone()
},
});
self.generated.push(index..index + 1);
self.rooms.push(Room { index, before, extra });
self.seal();
}
fn widen_rooms(&mut self) {
let rooms = std::mem::take(&mut self.rooms);
let ends_a_box = |index: usize| rooms.iter().any(|room| !room.before && room.index == index);
let mut widen = Vec::new();
for room in &rooms {
if room.extra <= 0.0 {
continue;
}
let spaced = if room.before {
room.index.checked_sub(2).is_some_and(|text| {
let words = &self.spans[text].text;
words.ends_with(' ') && !(words == " " && text.checked_sub(1).is_some_and(ends_a_box))
})
} else {
self
.spans
.get(room.index + 1)
.is_some_and(|next| next.text.starts_with(' '))
};
if spaced {
widen.push((room.index, room.extra));
}
}
for (index, extra) in widen {
self.spans[index].style.letter_spacing += extra;
}
}
fn push_mark(&mut self, mark: char, style: &TextStyle) {
let index = self.seal();
self.spans.push(RichTextSpan {
text: mark.to_string(),
style: style.clone(),
});
self.generated.push(index..index + 1);
self.seal();
}
fn push_span(&mut self, mut span: RichTextSpan) {
if self.strip_controls {
span.text = paragraph_breaks_as_line_feeds(&strip_bidi_controls(&span.text)).into_owned();
}
if span.text.is_empty() {
return;
}
if self.spans.len() > self.sealed
&& let Some(last) = self.spans.last_mut()
&& last.style == span.style
{
last.text.push_str(&span.text);
return;
}
self.spans.push(span);
}
fn seal(&mut self) -> usize {
self.sealed = self.spans.len();
self.sealed
}
}
fn has_link(inlines: &[MarkdownInline]) -> bool {
inlines.iter().any(|inline| match inline {
MarkdownInline::Link { .. } => true,
MarkdownInline::Emphasis(children) | MarkdownInline::Strong(children) | MarkdownInline::Strikethrough(children) => {
has_link(children)
}
_ => false,
})
}
struct PlacedLink {
label: Range<usize>,
trailing: Range<usize>,
target: Range<usize>,
}
fn link_words(children: &[MarkdownInline], theme: &ThemeMarkdown) -> String {
let words = markdown_inline_rich_text(children, &TextStyle::default(), theme)
.into_iter()
.map(|span| span.text)
.collect::<String>();
paragraph_breaks_as_spaces(&strip_bidi_controls(&words)).into_owned()
}