Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions moli-html2md/src/machine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ enum Task<'a, Id> {
Children(Option<Id>, usize),
Boundary,
PopStyle,
EndLink(usize),
EndLink(usize, Option<&'a str>),
EndQuote,
EndHeading(usize),
EndList(usize),
Expand Down Expand Up @@ -70,7 +70,9 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> {
Task::Children(None, _) | Task::RawChildren(None, _, _) => {}
Task::Boundary => self.writer().boundary(2),
Task::PopStyle => self.writer().pop_style(),
Task::EndLink(serial) => self.writer().end_link(serial),
Task::EndLink(serial, fallback_label) => {
self.writer().end_link(serial, fallback_label)
}
Task::EndQuote => {
let content = self.take_writer().into_string();
let mut quote = String::new();
Expand Down Expand Up @@ -166,6 +168,7 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> {
let writer = self.writers.pop().expect("capture has an output");
if let Some(parent) = self.writers.last_mut() {
parent.last_link = parent.last_link.max(writer.last_link);
parent.last_link_content = parent.last_link_content.max(writer.last_link_content);
}
writer.finish()
}
Expand Down Expand Up @@ -232,7 +235,10 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> {
title: self.dom.attribute(node, "title"),
};
if self.writer().push_style(style) {
self.tasks.push(Task::EndLink(serial));
self.tasks.push(Task::EndLink(
serial,
self.dom.attribute(node, "aria-label"),
));
}
}
}
Expand Down
24 changes: 20 additions & 4 deletions moli-html2md/src/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ pub(crate) struct Writer<'a> {
heading: bool,
single_line_attributes: bool,
pub(crate) last_link: usize,
pub(crate) last_link_content: usize,
// Block events in this output buffer, used when finalizing a list item.
pub(crate) has_blocks: bool,
}
Expand Down Expand Up @@ -86,12 +87,21 @@ impl<'a> Writer<'a> {
self.desired.pop();
}

