fix(style): resolve text scale per document

This commit is contained in:
ldm0
2026-11-24 06:06:01 +08:00
committed by Donough Liu
parent 85a0386045
commit f5caa272ec
26 changed files with 444 additions and 276 deletions
-19
View File
@@ -706,25 +706,6 @@ impl DomHost {
self.dom.document_head_handle_for_document(document_handle)
}
pub fn document_meta_content_for_document(
&self,
document: DomHandle,
name: &str,
) -> Option<&str> {
let head = self.document_head_handle_for_document(document)?;
self.child_handles(head)
.filter_map(|node| {
let meta = self.node(node)?.as_element()?;
if !meta.is_html_element("meta")
|| !meta.attribute_ns("", "name")?.eq_ignore_ascii_case(name)
{
return None;
}
meta.attribute_ns("", "content")
})
.last()
}
pub fn document_body_handle(&self) -> Option<DomHandle> {
self.dom.document_body_handle()
}
+135 -37
View File
@@ -24,43 +24,141 @@ mod native_navigator;
mod scrollbars;
#[tokio::test(flavor = "multi_thread")]
async fn os_text_scale_updates_the_default_font_and_env_in_opted_in_documents() {
let mut ctx = TestContext::new();
load_session_page_for_pending_emulation_test(&mut ctx).await;
evaluate(
&mut ctx,
r#"
document.head.innerHTML = '<style>body { line-height: calc(16px * env(preferred-text-scale, 1)) }</style>';
undefined
"#,
)
.await;
let sizes =
"[getComputedStyle(document.body).fontSize, getComputedStyle(document.body).lineHeight]";
expect_session_command_result(
&mut ctx,
88500,
"SID-1",
"Emulation.setEmulatedOSTextScale",
json!({"scale": 1.5}),
)
.await;
assert_eq!(evaluate(&mut ctx, sizes).await, json!(["16px", "16px"]));
evaluate(
&mut ctx,
"document.head.insertAdjacentHTML('beforeend', '<meta name=text-scale content=scale>'); undefined",
)
.await;
assert_eq!(evaluate(&mut ctx, sizes).await, json!(["24px", "24px"]));
expect_session_command_result(
&mut ctx,
88501,
"SID-1",
"Emulation.setEmulatedOSTextScale",
json!({}),
)
.await;
assert_eq!(evaluate(&mut ctx, sizes).await, json!(["16px", "16px"]));
async fn os_text_scale_keeps_styles_document_media_queries_and_font_faces_in_sync() {
for policy in [
moli_core::LayoutPolicy::OnDemand,
moli_core::LayoutPolicy::Realtime,
] {
let mut ctx = TestContext::new_with_layout_policy(policy);
load_session_page_for_pending_emulation_test(&mut ctx).await;
expect_session_command_result(
&mut ctx,
88499,
"SID-1",
"Emulation.setDeviceMetricsOverride",
json!({"width": 800, "height": 600, "deviceScaleFactor": 1, "mobile": false}),
)
.await;
evaluate(
&mut ctx,
r#"
document.head.innerHTML = `<style id="test-style">
body { line-height: calc(16px * env(preferred-text-scale, 1)); --em: off; --rem: off }
@media (min-width: 40em) {
body { --em: on }
@font-face { font-family: Wide; src: local("Arial") }
}
@media (min-width: 40rem) { body { --rem: on } }
</style>`;
globalThis.queries = ["(min-width: 40em)", "(min-width: 40rem)"].map(query => matchMedia(query));
globalThis.faces = document.fonts;
undefined
"#,
)
.await;
let read_environment = r#"
(() => {
const style = getComputedStyle(document.body);
const sheet = document.getElementById("test-style").sheet;
return [
style.fontSize, style.lineHeight, style.getPropertyValue("--em").trim(),
style.getPropertyValue("--rem").trim(), ...queries.map(query => query.matches),
...queries.map(query => matchMedia(query.media).matches),
sheet.cssRules[1].matches, [...faces].map(face => face.family),
];
})()
"#;
let normal = json!([
"16px",
"16px",
"on",
"on",
true,
true,
true,
true,
true,
["Wide"]
]);
let scaled = json!([
"24px",
"24px",
"off",
"off",
false,
false,
false,
false,
false,
[]
]);
expect_session_command_result(
&mut ctx,
88500,
"SID-1",
"Emulation.setEmulatedOSTextScale",
json!({"scale": 1.5}),
)
.await;
assert_eq!(
evaluate(&mut ctx, read_environment).await,
normal,
"{policy:?}"
);
evaluate(
&mut ctx,
"document.body.insertAdjacentHTML('afterbegin', '<meta name=TEXT-SCALE content=SCALE>'); undefined",
)
.await;
assert_eq!(
evaluate(&mut ctx, read_environment).await,
scaled,
"{policy:?}"
);
evaluate(
&mut ctx,
"document.head.insertAdjacentHTML('afterbegin', '<meta id=first-meta name=text-scale>'); undefined",
)
.await;
assert_eq!(
evaluate(&mut ctx, read_environment).await,
normal,
"{policy:?}"
);
evaluate(
&mut ctx,
"document.querySelector('#first-meta').content = ' scale '",
)
.await;
assert_eq!(
evaluate(&mut ctx, read_environment).await,
normal,
"{policy:?}"
);
evaluate(
&mut ctx,
"document.querySelector('#first-meta').remove(); undefined",
)
.await;
assert_eq!(
evaluate(&mut ctx, read_environment).await,
scaled,
"{policy:?}"
);
expect_session_command_result(
&mut ctx,
88501,
"SID-1",
"Emulation.setEmulatedOSTextScale",
json!({}),
)
.await;
assert_eq!(
evaluate(&mut ctx, read_environment).await,
normal,
"{policy:?}"
);
}
}
async fn evaluate(ctx: &mut TestContext, expression: &str) -> serde_json::Value {
@@ -79,7 +79,7 @@ impl Inputs {
style_generations: host.document_style_input_generations(document),
visual_generation: host.visual_state_generation(),
viewport,
environment: StyloStyleEnvironment::from_emulated_media(host.emulated_media()),
environment: host.style_environment_for_document(document),
faces: faces.iter().map(FontSourceSignature::new).collect(),
}
}
@@ -275,18 +275,26 @@ pub(crate) fn css_media_rule_matches_getter_callback<'s>(
.filter(|view| view.rule_type == CssRuleType::Media)
.map(|view| view.condition_text)
.unwrap_or_default();
let (emulated_media, viewport) =
if let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) {
let host = unsafe { &*host_ptr };
(Some(host.emulated_media().clone()), host.style_viewport())
} else {
(None, crate::style_engine::StyleViewport::default())
};
let matches = crate::style_engine::media_list::evaluate_media_query_list(
&media_text,
emulated_media.as_ref(),
viewport,
);
let context = args
.this()
.get_creation_context(scope)
.unwrap_or_else(|| scope.get_current_context());
let scope = &mut v8::ContextScope::new(scope, context);
let matches = if let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) {
let host = unsafe { &*host_ptr };
let global = context.global(scope);
crate::context_bootstrap::window_accessors::window_current_dispatch_scope(
scope, global, host,
)
.and_then(|dispatch| host.window_document_handle_for_dispatch_scope(dispatch))
.is_some_and(|document| host.media_query_matches_for_document(document, &media_text))
} else {
crate::style_engine::media_list::evaluate_media_query_list(
&media_text,
Default::default(),
Default::default(),
)
};
rv.set_bool(matches);
}
@@ -4,7 +4,6 @@ use super::{
simple_object_event_set_handler,
};
use crate::context_bootstrap::DEFAULT_WINDOW_SURFACE_PROFILE;
use crate::context_bootstrap::current_window_style_viewport;
use crate::context_bootstrap::window_accessors::{
prepare_window_viewport_read, window_current_dispatch_scope,
};
@@ -17,7 +16,7 @@ use crate::native_bridge::{
PageScriptHost, WindowDocumentTaskTarget, WindowExecutionContextBinding,
};
use crate::style_engine::{
StyleViewport,
StyleViewport, StyloStyleEnvironment,
media_list::{evaluate_media_query_list, normalize_media_query_list},
};
use crate::util::{
@@ -124,9 +123,11 @@ pub(in crate::context_bootstrap) fn read_media_query_matches<'s>(
return Some(evaluate_match_media_query_list(&media, None));
};
let host = unsafe { &*host_ptr };
if window_current_dispatch_scope(scope, global, host).is_none() {
let Some(document) = window_current_dispatch_scope(scope, global, host)
.and_then(|dispatch| host.window_document_handle_for_dispatch_scope(dispatch))
else {
return Some(false);
}
};
if !prepare_window_viewport_read(scope, global) {
return None;
}
@@ -135,11 +136,7 @@ pub(in crate::context_bootstrap) fn read_media_query_matches<'s>(
{
return Some(host.realtime_media_query_matches(id));
}
Some(evaluate_media_query_list(
&media,
Some(host.emulated_media()),
current_window_style_viewport(scope, host),
))
Some(host.media_query_matches_for_document(document, &media))
}
pub(in crate::context_bootstrap) fn realtime_media_query_listeners_changed<'s>(
@@ -283,17 +280,16 @@ pub(crate) fn window_match_media_callback<'s>(
if !prepare_window_viewport_read(scope, global) {
return;
}
let (emulated_media, viewport) =
if let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) {
let host = unsafe { &*host_ptr };
(
Some(host.emulated_media().clone()),
current_window_style_viewport(scope, host),
)
} else {
(None, match_media_style_viewport(None))
};
let matches = evaluate_media_query_list(&serialized_query, emulated_media.as_ref(), viewport);
let matches = if let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) {
let host = unsafe { &*host_ptr };
window_current_dispatch_scope(scope, global, host)
.and_then(|dispatch| host.window_document_handle_for_dispatch_scope(dispatch))
.is_some_and(|document| {
host.media_query_matches_for_document(document, &serialized_query)
})
} else {
evaluate_match_media_query_list(&serialized_query, None)
};
let realtime_registration = if let Some(host_ptr) = context_host_ptr_from_global_bridge(scope)
&& unsafe { &*host_ptr }.layout_policy().is_realtime()
&& let Some(target) = unsafe { &*host_ptr }.current_window_document_task_target(scope)
@@ -339,9 +335,13 @@ pub(crate) fn dispatch_media_query_list_change_events<'s>(
return false;
};
let host = unsafe { &*host_ptr };
let target = host.current_window_document_task_target(scope);
let current_media = host.emulated_media().clone();
let current_viewport = current_window_style_viewport(scope, host);
let Some(target) = host.current_window_document_task_target(scope) else {
return false;
};
let Some(document) = host.window_document_handle_for_dispatch_scope(target.dispatch_scope())
else {
return false;
};
let Some(registry) = global_queue_array(scope, MEDIA_QUERY_LIST_REGISTRY_SLOT) else {
return false;
};
@@ -356,18 +356,16 @@ pub(crate) fn dispatch_media_query_list_change_events<'s>(
let Some(media) = media_query_list_media_slot(scope, mql) else {
continue;
};
if target.is_none_or(|target| {
!unsafe { &*host_ptr }.window_document_owner_is_current_for_dispatch_scope(
target.owner(),
target.dispatch_scope(),
)
}) {
let host = unsafe { &*host_ptr };
if !host.window_document_owner_is_current_for_dispatch_scope(
target.owner(),
target.dispatch_scope(),
) {
break;
}
let previous_matches = get_private_value(scope, mql, MEDIA_QUERY_LIST_MATCHES_SLOT)
.is_some_and(|value| value.boolean_value(scope));
let current_matches =
evaluate_media_query_list(&media, Some(&current_media), current_viewport);
let current_matches = host.media_query_matches_for_document(document, &media);
set_media_query_list_bool_slot(scope, mql, MEDIA_QUERY_LIST_MATCHES_SLOT, current_matches);
if previous_matches == current_matches {
continue;
@@ -435,7 +433,9 @@ pub(crate) fn evaluate_match_media_query_list_with_viewport_width(
) -> bool {
evaluate_media_query_list(
query,
emulated_media,
emulated_media
.map(StyloStyleEnvironment::from_emulated_media)
.unwrap_or_default(),
match_media_style_viewport(viewport_width),
)
}
+8 -4
View File
@@ -1291,14 +1291,18 @@ impl super::planning::ParserPlanningReadView for LiveRuntimeDomHost {
impl super::stylesheet_blocking::StylesheetBlockingReadView for LiveRuntimeDomHost {
fn media_query_matches(&self, media: &str) -> bool {
let document = self
.borrow()
.node(self.borrow().document_handle())
let host = self.borrow();
let handle = host.document_handle();
let document = host
.node(handle)
.and_then(Node::as_document)
.expect("live Document");
let environment =
crate::style_engine::StyloStyleEnvironment::from_emulated_media(&self.emulated_media)
.for_document(host, Some(handle));
crate::style_engine::media_list::evaluate_media_query_list_with_context(
media,
Some(&self.emulated_media),
environment,
self.style_viewport(),
document.base_url(),
document.quirks_mode(),
@@ -91,6 +91,12 @@ impl DocumentRuntime {
}
continue;
}
if element
.attribute("media")
.is_some_and(|media| !self.stylesheet_media_matches(media.trim()))
{
continue;
}
let Some(candidate) = modulepreload_fetch_candidate(
element,
request_url.clone(),
+1 -8
View File
@@ -133,10 +133,6 @@ fn modulepreload_attributes_for_state(state: ModulepreloadAsState) -> Option<Mod
}
}
pub(crate) fn modulepreload_media_matches(element: &Element) -> bool {
modulepreload_media_attribute_matches(element.attribute("media"))
}
pub(crate) fn modulepreload_media_attribute_matches(media: Option<&str>) -> bool {
let Some(media) = media.map(str::trim) else {
return true;
@@ -146,7 +142,7 @@ pub(crate) fn modulepreload_media_attribute_matches(media: Option<&str>) -> bool
}
crate::style_engine::media_list::evaluate_media_query_list(
media,
None,
crate::style_engine::StyloStyleEnvironment::default(),
crate::style_engine::StyleViewport::default(),
)
}
@@ -168,9 +164,6 @@ pub(crate) fn modulepreload_fetch_candidate(
document_url: &Url,
import_map_integrity: Option<String>,
) -> Option<ModulepreloadFetchCandidate> {
if !modulepreload_media_matches(element) {
return None;
}
let state = modulepreload_as_state(element);
let attributes = modulepreload_attributes_for_state(state)?;
let fetch_metadata = crate::planning::ScriptFetchMetadata::from_script_attributes(
@@ -1,7 +1,8 @@
use std::time::Instant;
use crate::{
dom::native::{DomHost, DomMutationEffects},
document_runtime::DomHandle,
dom::native::{DomHost, DomMutationEffects, Node},
native_bridge::PageScriptHost,
observer_runtime,
style_engine::StyleMutationEffect,
@@ -34,6 +35,18 @@ pub(crate) fn notify_dom_mutation(
scope, host_ptr, dom_host, effects,
);
let timings = notify_native_dom_mutation(host_ptr, dom_host, effects);
let host = unsafe { &mut *host_ptr };
if host.emulated_media().os_text_scale_percent.is_some() {
let documents = documents_with_changed_text_scale_meta(dom_host, effects);
if !documents.is_empty() {
host.note_text_scale_meta_change();
for document in documents {
crate::native_bridge::document::sync_document_fonts_for_handle(
scope, host, document,
);
}
}
}
crate::context_bootstrap::web_mcp::note_mutation(
scope,
unsafe { &mut *host_ptr },
@@ -52,6 +65,46 @@ pub(crate) fn notify_dom_mutation(
}
}
fn documents_with_changed_text_scale_meta(
host: &DomHost,
effects: &DomMutationEffects,
) -> Vec<DomHandle> {
let style = effects.style();
let attribute_changes = style
.attribute_mutations()
.iter()
.filter(|change| {
matches!(change.local_name(), "name" | "content")
&& change.namespace().is_none()
&& host.is_html_element_named(change.target(), "meta")
})
.map(|change| change.target());
let tree_changes = style
.child_list_mutations()
.iter()
.filter(|change| {
change
.added_nodes()
.iter()
.chain(change.removed_nodes())
.any(|root| {
host.is_html_element_named(*root, "meta")
|| !host
.html_elements_by_local_name_in_shadow_including_subtree(*root, "meta")
.is_empty()
})
})
.map(|change| change.target());
let mut documents: Vec<_> = attribute_changes
.chain(tree_changes)
.filter_map(|target| host.root_node_handle(target))
.filter(|root| host.node(*root).is_some_and(Node::is_document))
.collect();
documents.sort_unstable_by_key(|document| document.index());
documents.dedup();
documents
}
/// Style and resource identity notifications do not require a Window realm.
/// No wrappers, MutationObservers or WebMCP scripts exist before that realm.
pub(crate) fn notify_native_dom_mutation(
@@ -1200,6 +1200,11 @@ impl PageScriptHost {
else {
continue;
};
if element.attribute("media").is_some_and(|media| {
!self.media_query_matches_for_document(document_handle, media.trim())
}) {
continue;
}
let Some(candidate) =
modulepreload_fetch_candidate(element, request_url, &initiator_url, None)
else {
@@ -79,6 +79,14 @@ fn hover_chain_for_input_hit(runtime: &PageScriptHost, hit: Option<DomHandle>) -
}
impl PageScriptHost {
pub(crate) fn style_environment_for_document(
&self,
document: DomHandle,
) -> StyloStyleEnvironment {
StyloStyleEnvironment::from_emulated_media(self.emulated_media())
.for_document(self.dom_host(), Some(document))
}
pub(crate) fn media_query_matches_for_document(
&self,
document: DomHandle,
@@ -89,7 +97,7 @@ impl PageScriptHost {
};
crate::style_engine::media_list::evaluate_media_query_list_with_context(
media,
Some(self.emulated_media()),
self.style_environment_for_document(document),
crate::native_bridge::element::style_viewport_for_document(self, document),
document_node.base_url(),
document_node.quirks_mode(),
@@ -862,6 +870,11 @@ impl PageScriptHost {
)
}
pub(crate) fn note_text_scale_meta_change(&mut self) {
self.queue_environment_change();
self.sample_realtime_media_queries(None);
}
pub(crate) fn set_emulated_media(
&mut self,
overrides: &crate::protocol_types::EmulatedMediaOverrides,
@@ -1,10 +1,9 @@
use std::{collections::BTreeMap, rc::Rc};
use super::{
OwnerDispatchScope, PageScriptHost, RuntimeObservableContextToken, WindowDocumentOwner,
WindowDocumentTaskTarget, WindowExecutionContextIdentity, WindowExecutionContextOwner,
PageScriptHost, RuntimeObservableContextToken, WindowDocumentOwner, WindowDocumentTaskTarget,
WindowExecutionContextIdentity, WindowExecutionContextOwner,
};
use crate::style_engine::StyleViewport;
#[derive(Clone, Copy)]
pub(crate) struct RealtimeEnvironmentNotification {
@@ -256,15 +255,12 @@ impl PageScriptHost {
) && self.window_execution_context_identity_is_current(query.execution_context)
})
.map(|(id, query)| {
let viewport = self.realtime_environment_viewport(query.target);
(
*id,
crate::style_engine::media_list::evaluate_media_query_list(
&query.media,
Some(self.emulated_media()),
viewport,
),
)
let matches = self
.window_document_handle_for_dispatch_scope(query.target.dispatch_scope())
.is_some_and(|document| {
self.media_query_matches_for_document(document, &query.media)
});
(*id, matches)
})
.collect::<Vec<_>>();
{
@@ -280,16 +276,6 @@ impl PageScriptHost {
self.refresh_realtime_rendering_opportunity();
}
fn realtime_environment_viewport(&self, target: WindowDocumentTaskTarget) -> StyleViewport {
match target.dispatch_scope() {
OwnerDispatchScope::Child(frame) => {
super::super::element::iframe_handle_viewport(self, frame)
.unwrap_or_else(|| self.style_viewport())
}
_ => self.style_viewport(),
}
}
pub(super) fn queue_realtime_environment_notification(&self, target: WindowDocumentTaskTarget) {
if self.realtime_layout_state.is_none() {
return;
@@ -283,6 +283,13 @@ impl PageScriptHost {
if self.current_window_document_task_target_for_dispatch_scope(scope) != Some(owner) {
return None;
}
self.window_document_handle_for_dispatch_scope(scope)
}
pub(crate) fn window_document_handle_for_dispatch_scope(
&self,
scope: OwnerDispatchScope,
) -> Option<DomHandle> {
match scope {
OwnerDispatchScope::Top => Some(self.document_handle()),
OwnerDispatchScope::Child(frame) => self
@@ -25,10 +25,9 @@ pub(crate) fn sync_document_fonts_for_handle(
host: &crate::native_bridge::PageScriptHost,
document: crate::document_runtime::DomHandle,
) {
let Some(holder) = crate::util::node_wrapper_from_handle(scope, document) else {
return;
};
let _ = font_faces::sync_document_fonts(scope, holder, host, document);
crate::util::with_cached_node_wrapper_realm(scope, host, document, |scope, holder| {
let _ = font_faces::sync_document_fonts(scope, holder, host, document);
});
}
pub(crate) fn clear_adopted_stylesheet_font_face_wrappers(
@@ -59,13 +59,12 @@ pub(super) fn owner_font_face_projection(
.owner_live_stylesheet(owner)
.or_else(|| host.linked_live_stylesheet(owner))
{
let document = dom_host.owner_document_handle(owner)?;
return Some(OwnerFontFaceProjection::Live {
stylesheet_id: stylesheet.id(),
projection: stylesheet.font_faces(
crate::style_engine::StyloStyleEnvironment::from_emulated_media(
host.emulated_media(),
),
host.style_viewport(),
host.style_environment_for_document(document),
crate::native_bridge::element::style_viewport_for_document(host, document),
),
});
}
@@ -426,6 +425,8 @@ fn document_adopted_font_faces<'s>(
else {
return Vec::new();
};
let environment = host.style_environment_for_document(document);
let viewport = crate::native_bridge::element::style_viewport_for_document(host, document);
let mut seen = Vec::new();
let mut faces = Vec::new();
for index in 0..sheets.length() {
@@ -449,10 +450,7 @@ fn document_adopted_font_faces<'s>(
else {
continue;
};
let descriptors = stylesheet.font_faces(
crate::style_engine::StyloStyleEnvironment::from_emulated_media(host.emulated_media()),
host.style_viewport(),
);
let descriptors = stylesheet.font_faces(environment, viewport);
faces.extend(sync_adopted_stylesheet_font_faces(
scope,
sheet,
@@ -10,8 +10,6 @@ use crate::util::v8_string;
use crate::v8_execution_watchdog::V8ExecutionWatchdog;
use moli_browser_profile::DEFAULT_WINDOW_SURFACE_PROFILE;
use crate::style_engine::media_list::evaluate_media_query_list;
use super::super::super::node::node_runtime_and_handle_from_object_or_detached;
use super::super::geometry::compute_mock_client_rect;
use super::super::{construct_simple_event, dispatch_public_event, resolve_url_like_attribute};
@@ -348,6 +346,7 @@ fn image_selected_picture_source(
if !parent_element.is_html_element("picture") {
return None;
}
let document = runtime.dom_host().owner_document_handle(handle)?;
for child in runtime.dom_host().child_handles(parent) {
if child == handle {
break;
@@ -360,11 +359,7 @@ fn image_selected_picture_source(
}
if let Some(media) = source.attribute("media")
&& !media.trim().is_empty()
&& !evaluate_media_query_list(
media,
Some(runtime.emulated_media()),
runtime.style_viewport(),
)
&& !runtime.media_query_matches_for_document(document, media)
{
continue;
}
@@ -165,22 +165,7 @@ pub(super) fn stylo_style_environment(
runtime.note_style_observation_environment_resolution_for_test();
environment_override
.unwrap_or_else(|| StyloStyleEnvironment::from_emulated_media(runtime.emulated_media()))
.for_document_text_scale(document.is_some_and(|document| {
runtime
.dom_host()
.document_meta_content_for_document(document, "text-scale")
.is_some_and(|content| content.trim_ascii().eq_ignore_ascii_case("scale"))
}))
.with_page_color_schemes(
document
.map(|document| {
crate::document_color_scheme::document_page_color_schemes(
runtime.dom_host(),
document,
)
})
.unwrap_or_default(),
)
.for_document(runtime.dom_host(), document)
}
fn complete_style_world_snapshot(
@@ -388,10 +373,15 @@ pub(super) fn effective_raw_stylesheet_sources(
include_detached: bool,
viewport: StyleViewport,
) -> Vec<StyloStylesheetSource> {
let environment = StyloStyleEnvironment::from_emulated_media(runtime.emulated_media())
.for_document(
runtime.dom_host(),
runtime.dom_host().owner_document_handle(root),
);
active_stylesheet_handles(runtime, root, include_detached)
.into_iter()
.map(|handle| stylesheet_source(runtime, handle))
.filter(|source| source.media_matches(runtime.emulated_media(), viewport))
.filter(|source| source.media_matches(environment, viewport))
.collect()
}
@@ -192,7 +192,7 @@ fn visible_custom_functions_for_scope(
for source in inputs
.document_stylesheet_sources
.iter()
.filter(|source| source.media_matches(runtime.emulated_media(), viewport))
.filter(|source| source.media_matches(inputs.environment, viewport))
{
collect_custom_functions_from_stylesheet_source(runtime, source, &mut functions);
}
@@ -208,7 +208,7 @@ fn visible_custom_functions_for_scope(
if shadow_chain.contains(root) {
for source in sources
.iter()
.filter(|source| source.media_matches(runtime.emulated_media(), viewport))
.filter(|source| source.media_matches(inputs.environment, viewport))
{
collect_custom_functions_from_stylesheet_source(runtime, source, &mut functions);
}
@@ -229,15 +229,18 @@ impl ScriptVm {
&mut self,
overrides: &crate::protocol_types::EmulatedMediaOverrides,
) {
{
let text_scale_changed = {
let mut host = self._context_host.borrow_mut();
if host.emulated_media() == overrides {
return;
}
let changed =
host.emulated_media().os_text_scale_percent != overrides.os_text_scale_percent;
host.queue_environment_change();
host.set_emulated_media(overrides);
}
self.sync_document_fonts_for_environment();
changed
};
self.sync_document_fonts_for_environment(text_scale_changed);
}
pub(crate) fn set_emulated_media_for_bootstrap(
@@ -275,11 +278,7 @@ impl ScriptVm {
return true;
};
let host = self._context_host.borrow();
crate::style_engine::media_list::evaluate_media_query_list(
media,
Some(host.emulated_media()),
host.style_viewport(),
)
host.media_query_matches_for_document(host.document_handle(), media)
}
pub(crate) fn fetch_subresource_interception_matches(
@@ -303,7 +302,7 @@ impl ScriptVm {
host.queue_viewport_change(viewport_surface);
host.set_viewport_surface(viewport_surface);
}
self.sync_document_fonts_for_environment();
self.sync_document_fonts_for_environment(false);
Ok(())
}
@@ -354,11 +353,22 @@ impl ScriptVm {
.set_scrollbars_hidden(hidden)
}
pub(super) fn sync_document_fonts_for_environment(&mut self) {
fn sync_document_fonts_for_environment(&mut self, text_scale_changed: bool) {
let context_host = self._context_host.clone();
let _ = self.with_current_main_world_scope(|scope, _| {
let host = context_host.borrow();
for document in host.documents_with_adopted_style_sheets() {
let mut documents = host.documents_with_adopted_style_sheets();
if text_scale_changed {
documents.push(host.document_handle());
documents.extend(
host.child_browsing_context_handles_in_document_order()
.into_iter()
.filter_map(|frame| host.child_browsing_context_document_handle(frame)),
);
documents.sort_unstable_by_key(|document| document.index());
documents.dedup();
}
for document in documents {
crate::native_bridge::document::sync_document_fonts_for_handle(
scope, &host, document,
);
+40 -50
View File
@@ -1,4 +1,3 @@
use euclid::{Scale, Size2D};
use style::context::QuirksMode;
pub(crate) use moli_css_parse::{
@@ -6,17 +5,17 @@ pub(crate) use moli_css_parse::{
normalize_media_query_list, parse_media_query_list_with_context,
};
use super::stylesheet::new_style_device_with_viewport;
use super::{StyleViewport, StyloStyleEnvironment};
use crate::style_engine::world_key::{DEFAULT_VIEWPORT_HEIGHT, DEFAULT_VIEWPORT_WIDTH};
pub(crate) fn evaluate_media_query_list(
media_text: &str,
emulated_media: Option<&crate::protocol_types::EmulatedMediaOverrides>,
environment: StyloStyleEnvironment,
viewport: StyleViewport,
) -> bool {
evaluate_media_query_list_with_context(
media_text,
emulated_media,
environment,
viewport,
&url::Url::parse("about:blank").expect("static URL"),
QuirksMode::NoQuirks,
@@ -25,7 +24,7 @@ pub(crate) fn evaluate_media_query_list(
pub(crate) fn evaluate_media_query_list_with_context(
media_text: &str,
emulated_media: Option<&crate::protocol_types::EmulatedMediaOverrides>,
environment: StyloStyleEnvironment,
viewport: StyleViewport,
base_url: &url::Url,
quirks_mode: QuirksMode,
@@ -35,24 +34,7 @@ pub(crate) fn evaluate_media_query_list_with_context(
return true;
}
let environment = emulated_media
.map(StyloStyleEnvironment::from_emulated_media)
.unwrap_or_default();
let width = viewport.width.unwrap_or(DEFAULT_VIEWPORT_WIDTH as f64) as f32;
let height = viewport.height.unwrap_or(DEFAULT_VIEWPORT_HEIGHT as f64) as f32;
let ratio = viewport.device_pixel_ratio.unwrap_or(1.0) as f32;
let device = moli_css_parse::create_media_query_device(
environment.stylo_media_type(),
quirks_mode,
Size2D::new(width, height),
Size2D::new(
viewport.screen_width.unwrap_or(f64::from(width)) as f32 * ratio,
viewport.screen_height.unwrap_or(f64::from(height)) as f32 * ratio,
),
Scale::new(ratio),
environment.stylo_prefers_color_scheme(),
environment.stylo_media_feature_preferences(),
);
let device = new_style_device_with_viewport(viewport, environment, quirks_mode);
moli_css_parse::evaluate_media_query_list(media_text, &device, base_url, quirks_mode)
}
@@ -97,57 +79,65 @@ mod tests {
fn media_query_list_evaluation_uses_stylo_device() {
assert!(evaluate_media_query_list(
"(width >= 768px) and (color)",
None,
StyloStyleEnvironment::default(),
StyleViewport::new(Some(1920.0), Some(1080.0)),
));
assert!(!evaluate_media_query_list(
"print and (width >= 768px)",
None,
StyloStyleEnvironment::default(),
StyleViewport::new(Some(1920.0), Some(1080.0)),
));
assert!(evaluate_media_query_list(
"print and (prefers-color-scheme: dark)",
Some(&crate::protocol_types::EmulatedMediaOverrides {
media: Some("print".to_owned()),
color_scheme: Some("dark".to_owned()),
..Default::default()
}),
StyloStyleEnvironment::from_emulated_media(
&crate::protocol_types::EmulatedMediaOverrides {
media: Some("print".to_owned()),
color_scheme: Some("dark".to_owned()),
..Default::default()
}
),
StyleViewport::new(Some(1920.0), Some(1080.0)),
));
assert!(evaluate_media_query_list(
"(prefers-color-scheme: dark) and (prefers-reduced-motion: reduce)",
Some(&crate::protocol_types::EmulatedMediaOverrides {
color_scheme: Some("dark".to_owned()),
reduced_motion: Some("reduce".to_owned()),
..Default::default()
}),
StyloStyleEnvironment::from_emulated_media(
&crate::protocol_types::EmulatedMediaOverrides {
color_scheme: Some("dark".to_owned()),
reduced_motion: Some("reduce".to_owned()),
..Default::default()
}
),
StyleViewport::new(Some(1920.0), Some(1080.0)),
));
assert!(!evaluate_media_query_list(
"(prefers-reduced-motion) and (prefers-contrast)",
None,
StyloStyleEnvironment::default(),
StyleViewport::new(Some(1920.0), Some(1080.0)),
));
assert!(evaluate_media_query_list(
"(prefers-reduced-motion: no-preference) and (prefers-contrast: no-preference)",
None,
StyloStyleEnvironment::default(),
StyleViewport::new(Some(1920.0), Some(1080.0)),
));
assert!(evaluate_media_query_list(
"(prefers-reduced-motion: no-preference) and (forced-colors: active)",
Some(&crate::protocol_types::EmulatedMediaOverrides {
reduced_motion: Some("no-preference".to_owned()),
forced_colors: Some("active".to_owned()),
..Default::default()
}),
StyloStyleEnvironment::from_emulated_media(
&crate::protocol_types::EmulatedMediaOverrides {
reduced_motion: Some("no-preference".to_owned()),
forced_colors: Some("active".to_owned()),
..Default::default()
}
),
StyleViewport::new(Some(1920.0), Some(1080.0)),
));
assert!(evaluate_media_query_list(
"(prefers-reduced-transparency: reduce)",
Some(&crate::protocol_types::EmulatedMediaOverrides {
reduced_transparency: Some("reduce".to_owned()),
..Default::default()
}),
StyloStyleEnvironment::from_emulated_media(
&crate::protocol_types::EmulatedMediaOverrides {
reduced_transparency: Some("reduce".to_owned()),
..Default::default()
}
),
StyleViewport::new(Some(1920.0), Some(1080.0)),
));
}
@@ -159,22 +149,22 @@ mod tests {
assert!(evaluate_media_query_list(
"(width: 800px) and (height: 600px)",
None,
StyloStyleEnvironment::default(),
viewport,
));
assert!(evaluate_media_query_list(
"(device-width: 1920px) and (device-height: 1080px)",
None,
StyloStyleEnvironment::default(),
viewport,
));
assert!(evaluate_media_query_list(
"(device-aspect-ratio: 16 / 9)",
None,
StyloStyleEnvironment::default(),
viewport,
));
assert!(!evaluate_media_query_list(
"(device-width: 800px) or (device-height: 600px)",
None,
StyloStyleEnvironment::default(),
viewport,
));
}
@@ -16,8 +16,8 @@ use super::super::{
};
use super::shared_cache::{SharedStyleSourceContents, shared_style_source_contents};
use crate::{
document_runtime::DomHandle, protocol_types::EmulatedMediaOverrides,
style_engine::StyleViewport,
document_runtime::DomHandle,
style_engine::{StyleViewport, StyloStyleEnvironment},
};
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
@@ -204,12 +204,12 @@ impl StyloStylesheetSource {
/// compatibility paths that inspect serialized CSS outside Stylo.
pub(crate) fn media_matches(
&self,
emulated_media: &EmulatedMediaOverrides,
environment: StyloStyleEnvironment,
viewport: StyleViewport,
) -> bool {
crate::style_engine::source_owner::stylesheet_source_media_matches(
&self.media_text,
emulated_media,
environment,
viewport,
)
}
@@ -1,9 +1,7 @@
use crate::{
document_runtime::DomHandle,
dom::native::{DomHost, Element, Node},
protocol_types::EmulatedMediaOverrides,
style_engine::StyleViewport,
style_engine::media_list::evaluate_media_query_list,
style_engine::{StyleViewport, StyloStyleEnvironment, media_list::evaluate_media_query_list},
};
pub(crate) fn link_rel_qualifies_as_stylesheet(rel: Option<&str>, title: Option<&str>) -> bool {
@@ -35,7 +33,7 @@ pub(super) fn stylesheet_owner_is_stylesheet_source_enabled(
host: &DomHost,
handle: DomHandle,
media_text: &str,
emulated_media: &EmulatedMediaOverrides,
environment: StyloStyleEnvironment,
viewport: StyleViewport,
) -> bool {
host.node(handle).is_some_and(|node| {
@@ -45,7 +43,7 @@ pub(super) fn stylesheet_owner_is_stylesheet_source_enabled(
host,
handle,
media_text,
emulated_media,
environment,
viewport,
)
})
@@ -67,7 +65,7 @@ fn style_element_is_stylesheet_source_enabled(
host: &DomHost,
handle: DomHandle,
media_text: &str,
emulated_media: &EmulatedMediaOverrides,
environment: StyloStyleEnvironment,
viewport: StyleViewport,
) -> bool {
let Some(element) = host.node(handle).and_then(Node::as_element) else {
@@ -76,24 +74,24 @@ fn style_element_is_stylesheet_source_enabled(
element.is_inline_style_element()
&& host.get_attribute(handle, "disabled").is_none()
&& stylesheet_owner_type_is_supported(element)
&& stylesheet_source_media_matches(media_text, emulated_media, viewport)
&& stylesheet_source_media_matches(media_text, environment, viewport)
}
pub(super) fn linked_stylesheet_media_matches_for_stylesheet_source(
media_text: &str,
emulated_media: &EmulatedMediaOverrides,
environment: StyloStyleEnvironment,
viewport: StyleViewport,
) -> bool {
stylesheet_source_media_matches(media_text, emulated_media, viewport)
stylesheet_source_media_matches(media_text, environment, viewport)
}
pub(super) fn stylesheet_source_media_matches(
media_text: &str,
emulated_media: &EmulatedMediaOverrides,
environment: StyloStyleEnvironment,
viewport: StyleViewport,
) -> bool {
let media = media_text.trim();
media.is_empty() || evaluate_media_query_list(media, Some(emulated_media), viewport)
media.is_empty() || evaluate_media_query_list(media, environment, viewport)
}
#[cfg(test)]
@@ -1,6 +1,8 @@
use crate::{
document_runtime::DomHandle, dom::native::DomHost, protocol_types::EmulatedMediaOverrides,
style_engine::StyleViewport,
document_runtime::DomHandle,
dom::native::DomHost,
protocol_types::EmulatedMediaOverrides,
style_engine::{StyleViewport, StyloStyleEnvironment},
};
use std::sync::Arc;
@@ -145,20 +147,24 @@ impl<'a> RetainedStylesheetSourceRecord<'a> {
emulated_media: &EmulatedMediaOverrides,
viewport: StyleViewport,
) -> bool {
let environment_for_owner = |owner| {
StyloStyleEnvironment::from_emulated_media(emulated_media)
.for_document(host, host.owner_document_handle(owner))
};
match self.id.kind {
StyleSourceKind::OwnerStyleSheet { owner } => {
stylesheet_owner_is_stylesheet_source_enabled(
host,
owner,
&self.effective_media_text(host, owner),
emulated_media,
environment_for_owner(owner),
viewport,
)
}
StyleSourceKind::LinkedStyleSheet { owner } => {
linked_stylesheet_media_matches_for_stylesheet_source(
&self.effective_media_text(host, owner),
emulated_media,
environment_for_owner(owner),
viewport,
)
}
@@ -6,7 +6,10 @@ use style::{
values::specified::color::{ColorSchemeFlags, ForcedColors},
};
use crate::{document_runtime::DomHandle, dom::native::DomHost};
use crate::{
document_runtime::DomHandle,
dom::native::{DomHost, Node},
};
/// Cheap, Document-local identity of the connected ShadowRoot universe
/// sampled for one style observation. The actual root vector is cloned only
@@ -194,11 +197,19 @@ impl StyloStyleEnvironment {
}
}
pub(crate) fn for_document_text_scale(mut self, opted_in: bool) -> Self {
if !opted_in {
pub(crate) fn for_document(mut self, host: &DomHost, document: Option<DomHandle>) -> Self {
if self.preferred_text_scale_percent.is_some()
&& !document.is_some_and(|document| document_uses_text_scale(host, document))
{
self.preferred_text_scale_percent = None;
}
self
self.with_page_color_schemes(
document
.map(|document| {
crate::document_color_scheme::document_page_color_schemes(host, document)
})
.unwrap_or_default(),
)
}
pub(super) fn preferred_text_scale(self) -> f32 {
@@ -247,6 +258,18 @@ impl StyloStyleEnvironment {
}
}
fn document_uses_text_scale(host: &DomHost, document: DomHandle) -> bool {
host.html_elements_by_local_name_in_document_tree_order(document, "meta")
.into_iter()
.filter_map(|handle| host.node(handle).and_then(Node::as_element))
.find(|meta| {
meta.attribute_ns("", "name")
.is_some_and(|name| name.eq_ignore_ascii_case("text-scale"))
})
.and_then(|meta| meta.attribute_ns("", "content"))
.is_some_and(|content| content.eq_ignore_ascii_case("scale"))
}
impl StyloStyleReducedPreference {
fn prefers_reduced(self) -> bool {
matches!(self, Self::Reduce)
@@ -959,7 +959,7 @@ impl DocumentRuntime {
}
let load_event_binding =
Self::load_event_binding_for_connected_admission(event_admission);
if connected_modulepreload_has_non_matching_media(&self.dom_host, handle) {
if self.connected_modulepreload_has_non_matching_media(handle) {
self.stylesheet_lifecycle
.owner_states
.clear_async_operations(handle);
@@ -1788,6 +1788,12 @@ impl DocumentRuntime {
.node(self.dom_host.document_handle())
.and_then(Node::as_document)
.map(|document| document.url().clone())?;
if element
.attribute("media")
.is_some_and(|media| !self.stylesheet_media_matches(media.trim()))
{
return None;
}
let candidate = modulepreload_fetch_candidate(
element,
url.clone(),
@@ -1797,6 +1803,21 @@ impl DocumentRuntime {
Some((candidate.key, candidate.request))
}
fn connected_modulepreload_has_non_matching_media(&self, handle: DomHandle) -> bool {
let Some(element) = self.dom_host.node(handle).and_then(Node::as_element) else {
return false;
};
element.is_html_element("link")
&& element
.attribute("rel")
.is_some_and(|rel| link_rel_includes_token(rel, "modulepreload"))
&& connected_preload_like_link_url(&self.dom_host, NodeId::new(handle.index()))
.is_some()
&& element
.attribute("media")
.is_some_and(|media| !self.stylesheet_media_matches(media.trim()))
}
fn connected_modulepreload_url_matches(
&self,
handle: DomHandle,
@@ -1900,21 +1921,6 @@ fn connected_modulepreload_invalid_as(
.map(str::to_ascii_lowercase)
}
fn connected_modulepreload_has_non_matching_media(
dom_host: &crate::dom::native::DomHost,
handle: DomHandle,
) -> bool {
let Some(element) = dom_host.node(handle).and_then(Node::as_element) else {
return false;
};
element.is_html_element("link")
&& element
.attribute("rel")
.is_some_and(|rel| link_rel_includes_token(rel, "modulepreload"))
&& connected_preload_like_link_url(dom_host, NodeId::new(handle.index())).is_some()
&& !modulepreload_media_matches(element)
}
fn connected_style_owner_kind(
element: &crate::dom::native::Element,
) -> Option<ConnectedStyleOwnerKind> {
@@ -6,7 +6,6 @@
use super::*;
use crate::modulepreload::{
ModulepreloadAsState, modulepreload_as_state, modulepreload_fetch_candidate,
modulepreload_media_matches,
};
mod attributes;