Skip to main content

lexical_ui/code/
code_import_extension.rs

1//! `CodeImportExtension.ts`: the `DOMImportExtension` rules for code
2//! blocks (`@experimental` upstream), with the GitHub raw file view
3//! detectors and the VS Code paste overlay, which `CodeExtension`
4//! contributes.
5
6use super::code_node::create_code_node;
7use super::flat_structure_utils::plainify_code_content;
8use crate::LexicalError;
9use crate::dom::DomNode;
10use crate::html::import::{
11    CompiledOverlayRules, DomImportRule, DomPreprocessFn, ImportChildrenOpts, define_import_rule,
12    define_overlay_rules, import_overlays, is_block_level, sel,
13};
14use crate::node::NodeRef;
15use std::rc::Rc;
16
17const LANGUAGE_DATA_ATTRIBUTE: &str = "data-language";
18const THEME_DATA_ATTRIBUTE: &str = "data-theme";
19
20/// `$normalizeCodeChildren(children)`: the children's plain text, with a
21/// line break on each side of a block, as code highlight nodes.
22fn normalize_code_children(children: &[NodeRef]) -> Vec<NodeRef> {
23    let mut text = String::new();
24    let mut previous_was_block = false;
25    for (i, child) in children.iter().enumerate() {
26        let is_block = is_block_level(child);
27        if i > 0 && (is_block || previous_was_block) {
28            text.push('\n');
29        }
30        text.push_str(&child.get_text_content());
31        previous_was_block = is_block;
32    }
33    plainify_code_content(&text)
34}
35
36/// A code block of `language` and `theme` with `children`.
37fn code_block(
38    language: Option<String>,
39    theme: Option<String>,
40    children: &[NodeRef],
41) -> Result<Vec<NodeRef>, LexicalError> {
42    let node = create_code_node(language.as_deref(), theme.as_deref());
43    node.splice(0, 0, children)?;
44    Ok(vec![node])
45}
46
47/// `isMonospaceElement(el)`: a `font-family` that mentions `monospace`
48/// (case-sensitively, as `String#match` with a string does).
49fn is_monospace_element(el: &DomNode) -> bool {
50    el.style()
51        .get_property_value("font-family")
52        .contains("monospace")
53}
54
55/// `isMonospaceDescendant(node)`.
56fn is_monospace_descendant(node: &DomNode) -> bool {
57    let mut parent = node.parent_element();
58    while let Some(p) = parent {
59        if is_monospace_element(&p) {
60            return true;
61        }
62        parent = p.parent_element();
63    }
64    false
65}
66
67/// `GitHubCodeTableOverlayRules`: inside a GitHub code table every `<tr>`
68/// and `<td>` gives way to its children.
69fn github_code_table_overlay_rules() -> Rc<CompiledOverlayRules> {
70    define_overlay_rules(&[define_import_rule(
71        Some("@lexical/code/github-code-table/unwrap"),
72        sel::tag(&["tr", "td"]),
73        |ctx, el, _| ctx.import_children(el, &ImportChildrenOpts::default()),
74    )
75    .into()])
76}
77
78/// `PreRule`.
79fn pre_rule() -> DomImportRule {
80    define_import_rule(
81        Some("@lexical/code/pre"),
82        sel::tag(&["pre"]),
83        |ctx, el, _| {
84            let children = ctx.import_children(el, &ImportChildrenOpts::default())?;
85            code_block(
86                el.get_attribute(LANGUAGE_DATA_ATTRIBUTE),
87                el.get_attribute(THEME_DATA_ATTRIBUTE),
88                &normalize_code_children(&children),
89            )
90        },
91    )
92}
93
94/// `MultilineCodeRule`: a `<code>` with a newline or a `<br>` is a code
95/// block; a single line defers to the inline format rule.
96fn multiline_code_rule() -> DomImportRule {
97    define_import_rule(
98        Some("@lexical/code/code-multiline"),
99        sel::tag(&["code"]),
100        |ctx, el, next| {
101            let is_multi_line = el.text_content().contains('\n')
102                || el
103                    .query_selector_all("br")
104                    .is_ok_and(|found| !found.is_empty());
105            if !is_multi_line {
106                return next();
107            }
108            let children = ctx.import_children(el, &ImportChildrenOpts::default())?;
109            code_block(
110                el.get_attribute(LANGUAGE_DATA_ATTRIBUTE),
111                el.get_attribute(THEME_DATA_ATTRIBUTE),
112                &normalize_code_children(&children),
113            )
114        },
115    )
116}
117
118/// `isMonospacePreElement(el)`: a `font-family` with `monospace` (in any
119/// case) and a `white-space` of `pre*`, the shape of each line VS Code
120/// copies.
121fn is_monospace_pre_element(el: &DomNode) -> bool {
122    if !el.is_element() {
123        return false;
124    }
125    let style = el.style();
126    style
127        .get_property_value("font-family")
128        .to_lowercase()
129        .contains("monospace")
130        && style.get_property_value("white-space").starts_with("pre")
131}
132
133/// `splitMonospaceWrapperLines(el)`: a wrapper's lines (a `<div>` child's
134/// text, an empty line for a `<br>`, and runs of other children joined),
135/// or `None` when it has no block child.
136fn split_monospace_wrapper_lines(el: &DomNode) -> Option<Vec<String>> {
137    let mut has_block_child = false;
138    let mut lines = Vec::new();
139    let mut acc: Option<String> = None;
140    for child in el.child_nodes() {
141        if child.is_element() {
142            match child.tag_name().as_str() {
143                "DIV" => {
144                    lines.extend(acc.take());
145                    lines.push(child.text_content());
146                    has_block_child = true;
147                }
148                "BR" => {
149                    lines.extend(acc.take());
150                    lines.push(String::new());
151                    has_block_child = true;
152                }
153                _ => acc.get_or_insert_default().push_str(&child.text_content()),
154            }
155        } else if child.is_text() {
156            let t = child.text_content();
157            if !t.is_empty() {
158                acc.get_or_insert_default().push_str(&t);
159            }
160        }
161    }
162    lines.extend(acc);
163    has_block_child.then_some(lines)
164}
165
166/// `looksLikeVscodePaste(root)`: a monospace pre wrapper with a block
167/// child (Chrome), or two monospace pre siblings (Safari).
168fn looks_like_vscode_paste(root: &DomNode) -> bool {
169    for child in root.children() {
170        if is_monospace_pre_element(&child) {
171            if split_monospace_wrapper_lines(&child).is_some() {
172                return true;
173            }
174            if child
175                .next_element_sibling()
176                .is_some_and(|next| is_monospace_pre_element(&next))
177            {
178                return true;
179            }
180            continue;
181        }
182        if looks_like_vscode_paste(&child) {
183            return true;
184        }
185    }
186    false
187}
188
189/// `VscodeWrapperRule`: Chrome's one wrapper around per-line `<div>`s and
190/// `<br>`s, as one code block.
191fn vscode_wrapper_rule() -> DomImportRule {
192    define_import_rule(
193        Some("@lexical/code/vscode-wrapper"),
194        sel::tag(&["div"]),
195        |_, el, next| {
196            if !is_monospace_pre_element(el) || is_monospace_descendant(el) {
197                return next();
198            }
199            match split_monospace_wrapper_lines(el) {
200                Some(lines) if !lines.is_empty() => {
201                    code_block(None, None, &plainify_code_content(&lines.join("\n")))
202                }
203                _ => next(),
204            }
205        },
206    )
207}
208
209/// `VscodeLineRunRule`: Safari's run of monospace pre `<div>` and `<br>`
210/// siblings, as one code block made by the run's first element.
211fn vscode_line_run_rule() -> DomImportRule {
212    define_import_rule(
213        Some("@lexical/code/vscode-line-run"),
214        sel::tag(&["div", "br"]),
215        |_, el, next| {
216            if !is_monospace_pre_element(el) || is_monospace_descendant(el) {
217                return next();
218            }
219            if el
220                .previous_element_sibling()
221                .is_some_and(|prev| is_monospace_pre_element(&prev))
222            {
223                // An earlier sibling's run took this one in.
224                return Ok(Vec::new());
225            }
226            let mut lines = Vec::new();
227            let mut cur = Some(el.clone());
228            while let Some(node) = cur.filter(is_monospace_pre_element) {
229                lines.push(if node.tag_name() == "BR" {
230                    String::new()
231                } else {
232                    node.text_content()
233                });
234                cur = node.next_element_sibling();
235            }
236            if lines.len() < 2 {
237                return next();
238            }
239            code_block(None, None, &plainify_code_content(&lines.join("\n")))
240        },
241    )
242}
243
244/// `$installVscodeCodePasteOverlay` (`@experimental`): installs the VS
245/// Code overlay (its wrapper and line run rules) when the DOM looks like a
246/// VS Code code block paste.
247pub fn install_vscode_code_paste_overlay() -> DomPreprocessFn {
248    let overlay =
249        define_overlay_rules(&[vscode_wrapper_rule().into(), vscode_line_run_rule().into()]);
250    Rc::new(move |dom, ctx, next| {
251        let root = if dom.is_document() {
252            dom.body()
253        } else {
254            Some(dom.clone())
255        };
256        if root.is_some_and(|root| looks_like_vscode_paste(&root)) {
257            let overlay = overlay.clone();
258            ctx.session.update(&import_overlays(), move |mut prev| {
259                prev.push(overlay);
260                prev
261            });
262        }
263        next()
264    })
265}
266
267/// `DivRule`: a monospace `<div>` (Google Docs' code block) is a code
268/// block.
269fn div_rule() -> DomImportRule {
270    define_import_rule(
271        Some("@lexical/code/div"),
272        sel::tag(&["div"]),
273        |ctx, el, next| {
274            if !is_monospace_element(el) {
275                return next();
276            }
277            let children = ctx.import_children(el, &ImportChildrenOpts::default())?;
278            code_block(None, None, &normalize_code_children(&children))
279        },
280    )
281}
282
283/// `GitHubCodeTableRule`: GitHub's raw file view table is a code block,
284/// its rows and cells unwrapped by an overlay.
285fn github_code_table_rule() -> DomImportRule {
286    let overlay = github_code_table_overlay_rules();
287    define_import_rule(
288        Some("@lexical/code/github-code-table"),
289        sel::tag(&["table"]).class_all(&["js-file-line-container"]),
290        move |ctx, el, _| {
291            let opts = ImportChildrenOpts {
292                rules: Some(overlay.clone()),
293                ..ImportChildrenOpts::default()
294            };
295            let children = ctx.import_children(el, &opts)?;
296            code_block(None, None, &normalize_code_children(&children))
297        },
298    )
299}
300
301/// `GitHubCodeCellByClassRule`: a stray GitHub code line cell gives way to
302/// its children.
303fn github_code_cell_by_class_rule() -> DomImportRule {
304    define_import_rule(
305        Some("@lexical/code/github-code-cell-by-class"),
306        sel::tag(&["td"]).class_all(&["js-file-line"]),
307        |ctx, el, _| ctx.import_children(el, &ImportChildrenOpts::default()),
308    )
309}
310
311/// `CodeImportRules` (`@experimental`): the import rules for `CodeNode`,
312/// the GitHub detectors first. `CodeExtension` contributes them, with
313/// `CoreImportExtension` and [`install_vscode_code_paste_overlay`].
314pub fn code_import_rules() -> Vec<DomImportRule> {
315    vec![
316        github_code_table_rule(),
317        github_code_cell_by_class_rule(),
318        multiline_code_rule(),
319        pre_rule(),
320        div_rule(),
321    ]
322}