use std::rc::Rc;
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography};
use gpui_kit::{
AnyElement, App, ElementId, FocusHandle, IntoElement, KeyDownEvent, ParentElement, Pixels,
RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window,
base::{Button as BaseButton, StyledExt as _},
div,
prelude::*,
px,
};
pub const RICH_TEXT_TOOLBAR_MORPH_SPRING: SpringSpec = SpringSpec::visual(0.28, 0.12);
pub const RICH_TEXT_GLIDE_SPRING: SpringSpec = SpringSpec::visual(0.30, 0.0);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum RichTextBlockType {
#[default]
Paragraph,
Heading1,
Heading2,
Heading3,
BulletedList,
NumberedList,
Blockquote,
CodeBlock,
Divider,
}
impl RichTextBlockType {
pub const ALL: [RichTextBlockType; 9] = [
Self::Paragraph,
Self::Heading1,
Self::Heading2,
Self::Heading3,
Self::BulletedList,
Self::NumberedList,
Self::Blockquote,
Self::CodeBlock,
Self::Divider,
];
pub const fn tag(self) -> &'static str {
match self {
Self::Paragraph => "p",
Self::Heading1 => "h1",
Self::Heading2 => "h2",
Self::Heading3 => "h3",
Self::BulletedList => "ul",
Self::NumberedList => "ol",
Self::Blockquote => "blockquote",
Self::CodeBlock => "pre",
Self::Divider => "hr",
}
}
pub const fn label(self) -> &'static str {
match self {
Self::Paragraph => "Text",
Self::Heading1 => "Heading 1",
Self::Heading2 => "Heading 2",
Self::Heading3 => "Heading 3",
Self::BulletedList => "Bulleted list",
Self::NumberedList => "Numbered list",
Self::Blockquote => "Quote",
Self::CodeBlock => "Code block",
Self::Divider => "Divider",
}
}
pub const fn hint(self) -> &'static str {
match self {
Self::Paragraph => "¶",
Self::Heading1 => "#",
Self::Heading2 => "##",
Self::Heading3 => "###",
Self::BulletedList => "-",
Self::NumberedList => "1.",
Self::Blockquote => ">",
Self::CodeBlock => "```",
Self::Divider => "---",
}
}
pub const fn keywords(self) -> &'static str {
match self {
Self::Paragraph => "paragraph plain body text",
Self::Heading1 => "title h1 large heading 1",
Self::Heading2 => "subtitle h2 section heading 2",
Self::Heading3 => "h3 small heading 3",
Self::BulletedList => "bullet unordered ul points list",
Self::NumberedList => "ordered ol steps numbers list",
Self::Blockquote => "blockquote citation callout quote",
Self::CodeBlock => "pre snippet monospace code",
Self::Divider => "rule hr line separator divider",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RichTextInlineMark {
Bold,
Italic,
Strikethrough,
Code,
}
impl RichTextInlineMark {
pub const ALL: [RichTextInlineMark; 4] =
[Self::Bold, Self::Italic, Self::Strikethrough, Self::Code];
pub const fn label(self) -> &'static str {
match self {
Self::Bold => "Bold",
Self::Italic => "Italic",
Self::Strikethrough => "Strikethrough",
Self::Code => "Inline code",
}
}
pub const fn short_glyph(self) -> &'static str {
match self {
Self::Bold => "B",
Self::Italic => "I",
Self::Strikethrough => "S",
Self::Code => "<>",
}
}
pub const fn marker(self) -> &'static str {
match self {
Self::Bold => "**",
Self::Italic => "_",
Self::Strikethrough => "~~",
Self::Code => "`",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RichTextValue {
pub html: SharedString,
pub markdown: SharedString,
pub text: SharedString,
pub empty: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RichTextHistoryState {
pub can_undo: bool,
pub can_redo: bool,
}
pub fn is_safe_rich_url(url: &str) -> bool {
let trimmed = url.trim();
let lower = trimmed.to_ascii_lowercase();
lower.starts_with("https:")
|| lower.starts_with("http:")
|| lower.starts_with("mailto:")
|| lower.starts_with("tel:")
|| lower.starts_with('/')
|| lower.starts_with('#')
}
pub fn normalize_rich_url(input: &str) -> String {
let url = input.trim();
if url.is_empty() {
return String::new();
}
if url.starts_with('/') || url.starts_with('#') {
return url.to_string();
}
if let Some((scheme, _)) = url.split_once(':')
&& !scheme.is_empty()
&& scheme
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-'))
{
return url.to_string();
}
if !url.contains(char::is_whitespace)
&& let Some((user, host)) = url.split_once('@')
&& !user.is_empty()
&& host.contains('.')
{
return format!("mailto:{url}");
}
format!("https://{url}")
}
fn escape_html(value: &str) -> String {
value
.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
}
fn unescape_html(value: &str) -> String {
value
.replace(""", "\"")
.replace(">", ">")
.replace("<", "<")
.replace("&", "&")
}
fn replace_delimited(input: &str, delim: &str, open_tag: &str, close_tag: &str) -> String {
let mut out = String::with_capacity(input.len() + 16);
let mut rest = input;
while let Some(start) = rest.find(delim) {
out.push_str(&rest[..start]);
let after_start = &rest[start + delim.len()..];
if let Some(end) = after_start.find(delim) {
let inner = &after_start[..end];
if !inner.trim().is_empty() {
out.push_str(open_tag);
out.push_str(inner);
out.push_str(close_tag);
rest = &after_start[end + delim.len()..];
continue;
}
}
out.push_str(delim);
rest = after_start;
}
out.push_str(rest);
out
}
fn replace_links_md(input: &str) -> String {
let mut out = String::with_capacity(input.len());
let mut rest = input;
while let Some(lb) = rest.find('[') {
out.push_str(&rest[..lb]);
let after_lb = &rest[lb + 1..];
if let Some(rb) = after_lb.find("](") {
let label = &after_lb[..rb];
let after_rb = &after_lb[rb + 2..];
if let Some(rp) = after_rb.find(')') {
let url = &after_rb[..rp];
if !url.contains(char::is_whitespace) && is_safe_rich_url(url) {
out.push_str(&format!("<a href=\"{url}\">{label}</a>"));
} else {
out.push_str(label);
}
rest = &after_rb[rp + 1..];
continue;
}
}
out.push('[');
rest = after_lb;
}
out.push_str(rest);
out
}
fn inline_markdown_to_html(text: &str) -> String {
let mut codes: Vec<String> = Vec::new();
let mut with_placeholders = String::new();
let mut rest = escape_html(text);
while let Some(start) = rest.find('`') {
with_placeholders.push_str(&rest[..start]);
let after = &rest[start + 1..];
if let Some(end) = after.find('`') {
let code = &after[..end];
if !code.is_empty() {
let idx = codes.len();
codes.push(code.to_string());
with_placeholders.push_str(&format!("\u{0000}{idx}\u{0000}"));
rest = after[end + 1..].to_string();
continue;
}
}
with_placeholders.push('`');
rest = after.to_string();
}
with_placeholders.push_str(&rest);
let mut out = replace_links_md(&with_placeholders);
out = replace_delimited(&out, "**", "<strong>", "</strong>");
out = replace_delimited(&out, "__", "<strong>", "</strong>");
out = replace_delimited(&out, "~~", "<s>", "</s>");
out = replace_delimited(&out, "*", "<em>", "</em>");
out = replace_delimited(&out, "_", "<em>", "</em>");
for (idx, code) in codes.iter().enumerate() {
let token = format!("\u{0000}{idx}\u{0000}");
out = out.replace(&token, &format!("<code>{code}</code>"));
}
out
}
fn parse_list_item(line: &str) -> Option<(&'static str, &str)> {
let trimmed = line.trim_start();
for prefix in ["- ", "* ", "+ "] {
if let Some(body) = trimmed.strip_prefix(prefix) {
return Some(("ul", body));
}
}
let digits_len = trimmed.bytes().take_while(|b| b.is_ascii_digit()).count();
if digits_len > 0 {
let after_digits = &trimmed[digits_len..];
if let Some(body) = after_digits
.strip_prefix(". ")
.or_else(|| after_digits.strip_prefix(") "))
{
return Some(("ol", body));
}
}
None
}
fn is_hr_line(line: &str) -> bool {
let t = line.trim();
t == "---" || t == "***" || t == "___"
}
pub fn markdown_to_html(markdown: &str) -> String {
let normalized = markdown.replace("\r\n", "\n").replace('\r', "\n");
let lines: Vec<&str> = normalized.split('\n').collect();
let mut out: Vec<String> = Vec::new();
let mut paragraph: Vec<&str> = Vec::new();
let flush_paragraph = |paragraph: &mut Vec<&str>, out: &mut Vec<String>| {
if !paragraph.is_empty() {
let joined = paragraph.join(" ");
out.push(format!("<p>{}</p>", inline_markdown_to_html(&joined)));
paragraph.clear();
}
};
let mut i = 0;
while i < lines.len() {
let line = lines[i];
if line.trim_start().starts_with("```") {
flush_paragraph(&mut paragraph, &mut out);
i += 1;
let mut code_lines = Vec::new();
while i < lines.len() && !lines[i].trim_start().starts_with("```") {
code_lines.push(lines[i]);
i += 1;
}
if i < lines.len() {
i += 1;
}
let body = escape_html(&code_lines.join("\n"));
out.push(format!(
"<pre>{}</pre>",
if body.is_empty() { "<br>" } else { &body }
));
continue;
}
if line.trim().is_empty() {
flush_paragraph(&mut paragraph, &mut out);
i += 1;
continue;
}
let trimmed = line.trim_start();
let hashes = trimmed.bytes().take_while(|&b| b == b'#').count();
if (1..=6).contains(&hashes) && trimmed[hashes..].starts_with(' ') {
flush_paragraph(&mut paragraph, &mut out);
let level = hashes.min(3);
let title = trimmed[hashes..].trim();
out.push(format!(
"<h{level}>{}</h{level}>",
inline_markdown_to_html(title)
));
i += 1;
continue;
}
if is_hr_line(line) {
flush_paragraph(&mut paragraph, &mut out);
out.push("<hr>".to_string());
i += 1;
continue;
}
if trimmed.starts_with('>') {
flush_paragraph(&mut paragraph, &mut out);
let mut quotes = Vec::new();
while i < lines.len() && lines[i].trim_start().starts_with('>') {
let q = lines[i]
.trim_start()
.strip_prefix('>')
.unwrap_or("")
.trim_start();
quotes.push(inline_markdown_to_html(q));
i += 1;
}
out.push(format!("<blockquote>{}</blockquote>", quotes.join("<br>")));
continue;
}
if let Some((tag, _)) = parse_list_item(line) {
flush_paragraph(&mut paragraph, &mut out);
let mut list_tag = tag;
let mut items_html = String::new();
while i < lines.len() {
let Some((item_tag, item_text)) = parse_list_item(lines[i]) else {
break;
};
if item_tag != list_tag {
out.push(format!("<{list_tag}>{items_html}</{list_tag}>"));
items_html.clear();
list_tag = item_tag;
}
items_html.push_str(&format!("<li>{}</li>", inline_markdown_to_html(item_text)));
i += 1;
}
if !items_html.is_empty() {
out.push(format!("<{list_tag}>{items_html}</{list_tag}>"));
}
continue;
}
paragraph.push(line.trim());
i += 1;
}
flush_paragraph(&mut paragraph, &mut out);
if out.is_empty() {
"<p><br></p>".to_string()
} else {
out.join("")
}
}
fn inline_html_to_markdown(html: &str) -> String {
let mut s = html
.replace("<br>", "\n")
.replace("<br/>", "\n")
.replace("<strong>", "**")
.replace("</strong>", "**")
.replace("<b>", "**")
.replace("</b>", "**")
.replace("<em>", "_")
.replace("</em>", "_")
.replace("<i>", "_")
.replace("</i>", "_")
.replace("<s>", "~~")
.replace("</s>", "~~")
.replace("<del>", "~~")
.replace("</del>", "~~")
.replace("<code>", "`")
.replace("</code>", "`");
while let Some(a_start) = s.find("<a ") {
let after_a = &s[a_start..];
let Some(gt) = after_a.find('>') else {
break;
};
let open_tag = &after_a[..gt + 1];
let href = open_tag
.split("href=\"")
.nth(1)
.and_then(|r| r.split('"').next())
.unwrap_or("");
let rest = &after_a[gt + 1..];
let Some(end_a) = rest.find("</a>") else {
break;
};
let label = &rest[..end_a];
let replacement = format!("[{label}]({href})");
s.replace_range(a_start..a_start + gt + 1 + end_a + 4, &replacement);
}
unescape_html(&s)
}
pub fn html_to_markdown(html: &str) -> String {
let trimmed = html.trim();
if trimmed.is_empty() || trimmed == "<p><br></p>" {
return String::new();
}
let mut blocks: Vec<String> = Vec::new();
let mut rest = trimmed;
while !rest.is_empty() {
rest = rest.trim_start();
if let Some(after) = rest.strip_prefix("<hr>") {
blocks.push("---".to_string());
rest = after;
continue;
}
let mut matched = false;
for (tag, prefix) in [
("p", ""),
("h1", "# "),
("h2", "## "),
("h3", "### "),
("blockquote", "> "),
("pre", "```"),
("ul", "ul"),
("ol", "ol"),
] {
let open = format!("<{tag}>");
let close = format!("</{tag}>");
if let Some(after_open) = rest.strip_prefix(&open)
&& let Some(end_idx) = after_open.find(&close)
{
let inner = &after_open[..end_idx];
rest = &after_open[end_idx + close.len()..];
matched = true;
match tag {
"pre" => {
let code = if inner == "<br>" {
String::new()
} else {
unescape_html(inner)
};
blocks.push(format!("```\n{code}\n```"));
}
"blockquote" => {
let text = inline_html_to_markdown(inner);
let quoted = text
.lines()
.map(|l| {
if l.is_empty() {
">".to_string()
} else {
format!("> {l}")
}
})
.collect::<Vec<_>>()
.join("\n");
blocks.push(quoted);
}
"ul" | "ol" => {
let mut items = Vec::new();
let mut list_rest = inner;
let mut num = 1usize;
while let Some(li_open) = list_rest.find("<li>") {
let after_li = &list_rest[li_open + 4..];
let Some(li_close) = after_li.find("</li>") else {
break;
};
let item_md = inline_html_to_markdown(&after_li[..li_close]);
if tag == "ol" {
items.push(format!("{num}. {}", item_md.trim()));
num += 1;
} else {
items.push(format!("- {}", item_md.trim()));
}
list_rest = &after_li[li_close + 5..];
}
if !items.is_empty() {
blocks.push(items.join("\n"));
}
}
_ => {
let text = inline_html_to_markdown(inner).trim().to_string();
if !text.is_empty() {
blocks.push(format!("{prefix}{text}"));
}
}
}
break;
}
}
if !matched {
let text = inline_html_to_markdown(rest).trim().to_string();
if !text.is_empty() {
blocks.push(text);
}
break;
}
}
blocks.join("\n\n")
}
pub fn rich_text_value_from_markdown(markdown: &str) -> RichTextValue {
let html = markdown_to_html(markdown);
let canonical_md = html_to_markdown(&html);
let plain = canonical_md
.lines()
.map(|l| {
l.trim_start_matches(['#', '>', '-', '*', ' '])
.replace("**", "")
.replace("~~", "")
.replace('`', "")
})
.filter(|l| !l.trim().is_empty())
.collect::<Vec<_>>()
.join("\n");
let empty = canonical_md.trim().is_empty();
RichTextValue {
html: SharedString::from(html),
markdown: SharedString::from(canonical_md),
text: SharedString::from(plain),
empty,
}
}
pub fn filter_slash_items(query: &str) -> Vec<RichTextBlockType> {
let q = query.trim().to_ascii_lowercase();
if q.is_empty() {
return RichTextBlockType::ALL.to_vec();
}
RichTextBlockType::ALL
.into_iter()
.filter(|item| {
item.label().to_ascii_lowercase().contains(&q)
|| item.hint().to_ascii_lowercase().contains(&q)
|| item.keywords().contains(&q)
})
.collect()
}
pub fn apply_block_to_markdown(markdown: &str, block: RichTextBlockType) -> String {
if block == RichTextBlockType::Divider {
return if markdown.trim().is_empty() {
"---".to_string()
} else {
format!("{}\n\n---", markdown.trim_end())
};
}
let mut paras: Vec<String> = if markdown.trim().is_empty() {
vec!["Sample block text".to_string()]
} else {
markdown
.trim()
.split("\n\n")
.map(|s| s.to_string())
.collect()
};
let Some(last) = paras.last_mut() else {
return String::new();
};
let clean = last
.trim()
.trim_start_matches("```\n")
.trim_end_matches("\n```")
.trim_start_matches("### ")
.trim_start_matches("## ")
.trim_start_matches("# ")
.trim_start_matches("- ")
.trim_start_matches("1. ")
.trim_start_matches("> ")
.trim()
.to_string();
*last = match block {
RichTextBlockType::Paragraph => clean,
RichTextBlockType::Heading1 => format!("# {clean}"),
RichTextBlockType::Heading2 => format!("## {clean}"),
RichTextBlockType::Heading3 => format!("### {clean}"),
RichTextBlockType::BulletedList => format!("- {clean}"),
RichTextBlockType::NumberedList => format!("1. {clean}"),
RichTextBlockType::Blockquote => format!("> {clean}"),
RichTextBlockType::CodeBlock => format!("```\n{clean}\n```"),
RichTextBlockType::Divider => "---".to_string(),
};
paras.join("\n\n")
}
pub fn toggle_inline_mark_in_markdown(markdown: &str, mark: RichTextInlineMark) -> String {
let m = mark.marker();
let trimmed = markdown.trim();
if trimmed.is_empty() {
return String::new();
}
let mut paras: Vec<String> = trimmed.split("\n\n").map(|s| s.to_string()).collect();
if let Some(last) = paras.last_mut() {
let mut lines: Vec<String> = last.lines().map(|l| l.to_string()).collect();
if let Some(target_line) = lines.last_mut() {
let prefixes = ["### ", "## ", "# ", "- ", "1. ", "> "];
let mut split_prefix = "";
let mut body = target_line.as_str();
for p in prefixes {
if let Some(rest) = target_line.strip_prefix(p) {
split_prefix = p;
body = rest;
break;
}
}
let updated_body = if body.contains(m) {
body.replace(m, "")
} else if body.trim().is_empty() {
body.to_string()
} else {
format!("{m}{}{m}", body.trim())
};
*target_line = format!("{split_prefix}{updated_body}");
}
*last = lines.join("\n");
}
paras.join("\n\n")
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ToolbarFace {
Format,
Link,
}
#[derive(Clone)]
struct RichTextEditorInternal {
stack: Vec<String>,
index: usize,
face: ToolbarFace,
active_block: RichTextBlockType,
bold: bool,
italic: bool,
strike: bool,
code: bool,
link_url: Option<SharedString>,
slash_open: bool,
slash_query: SharedString,
slash_active: usize,
focus_handle: FocusHandle,
}
impl RichTextEditorInternal {
fn new(initial_markdown: String, cx: &mut App) -> Self {
Self {
stack: vec![initial_markdown],
index: 0,
face: ToolbarFace::Format,
active_block: RichTextBlockType::Paragraph,
bold: false,
italic: false,
strike: false,
code: false,
link_url: None,
slash_open: false,
slash_query: SharedString::default(),
slash_active: 0,
focus_handle: cx.focus_handle(),
}
}
fn current(&self) -> &str {
self.stack.get(self.index).map(|s| s.as_str()).unwrap_or("")
}
fn push_snapshot(&mut self, next: String) {
if self.current() == next {
return;
}
self.stack.truncate(self.index + 1);
self.stack.push(next);
if self.stack.len() > 300 {
self.stack.remove(0);
}
self.index = self.stack.len() - 1;
}
fn undo(&mut self) -> bool {
if self.index == 0 {
return false;
}
self.index -= 1;
true
}
fn redo(&mut self) -> bool {
if self.index + 1 >= self.stack.len() {
return false;
}
self.index += 1;
true
}
fn history_state(&self) -> RichTextHistoryState {
RichTextHistoryState {
can_undo: self.index > 0,
can_redo: self.index + 1 < self.stack.len(),
}
}
}
#[derive(IntoElement)]
pub struct RichTextEditor {
id: ElementId,
aria_label: SharedString,
default_markdown: SharedString,
placeholder: SharedString,
block_hint: SharedString,
read_only: bool,
width: Option<Pixels>,
#[allow(clippy::type_complexity)]
on_change: Option<Rc<dyn Fn(&RichTextValue, &mut Window, &mut App)>>,
#[allow(clippy::type_complexity)]
on_history_change: Option<Rc<dyn Fn(&RichTextHistoryState, &mut Window, &mut App)>>,
}
impl RichTextEditor {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
aria_label: "Editor".into(),
default_markdown: "# Quarterly Design Review\n\nEvery motion in **Arc** carries a single coherent velocity from press to settle.\n\n> Keep transitions honest and interruptible.\n\n- Zero hardcoded colors or spring magic numbers\n- Bilateral `HTML` and `Markdown` output".into(),
placeholder: "Start writing".into(),
block_hint: "Type / for blocks".into(),
read_only: false,
width: None,
on_change: None,
on_history_change: None,
}
}
pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
self.aria_label = label.into();
self
}
pub fn default_markdown(mut self, markdown: impl Into<SharedString>) -> Self {
self.default_markdown = markdown.into();
self
}
pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
self.placeholder = placeholder.into();
self
}
pub fn block_hint(mut self, hint: impl Into<SharedString>) -> Self {
self.block_hint = hint.into();
self
}
pub fn read_only(mut self, read_only: bool) -> Self {
self.read_only = read_only;
self
}
pub fn width(mut self, width: impl Into<Pixels>) -> Self {
self.width = Some(width.into());
self
}
pub fn on_change(
mut self,
handler: impl Fn(&RichTextValue, &mut Window, &mut App) + 'static,
) -> Self {
self.on_change = Some(Rc::new(handler));
self
}
pub fn on_history_change(
mut self,
handler: impl Fn(&RichTextHistoryState, &mut Window, &mut App) + 'static,
) -> Self {
self.on_history_change = Some(Rc::new(handler));
self
}
}
impl RenderOnce for RichTextEditor {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let colors = cx.arc_theme().colors;
let state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-rich-text-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, cx| {
RichTextEditorInternal::new(self.default_markdown.to_string(), cx)
});
let snap = internal.read(cx).clone();
let current_md = snap.current().to_string();
let value = rich_text_value_from_markdown(¤t_md);
let hist = snap.history_state();
let read_only = self.read_only;
let notify_change = {
let cb_val = self.on_change.clone();
let cb_hist = self.on_history_change.clone();
move |md: &str, h: RichTextHistoryState, window: &mut Window, cx: &mut App| {
let v = rich_text_value_from_markdown(md);
if let Some(ref f) = cb_val {
f(&v, window, cx);
}
if let Some(ref f) = cb_hist {
f(&h, window, cx);
}
window.refresh();
}
};
let toolbar = match snap.face {
ToolbarFace::Format => {
let mark_btns = RichTextInlineMark::ALL.into_iter().map(|mark| {
let active = match mark {
RichTextInlineMark::Bold => snap.bold,
RichTextInlineMark::Italic => snap.italic,
RichTextInlineMark::Strikethrough => snap.strike,
RichTextInlineMark::Code => snap.code,
};
let st_m = internal.clone();
let notify_m = notify_change.clone();
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("mark-{}", mark.label())),
))
.accessibility_label(mark.label())
.disabled(read_only)
.on_click(move |_, window, cx| {
let mut out_md = String::new();
let mut out_h = RichTextHistoryState {
can_undo: false,
can_redo: false,
};
st_m.update(cx, |s, _| {
match mark {
RichTextInlineMark::Bold => s.bold = !s.bold,
RichTextInlineMark::Italic => s.italic = !s.italic,
RichTextInlineMark::Strikethrough => s.strike = !s.strike,
RichTextInlineMark::Code => s.code = !s.code,
}
let next = toggle_inline_mark_in_markdown(s.current(), mark);
s.push_snapshot(next.clone());
out_md = next;
out_h = s.history_state();
});
notify_m(&out_md, out_h, window, cx);
})
.w(px(30.0))
.h(px(30.0))
.flex()
.items_center()
.justify_center()
.rounded(px(10.0))
.bg(if active {
colors.accent_subtle
} else {
gpui_kit::Hsla::transparent_black()
})
.text_size(Typography::TEXT_XS)
.font_semibold()
.text_color(if active {
colors.accent_strong
} else {
colors.text_secondary
})
.when(!read_only, |b| b.cursor_pointer())
.child(mark.short_glyph())
});
let block_shortcuts = [
RichTextBlockType::Heading1,
RichTextBlockType::Heading2,
RichTextBlockType::BulletedList,
RichTextBlockType::NumberedList,
RichTextBlockType::Blockquote,
RichTextBlockType::CodeBlock,
RichTextBlockType::Divider,
];
let block_btns = block_shortcuts.into_iter().map(|blk| {
let active = snap.active_block == blk;
let st_b = internal.clone();
let notify_b = notify_change.clone();
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("block-{}", blk.tag())),
))
.accessibility_label(blk.label())
.disabled(read_only)
.on_click(move |_, window, cx| {
let mut out_md = String::new();
let mut out_h = RichTextHistoryState {
can_undo: false,
can_redo: false,
};
st_b.update(cx, |s, _| {
let target = if s.active_block == blk {
RichTextBlockType::Paragraph
} else {
blk
};
s.active_block = target;
let next = apply_block_to_markdown(s.current(), target);
s.push_snapshot(next.clone());
out_md = next;
out_h = s.history_state();
});
notify_b(&out_md, out_h, window, cx);
})
.h(px(30.0))
.px(px(8.0))
.flex()
.items_center()
.justify_center()
.rounded(px(10.0))
.bg(if active {
colors.accent_subtle
} else {
gpui_kit::Hsla::transparent_black()
})
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(if active {
colors.accent_strong
} else {
colors.text_secondary
})
.when(!read_only, |b| b.cursor_pointer())
.child(blk.hint())
});
let st_link = internal.clone();
let st_slash = internal.clone();
let st_undo = internal.clone();
let notify_undo = notify_change.clone();
let st_redo = internal.clone();
let notify_redo = notify_change.clone();
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"toolbar".into(),
))
.test_support()
.role(Role::Toolbar)
.aria_label("Formatting")
.w_full()
.p(px(4.0))
.flex()
.flex_wrap()
.items_center()
.justify_between()
.gap(px(4.0))
.rounded(Radii::CONTROL)
.border_1()
.border_color(colors.border)
.bg(colors.surface_raised)
.child(
div()
.flex()
.flex_wrap()
.items_center()
.gap(px(2.0))
.children(mark_btns)
.child(
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"open-link".into(),
))
.accessibility_label("Link")
.disabled(read_only)
.on_click(move |_, window, cx| {
st_link.update(cx, |s, _| {
s.face = ToolbarFace::Link;
});
window.refresh();
})
.h(px(30.0))
.px(px(8.0))
.flex()
.items_center()
.rounded(px(10.0))
.bg(if snap.link_url.is_some() {
colors.accent_subtle
} else {
gpui_kit::Hsla::transparent_black()
})
.text_size(Typography::TEXT_XS)
.text_color(if snap.link_url.is_some() {
colors.accent_strong
} else {
colors.text_secondary
})
.cursor_pointer()
.child("Link"),
)
.child(div().w(px(1.0)).h(px(18.0)).mx(px(4.0)).bg(colors.border))
.children(block_btns)
.child(
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"toggle-slash".into(),
))
.accessibility_label("Insert block")
.disabled(read_only)
.on_click(move |_, window, cx| {
st_slash.update(cx, |s, _| {
s.slash_open = !s.slash_open;
s.slash_active = 0;
});
window.refresh();
})
.h(px(30.0))
.px(px(8.0))
.flex()
.items_center()
.rounded(px(10.0))
.bg(if snap.slash_open {
colors.accent_subtle
} else {
gpui_kit::Hsla::transparent_black()
})
.text_size(Typography::TEXT_XS)
.text_color(if snap.slash_open {
colors.accent_strong
} else {
colors.text_secondary
})
.cursor_pointer()
.child("/ Blocks"),
),
)
.child(
div()
.flex()
.items_center()
.gap(px(4.0))
.child(
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"undo".into(),
))
.accessibility_label("Undo")
.disabled(read_only || !hist.can_undo)
.on_click(move |_, window, cx| {
let mut changed = None;
st_undo.update(cx, |s, _| {
if s.undo() {
changed =
Some((s.current().to_string(), s.history_state()));
}
});
if let Some((md, h)) = changed {
notify_undo(&md, h, window, cx);
}
})
.h(px(28.0))
.px(px(8.0))
.flex()
.items_center()
.rounded(px(9.0))
.text_size(Typography::TEXT_XS)
.text_color(if hist.can_undo {
colors.foreground
} else {
colors.text_muted
})
.when(hist.can_undo, |b| b.cursor_pointer())
.child("Undo"),
)
.child(
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"redo".into(),
))
.accessibility_label("Redo")
.disabled(read_only || !hist.can_redo)
.on_click(move |_, window, cx| {
let mut changed = None;
st_redo.update(cx, |s, _| {
if s.redo() {
changed =
Some((s.current().to_string(), s.history_state()));
}
});
if let Some((md, h)) = changed {
notify_redo(&md, h, window, cx);
}
})
.h(px(28.0))
.px(px(8.0))
.flex()
.items_center()
.rounded(px(9.0))
.text_size(Typography::TEXT_XS)
.text_color(if hist.can_redo {
colors.foreground
} else {
colors.text_muted
})
.when(hist.can_redo, |b| b.cursor_pointer())
.child("Redo"),
),
)
}
ToolbarFace::Link => {
let st_back = internal.clone();
let st_apply = internal.clone();
let notify_apply = notify_change.clone();
let st_unlink = internal.clone();
let notify_unlink = notify_change.clone();
let current_link = snap
.link_url
.clone()
.unwrap_or_else(|| "https://uiarc.dev".into());
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"toolbar-link".into(),
))
.test_support()
.role(Role::Toolbar)
.aria_label("Link")
.w_full()
.p(px(4.0))
.flex()
.items_center()
.justify_between()
.gap(px(6.0))
.rounded(Radii::CONTROL)
.border_1()
.border_color(colors.border)
.bg(colors.surface_raised)
.child(
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"link-back".into(),
))
.accessibility_label("Back to formatting")
.on_click(move |_, window, cx| {
st_back.update(cx, |s, _| s.face = ToolbarFace::Format);
window.refresh();
})
.h(px(30.0))
.px(px(10.0))
.flex()
.items_center()
.rounded(px(10.0))
.text_size(Typography::TEXT_XS)
.text_color(colors.text_secondary)
.cursor_pointer()
.child("← Back"),
)
.child(
div()
.flex_1()
.px(px(8.0))
.text_size(Typography::TEXT_SM)
.text_color(colors.foreground)
.child(current_link.clone()),
)
.child(
div()
.flex()
.items_center()
.gap(px(4.0))
.child(
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"apply-link".into(),
))
.accessibility_label("Apply link")
.on_click(move |_, window, cx| {
let normalized = normalize_rich_url("uiarc.dev");
let mut out_md = String::new();
let mut out_h = RichTextHistoryState {
can_undo: false,
can_redo: false,
};
st_apply.update(cx, |s, _| {
s.link_url = Some(SharedString::from(normalized.clone()));
s.face = ToolbarFace::Format;
let next = format!(
"{}\n\n[Arc Documentation]({normalized})",
s.current().trim_end()
);
s.push_snapshot(next.clone());
out_md = next;
out_h = s.history_state();
});
notify_apply(&out_md, out_h, window, cx);
})
.h(px(30.0))
.px(px(10.0))
.flex()
.items_center()
.rounded(px(10.0))
.bg(colors.control_fill)
.text_size(Typography::TEXT_XS)
.text_color(colors.accent_foreground)
.cursor_pointer()
.child("Apply"),
)
.when(snap.link_url.is_some(), |this| {
this.child(
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"unlink".into(),
))
.accessibility_label("Remove link")
.on_click(move |_, window, cx| {
let mut out_md = String::new();
let mut out_h = RichTextHistoryState {
can_undo: false,
can_redo: false,
};
st_unlink.update(cx, |s, _| {
s.link_url = None;
s.face = ToolbarFace::Format;
let next = s.current().replace(
"[Arc Documentation](https://uiarc.dev)",
"Arc Documentation",
);
s.push_snapshot(next.clone());
out_md = next;
out_h = s.history_state();
});
notify_unlink(&out_md, out_h, window, cx);
})
.h(px(30.0))
.px(px(10.0))
.flex()
.items_center()
.rounded(px(10.0))
.text_size(Typography::TEXT_XS)
.text_color(colors.danger)
.cursor_pointer()
.child("Unlink"),
)
}),
)
}
};
let slash_menu = if snap.slash_open {
let items = filter_slash_items(snap.slash_query.as_ref());
let active_idx = snap.slash_active.min(items.len().saturating_sub(1));
let rows = items.iter().copied().enumerate().map(|(idx, item)| {
let selected = idx == active_idx;
let st_pick = internal.clone();
let notify_pick = notify_change.clone();
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("slash-{}", item.tag())),
))
.accessibility_label(item.label())
.on_click(move |_, window, cx| {
let mut out_md = String::new();
let mut out_h = RichTextHistoryState {
can_undo: false,
can_redo: false,
};
st_pick.update(cx, |s, _| {
s.slash_open = false;
s.active_block = item;
let next = apply_block_to_markdown(s.current(), item);
s.push_snapshot(next.clone());
out_md = next;
out_h = s.history_state();
});
notify_pick(&out_md, out_h, window, cx);
})
.w_full()
.h(px(32.0))
.px(px(10.0))
.flex()
.items_center()
.justify_between()
.rounded(px(10.0))
.bg(if selected {
colors.surface_muted
} else {
gpui_kit::Hsla::transparent_black()
})
.cursor_pointer()
.child(
div()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(if selected {
colors.foreground
} else {
colors.text_secondary
})
.child(item.label()),
)
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(item.hint()),
)
});
Some(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"slash-menu".into(),
))
.test_support()
.role(Role::ListBox)
.aria_label("Block types")
.w(px(240.0))
.p(px(6.0))
.flex()
.flex_col()
.gap(px(2.0))
.rounded(Radii::CONTROL)
.border_1()
.border_color(colors.border)
.bg(colors.surface_raised)
.children(rows),
)
} else {
None
};
let is_editor_focused = snap.focus_handle.is_focused(window);
let strip_inline_markers = |s: &str| -> String {
let mut out = s
.replace("**", "")
.replace("~~", "")
.replace(['`', '_'], "");
while let Some(open_b) = out.find('[') {
if let Some(mid_rel) = out[open_b..].find("](") {
let mid = open_b + mid_rel;
if let Some(close_rel) = out[mid + 2..].find(')') {
let close_p = mid + 2 + close_rel;
let label = out[open_b + 1..mid].to_string();
out.replace_range(open_b..=close_p, &label);
continue;
}
}
break;
}
out
};
let block_elements: Vec<AnyElement> = if value.empty {
vec![
div()
.text_size(Typography::TEXT_BASE)
.text_color(colors.text_muted)
.child(self.placeholder.clone())
.into_any_element(),
]
} else {
let blocks_vec: Vec<&str> = current_md
.split("\n\n")
.filter(|b| !b.trim().is_empty())
.collect();
let last_block_idx = blocks_vec.len().saturating_sub(1);
blocks_vec
.into_iter()
.enumerate()
.map(|(b_idx, block_str)| {
let t = block_str.trim();
let is_last = b_idx == last_block_idx;
let has_bold = t.contains("**");
let has_italic = t.contains('_');
let has_strike = t.contains("~~");
let has_code = t.contains('`') && !t.starts_with("```");
if t == "---" {
return div()
.w_full()
.h(px(1.0))
.my(Spacing::S2)
.bg(colors.border)
.into_any_element();
}
if let Some(h1) = t.strip_prefix("# ") {
return div()
.text_size(Typography::TEXT_2XL)
.font_semibold()
.when(has_italic, |d| d.italic())
.when(has_strike, |d| d.line_through())
.text_color(colors.foreground)
.child(SharedString::from(strip_inline_markers(h1)))
.into_any_element();
}
if let Some(h2) = t.strip_prefix("## ") {
return div()
.text_size(Typography::TEXT_XL)
.font_semibold()
.when(has_italic, |d| d.italic())
.when(has_strike, |d| d.line_through())
.text_color(colors.foreground)
.child(SharedString::from(strip_inline_markers(h2)))
.into_any_element();
}
if let Some(h3) = t.strip_prefix("### ") {
return div()
.text_size(Typography::TEXT_LG)
.font_semibold()
.when(has_italic, |d| d.italic())
.when(has_strike, |d| d.line_through())
.text_color(colors.foreground)
.child(SharedString::from(strip_inline_markers(h3)))
.into_any_element();
}
if t.starts_with("```") {
let code = t.trim_start_matches("```").trim_end_matches("```").trim();
return div()
.w_full()
.p(Spacing::S3)
.rounded(px(6.0))
.border_1()
.border_color(colors.border_subtle)
.bg(colors.surface_muted)
.text_size(Typography::TEXT_SM)
.text_color(colors.foreground)
.child(SharedString::from(code.to_string()))
.into_any_element();
}
if t.starts_with('>') {
let quote_text = t
.lines()
.map(|l| strip_inline_markers(l.trim_start_matches('>').trim()))
.collect::<Vec<_>>()
.join("\n");
return div()
.pl(px(14.0))
.border_l_2()
.border_color(colors.border_strong)
.text_size(Typography::TEXT_BASE)
.when(has_bold, |d| d.font_semibold())
.when(has_italic, |d| d.italic())
.when(has_strike, |d| d.line_through())
.text_color(colors.text_secondary)
.child(SharedString::from(quote_text))
.into_any_element();
}
let mut display_txt = strip_inline_markers(t);
if is_last && is_editor_focused && !read_only {
display_txt.push('▏');
}
div()
.text_size(Typography::TEXT_BASE)
.when(has_bold, |d| d.font_semibold())
.when(has_italic, |d| d.italic())
.when(has_strike, |d| d.line_through())
.when(has_code, |d| {
d.px(px(6.0))
.py(px(2.0))
.rounded(px(6.0))
.bg(colors.surface_muted)
})
.text_color(colors.foreground)
.child(SharedString::from(display_txt))
.into_any_element()
})
.collect()
};
let focus_handle = snap.focus_handle.clone();
let focus_for_click = snap.focus_handle.clone();
let st_key = internal.clone();
let notify_key = notify_change.clone();
let editor_surface = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"editor".into(),
))
.test_support()
.track_focus(&focus_handle)
.role(Role::Group)
.aria_label(self.aria_label.clone())
.w_full()
.min_h(px(148.0))
.p(Spacing::S4)
.flex()
.flex_col()
.gap(Spacing::S3)
.rounded(Radii::PANEL)
.border_1()
.border_color(if is_editor_focused && !read_only {
colors.control_fill
} else {
colors.border
})
.bg(colors.surface)
.when(!read_only, |d| {
d.cursor_text()
.on_mouse_down(gpui_kit::MouseButton::Left, move |_, window, cx| {
window.focus(&focus_for_click, cx);
window.refresh();
})
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if read_only {
return;
}
let mods = event.keystroke.modifiers;
let cmd = mods.platform || mods.control;
let key = event.keystroke.key.as_str();
let mut changed = None;
st_key.update(cx, |s, _| {
if cmd && key.eq_ignore_ascii_case("z") {
let ok = if mods.shift { s.redo() } else { s.undo() };
if ok {
changed = Some((s.current().to_string(), s.history_state()));
}
} else if cmd && key.eq_ignore_ascii_case("b") {
s.bold = !s.bold;
let next =
toggle_inline_mark_in_markdown(s.current(), RichTextInlineMark::Bold);
s.push_snapshot(next.clone());
changed = Some((next, s.history_state()));
} else if cmd && key.eq_ignore_ascii_case("i") {
s.italic = !s.italic;
let next =
toggle_inline_mark_in_markdown(s.current(), RichTextInlineMark::Italic);
s.push_snapshot(next.clone());
changed = Some((next, s.history_state()));
} else if key == "/" && !cmd {
s.slash_open = !s.slash_open;
s.slash_active = 0;
} else if key == "escape" {
s.slash_open = false;
s.face = ToolbarFace::Format;
} else if key == "backspace" && !cmd {
let cur = s.current();
let next: String = cur
.chars()
.take(cur.chars().count().saturating_sub(1))
.collect();
s.push_snapshot(next.clone());
changed = Some((next, s.history_state()));
} else if key == "enter" && !cmd {
let next = format!("{}\n\n", s.current().trim_end());
s.push_snapshot(next.clone());
changed = Some((next, s.history_state()));
} else if (key == "space" || key == " ") && !cmd {
let next = format!("{} ", s.current());
s.push_snapshot(next.clone());
changed = Some((next, s.history_state()));
} else if !cmd {
let ch_str = event
.keystroke
.key_char
.as_deref()
.filter(|kc| !kc.is_empty() && kc.chars().all(|c| !c.is_control()))
.map(|kc| kc.to_string())
.or_else(|| {
(key.len() == 1)
.then(|| key.chars().next())
.flatten()
.filter(|c| !c.is_control())
.map(|c| {
if mods.shift {
c.to_ascii_uppercase().to_string()
} else {
c.to_string()
}
})
});
if let Some(append) = ch_str {
let next = format!("{}{append}", s.current());
s.push_snapshot(next.clone());
changed = Some((next, s.history_state()));
}
}
});
if let Some((md, h)) = changed {
notify_key(&md, h, window, cx);
} else {
window.refresh();
}
})
.children(block_elements)
.child(
div()
.pt(Spacing::S2)
.border_t_1()
.border_color(colors.border_subtle)
.flex()
.items_center()
.justify_between()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(self.block_hint.clone())
.child(SharedString::from(format!(
"{} chars · HTML {}B",
value.text.len(),
value.html.len()
))),
);
div()
.id(self.id.clone())
.test_support()
.when_some(self.width, |this, w| this.w(w))
.when(self.width.is_none(), |this| this.w_full())
.flex()
.flex_col()
.gap(Spacing::S3)
.child(toolbar)
.when_some(slash_menu, |this, menu| this.child(menu))
.child(editor_surface)
}
}
#[cfg(test)]
mod tests {
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
use super::*;
#[test]
fn url_normalization_and_safety() {
assert_eq!(
normalize_rich_url("uiarc.dev/docs"),
"https://uiarc.dev/docs"
);
assert_eq!(
normalize_rich_url("team@uiarc.dev"),
"mailto:team@uiarc.dev"
);
assert_eq!(normalize_rich_url("/local/path"), "/local/path");
assert_eq!(normalize_rich_url("#section"), "#section");
assert!(is_safe_rich_url("https://uiarc.dev"));
assert!(!is_safe_rich_url("javascript:alert(1)"));
}
#[test]
fn markdown_and_html_round_trip_blocks_and_marks() {
let md = "# Title\n\nParagraph with **bold**, _italic_, ~~strike~~, `code`, and [Arc](https://uiarc.dev).\n\n> A quiet quote\n\n- First item\n- Second item\n\n```\nlet x = 1;\n```\n\n---";
let html = markdown_to_html(md);
assert!(html.contains("<h1>Title</h1>"));
assert!(html.contains("<strong>bold</strong>"));
assert!(html.contains("<em>italic</em>"));
assert!(html.contains("<s>strike</s>"));
assert!(html.contains("<code>code</code>"));
assert!(html.contains("<a href=\"https://uiarc.dev\">Arc</a>"));
assert!(html.contains("<blockquote>A quiet quote</blockquote>"));
assert!(html.contains("<ul><li>First item</li><li>Second item</li></ul>"));
assert!(html.contains("<pre>let x = 1;</pre>"));
assert!(html.contains("<hr>"));
let round_tripped = html_to_markdown(&html);
assert_eq!(round_tripped, md);
}
#[test]
fn slash_filter_matches_keywords_and_hints() {
assert_eq!(filter_slash_items("").len(), 9);
assert_eq!(filter_slash_items("h2"), vec![RichTextBlockType::Heading2]);
assert_eq!(
filter_slash_items("quote"),
vec![RichTextBlockType::Blockquote]
);
}
struct EditorHost;
impl Render for EditorHost {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
.w(px(620.0))
.p(px(16.0))
.child(RichTextEditor::new("rte-test"))
}
}
#[gpui_kit::test]
fn rich_text_editor_renders_toolbar_and_surface(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let (_view, cx) = cx.add_window_view(|_, _| EditorHost);
cx.update(|window, cx| {
window.render_frame(cx);
let toolbar = window.find(ElementId::NamedChild(
ElementId::Name("rte-test".into()).into(),
"toolbar".into(),
));
assert_eq!(toolbar.role(), Some(Role::Toolbar));
let editor = window.find(ElementId::NamedChild(
ElementId::Name("rte-test".into()).into(),
"editor".into(),
));
assert_eq!(editor.role(), Some(Role::Group));
});
}
}