pub(crate) fn end_link(&mut self, serial: usize) {
pub(crate) fn end_link(&mut self, serial: usize, fallback_label: Option<&str>) {
self.flush_code();
if self.last_link < serial {
// Empty anchors still carry a destination. Materialize the link
// after its leading whitespace, even without a text event.
self.prepare_inline('[');
if let Some(label) = fallback_label
.filter(|label| self.last_link_content < serial && !label.trim().is_empty())
{
// An empty anchor can still have an author-provided accessible
// name. Preserve that name inside the link instead of emitting
// an unusable empty label. Visible descendants remain primary.
self.text(label);
} else {
// Empty anchors still carry a destination. Materialize the link
// after its leading whitespace, even without a text event.
self.prepare_inline('[');
}
}
self.pop_style();
}
Expand Down Expand Up @@ -250,6 +260,11 @@ impl<'a> Writer<'a> {
self.boundary(before.max(after));
return;
}
for style in &self.desired {
if let Style::Link { serial, .. } = style {
self.last_link_content = self.last_link_content.max(*serial);
}
}
// Closing styles before detaching the tail keeps all inline edit
// offsets local to the current String, never inside a finished block.
self.boundary(before);
Expand Down Expand Up @@ -320,6 +335,7 @@ impl<'a> Writer<'a> {
Style::Strike => self.output.push_str(if html { "<del>" } else { "~~" }),
Style::Link { serial, .. } => {
self.last_link = self.last_link.max(serial);
self.last_link_content = self.last_link_content.max(serial);
if self.output.ends_with('!') {
self.output.insert(self.output.len() - 1, '\\');
}
Expand Down
76 changes: 76 additions & 0 deletions moli-html2md/tests/regressions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,40 @@ fn empty_links_keep_destinations_across_adjacent_and_nested_elements() {
}
}

#[test]
fn empty_links_use_their_own_accessible_label_without_replacing_visible_text() {
for (html, expected) in [
(
"<a href='/report' aria-label='Open report'></a>",
"[Open report](/report)",
),
(
"<a href='/report' aria-label='Open report'>Visible report</a>",
"[Visible report](/report)",
),
(
"<a href='/report' aria-label=' Open report '> </a>",
"[Open report](/report)",
),
("<a href='/report' aria-label=' '></a>", "[](/report)"),
(
"<a href='/report' aria-label='[Open] *report*'></a>",
r"[\[Open\] \*report\*](/report)",
),
(
"<a href='/one' aria-label='One'><span></span></a><a href='/two' aria-label='Two'></a>",
"[One](/one)[Two](/two)",
),
(
"<a href='/report' aria-label='Fallback'><img src='/cover.png' alt='Cover'></a>",
"[![Cover](/cover.png)](/report)",
),
("<a aria-label='No destination'></a>", ""),
] {
assert_eq!(markdown(html, false), expected, "{html}");
}
}

#[test]
fn href_without_a_destination_does_not_create_an_empty_markdown_link() {
for html in [
Expand Down Expand Up @@ -488,3 +522,45 @@ fn fallback_block_elements_separate_neighboring_words() {
);
}
}

#[test]
fn accessible_link_fallback_never_duplicates_visible_inline_or_block_descendants() {
for content in [
"Visible",
"<img src='/cover' alt='Cover'>",
"<code>code</code>",
"<pre>preformatted</pre>",
"<pre><code>nested code</code></pre>",
"<p>Paragraph</p>",
"<h2>Heading</h2>",
"<ul><li>Item</li></ul>",
"<blockquote>Quotation</blockquote>",
"<table><tr><td>Cell</td></tr></table>",
] {
let plain = format!("<a href='/target'>{content}</a>");
let labeled = format!("<a href='/target' aria-label='Fallback'>{content}</a>");
assert_eq!(
markdown(&labeled, false),
markdown(&plain, false),
"{content}"
);
}
}

#[test]
fn empty_link_fallback_belongs_only_to_that_anchor() {
assert_eq!(
markdown(
"<div aria-label='Ancestor'><a href='/one'></a><span aria-label='Adjacent'></span><a href='/two' aria-label='Own'></a></div>",
false
),
"[](/one)[Own](/two)"
);
assert_eq!(
markdown(
"<a href='/target' aria-label='Own'><span></span><code></code></a>",
false
),
"[Own](/target)"
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,10 @@ pub(crate) fn cached_cross_origin_window_surface<'s>(
target: v8::Local<'s, v8::Context>,
accessing: v8::Local<'s, v8::Context>,
build: impl FnOnce(&mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Object>,
) -> v8::Local<'s, v8::Object> {
) -> Option<v8::Local<'s, v8::Object>> {
if scope.is_execution_terminating() {
return None;
}
let (map, get, set) = {
let scope = &mut v8::ContextScope::new(scope, target);
let anchor = target.get_extras_binding_object(scope);
Expand All @@ -52,9 +55,9 @@ pub(crate) fn cached_cross_origin_window_surface<'s>(
.expect("Window cross-origin cache initialized during bootstrap");
let value = cache.get_index(scope, 0).expect("Window cache slot");
let map = if let Ok(constructor) = v8::Local::<v8::Function>::try_from(value) {
let map = constructor
.new_instance(scope, &[])
.expect("intrinsic WeakMap construction");
let map = intrinsic_or_termination(scope, "intrinsic WeakMap construction", |scope| {
constructor.new_instance(scope, &[])
})?;
assert_eq!(cache.set_index(scope, 0, map.into()), Some(true));
map
} else {
Expand All @@ -70,14 +73,136 @@ pub(crate) fn cached_cross_origin_window_surface<'s>(
};
let scope = &mut v8::ContextScope::new(scope, accessing);
let key = accessing.get_extras_binding_object(scope);
let existing = get
.call(scope, map.into(), &[key.into()])
.expect("intrinsic WeakMap.get");
let existing = intrinsic_or_termination(scope, "intrinsic WeakMap.get", |scope| {
get.call(scope, map.into(), &[key.into()])
})?;
if let Ok(surface) = v8::Local::<v8::Object>::try_from(existing) {
return surface;
return Some(surface);
}
let surface = build(scope);
set.call(scope, map.into(), &[key.into(), surface.into()])
.expect("intrinsic WeakMap.set");
surface
intrinsic_or_termination(scope, "intrinsic WeakMap.set", |scope| {
set.call(scope, map.into(), &[key.into(), surface.into()])
})?;
Some(surface)
}

fn intrinsic_or_termination<'s, T>(
scope: &mut v8::PinScope<'s, '_>,
operation: &str,
invoke: impl FnOnce(&mut v8::PinScope<'s, '_>) -> Option<T>,
) -> Option<T> {
let scope = std::pin::pin!(v8::TryCatch::new(scope));
let scope = &mut scope.init();
match invoke(scope) {
Some(value) => Some(value),
// The isolate flag can reset at the V8 call boundary; TryCatch retains
// the termination reason. Keep the interruption visible to its caller.
None if scope.has_terminated() || scope.is_execution_terminating() => {
let _ = scope.rethrow();
None
}
None => panic!("{operation}"),
}
}

#[cfg(test)]
mod tests {
use std::{cell::Cell, pin::pin};

use super::*;

#[test]
fn terminated_execution_stops_cross_origin_cache_lookup_without_building() {
crate::ensure_v8_for_test();
let mut isolate = v8::Isolate::new(Default::default());
let isolate_handle = isolate.thread_safe_handle();
let scope = pin!(v8::HandleScope::new(&mut isolate));
let scope = &mut scope.init();
let target = v8::Context::new(scope, Default::default());
let accessing = v8::Context::new(scope, Default::default());
{
let scope = &mut v8::ContextScope::new(scope, target);
initialize_cross_origin_window_cache(scope).unwrap();
}

let scope = &mut v8::ContextScope::new(scope, accessing);
assert!(isolate_handle.terminate_execution());
let built = Cell::new(false);
let surface = cached_cross_origin_window_surface(scope, target, accessing, |scope| {
built.set(true);
v8::Object::new(scope)
});
assert!(surface.is_none());
assert!(!built.get());
assert!(scope.is_execution_terminating());
assert!(isolate_handle.cancel_terminate_execution());
}

#[test]
fn termination_during_surface_creation_does_not_cache_and_can_recover() {
crate::ensure_v8_for_test();
let mut isolate = v8::Isolate::new(Default::default());
let handle = isolate.thread_safe_handle();
let scope = pin!(v8::HandleScope::new(&mut isolate));
let scope = &mut scope.init();
let target = v8::Context::new(scope, Default::default());
let accessing = v8::Context::new(scope, Default::default());
let other = v8::Context::new(scope, Default::default());
{
let scope = &mut v8::ContextScope::new(scope, target);
initialize_cross_origin_window_cache(scope).unwrap();
}
let scope = &mut v8::ContextScope::new(scope, accessing);
assert!(
cached_cross_origin_window_surface(scope, target, accessing, |scope| {
let surface = v8::Object::new(scope);
assert!(handle.terminate_execution());
surface
})
.is_none()
);
assert!(handle.cancel_terminate_execution());
let surface = cached_cross_origin_window_surface(scope, target, accessing, |scope| {
v8::Object::new(scope)
})
.unwrap();
let cached = cached_cross_origin_window_surface(scope, target, accessing, |_| {
panic!("the same observer must reuse its surface")
})
.unwrap();
assert!(surface.strict_equals(cached.into()));
let distinct = cached_cross_origin_window_surface(scope, target, other, |scope| {
v8::Object::new(scope)
})
.unwrap();
assert!(!surface.strict_equals(distinct.into()));
}

#[test]
#[should_panic(expected = "intrinsic WeakMap.get")]
fn non_termination_cache_errors_are_not_silenced() {
crate::ensure_v8_for_test();
let mut isolate = v8::Isolate::new(Default::default());
let scope = pin!(v8::HandleScope::new(&mut isolate));
let scope = &mut scope.init();
let target = v8::Context::new(scope, Default::default());
let accessing = v8::Context::new(scope, Default::default());
{
let scope = &mut v8::ContextScope::new(scope, target);
initialize_cross_origin_window_cache(scope).unwrap();
let anchor = target.get_extras_binding_object(scope);
let cache = get_private_value(scope, anchor, CACHE).unwrap();
let cache = v8::Local::<v8::Array>::try_from(cache).unwrap();
let source = v8str(scope, "(function () { throw new Error('broken cache'); })");
let script = v8::Script::compile(scope, source, None).unwrap();
let throwing = script.run(scope).unwrap();
assert_eq!(cache.set_index(scope, 1, throwing), Some(true));
}
let scope = &mut v8::ContextScope::new(scope, accessing);
let scope = pin!(v8::TryCatch::new(scope));
let scope = &mut scope.init();
let _ = cached_cross_origin_window_surface(scope, target, accessing, |scope| {
v8::Object::new(scope)
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -651,9 +651,11 @@ fn build_permission_status_object<'s>(
name: &str,
state: &str,
) -> v8::Local<'s, v8::Object> {
PermissionStatusObjectDeclaration::new(name.to_owned(), state.to_owned())
let status = PermissionStatusObjectDeclaration::new(name.to_owned(), state.to_owned())
.bind(scope)
.expect("PermissionStatus declaration should bind")
.expect("PermissionStatus declaration should bind");
mark_simple_event_target_slot(scope, status, "__moliPermissionStatusListeners");
status
}

pub(in crate::context_bootstrap) fn permission_status_name_getter_callback<'s>(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2221,7 +2221,7 @@ fn child_window_cross_origin_handler_data<'s>(
&& host.browsing_context_is_closed()
{
return Some((
main_page::access_surface(scope, holder_context),
main_page::access_surface(scope, holder_context)?,
holder_context.global(scope),
));
}
Expand All @@ -2233,7 +2233,7 @@ fn child_window_cross_origin_handler_data<'s>(
}
if identity.dispatch_scope() == super::super::OwnerDispatchScope::Top {
let window = holder_context.global(scope);
return Some((main_page::access_surface(scope, holder_context), window));
return Some((main_page::access_surface(scope, holder_context)?, window));
}
let super::super::OwnerDispatchScope::Child(handle) = identity.dispatch_scope() else {
return None;
Expand Down
Loading
Loading