Skip to main content

arc_ui/inputs/
rich_text_editor.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/rich-text-editor/rich-text-editor.tsx` & `.module.css`
3//!
4//! P4 Component #28: `rich-text-editor`
5//!
6//! - Lightweight Markdown + HTML rich text editor:
7//!   - Dependency-free converters `markdown_to_html`, `html_to_markdown`, `normalize_rich_url`,
8//!     and `is_safe_rich_url` covering paragraphs, H1–H3 headings, bulleted/numbered lists,
9//!     blockquotes, fenced code blocks, dividers (`<hr>`), and inline marks (`<strong>`, `<em>`,
10//!     `<s>`, `<code>`, `<a href="...">`).
11//!   - Two-face formatting toolbar (`Format` face with inline marks + block tools + link trigger +
12//!     undo/redo, morphing into the `Link` face with URL normalization and unlink).
13//!   - Slash block picker (`/`) with keyword filtering across all 9 block types.
14//!   - 300-step undo/redo history stack and live formatted document block preview.
15//!
16//! Known deviations from upstream:
17//! - Per `arc-rust-plan.md` §5, desktop text input delegates to GPUI's native editing capabilities
18//!   paired with a live structured rich block renderer and toolbar/slash commands rather than a
19//!   browser `contentEditable` DOM tree.
20
21use std::rc::Rc;
22
23use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography};
24use gpui_kit::{
25    AnyElement, App, ElementId, FocusHandle, IntoElement, KeyDownEvent, ParentElement, Pixels,
26    RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window,
27    base::{Button as BaseButton, StyledExt as _},
28    div,
29    prelude::*,
30    px,
31};
32
33/// Morph spring for the rich text toolbar face transition (`rich-text-editor.tsx` line 613).
34pub const RICH_TEXT_TOOLBAR_MORPH_SPRING: SpringSpec = SpringSpec::visual(0.28, 0.12);
35
36/// Glide spring for the slash menu highlight (`rich-text-editor.tsx` line 613).
37pub const RICH_TEXT_GLIDE_SPRING: SpringSpec = SpringSpec::visual(0.30, 0.0);
38
39/// Block types supported by [`RichTextEditor`].
40#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
41pub enum RichTextBlockType {
42    #[default]
43    Paragraph,
44    Heading1,
45    Heading2,
46    Heading3,
47    BulletedList,
48    NumberedList,
49    Blockquote,
50    CodeBlock,
51    Divider,
52}
53
54impl RichTextBlockType {
55    pub const ALL: [RichTextBlockType; 9] = [
56        Self::Paragraph,
57        Self::Heading1,
58        Self::Heading2,
59        Self::Heading3,
60        Self::BulletedList,
61        Self::NumberedList,
62        Self::Blockquote,
63        Self::CodeBlock,
64        Self::Divider,
65    ];
66
67    pub const fn tag(self) -> &'static str {
68        match self {
69            Self::Paragraph => "p",
70            Self::Heading1 => "h1",
71            Self::Heading2 => "h2",
72            Self::Heading3 => "h3",
73            Self::BulletedList => "ul",
74            Self::NumberedList => "ol",
75            Self::Blockquote => "blockquote",
76            Self::CodeBlock => "pre",
77            Self::Divider => "hr",
78        }
79    }
80
81    pub const fn label(self) -> &'static str {
82        match self {
83            Self::Paragraph => "Text",
84            Self::Heading1 => "Heading 1",
85            Self::Heading2 => "Heading 2",
86            Self::Heading3 => "Heading 3",
87            Self::BulletedList => "Bulleted list",
88            Self::NumberedList => "Numbered list",
89            Self::Blockquote => "Quote",
90            Self::CodeBlock => "Code block",
91            Self::Divider => "Divider",
92        }
93    }
94
95    pub const fn hint(self) -> &'static str {
96        match self {
97            Self::Paragraph => "¶",
98            Self::Heading1 => "#",
99            Self::Heading2 => "##",
100            Self::Heading3 => "###",
101            Self::BulletedList => "-",
102            Self::NumberedList => "1.",
103            Self::Blockquote => ">",
104            Self::CodeBlock => "```",
105            Self::Divider => "---",
106        }
107    }
108
109    pub const fn keywords(self) -> &'static str {
110        match self {
111            Self::Paragraph => "paragraph plain body text",
112            Self::Heading1 => "title h1 large heading 1",
113            Self::Heading2 => "subtitle h2 section heading 2",
114            Self::Heading3 => "h3 small heading 3",
115            Self::BulletedList => "bullet unordered ul points list",
116            Self::NumberedList => "ordered ol steps numbers list",
117            Self::Blockquote => "blockquote citation callout quote",
118            Self::CodeBlock => "pre snippet monospace code",
119            Self::Divider => "rule hr line separator divider",
120        }
121    }
122}
123
124/// Inline marks supported by [`RichTextEditor`].
125#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
126pub enum RichTextInlineMark {
127    Bold,
128    Italic,
129    Strikethrough,
130    Code,
131}
132
133impl RichTextInlineMark {
134    pub const ALL: [RichTextInlineMark; 4] =
135        [Self::Bold, Self::Italic, Self::Strikethrough, Self::Code];
136
137    pub const fn label(self) -> &'static str {
138        match self {
139            Self::Bold => "Bold",
140            Self::Italic => "Italic",
141            Self::Strikethrough => "Strikethrough",
142            Self::Code => "Inline code",
143        }
144    }
145
146    pub const fn short_glyph(self) -> &'static str {
147        match self {
148            Self::Bold => "B",
149            Self::Italic => "I",
150            Self::Strikethrough => "S",
151            Self::Code => "<>",
152        }
153    }
154
155    pub const fn marker(self) -> &'static str {
156        match self {
157            Self::Bold => "**",
158            Self::Italic => "_",
159            Self::Strikethrough => "~~",
160            Self::Code => "`",
161        }
162    }
163}
164
165/// Emitted value snapshot containing canonical HTML, Markdown, plain text, and emptiness flag.
166#[derive(Clone, Debug, PartialEq, Eq)]
167pub struct RichTextValue {
168    pub html: SharedString,
169    pub markdown: SharedString,
170    pub text: SharedString,
171    pub empty: bool,
172}
173
174/// Undo/redo availability state reported by [`RichTextEditor`].
175#[derive(Clone, Copy, Debug, PartialEq, Eq)]
176pub struct RichTextHistoryState {
177    pub can_undo: bool,
178    pub can_redo: bool,
179}
180
181/// Checks whether a URL uses an allowed scheme (`http:`, `https:`, `mailto:`, `tel:`, `/`, `#`).
182pub fn is_safe_rich_url(url: &str) -> bool {
183    let trimmed = url.trim();
184    let lower = trimmed.to_ascii_lowercase();
185    lower.starts_with("https:")
186        || lower.starts_with("http:")
187        || lower.starts_with("mailto:")
188        || lower.starts_with("tel:")
189        || lower.starts_with('/')
190        || lower.starts_with('#')
191}
192
193/// Adds a scheme to bare domains or email addresses so `example.com/docs` becomes `https://example.com/docs`.
194pub fn normalize_rich_url(input: &str) -> String {
195    let url = input.trim();
196    if url.is_empty() {
197        return String::new();
198    }
199    if url.starts_with('/') || url.starts_with('#') {
200        return url.to_string();
201    }
202    if let Some((scheme, _)) = url.split_once(':')
203        && !scheme.is_empty()
204        && scheme
205            .chars()
206            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-'))
207    {
208        return url.to_string();
209    }
210    if !url.contains(char::is_whitespace)
211        && let Some((user, host)) = url.split_once('@')
212        && !user.is_empty()
213        && host.contains('.')
214    {
215        return format!("mailto:{url}");
216    }
217    format!("https://{url}")
218}
219
220fn escape_html(value: &str) -> String {
221    value
222        .replace('&', "&amp;")
223        .replace('<', "&lt;")
224        .replace('>', "&gt;")
225        .replace('"', "&quot;")
226}
227
228fn unescape_html(value: &str) -> String {
229    value
230        .replace("&quot;", "\"")
231        .replace("&gt;", ">")
232        .replace("&lt;", "<")
233        .replace("&amp;", "&")
234}
235
236fn replace_delimited(input: &str, delim: &str, open_tag: &str, close_tag: &str) -> String {
237    let mut out = String::with_capacity(input.len() + 16);
238    let mut rest = input;
239    while let Some(start) = rest.find(delim) {
240        out.push_str(&rest[..start]);
241        let after_start = &rest[start + delim.len()..];
242        if let Some(end) = after_start.find(delim) {
243            let inner = &after_start[..end];
244            if !inner.trim().is_empty() {
245                out.push_str(open_tag);
246                out.push_str(inner);
247                out.push_str(close_tag);
248                rest = &after_start[end + delim.len()..];
249                continue;
250            }
251        }
252        out.push_str(delim);
253        rest = after_start;
254    }
255    out.push_str(rest);
256    out
257}
258
259fn replace_links_md(input: &str) -> String {
260    let mut out = String::with_capacity(input.len());
261    let mut rest = input;
262    while let Some(lb) = rest.find('[') {
263        out.push_str(&rest[..lb]);
264        let after_lb = &rest[lb + 1..];
265        if let Some(rb) = after_lb.find("](") {
266            let label = &after_lb[..rb];
267            let after_rb = &after_lb[rb + 2..];
268            if let Some(rp) = after_rb.find(')') {
269                let url = &after_rb[..rp];
270                if !url.contains(char::is_whitespace) && is_safe_rich_url(url) {
271                    out.push_str(&format!("<a href=\"{url}\">{label}</a>"));
272                } else {
273                    out.push_str(label);
274                }
275                rest = &after_rb[rp + 1..];
276                continue;
277            }
278        }
279        out.push('[');
280        rest = after_lb;
281    }
282    out.push_str(rest);
283    out
284}
285
286fn inline_markdown_to_html(text: &str) -> String {
287    // Extract inline code spans first so marks inside backticks stay literal.
288    let mut codes: Vec<String> = Vec::new();
289    let mut with_placeholders = String::new();
290    let mut rest = escape_html(text);
291    while let Some(start) = rest.find('`') {
292        with_placeholders.push_str(&rest[..start]);
293        let after = &rest[start + 1..];
294        if let Some(end) = after.find('`') {
295            let code = &after[..end];
296            if !code.is_empty() {
297                let idx = codes.len();
298                codes.push(code.to_string());
299                with_placeholders.push_str(&format!("\u{0000}{idx}\u{0000}"));
300                rest = after[end + 1..].to_string();
301                continue;
302            }
303        }
304        with_placeholders.push('`');
305        rest = after.to_string();
306    }
307    with_placeholders.push_str(&rest);
308
309    let mut out = replace_links_md(&with_placeholders);
310    out = replace_delimited(&out, "**", "<strong>", "</strong>");
311    out = replace_delimited(&out, "__", "<strong>", "</strong>");
312    out = replace_delimited(&out, "~~", "<s>", "</s>");
313    out = replace_delimited(&out, "*", "<em>", "</em>");
314    out = replace_delimited(&out, "_", "<em>", "</em>");
315
316    for (idx, code) in codes.iter().enumerate() {
317        let token = format!("\u{0000}{idx}\u{0000}");
318        out = out.replace(&token, &format!("<code>{code}</code>"));
319    }
320    out
321}
322
323fn parse_list_item(line: &str) -> Option<(&'static str, &str)> {
324    let trimmed = line.trim_start();
325    for prefix in ["- ", "* ", "+ "] {
326        if let Some(body) = trimmed.strip_prefix(prefix) {
327            return Some(("ul", body));
328        }
329    }
330    let digits_len = trimmed.bytes().take_while(|b| b.is_ascii_digit()).count();
331    if digits_len > 0 {
332        let after_digits = &trimmed[digits_len..];
333        if let Some(body) = after_digits
334            .strip_prefix(". ")
335            .or_else(|| after_digits.strip_prefix(") "))
336        {
337            return Some(("ol", body));
338        }
339    }
340    None
341}
342
343fn is_hr_line(line: &str) -> bool {
344    let t = line.trim();
345    t == "---" || t == "***" || t == "___"
346}
347
348/// Converts Markdown to the editor's canonical HTML (`<p>`, `<h1>`..`<h3>`, `<ul>`, `<ol>`,
349/// `<blockquote>`, `<pre>`, `<hr>`, and inline marks).
350pub fn markdown_to_html(markdown: &str) -> String {
351    let normalized = markdown.replace("\r\n", "\n").replace('\r', "\n");
352    let lines: Vec<&str> = normalized.split('\n').collect();
353    let mut out: Vec<String> = Vec::new();
354    let mut paragraph: Vec<&str> = Vec::new();
355    let flush_paragraph = |paragraph: &mut Vec<&str>, out: &mut Vec<String>| {
356        if !paragraph.is_empty() {
357            let joined = paragraph.join(" ");
358            out.push(format!("<p>{}</p>", inline_markdown_to_html(&joined)));
359            paragraph.clear();
360        }
361    };
362
363    let mut i = 0;
364    while i < lines.len() {
365        let line = lines[i];
366        if line.trim_start().starts_with("```") {
367            flush_paragraph(&mut paragraph, &mut out);
368            i += 1;
369            let mut code_lines = Vec::new();
370            while i < lines.len() && !lines[i].trim_start().starts_with("```") {
371                code_lines.push(lines[i]);
372                i += 1;
373            }
374            if i < lines.len() {
375                i += 1;
376            }
377            let body = escape_html(&code_lines.join("\n"));
378            out.push(format!(
379                "<pre>{}</pre>",
380                if body.is_empty() { "<br>" } else { &body }
381            ));
382            continue;
383        }
384        if line.trim().is_empty() {
385            flush_paragraph(&mut paragraph, &mut out);
386            i += 1;
387            continue;
388        }
389        let trimmed = line.trim_start();
390        let hashes = trimmed.bytes().take_while(|&b| b == b'#').count();
391        if (1..=6).contains(&hashes) && trimmed[hashes..].starts_with(' ') {
392            flush_paragraph(&mut paragraph, &mut out);
393            let level = hashes.min(3);
394            let title = trimmed[hashes..].trim();
395            out.push(format!(
396                "<h{level}>{}</h{level}>",
397                inline_markdown_to_html(title)
398            ));
399            i += 1;
400            continue;
401        }
402        if is_hr_line(line) {
403            flush_paragraph(&mut paragraph, &mut out);
404            out.push("<hr>".to_string());
405            i += 1;
406            continue;
407        }
408        if trimmed.starts_with('>') {
409            flush_paragraph(&mut paragraph, &mut out);
410            let mut quotes = Vec::new();
411            while i < lines.len() && lines[i].trim_start().starts_with('>') {
412                let q = lines[i]
413                    .trim_start()
414                    .strip_prefix('>')
415                    .unwrap_or("")
416                    .trim_start();
417                quotes.push(inline_markdown_to_html(q));
418                i += 1;
419            }
420            out.push(format!("<blockquote>{}</blockquote>", quotes.join("<br>")));
421            continue;
422        }
423        if let Some((tag, _)) = parse_list_item(line) {
424            flush_paragraph(&mut paragraph, &mut out);
425            let mut list_tag = tag;
426            let mut items_html = String::new();
427            while i < lines.len() {
428                let Some((item_tag, item_text)) = parse_list_item(lines[i]) else {
429                    break;
430                };
431                if item_tag != list_tag {
432                    out.push(format!("<{list_tag}>{items_html}</{list_tag}>"));
433                    items_html.clear();
434                    list_tag = item_tag;
435                }
436                items_html.push_str(&format!("<li>{}</li>", inline_markdown_to_html(item_text)));
437                i += 1;
438            }
439            if !items_html.is_empty() {
440                out.push(format!("<{list_tag}>{items_html}</{list_tag}>"));
441            }
442            continue;
443        }
444        paragraph.push(line.trim());
445        i += 1;
446    }
447    flush_paragraph(&mut paragraph, &mut out);
448    if out.is_empty() {
449        "<p><br></p>".to_string()
450    } else {
451        out.join("")
452    }
453}
454
455fn inline_html_to_markdown(html: &str) -> String {
456    let mut s = html
457        .replace("<br>", "\n")
458        .replace("<br/>", "\n")
459        .replace("<strong>", "**")
460        .replace("</strong>", "**")
461        .replace("<b>", "**")
462        .replace("</b>", "**")
463        .replace("<em>", "_")
464        .replace("</em>", "_")
465        .replace("<i>", "_")
466        .replace("</i>", "_")
467        .replace("<s>", "~~")
468        .replace("</s>", "~~")
469        .replace("<del>", "~~")
470        .replace("</del>", "~~")
471        .replace("<code>", "`")
472        .replace("</code>", "`");
473
474    while let Some(a_start) = s.find("<a ") {
475        let after_a = &s[a_start..];
476        let Some(gt) = after_a.find('>') else {
477            break;
478        };
479        let open_tag = &after_a[..gt + 1];
480        let href = open_tag
481            .split("href=\"")
482            .nth(1)
483            .and_then(|r| r.split('"').next())
484            .unwrap_or("");
485        let rest = &after_a[gt + 1..];
486        let Some(end_a) = rest.find("</a>") else {
487            break;
488        };
489        let label = &rest[..end_a];
490        let replacement = format!("[{label}]({href})");
491        s.replace_range(a_start..a_start + gt + 1 + end_a + 4, &replacement);
492    }
493    unescape_html(&s)
494}
495
496/// Converts canonical editor HTML back to Markdown.
497pub fn html_to_markdown(html: &str) -> String {
498    let trimmed = html.trim();
499    if trimmed.is_empty() || trimmed == "<p><br></p>" {
500        return String::new();
501    }
502    let mut blocks: Vec<String> = Vec::new();
503    let mut rest = trimmed;
504    while !rest.is_empty() {
505        rest = rest.trim_start();
506        if let Some(after) = rest.strip_prefix("<hr>") {
507            blocks.push("---".to_string());
508            rest = after;
509            continue;
510        }
511        let mut matched = false;
512        for (tag, prefix) in [
513            ("p", ""),
514            ("h1", "# "),
515            ("h2", "## "),
516            ("h3", "### "),
517            ("blockquote", "> "),
518            ("pre", "```"),
519            ("ul", "ul"),
520            ("ol", "ol"),
521        ] {
522            let open = format!("<{tag}>");
523            let close = format!("</{tag}>");
524            if let Some(after_open) = rest.strip_prefix(&open)
525                && let Some(end_idx) = after_open.find(&close)
526            {
527                let inner = &after_open[..end_idx];
528                rest = &after_open[end_idx + close.len()..];
529                matched = true;
530                match tag {
531                    "pre" => {
532                        let code = if inner == "<br>" {
533                            String::new()
534                        } else {
535                            unescape_html(inner)
536                        };
537                        blocks.push(format!("```\n{code}\n```"));
538                    }
539                    "blockquote" => {
540                        let text = inline_html_to_markdown(inner);
541                        let quoted = text
542                            .lines()
543                            .map(|l| {
544                                if l.is_empty() {
545                                    ">".to_string()
546                                } else {
547                                    format!("> {l}")
548                                }
549                            })
550                            .collect::<Vec<_>>()
551                            .join("\n");
552                        blocks.push(quoted);
553                    }
554                    "ul" | "ol" => {
555                        let mut items = Vec::new();
556                        let mut list_rest = inner;
557                        let mut num = 1usize;
558                        while let Some(li_open) = list_rest.find("<li>") {
559                            let after_li = &list_rest[li_open + 4..];
560                            let Some(li_close) = after_li.find("</li>") else {
561                                break;
562                            };
563                            let item_md = inline_html_to_markdown(&after_li[..li_close]);
564                            if tag == "ol" {
565                                items.push(format!("{num}. {}", item_md.trim()));
566                                num += 1;
567                            } else {
568                                items.push(format!("- {}", item_md.trim()));
569                            }
570                            list_rest = &after_li[li_close + 5..];
571                        }
572                        if !items.is_empty() {
573                            blocks.push(items.join("\n"));
574                        }
575                    }
576                    _ => {
577                        let text = inline_html_to_markdown(inner).trim().to_string();
578                        if !text.is_empty() {
579                            blocks.push(format!("{prefix}{text}"));
580                        }
581                    }
582                }
583                break;
584            }
585        }
586        if !matched {
587            let text = inline_html_to_markdown(rest).trim().to_string();
588            if !text.is_empty() {
589                blocks.push(text);
590            }
591            break;
592        }
593    }
594    blocks.join("\n\n")
595}
596
597/// Builds a [`RichTextValue`] snapshot from Markdown content.
598pub fn rich_text_value_from_markdown(markdown: &str) -> RichTextValue {
599    let html = markdown_to_html(markdown);
600    let canonical_md = html_to_markdown(&html);
601    let plain = canonical_md
602        .lines()
603        .map(|l| {
604            l.trim_start_matches(['#', '>', '-', '*', ' '])
605                .replace("**", "")
606                .replace("~~", "")
607                .replace('`', "")
608        })
609        .filter(|l| !l.trim().is_empty())
610        .collect::<Vec<_>>()
611        .join("\n");
612    let empty = canonical_md.trim().is_empty();
613    RichTextValue {
614        html: SharedString::from(html),
615        markdown: SharedString::from(canonical_md),
616        text: SharedString::from(plain),
617        empty,
618    }
619}
620
621/// Filters the 9 slash menu block types by query string.
622pub fn filter_slash_items(query: &str) -> Vec<RichTextBlockType> {
623    let q = query.trim().to_ascii_lowercase();
624    if q.is_empty() {
625        return RichTextBlockType::ALL.to_vec();
626    }
627    RichTextBlockType::ALL
628        .into_iter()
629        .filter(|item| {
630            item.label().to_ascii_lowercase().contains(&q)
631                || item.hint().to_ascii_lowercase().contains(&q)
632                || item.keywords().contains(&q)
633        })
634        .collect()
635}
636
637/// Toggles or applies a block type to the last block of a Markdown document.
638pub fn apply_block_to_markdown(markdown: &str, block: RichTextBlockType) -> String {
639    if block == RichTextBlockType::Divider {
640        return if markdown.trim().is_empty() {
641            "---".to_string()
642        } else {
643            format!("{}\n\n---", markdown.trim_end())
644        };
645    }
646    let mut paras: Vec<String> = if markdown.trim().is_empty() {
647        vec!["Sample block text".to_string()]
648    } else {
649        markdown
650            .trim()
651            .split("\n\n")
652            .map(|s| s.to_string())
653            .collect()
654    };
655    let Some(last) = paras.last_mut() else {
656        return String::new();
657    };
658    let clean = last
659        .trim()
660        .trim_start_matches("```\n")
661        .trim_end_matches("\n```")
662        .trim_start_matches("### ")
663        .trim_start_matches("## ")
664        .trim_start_matches("# ")
665        .trim_start_matches("- ")
666        .trim_start_matches("1. ")
667        .trim_start_matches("> ")
668        .trim()
669        .to_string();
670    *last = match block {
671        RichTextBlockType::Paragraph => clean,
672        RichTextBlockType::Heading1 => format!("# {clean}"),
673        RichTextBlockType::Heading2 => format!("## {clean}"),
674        RichTextBlockType::Heading3 => format!("### {clean}"),
675        RichTextBlockType::BulletedList => format!("- {clean}"),
676        RichTextBlockType::NumberedList => format!("1. {clean}"),
677        RichTextBlockType::Blockquote => format!("> {clean}"),
678        RichTextBlockType::CodeBlock => format!("```\n{clean}\n```"),
679        RichTextBlockType::Divider => "---".to_string(),
680    };
681    paras.join("\n\n")
682}
683
684/// Toggles an inline mark on the last paragraph or list item of a Markdown document.
685pub fn toggle_inline_mark_in_markdown(markdown: &str, mark: RichTextInlineMark) -> String {
686    let m = mark.marker();
687    let trimmed = markdown.trim();
688    if trimmed.is_empty() {
689        return String::new();
690    }
691    let mut paras: Vec<String> = trimmed.split("\n\n").map(|s| s.to_string()).collect();
692    if let Some(last) = paras.last_mut() {
693        let mut lines: Vec<String> = last.lines().map(|l| l.to_string()).collect();
694        if let Some(target_line) = lines.last_mut() {
695            let prefixes = ["### ", "## ", "# ", "- ", "1. ", "> "];
696            let mut split_prefix = "";
697            let mut body = target_line.as_str();
698            for p in prefixes {
699                if let Some(rest) = target_line.strip_prefix(p) {
700                    split_prefix = p;
701                    body = rest;
702                    break;
703                }
704            }
705            let updated_body = if body.contains(m) {
706                body.replace(m, "")
707            } else if body.trim().is_empty() {
708                body.to_string()
709            } else {
710                format!("{m}{}{m}", body.trim())
711            };
712            *target_line = format!("{split_prefix}{updated_body}");
713        }
714        *last = lines.join("\n");
715    }
716    paras.join("\n\n")
717}
718
719#[derive(Clone, Copy, Debug, PartialEq, Eq)]
720enum ToolbarFace {
721    Format,
722    Link,
723}
724
725#[derive(Clone)]
726struct RichTextEditorInternal {
727    stack: Vec<String>,
728    index: usize,
729    face: ToolbarFace,
730    active_block: RichTextBlockType,
731    bold: bool,
732    italic: bool,
733    strike: bool,
734    code: bool,
735    link_url: Option<SharedString>,
736    slash_open: bool,
737    slash_query: SharedString,
738    slash_active: usize,
739    focus_handle: FocusHandle,
740}
741
742impl RichTextEditorInternal {
743    fn new(initial_markdown: String, cx: &mut App) -> Self {
744        Self {
745            stack: vec![initial_markdown],
746            index: 0,
747            face: ToolbarFace::Format,
748            active_block: RichTextBlockType::Paragraph,
749            bold: false,
750            italic: false,
751            strike: false,
752            code: false,
753            link_url: None,
754            slash_open: false,
755            slash_query: SharedString::default(),
756            slash_active: 0,
757            focus_handle: cx.focus_handle(),
758        }
759    }
760
761    fn current(&self) -> &str {
762        self.stack.get(self.index).map(|s| s.as_str()).unwrap_or("")
763    }
764
765    fn push_snapshot(&mut self, next: String) {
766        if self.current() == next {
767            return;
768        }
769        self.stack.truncate(self.index + 1);
770        self.stack.push(next);
771        if self.stack.len() > 300 {
772            self.stack.remove(0);
773        }
774        self.index = self.stack.len() - 1;
775    }
776
777    fn undo(&mut self) -> bool {
778        if self.index == 0 {
779            return false;
780        }
781        self.index -= 1;
782        true
783    }
784
785    fn redo(&mut self) -> bool {
786        if self.index + 1 >= self.stack.len() {
787            return false;
788        }
789        self.index += 1;
790        true
791    }
792
793    fn history_state(&self) -> RichTextHistoryState {
794        RichTextHistoryState {
795            can_undo: self.index > 0,
796            can_redo: self.index + 1 < self.stack.len(),
797        }
798    }
799}
800
801/// Arc `RichTextEditor` — structured Markdown & HTML rich text editor with a morphing two-face
802/// toolbar (`Format` / `Link`), `/` slash block menu, 300-step undo/redo history, and live block
803/// rendering.
804#[derive(IntoElement)]
805pub struct RichTextEditor {
806    id: ElementId,
807    aria_label: SharedString,
808    default_markdown: SharedString,
809    placeholder: SharedString,
810    block_hint: SharedString,
811    read_only: bool,
812    width: Option<Pixels>,
813    #[allow(clippy::type_complexity)]
814    on_change: Option<Rc<dyn Fn(&RichTextValue, &mut Window, &mut App)>>,
815    #[allow(clippy::type_complexity)]
816    on_history_change: Option<Rc<dyn Fn(&RichTextHistoryState, &mut Window, &mut App)>>,
817}
818
819impl RichTextEditor {
820    pub fn new(id: impl Into<ElementId>) -> Self {
821        Self {
822            id: id.into(),
823            aria_label: "Editor".into(),
824            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(),
825            placeholder: "Start writing".into(),
826            block_hint: "Type / for blocks".into(),
827            read_only: false,
828            width: None,
829            on_change: None,
830            on_history_change: None,
831        }
832    }
833
834    pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
835        self.aria_label = label.into();
836        self
837    }
838
839    pub fn default_markdown(mut self, markdown: impl Into<SharedString>) -> Self {
840        self.default_markdown = markdown.into();
841        self
842    }
843
844    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
845        self.placeholder = placeholder.into();
846        self
847    }
848
849    pub fn block_hint(mut self, hint: impl Into<SharedString>) -> Self {
850        self.block_hint = hint.into();
851        self
852    }
853
854    pub fn read_only(mut self, read_only: bool) -> Self {
855        self.read_only = read_only;
856        self
857    }
858
859    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
860        self.width = Some(width.into());
861        self
862    }
863
864    pub fn on_change(
865        mut self,
866        handler: impl Fn(&RichTextValue, &mut Window, &mut App) + 'static,
867    ) -> Self {
868        self.on_change = Some(Rc::new(handler));
869        self
870    }
871
872    pub fn on_history_change(
873        mut self,
874        handler: impl Fn(&RichTextHistoryState, &mut Window, &mut App) + 'static,
875    ) -> Self {
876        self.on_history_change = Some(Rc::new(handler));
877        self
878    }
879}
880
881impl RenderOnce for RichTextEditor {
882    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
883        let colors = cx.arc_theme().colors;
884        let state_id =
885            ElementId::NamedChild(self.id.clone().into(), "__arc-rich-text-state".into());
886        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
887            RichTextEditorInternal::new(self.default_markdown.to_string(), cx)
888        });
889
890        let snap = internal.read(cx).clone();
891        let current_md = snap.current().to_string();
892        let value = rich_text_value_from_markdown(&current_md);
893        let hist = snap.history_state();
894        let read_only = self.read_only;
895
896        let notify_change = {
897            let cb_val = self.on_change.clone();
898            let cb_hist = self.on_history_change.clone();
899            move |md: &str, h: RichTextHistoryState, window: &mut Window, cx: &mut App| {
900                let v = rich_text_value_from_markdown(md);
901                if let Some(ref f) = cb_val {
902                    f(&v, window, cx);
903                }
904                if let Some(ref f) = cb_hist {
905                    f(&h, window, cx);
906                }
907                window.refresh();
908            }
909        };
910
911        // Two-face floating/docked toolbar
912        let toolbar = match snap.face {
913            ToolbarFace::Format => {
914                let mark_btns = RichTextInlineMark::ALL.into_iter().map(|mark| {
915                    let active = match mark {
916                        RichTextInlineMark::Bold => snap.bold,
917                        RichTextInlineMark::Italic => snap.italic,
918                        RichTextInlineMark::Strikethrough => snap.strike,
919                        RichTextInlineMark::Code => snap.code,
920                    };
921                    let st_m = internal.clone();
922                    let notify_m = notify_change.clone();
923                    BaseButton::new(ElementId::NamedChild(
924                        self.id.clone().into(),
925                        SharedString::from(format!("mark-{}", mark.label())),
926                    ))
927                    .accessibility_label(mark.label())
928                    .disabled(read_only)
929                    .on_click(move |_, window, cx| {
930                        let mut out_md = String::new();
931                        let mut out_h = RichTextHistoryState {
932                            can_undo: false,
933                            can_redo: false,
934                        };
935                        st_m.update(cx, |s, _| {
936                            match mark {
937                                RichTextInlineMark::Bold => s.bold = !s.bold,
938                                RichTextInlineMark::Italic => s.italic = !s.italic,
939                                RichTextInlineMark::Strikethrough => s.strike = !s.strike,
940                                RichTextInlineMark::Code => s.code = !s.code,
941                            }
942                            let next = toggle_inline_mark_in_markdown(s.current(), mark);
943                            s.push_snapshot(next.clone());
944                            out_md = next;
945                            out_h = s.history_state();
946                        });
947                        notify_m(&out_md, out_h, window, cx);
948                    })
949                    .w(px(30.0))
950                    .h(px(30.0))
951                    .flex()
952                    .items_center()
953                    .justify_center()
954                    .rounded(px(10.0))
955                    .bg(if active {
956                        colors.accent_subtle
957                    } else {
958                        gpui_kit::Hsla::transparent_black()
959                    })
960                    .text_size(Typography::TEXT_XS)
961                    .font_semibold()
962                    .text_color(if active {
963                        colors.accent_strong
964                    } else {
965                        colors.text_secondary
966                    })
967                    .when(!read_only, |b| b.cursor_pointer())
968                    .child(mark.short_glyph())
969                });
970
971                let block_shortcuts = [
972                    RichTextBlockType::Heading1,
973                    RichTextBlockType::Heading2,
974                    RichTextBlockType::BulletedList,
975                    RichTextBlockType::NumberedList,
976                    RichTextBlockType::Blockquote,
977                    RichTextBlockType::CodeBlock,
978                    RichTextBlockType::Divider,
979                ];
980                let block_btns = block_shortcuts.into_iter().map(|blk| {
981                    let active = snap.active_block == blk;
982                    let st_b = internal.clone();
983                    let notify_b = notify_change.clone();
984                    BaseButton::new(ElementId::NamedChild(
985                        self.id.clone().into(),
986                        SharedString::from(format!("block-{}", blk.tag())),
987                    ))
988                    .accessibility_label(blk.label())
989                    .disabled(read_only)
990                    .on_click(move |_, window, cx| {
991                        let mut out_md = String::new();
992                        let mut out_h = RichTextHistoryState {
993                            can_undo: false,
994                            can_redo: false,
995                        };
996                        st_b.update(cx, |s, _| {
997                            let target = if s.active_block == blk {
998                                RichTextBlockType::Paragraph
999                            } else {
1000                                blk
1001                            };
1002                            s.active_block = target;
1003                            let next = apply_block_to_markdown(s.current(), target);
1004                            s.push_snapshot(next.clone());
1005                            out_md = next;
1006                            out_h = s.history_state();
1007                        });
1008                        notify_b(&out_md, out_h, window, cx);
1009                    })
1010                    .h(px(30.0))
1011                    .px(px(8.0))
1012                    .flex()
1013                    .items_center()
1014                    .justify_center()
1015                    .rounded(px(10.0))
1016                    .bg(if active {
1017                        colors.accent_subtle
1018                    } else {
1019                        gpui_kit::Hsla::transparent_black()
1020                    })
1021                    .text_size(Typography::TEXT_XS)
1022                    .font_medium()
1023                    .text_color(if active {
1024                        colors.accent_strong
1025                    } else {
1026                        colors.text_secondary
1027                    })
1028                    .when(!read_only, |b| b.cursor_pointer())
1029                    .child(blk.hint())
1030                });
1031
1032                let st_link = internal.clone();
1033                let st_slash = internal.clone();
1034                let st_undo = internal.clone();
1035                let notify_undo = notify_change.clone();
1036                let st_redo = internal.clone();
1037                let notify_redo = notify_change.clone();
1038
1039                div()
1040                    .id(ElementId::NamedChild(
1041                        self.id.clone().into(),
1042                        "toolbar".into(),
1043                    ))
1044                    .test_support()
1045                    .role(Role::Toolbar)
1046                    .aria_label("Formatting")
1047                    .w_full()
1048                    .p(px(4.0))
1049                    .flex()
1050                    .flex_wrap()
1051                    .items_center()
1052                    .justify_between()
1053                    .gap(px(4.0))
1054                    .rounded(Radii::CONTROL)
1055                    .border_1()
1056                    .border_color(colors.border)
1057                    .bg(colors.surface_raised)
1058                    .child(
1059                        div()
1060                            .flex()
1061                            .flex_wrap()
1062                            .items_center()
1063                            .gap(px(2.0))
1064                            .children(mark_btns)
1065                            .child(
1066                                BaseButton::new(ElementId::NamedChild(
1067                                    self.id.clone().into(),
1068                                    "open-link".into(),
1069                                ))
1070                                .accessibility_label("Link")
1071                                .disabled(read_only)
1072                                .on_click(move |_, window, cx| {
1073                                    st_link.update(cx, |s, _| {
1074                                        s.face = ToolbarFace::Link;
1075                                    });
1076                                    window.refresh();
1077                                })
1078                                .h(px(30.0))
1079                                .px(px(8.0))
1080                                .flex()
1081                                .items_center()
1082                                .rounded(px(10.0))
1083                                .bg(if snap.link_url.is_some() {
1084                                    colors.accent_subtle
1085                                } else {
1086                                    gpui_kit::Hsla::transparent_black()
1087                                })
1088                                .text_size(Typography::TEXT_XS)
1089                                .text_color(if snap.link_url.is_some() {
1090                                    colors.accent_strong
1091                                } else {
1092                                    colors.text_secondary
1093                                })
1094                                .cursor_pointer()
1095                                .child("Link"),
1096                            )
1097                            .child(div().w(px(1.0)).h(px(18.0)).mx(px(4.0)).bg(colors.border))
1098                            .children(block_btns)
1099                            .child(
1100                                BaseButton::new(ElementId::NamedChild(
1101                                    self.id.clone().into(),
1102                                    "toggle-slash".into(),
1103                                ))
1104                                .accessibility_label("Insert block")
1105                                .disabled(read_only)
1106                                .on_click(move |_, window, cx| {
1107                                    st_slash.update(cx, |s, _| {
1108                                        s.slash_open = !s.slash_open;
1109                                        s.slash_active = 0;
1110                                    });
1111                                    window.refresh();
1112                                })
1113                                .h(px(30.0))
1114                                .px(px(8.0))
1115                                .flex()
1116                                .items_center()
1117                                .rounded(px(10.0))
1118                                .bg(if snap.slash_open {
1119                                    colors.accent_subtle
1120                                } else {
1121                                    gpui_kit::Hsla::transparent_black()
1122                                })
1123                                .text_size(Typography::TEXT_XS)
1124                                .text_color(if snap.slash_open {
1125                                    colors.accent_strong
1126                                } else {
1127                                    colors.text_secondary
1128                                })
1129                                .cursor_pointer()
1130                                .child("/ Blocks"),
1131                            ),
1132                    )
1133                    .child(
1134                        div()
1135                            .flex()
1136                            .items_center()
1137                            .gap(px(4.0))
1138                            .child(
1139                                BaseButton::new(ElementId::NamedChild(
1140                                    self.id.clone().into(),
1141                                    "undo".into(),
1142                                ))
1143                                .accessibility_label("Undo")
1144                                .disabled(read_only || !hist.can_undo)
1145                                .on_click(move |_, window, cx| {
1146                                    let mut changed = None;
1147                                    st_undo.update(cx, |s, _| {
1148                                        if s.undo() {
1149                                            changed =
1150                                                Some((s.current().to_string(), s.history_state()));
1151                                        }
1152                                    });
1153                                    if let Some((md, h)) = changed {
1154                                        notify_undo(&md, h, window, cx);
1155                                    }
1156                                })
1157                                .h(px(28.0))
1158                                .px(px(8.0))
1159                                .flex()
1160                                .items_center()
1161                                .rounded(px(9.0))
1162                                .text_size(Typography::TEXT_XS)
1163                                .text_color(if hist.can_undo {
1164                                    colors.foreground
1165                                } else {
1166                                    colors.text_muted
1167                                })
1168                                .when(hist.can_undo, |b| b.cursor_pointer())
1169                                .child("Undo"),
1170                            )
1171                            .child(
1172                                BaseButton::new(ElementId::NamedChild(
1173                                    self.id.clone().into(),
1174                                    "redo".into(),
1175                                ))
1176                                .accessibility_label("Redo")
1177                                .disabled(read_only || !hist.can_redo)
1178                                .on_click(move |_, window, cx| {
1179                                    let mut changed = None;
1180                                    st_redo.update(cx, |s, _| {
1181                                        if s.redo() {
1182                                            changed =
1183                                                Some((s.current().to_string(), s.history_state()));
1184                                        }
1185                                    });
1186                                    if let Some((md, h)) = changed {
1187                                        notify_redo(&md, h, window, cx);
1188                                    }
1189                                })
1190                                .h(px(28.0))
1191                                .px(px(8.0))
1192                                .flex()
1193                                .items_center()
1194                                .rounded(px(9.0))
1195                                .text_size(Typography::TEXT_XS)
1196                                .text_color(if hist.can_redo {
1197                                    colors.foreground
1198                                } else {
1199                                    colors.text_muted
1200                                })
1201                                .when(hist.can_redo, |b| b.cursor_pointer())
1202                                .child("Redo"),
1203                            ),
1204                    )
1205            }
1206            ToolbarFace::Link => {
1207                let st_back = internal.clone();
1208                let st_apply = internal.clone();
1209                let notify_apply = notify_change.clone();
1210                let st_unlink = internal.clone();
1211                let notify_unlink = notify_change.clone();
1212                let current_link = snap
1213                    .link_url
1214                    .clone()
1215                    .unwrap_or_else(|| "https://uiarc.dev".into());
1216
1217                div()
1218                    .id(ElementId::NamedChild(
1219                        self.id.clone().into(),
1220                        "toolbar-link".into(),
1221                    ))
1222                    .test_support()
1223                    .role(Role::Toolbar)
1224                    .aria_label("Link")
1225                    .w_full()
1226                    .p(px(4.0))
1227                    .flex()
1228                    .items_center()
1229                    .justify_between()
1230                    .gap(px(6.0))
1231                    .rounded(Radii::CONTROL)
1232                    .border_1()
1233                    .border_color(colors.border)
1234                    .bg(colors.surface_raised)
1235                    .child(
1236                        BaseButton::new(ElementId::NamedChild(
1237                            self.id.clone().into(),
1238                            "link-back".into(),
1239                        ))
1240                        .accessibility_label("Back to formatting")
1241                        .on_click(move |_, window, cx| {
1242                            st_back.update(cx, |s, _| s.face = ToolbarFace::Format);
1243                            window.refresh();
1244                        })
1245                        .h(px(30.0))
1246                        .px(px(10.0))
1247                        .flex()
1248                        .items_center()
1249                        .rounded(px(10.0))
1250                        .text_size(Typography::TEXT_XS)
1251                        .text_color(colors.text_secondary)
1252                        .cursor_pointer()
1253                        .child("← Back"),
1254                    )
1255                    .child(
1256                        div()
1257                            .flex_1()
1258                            .px(px(8.0))
1259                            .text_size(Typography::TEXT_SM)
1260                            .text_color(colors.foreground)
1261                            .child(current_link.clone()),
1262                    )
1263                    .child(
1264                        div()
1265                            .flex()
1266                            .items_center()
1267                            .gap(px(4.0))
1268                            .child(
1269                                BaseButton::new(ElementId::NamedChild(
1270                                    self.id.clone().into(),
1271                                    "apply-link".into(),
1272                                ))
1273                                .accessibility_label("Apply link")
1274                                .on_click(move |_, window, cx| {
1275                                    let normalized = normalize_rich_url("uiarc.dev");
1276                                    let mut out_md = String::new();
1277                                    let mut out_h = RichTextHistoryState {
1278                                        can_undo: false,
1279                                        can_redo: false,
1280                                    };
1281                                    st_apply.update(cx, |s, _| {
1282                                        s.link_url = Some(SharedString::from(normalized.clone()));
1283                                        s.face = ToolbarFace::Format;
1284                                        let next = format!(
1285                                            "{}\n\n[Arc Documentation]({normalized})",
1286                                            s.current().trim_end()
1287                                        );
1288                                        s.push_snapshot(next.clone());
1289                                        out_md = next;
1290                                        out_h = s.history_state();
1291                                    });
1292                                    notify_apply(&out_md, out_h, window, cx);
1293                                })
1294                                .h(px(30.0))
1295                                .px(px(10.0))
1296                                .flex()
1297                                .items_center()
1298                                .rounded(px(10.0))
1299                                .bg(colors.control_fill)
1300                                .text_size(Typography::TEXT_XS)
1301                                .text_color(colors.accent_foreground)
1302                                .cursor_pointer()
1303                                .child("Apply"),
1304                            )
1305                            .when(snap.link_url.is_some(), |this| {
1306                                this.child(
1307                                    BaseButton::new(ElementId::NamedChild(
1308                                        self.id.clone().into(),
1309                                        "unlink".into(),
1310                                    ))
1311                                    .accessibility_label("Remove link")
1312                                    .on_click(move |_, window, cx| {
1313                                        let mut out_md = String::new();
1314                                        let mut out_h = RichTextHistoryState {
1315                                            can_undo: false,
1316                                            can_redo: false,
1317                                        };
1318                                        st_unlink.update(cx, |s, _| {
1319                                            s.link_url = None;
1320                                            s.face = ToolbarFace::Format;
1321                                            let next = s.current().replace(
1322                                                "[Arc Documentation](https://uiarc.dev)",
1323                                                "Arc Documentation",
1324                                            );
1325                                            s.push_snapshot(next.clone());
1326                                            out_md = next;
1327                                            out_h = s.history_state();
1328                                        });
1329                                        notify_unlink(&out_md, out_h, window, cx);
1330                                    })
1331                                    .h(px(30.0))
1332                                    .px(px(10.0))
1333                                    .flex()
1334                                    .items_center()
1335                                    .rounded(px(10.0))
1336                                    .text_size(Typography::TEXT_XS)
1337                                    .text_color(colors.danger)
1338                                    .cursor_pointer()
1339                                    .child("Unlink"),
1340                                )
1341                            }),
1342                    )
1343            }
1344        };
1345
1346        // Slash menu when open
1347        let slash_menu = if snap.slash_open {
1348            let items = filter_slash_items(snap.slash_query.as_ref());
1349            let active_idx = snap.slash_active.min(items.len().saturating_sub(1));
1350            let rows = items.iter().copied().enumerate().map(|(idx, item)| {
1351                let selected = idx == active_idx;
1352                let st_pick = internal.clone();
1353                let notify_pick = notify_change.clone();
1354                BaseButton::new(ElementId::NamedChild(
1355                    self.id.clone().into(),
1356                    SharedString::from(format!("slash-{}", item.tag())),
1357                ))
1358                .accessibility_label(item.label())
1359                .on_click(move |_, window, cx| {
1360                    let mut out_md = String::new();
1361                    let mut out_h = RichTextHistoryState {
1362                        can_undo: false,
1363                        can_redo: false,
1364                    };
1365                    st_pick.update(cx, |s, _| {
1366                        s.slash_open = false;
1367                        s.active_block = item;
1368                        let next = apply_block_to_markdown(s.current(), item);
1369                        s.push_snapshot(next.clone());
1370                        out_md = next;
1371                        out_h = s.history_state();
1372                    });
1373                    notify_pick(&out_md, out_h, window, cx);
1374                })
1375                .w_full()
1376                .h(px(32.0))
1377                .px(px(10.0))
1378                .flex()
1379                .items_center()
1380                .justify_between()
1381                .rounded(px(10.0))
1382                .bg(if selected {
1383                    colors.surface_muted
1384                } else {
1385                    gpui_kit::Hsla::transparent_black()
1386                })
1387                .cursor_pointer()
1388                .child(
1389                    div()
1390                        .text_size(Typography::TEXT_SM)
1391                        .font_medium()
1392                        .text_color(if selected {
1393                            colors.foreground
1394                        } else {
1395                            colors.text_secondary
1396                        })
1397                        .child(item.label()),
1398                )
1399                .child(
1400                    div()
1401                        .text_size(Typography::TEXT_XS)
1402                        .text_color(colors.text_muted)
1403                        .child(item.hint()),
1404                )
1405            });
1406
1407            Some(
1408                div()
1409                    .id(ElementId::NamedChild(
1410                        self.id.clone().into(),
1411                        "slash-menu".into(),
1412                    ))
1413                    .test_support()
1414                    .role(Role::ListBox)
1415                    .aria_label("Block types")
1416                    .w(px(240.0))
1417                    .p(px(6.0))
1418                    .flex()
1419                    .flex_col()
1420                    .gap(px(2.0))
1421                    .rounded(Radii::CONTROL)
1422                    .border_1()
1423                    .border_color(colors.border)
1424                    .bg(colors.surface_raised)
1425                    .children(rows),
1426            )
1427        } else {
1428            None
1429        };
1430
1431        let is_editor_focused = snap.focus_handle.is_focused(window);
1432        let strip_inline_markers = |s: &str| -> String {
1433            let mut out = s
1434                .replace("**", "")
1435                .replace("~~", "")
1436                .replace(['`', '_'], "");
1437            while let Some(open_b) = out.find('[') {
1438                if let Some(mid_rel) = out[open_b..].find("](") {
1439                    let mid = open_b + mid_rel;
1440                    if let Some(close_rel) = out[mid + 2..].find(')') {
1441                        let close_p = mid + 2 + close_rel;
1442                        let label = out[open_b + 1..mid].to_string();
1443                        out.replace_range(open_b..=close_p, &label);
1444                        continue;
1445                    }
1446                }
1447                break;
1448            }
1449            out
1450        };
1451
1452        // Render structured document blocks from `current_md`.
1453        let block_elements: Vec<AnyElement> = if value.empty {
1454            vec![
1455                div()
1456                    .text_size(Typography::TEXT_BASE)
1457                    .text_color(colors.text_muted)
1458                    .child(self.placeholder.clone())
1459                    .into_any_element(),
1460            ]
1461        } else {
1462            let blocks_vec: Vec<&str> = current_md
1463                .split("\n\n")
1464                .filter(|b| !b.trim().is_empty())
1465                .collect();
1466            let last_block_idx = blocks_vec.len().saturating_sub(1);
1467            blocks_vec
1468                .into_iter()
1469                .enumerate()
1470                .map(|(b_idx, block_str)| {
1471                    let t = block_str.trim();
1472                    let is_last = b_idx == last_block_idx;
1473                    let has_bold = t.contains("**");
1474                    let has_italic = t.contains('_');
1475                    let has_strike = t.contains("~~");
1476                    let has_code = t.contains('`') && !t.starts_with("```");
1477                    if t == "---" {
1478                        return div()
1479                            .w_full()
1480                            .h(px(1.0))
1481                            .my(Spacing::S2)
1482                            .bg(colors.border)
1483                            .into_any_element();
1484                    }
1485                    if let Some(h1) = t.strip_prefix("# ") {
1486                        return div()
1487                            .text_size(Typography::TEXT_2XL)
1488                            .font_semibold()
1489                            .when(has_italic, |d| d.italic())
1490                            .when(has_strike, |d| d.line_through())
1491                            .text_color(colors.foreground)
1492                            .child(SharedString::from(strip_inline_markers(h1)))
1493                            .into_any_element();
1494                    }
1495                    if let Some(h2) = t.strip_prefix("## ") {
1496                        return div()
1497                            .text_size(Typography::TEXT_XL)
1498                            .font_semibold()
1499                            .when(has_italic, |d| d.italic())
1500                            .when(has_strike, |d| d.line_through())
1501                            .text_color(colors.foreground)
1502                            .child(SharedString::from(strip_inline_markers(h2)))
1503                            .into_any_element();
1504                    }
1505                    if let Some(h3) = t.strip_prefix("### ") {
1506                        return div()
1507                            .text_size(Typography::TEXT_LG)
1508                            .font_semibold()
1509                            .when(has_italic, |d| d.italic())
1510                            .when(has_strike, |d| d.line_through())
1511                            .text_color(colors.foreground)
1512                            .child(SharedString::from(strip_inline_markers(h3)))
1513                            .into_any_element();
1514                    }
1515                    if t.starts_with("```") {
1516                        let code = t.trim_start_matches("```").trim_end_matches("```").trim();
1517                        return div()
1518                            .w_full()
1519                            .p(Spacing::S3)
1520                            .rounded(px(6.0))
1521                            .border_1()
1522                            .border_color(colors.border_subtle)
1523                            .bg(colors.surface_muted)
1524                            .text_size(Typography::TEXT_SM)
1525                            .text_color(colors.foreground)
1526                            .child(SharedString::from(code.to_string()))
1527                            .into_any_element();
1528                    }
1529                    if t.starts_with('>') {
1530                        let quote_text = t
1531                            .lines()
1532                            .map(|l| strip_inline_markers(l.trim_start_matches('>').trim()))
1533                            .collect::<Vec<_>>()
1534                            .join("\n");
1535                        return div()
1536                            .pl(px(14.0))
1537                            .border_l_2()
1538                            .border_color(colors.border_strong)
1539                            .text_size(Typography::TEXT_BASE)
1540                            .when(has_bold, |d| d.font_semibold())
1541                            .when(has_italic, |d| d.italic())
1542                            .when(has_strike, |d| d.line_through())
1543                            .text_color(colors.text_secondary)
1544                            .child(SharedString::from(quote_text))
1545                            .into_any_element();
1546                    }
1547                    let mut display_txt = strip_inline_markers(t);
1548                    if is_last && is_editor_focused && !read_only {
1549                        display_txt.push('▏');
1550                    }
1551                    div()
1552                        .text_size(Typography::TEXT_BASE)
1553                        .when(has_bold, |d| d.font_semibold())
1554                        .when(has_italic, |d| d.italic())
1555                        .when(has_strike, |d| d.line_through())
1556                        .when(has_code, |d| {
1557                            d.px(px(6.0))
1558                                .py(px(2.0))
1559                                .rounded(px(6.0))
1560                                .bg(colors.surface_muted)
1561                        })
1562                        .text_color(colors.foreground)
1563                        .child(SharedString::from(display_txt))
1564                        .into_any_element()
1565                })
1566                .collect()
1567        };
1568
1569        let focus_handle = snap.focus_handle.clone();
1570        let focus_for_click = snap.focus_handle.clone();
1571        let st_key = internal.clone();
1572        let notify_key = notify_change.clone();
1573
1574        let editor_surface = div()
1575            .id(ElementId::NamedChild(
1576                self.id.clone().into(),
1577                "editor".into(),
1578            ))
1579            .test_support()
1580            .track_focus(&focus_handle)
1581            .role(Role::Group)
1582            .aria_label(self.aria_label.clone())
1583            .w_full()
1584            .min_h(px(148.0))
1585            .p(Spacing::S4)
1586            .flex()
1587            .flex_col()
1588            .gap(Spacing::S3)
1589            .rounded(Radii::PANEL)
1590            .border_1()
1591            .border_color(if is_editor_focused && !read_only {
1592                colors.control_fill
1593            } else {
1594                colors.border
1595            })
1596            .bg(colors.surface)
1597            .when(!read_only, |d| {
1598                d.cursor_text()
1599                    .on_mouse_down(gpui_kit::MouseButton::Left, move |_, window, cx| {
1600                        window.focus(&focus_for_click, cx);
1601                        window.refresh();
1602                    })
1603            })
1604            .on_key_down(move |event: &KeyDownEvent, window, cx| {
1605                if read_only {
1606                    return;
1607                }
1608                let mods = event.keystroke.modifiers;
1609                let cmd = mods.platform || mods.control;
1610                let key = event.keystroke.key.as_str();
1611                let mut changed = None;
1612                st_key.update(cx, |s, _| {
1613                    if cmd && key.eq_ignore_ascii_case("z") {
1614                        let ok = if mods.shift { s.redo() } else { s.undo() };
1615                        if ok {
1616                            changed = Some((s.current().to_string(), s.history_state()));
1617                        }
1618                    } else if cmd && key.eq_ignore_ascii_case("b") {
1619                        s.bold = !s.bold;
1620                        let next =
1621                            toggle_inline_mark_in_markdown(s.current(), RichTextInlineMark::Bold);
1622                        s.push_snapshot(next.clone());
1623                        changed = Some((next, s.history_state()));
1624                    } else if cmd && key.eq_ignore_ascii_case("i") {
1625                        s.italic = !s.italic;
1626                        let next =
1627                            toggle_inline_mark_in_markdown(s.current(), RichTextInlineMark::Italic);
1628                        s.push_snapshot(next.clone());
1629                        changed = Some((next, s.history_state()));
1630                    } else if key == "/" && !cmd {
1631                        s.slash_open = !s.slash_open;
1632                        s.slash_active = 0;
1633                    } else if key == "escape" {
1634                        s.slash_open = false;
1635                        s.face = ToolbarFace::Format;
1636                    } else if key == "backspace" && !cmd {
1637                        let cur = s.current();
1638                        let next: String = cur
1639                            .chars()
1640                            .take(cur.chars().count().saturating_sub(1))
1641                            .collect();
1642                        s.push_snapshot(next.clone());
1643                        changed = Some((next, s.history_state()));
1644                    } else if key == "enter" && !cmd {
1645                        let next = format!("{}\n\n", s.current().trim_end());
1646                        s.push_snapshot(next.clone());
1647                        changed = Some((next, s.history_state()));
1648                    } else if (key == "space" || key == " ") && !cmd {
1649                        let next = format!("{} ", s.current());
1650                        s.push_snapshot(next.clone());
1651                        changed = Some((next, s.history_state()));
1652                    } else if !cmd {
1653                        let ch_str = event
1654                            .keystroke
1655                            .key_char
1656                            .as_deref()
1657                            .filter(|kc| !kc.is_empty() && kc.chars().all(|c| !c.is_control()))
1658                            .map(|kc| kc.to_string())
1659                            .or_else(|| {
1660                                (key.len() == 1)
1661                                    .then(|| key.chars().next())
1662                                    .flatten()
1663                                    .filter(|c| !c.is_control())
1664                                    .map(|c| {
1665                                        if mods.shift {
1666                                            c.to_ascii_uppercase().to_string()
1667                                        } else {
1668                                            c.to_string()
1669                                        }
1670                                    })
1671                            });
1672                        if let Some(append) = ch_str {
1673                            let next = format!("{}{append}", s.current());
1674                            s.push_snapshot(next.clone());
1675                            changed = Some((next, s.history_state()));
1676                        }
1677                    }
1678                });
1679                if let Some((md, h)) = changed {
1680                    notify_key(&md, h, window, cx);
1681                } else {
1682                    window.refresh();
1683                }
1684            })
1685            .children(block_elements)
1686            .child(
1687                div()
1688                    .pt(Spacing::S2)
1689                    .border_t_1()
1690                    .border_color(colors.border_subtle)
1691                    .flex()
1692                    .items_center()
1693                    .justify_between()
1694                    .text_size(Typography::TEXT_XS)
1695                    .text_color(colors.text_muted)
1696                    .child(self.block_hint.clone())
1697                    .child(SharedString::from(format!(
1698                        "{} chars · HTML {}B",
1699                        value.text.len(),
1700                        value.html.len()
1701                    ))),
1702            );
1703
1704        div()
1705            .id(self.id.clone())
1706            .test_support()
1707            .when_some(self.width, |this, w| this.w(w))
1708            .when(self.width.is_none(), |this| this.w_full())
1709            .flex()
1710            .flex_col()
1711            .gap(Spacing::S3)
1712            .child(toolbar)
1713            .when_some(slash_menu, |this, menu| this.child(menu))
1714            .child(editor_surface)
1715    }
1716}
1717
1718#[cfg(test)]
1719mod tests {
1720    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
1721    use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
1722
1723    use super::*;
1724
1725    #[test]
1726    fn url_normalization_and_safety() {
1727        assert_eq!(
1728            normalize_rich_url("uiarc.dev/docs"),
1729            "https://uiarc.dev/docs"
1730        );
1731        assert_eq!(
1732            normalize_rich_url("team@uiarc.dev"),
1733            "mailto:team@uiarc.dev"
1734        );
1735        assert_eq!(normalize_rich_url("/local/path"), "/local/path");
1736        assert_eq!(normalize_rich_url("#section"), "#section");
1737        assert!(is_safe_rich_url("https://uiarc.dev"));
1738        assert!(!is_safe_rich_url("javascript:alert(1)"));
1739    }
1740
1741    #[test]
1742    fn markdown_and_html_round_trip_blocks_and_marks() {
1743        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---";
1744        let html = markdown_to_html(md);
1745        assert!(html.contains("<h1>Title</h1>"));
1746        assert!(html.contains("<strong>bold</strong>"));
1747        assert!(html.contains("<em>italic</em>"));
1748        assert!(html.contains("<s>strike</s>"));
1749        assert!(html.contains("<code>code</code>"));
1750        assert!(html.contains("<a href=\"https://uiarc.dev\">Arc</a>"));
1751        assert!(html.contains("<blockquote>A quiet quote</blockquote>"));
1752        assert!(html.contains("<ul><li>First item</li><li>Second item</li></ul>"));
1753        assert!(html.contains("<pre>let x = 1;</pre>"));
1754        assert!(html.contains("<hr>"));
1755
1756        let round_tripped = html_to_markdown(&html);
1757        assert_eq!(round_tripped, md);
1758    }
1759
1760    #[test]
1761    fn slash_filter_matches_keywords_and_hints() {
1762        assert_eq!(filter_slash_items("").len(), 9);
1763        assert_eq!(filter_slash_items("h2"), vec![RichTextBlockType::Heading2]);
1764        assert_eq!(
1765            filter_slash_items("quote"),
1766            vec![RichTextBlockType::Blockquote]
1767        );
1768    }
1769
1770    struct EditorHost;
1771
1772    impl Render for EditorHost {
1773        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1774            div()
1775                .w(px(620.0))
1776                .p(px(16.0))
1777                .child(RichTextEditor::new("rte-test"))
1778        }
1779    }
1780
1781    #[gpui_kit::test]
1782    fn rich_text_editor_renders_toolbar_and_surface(cx: &mut TestAppContext) {
1783        cx.update(|cx| {
1784            gpui_kit::init(cx);
1785            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
1786        });
1787
1788        let (_view, cx) = cx.add_window_view(|_, _| EditorHost);
1789        cx.update(|window, cx| {
1790            window.render_frame(cx);
1791            let toolbar = window.find(ElementId::NamedChild(
1792                ElementId::Name("rte-test".into()).into(),
1793                "toolbar".into(),
1794            ));
1795            assert_eq!(toolbar.role(), Some(Role::Toolbar));
1796            let editor = window.find(ElementId::NamedChild(
1797                ElementId::Name("rte-test".into()).into(),
1798                "editor".into(),
1799            ));
1800            assert_eq!(editor.role(), Some(Role::Group));
1801        });
1802    }
1803}