mirror of
https://github.com/lexmount/moli.git
synced 2026-11-24 16:02:53 +00:00
fix: refresh automatic direction and preserve Markdown bidi semantics
This commit is contained in:
+25
-15
@@ -25,7 +25,7 @@ enum Task<'a, Id, Children> {
|
||||
EndRawBlock,
|
||||
EndCode,
|
||||
EndPre(Option<&'a str>),
|
||||
EndBidiIsolate,
|
||||
EndBidi(&'static str),
|
||||
TableCell,
|
||||
EndTableCell,
|
||||
}
|
||||
@@ -192,7 +192,7 @@ impl<'a, D: Dom + ?Sized, Children: Iterator<Item = D::NodeId>> Machine<'a, D, C
|
||||
self.writer().code_with_edges(&text, preformatted);
|
||||
}
|
||||
Task::EndPre(language) => self.end_pre(language),
|
||||
Task::EndBidiIsolate => self.writer().text("\u{2069}"),
|
||||
Task::EndBidi(controls) => self.writer().bidi_controls(controls),
|
||||
Task::TableCell => self.table_cell(),
|
||||
Task::EndTableCell => {
|
||||
let content = self.take_writer();
|
||||
@@ -342,20 +342,30 @@ impl<'a, D: Dom + ?Sized, Children: Iterator<Item = D::NodeId>> Machine<'a, D, C
|
||||
"sup" => self.style(Style::Superscript),
|
||||
"sub" => self.style(Style::Subscript),
|
||||
"bdi" | "bdo" => {
|
||||
if let Some(dir) = self.dom.attribute(node, "dir").map(str::trim) {
|
||||
let prefix = if dir.eq_ignore_ascii_case("ltr") {
|
||||
Some("\u{2066}")
|
||||
} else if dir.eq_ignore_ascii_case("rtl") {
|
||||
Some("\u{2067}")
|
||||
} else if dir.eq_ignore_ascii_case("auto") {
|
||||
Some("\u{2068}")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(p) = prefix {
|
||||
self.writer().text(p);
|
||||
self.tasks.push(Task::EndBidiIsolate);
|
||||
let dir = self.dom.attribute(node, "dir").map(str::trim);
|
||||
let controls = match (tag, dir) {
|
||||
("bdi", Some(dir)) if dir.eq_ignore_ascii_case("ltr") => {
|
||||
Some(("\u{2066}", "\u{2069}"))
|
||||
}
|
||||
("bdi", Some(dir)) if dir.eq_ignore_ascii_case("rtl") => {
|
||||
Some(("\u{2067}", "\u{2069}"))
|
||||
}
|
||||
("bdi", Some(dir)) if dir.eq_ignore_ascii_case("auto") => {
|
||||
Some(("\u{2068}", "\u{2069}"))
|
||||
}
|
||||
// BDO starts an isolate and an override. PDF ends the
|
||||
// override before PDI ends the isolate.
|
||||
("bdo", Some(dir)) if dir.eq_ignore_ascii_case("ltr") => {
|
||||
Some(("\u{2068}\u{202d}", "\u{202c}\u{2069}"))
|
||||
}
|
||||
("bdo", Some(dir)) if dir.eq_ignore_ascii_case("rtl") => {
|
||||
Some(("\u{2068}\u{202e}", "\u{202c}\u{2069}"))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some((start, end)) = controls {
|
||||
self.writer().bidi_controls(start);
|
||||
self.tasks.push(Task::EndBidi(end));
|
||||
}
|
||||
}
|
||||
"a" => {
|
||||
|
||||
@@ -140,6 +140,11 @@ impl<'a> Writer<'a> {
|
||||
self.pending_text.push_str(text);
|
||||
}
|
||||
|
||||
pub(crate) fn bidi_controls(&mut self, controls: &str) {
|
||||
// Generated formatting controls do not supply a readable name.
|
||||
self.pending_text.push_str(controls);
|
||||
}
|
||||
|
||||
fn flush_pending_text(&mut self) {
|
||||
if self.pending_text.is_empty() {
|
||||
return;
|
||||
|
||||
@@ -211,6 +211,8 @@ fn empty_targets_and_formatting_do_not_hide_accessible_names() {
|
||||
"<i class='fa fa-search'></i>",
|
||||
"<em><strong></strong></em>",
|
||||
"<sub></sub>",
|
||||
"<bdi dir='ltr'></bdi>",
|
||||
"<bdo dir='rtl'> </bdo>",
|
||||
"<span> </span>",
|
||||
] {
|
||||
for control in ["button", "a href='/search'"] {
|
||||
@@ -1306,9 +1308,19 @@ fn expanded_anchors_preserve_inherited_author_link_context() {
|
||||
#[test]
|
||||
fn preserves_explicit_bidi_isolation_for_arabic_rtl_and_ltr_tokens() {
|
||||
let source =
|
||||
r#"<p dir="rtl">السعر هو <bdi dir="ltr">100 USD</bdi> مع <bdo dir="rtl">ضمان</bdo></p>"#;
|
||||
r#"<p dir="rtl">السعر هو <bdi dir="ltr">100 USD</bdi> مع <bdi dir="rtl">ضمان</bdi></p>"#;
|
||||
let input = Tree::parse(source);
|
||||
let markdown = convert(&input, input.root);
|
||||
assert!(markdown.contains("\u{2066}100 USD\u{2069}"), "{markdown:?}");
|
||||
assert!(markdown.contains("\u{2067}ضمان\u{2069}"), "{markdown:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_bdo_overrides_of_opposite_direction_text() {
|
||||
let input = Tree::parse(r#"<bdo dir="rtl">abc</bdo> <bdo dir="ltr">אבג</bdo>"#);
|
||||
let markdown = convert(&input, input.root);
|
||||
assert_eq!(
|
||||
markdown,
|
||||
"\u{2068}\u{202e}abc\u{202c}\u{2069} \u{2068}\u{202d}אבג\u{202c}\u{2069}"
|
||||
);
|
||||
}
|
||||
|
||||
+67
@@ -527,6 +527,73 @@ fn computed_direction_tracks_input_html_directionality() {
|
||||
assert_eq!(result, "true:ltr|true:rtl|true:ltr|true:rtl|true:ltr");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn computed_auto_direction_tracks_text_edits_and_child_list_changes() {
|
||||
let mut vm = new_parsed_test_vm(
|
||||
"https://auto-direction-text.test/",
|
||||
"<!doctype html><div dir=auto><span>ת</span><em></em></div><bdi><span>ת</span><em></em></bdi>",
|
||||
);
|
||||
let result = vm
|
||||
.eval(
|
||||
r#"
|
||||
(() => {
|
||||
const results = [];
|
||||
for (const root of document.querySelectorAll('[dir=auto], bdi')) {
|
||||
const span = root.firstElementChild;
|
||||
const inherited = root.lastElementChild;
|
||||
const read = () => [
|
||||
root.matches(':dir(rtl)'),
|
||||
getComputedStyle(root).direction,
|
||||
getComputedStyle(inherited).direction,
|
||||
].join(':');
|
||||
results.push(read());
|
||||
span.firstChild.data = 'abc';
|
||||
results.push(read());
|
||||
span.textContent = '\u05ea';
|
||||
results.push(read());
|
||||
span.dir = 'ltr';
|
||||
results.push(read());
|
||||
span.removeAttribute('dir');
|
||||
results.push(read());
|
||||
span.firstChild.remove();
|
||||
results.push(read());
|
||||
}
|
||||
return results.join('|');
|
||||
})()
|
||||
"#,
|
||||
)
|
||||
.expect("computed direction should update after text mutations");
|
||||
let expected =
|
||||
"true:rtl:rtl|false:ltr:ltr|true:rtl:rtl|false:ltr:ltr|true:rtl:rtl|false:ltr:ltr";
|
||||
assert_eq!(result, format!("{expected}|{expected}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn computed_auto_direction_tracks_control_value_changes() {
|
||||
let mut vm = new_parsed_test_vm(
|
||||
"https://auto-direction-controls.test/",
|
||||
"<!doctype html><input dir=auto value=ת><textarea dir=auto>ת</textarea>",
|
||||
);
|
||||
let result = vm
|
||||
.eval(
|
||||
r#"
|
||||
(() => {
|
||||
const results = [];
|
||||
for (const control of document.querySelectorAll('[dir=auto]')) {
|
||||
results.push(getComputedStyle(control).direction);
|
||||
control.value = 'abc';
|
||||
results.push(getComputedStyle(control).direction);
|
||||
control.value = '\u05ea';
|
||||
results.push(getComputedStyle(control).direction);
|
||||
}
|
||||
return results.join('|');
|
||||
})()
|
||||
"#,
|
||||
)
|
||||
.expect("computed direction should update after control value changes");
|
||||
assert_eq!(result, "rtl|ltr|rtl|rtl|ltr|rtl");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn has_pseudo_class_computed_style_updates_after_dom_mutation() {
|
||||
let mut vm = new_storage_test_vm("https://has-pseudo-computed-style.test/");
|
||||
|
||||
@@ -2,7 +2,10 @@ use std::{borrow::Cow, collections::HashMap, sync::Arc};
|
||||
|
||||
use dom::ElementState as StyloElementState;
|
||||
use indexmap::IndexSet;
|
||||
use moli_selector::StyloStyleSourceScope as StyleSourceScope;
|
||||
use moli_selector::{
|
||||
CssDirection, StyloStyleSourceScope as StyleSourceScope, html_auto_directionality_root,
|
||||
html_directionality,
|
||||
};
|
||||
use smallvec::SmallVec;
|
||||
|
||||
use crate::{
|
||||
@@ -190,6 +193,7 @@ impl MoliStyleEngine {
|
||||
emulated_media: &EmulatedMediaOverrides,
|
||||
viewport: StyleViewport,
|
||||
) {
|
||||
self.invalidate_direction_hint_subtrees_for_mutations(world, host, effects);
|
||||
let profile_enabled = moli_trace::cpu_profile_enabled();
|
||||
let total_started = profile_enabled.then(std::time::Instant::now);
|
||||
let source_scope_started = profile_enabled.then(std::time::Instant::now);
|
||||
@@ -244,6 +248,7 @@ impl MoliStyleEngine {
|
||||
// Exhausted fragments can still contribute detached roots and source
|
||||
// ownership. Resolve these against the full history before pruning.
|
||||
self.invalidate_detached_style_subtrees_for_mutations(host, &effects);
|
||||
self.invalidate_direction_hint_subtrees_for_mutations(world, host, &effects);
|
||||
let source_scope = source_scope_for_mutations(host, &effects);
|
||||
let merged_count = effects.len();
|
||||
retain_live_structural_mutation_effects(host, &mut effects);
|
||||
@@ -280,6 +285,43 @@ impl MoliStyleEngine {
|
||||
}
|
||||
}
|
||||
|
||||
fn invalidate_direction_hint_subtrees_for_mutations(
|
||||
&self,
|
||||
world: &DocumentStyleWorld,
|
||||
host: &DomHost,
|
||||
effects: &[StyleMutationEffect],
|
||||
) {
|
||||
let mut roots = effects
|
||||
.iter()
|
||||
.filter_map(|effect| {
|
||||
let parent = match effect {
|
||||
StyleMutationEffect::CharacterData { node } => {
|
||||
let node = host.node(*node)?;
|
||||
node.as_text()?;
|
||||
node.parent_node()?
|
||||
}
|
||||
StyleMutationEffect::ChildList { parent, .. } => *parent,
|
||||
StyleMutationEffect::Attribute { element, name, .. } if name == "dir" => {
|
||||
// A dir change can also admit or exclude this subtree's
|
||||
// text from the enclosing element's auto-direction scan.
|
||||
let root = host
|
||||
.parent_node(*element)
|
||||
.and_then(|parent| html_auto_directionality_root(host, parent));
|
||||
return Some(root.unwrap_or(*element));
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
html_auto_directionality_root(host, parent)
|
||||
})
|
||||
.peekable();
|
||||
if roots.peek().is_some() {
|
||||
// The hint contributes to inherited computed style even when no
|
||||
// stylesheet selector depends on direction.
|
||||
self.invalidation_cleanup_for_world(world)
|
||||
.invalidate_subtrees(host, roots);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn invalidate_detached_style_subtrees_for_mutations(
|
||||
&self,
|
||||
host: &DomHost,
|
||||
@@ -402,6 +444,16 @@ impl MoliStyleEngine {
|
||||
};
|
||||
let source_scope = source_scope_for_element_state_change(host, element, state);
|
||||
let world = self.world_for_document(document);
|
||||
if state.intersects(StyloElementState::LTR | StyloElementState::RTL)
|
||||
&& html_auto_directionality_root(host, element) == Some(element)
|
||||
&& old_state.is_none_or(|old| {
|
||||
let is_rtl = html_directionality(host, element) == CssDirection::Rtl;
|
||||
old.contains(StyloElementState::RTL) != is_rtl
|
||||
})
|
||||
{
|
||||
self.invalidation_cleanup_for_world(&world)
|
||||
.invalidate_subtrees(host, [element]);
|
||||
}
|
||||
self.queue_style_invalidation_scope(
|
||||
document,
|
||||
&world,
|
||||
|
||||
@@ -19,6 +19,7 @@ pub use detached_stylo::{
|
||||
};
|
||||
pub use error::{SelectorError, SelectorErrorKind};
|
||||
pub use moli_dom as dom;
|
||||
pub use stylo::html_auto_directionality_root;
|
||||
pub use stylo::{
|
||||
MoliInvalidationResult, MoliInvalidationResultBuilder, MoliInvalidationSourceResultsSink,
|
||||
MoliStyleMutationElementSnapshot, MoliStyleMutationSnapshot,
|
||||
|
||||
@@ -77,6 +77,7 @@ pub use invalidation::{
|
||||
stylo_stylesheet_source_scope_fallback_roots,
|
||||
};
|
||||
pub use presentation::is_svg_presentation_attribute_name;
|
||||
pub use query::html_auto_directionality_root;
|
||||
pub(crate) use query::html_directionality;
|
||||
use query::{QueryDocument, QueryElement, QueryNode};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -26,7 +26,11 @@ use style_traits::{ParsingMode, ToCss};
|
||||
|
||||
use crate::dom::native::Element;
|
||||
|
||||
use super::{presentational_hints::synthesize_hidden_presentational_hint, query::QueryElement};
|
||||
use super::{
|
||||
atoms::normalized_direction,
|
||||
presentational_hints::synthesize_hidden_presentational_hint,
|
||||
query::{QueryElement, element_uses_auto_directionality},
|
||||
};
|
||||
|
||||
const HTML_NAMESPACE: &str = "http://www.w3.org/1999/xhtml";
|
||||
const SVG_NAMESPACE: &str = "http://www.w3.org/2000/svg";
|
||||
@@ -196,22 +200,17 @@ fn append_html_direction_declaration(
|
||||
// isolation rule is separate, and layout consumes both computed values.
|
||||
// Per WHATWG HTML §15.3.5, dir="auto" and <bdi> without valid dir="ltr|rtl"
|
||||
// resolve their directionality from first-strong text direction.
|
||||
let direction = match element.attribute("dir") {
|
||||
Some(value) if value.eq_ignore_ascii_case("ltr") => Some(Direction::Ltr),
|
||||
Some(value) if value.eq_ignore_ascii_case("rtl") => Some(Direction::Rtl),
|
||||
Some(value) if value.eq_ignore_ascii_case("auto") => {
|
||||
Some(match query_element.resolved_direction() {
|
||||
CssDirection::Ltr => Direction::Ltr,
|
||||
CssDirection::Rtl => Direction::Rtl,
|
||||
})
|
||||
}
|
||||
_ if element.local_name() == "bdi" => Some(match query_element.resolved_direction() {
|
||||
let direction = element
|
||||
.attribute_ns("", "dir")
|
||||
.and_then(normalized_direction)
|
||||
.or_else(|| {
|
||||
element_uses_auto_directionality(element).then(|| query_element.resolved_direction())
|
||||
});
|
||||
if let Some(direction) = direction {
|
||||
let direction = match direction {
|
||||
CssDirection::Ltr => Direction::Ltr,
|
||||
CssDirection::Rtl => Direction::Rtl,
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(direction) = direction {
|
||||
};
|
||||
block.push(
|
||||
PropertyDeclaration::Direction(direction),
|
||||
Importance::Normal,
|
||||
|
||||
@@ -18,6 +18,8 @@ mod element;
|
||||
// This logic is intentionally split from `element` because it changes with web
|
||||
// platform semantics, while the element adapter should stay mostly structural.
|
||||
mod pseudo;
|
||||
pub(super) use pseudo::element_uses_auto_directionality;
|
||||
pub use pseudo::html_auto_directionality_root;
|
||||
pub(crate) use pseudo::html_directionality;
|
||||
|
||||
use style::{
|
||||
|
||||
@@ -532,11 +532,7 @@ pub(crate) fn html_directionality(host: &DomHost, handle: NodeId) -> CssDirectio
|
||||
{
|
||||
return direction;
|
||||
}
|
||||
if element
|
||||
.attribute_ns("", "dir")
|
||||
.is_some_and(|value| value.eq_ignore_ascii_case("auto"))
|
||||
|| element.is_html_element("bdi")
|
||||
{
|
||||
if element_uses_auto_directionality(element) {
|
||||
return auto_direction_for_element(host, handle).unwrap_or(CssDirection::Ltr);
|
||||
}
|
||||
if element.is_html_input() && element.input_type() == InputType::Tel {
|
||||
@@ -551,6 +547,31 @@ pub(crate) fn html_directionality(host: &DomHost, handle: NodeId) -> CssDirectio
|
||||
CssDirection::Ltr
|
||||
}
|
||||
|
||||
pub(in crate::stylo) fn element_uses_auto_directionality(element: &Element) -> bool {
|
||||
let dir = element.attribute_ns("", "dir");
|
||||
dir.is_some_and(|value| value.eq_ignore_ascii_case("auto"))
|
||||
|| (element.is_html_element("bdi") && dir.and_then(normalized_direction).is_none())
|
||||
}
|
||||
|
||||
/// Finds the closest auto-direction element whose text scan can include
|
||||
/// content inside `start`, including `start` itself.
|
||||
pub fn html_auto_directionality_root(host: &DomHost, start: NodeId) -> Option<NodeId> {
|
||||
let mut current = Some(start);
|
||||
while let Some(handle) = current {
|
||||
let node = host.node(handle)?;
|
||||
if let Some(element) = node.as_element() {
|
||||
if element_uses_auto_directionality(element) {
|
||||
return Some(handle);
|
||||
}
|
||||
if descendant_is_directionally_isolated_for_auto(element) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
current = node.parent_node();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn auto_direction_for_element(host: &DomHost, root: NodeId) -> Option<CssDirection> {
|
||||
if let Some(element) = host.node(root).and_then(Node::as_element) {
|
||||
if element.is_html_textarea() {
|
||||
|
||||
Reference in New Issue
Block a user