mirror of
https://github.com/lexmount/moli.git
synced 2026-11-21 00:03:15 +00:00
fix(fonts): preserve native load promises and request ownership
Keep FontFace.loaded lazy without duplicating native load state, preserving promise identity, realm, and retention through asynchronous CSS or JS loads. Bind explicit font requests to the exact Window, retain redirect CSP checks, and distinguish Script request attribution from css ResourceTiming entries. Preserve main's explicit request policy and shared resource preparation. Drive local URL completions through real resource tasks in domain tests, keep the queued FontFaceSet finish-task regression, and retain both CSSOM and Typed OM font assertions with the parser fallback regression.
This commit is contained in:
@@ -5,10 +5,10 @@ pub enum ContentSecurityPolicyResourceKind {
|
||||
DocumentBase,
|
||||
DocumentConnect,
|
||||
DocumentFrame,
|
||||
DocumentFont,
|
||||
DocumentImage,
|
||||
DocumentManifest,
|
||||
DocumentMedia,
|
||||
DocumentFont,
|
||||
DocumentScriptElement,
|
||||
DocumentStyleElement,
|
||||
WorkerConstructor,
|
||||
|
||||
@@ -266,7 +266,24 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_numeric_follow_native_declaration_mutations() {
|
||||
fn font_shorthand_remains_usable_without_optional_size_adjust_support() {
|
||||
assert!(!crate::stylo_style_rule_property_name_is_enabled(
|
||||
"font-size-adjust"
|
||||
));
|
||||
let mut block = parse_declaration_block("font: 16px serif");
|
||||
assert_eq!(block.property_value("font").as_deref(), Some("16px serif"));
|
||||
assert_ne!(
|
||||
block.set_property("font", "12px sans-serif", false),
|
||||
CssSetResult::ParseError
|
||||
);
|
||||
assert_eq!(
|
||||
block.property_value("font").as_deref(),
|
||||
Some("12px sans-serif")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_numbers_follow_native_declaration_mutations() {
|
||||
let mut block = parse_declaration_block("opacity: 25%; margin-left: 1px");
|
||||
let percent = CssDeclaredUnitValue {
|
||||
value: 25.0,
|
||||
|
||||
@@ -182,9 +182,6 @@ fn queue_font_face_set_task<'s>(
|
||||
return;
|
||||
};
|
||||
let scope = &mut v8::ContextScope::new(scope, context);
|
||||
let Some(host_ptr) = crate::util::context_host_ptr_from_global_bridge(scope) else {
|
||||
return;
|
||||
};
|
||||
let data = v8::Array::new_with_elements(
|
||||
scope,
|
||||
&[owner.into(), v8::Boolean::new(scope, finish).into()],
|
||||
|
||||
@@ -201,30 +201,44 @@ pub(super) fn initialize<'s>(
|
||||
publish_state(scope, face);
|
||||
}
|
||||
|
||||
/// Observing .loaded creates its stable promise in the FontFace realm. Native
|
||||
/// status and CSS loading remain independent of whether the promise is read.
|
||||
pub(super) fn loaded_promise<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
face: v8::Local<'s, v8::Object>,
|
||||
) -> Option<v8::Local<'s, v8::Promise>> {
|
||||
let context = face.get_creation_context(scope)?;
|
||||
let scope = &mut v8::ContextScope::new(scope, context);
|
||||
if let Some(promise) = get_private_value(scope, face, FONT_FACE_LOADED_SLOT)
|
||||
.and_then(|value| v8::Local::<v8::Promise>::try_from(value).ok())
|
||||
{
|
||||
return Some(promise);
|
||||
}
|
||||
let load = super::state::get(scope, face)?;
|
||||
let context = face.get_creation_context(scope)?;
|
||||
let scope = &mut v8::ContextScope::new(scope, context);
|
||||
// Native errors can exist before page code observes .loaded. Creating a
|
||||
// rejected promise in the constructor would report an unhandled rejection
|
||||
// even when the page never obtains that promise.
|
||||
let resolver = v8::PromiseResolver::new(scope).expect("FontFace loaded resolver");
|
||||
let resource = super::state::get(scope, face)?;
|
||||
let (status, error) = {
|
||||
let resource = resource.borrow();
|
||||
(resource.status(), resource.error())
|
||||
};
|
||||
let resolver = v8::PromiseResolver::new(scope)?;
|
||||
let promise = resolver.get_promise(scope);
|
||||
set_private_value(scope, face, FONT_FACE_LOADED_SLOT, promise.into());
|
||||
set_private_value(scope, face, RESOLVER, resolver.into());
|
||||
// A retained pending .loaded promise also retains its settlement endpoint.
|
||||
// Loading faces have a Window-owned native root, released on completion
|
||||
// or retirement; unloaded JS-only cycles remain collectible.
|
||||
set_private_value(scope, promise.into(), PROMISE_OWNER, face.into());
|
||||
settle_loaded_promise(scope, face, &load);
|
||||
match status {
|
||||
FontFaceStatus::Loaded => {
|
||||
let _ = resolver.resolve(scope, face.into());
|
||||
}
|
||||
FontFaceStatus::Error => {
|
||||
let error = error.expect("native failed font has an error");
|
||||
let exception = new_dom_exception_value(scope, error.message, error.name);
|
||||
let _ = resolver.reject(scope, exception);
|
||||
}
|
||||
FontFaceStatus::Unloaded | FontFaceStatus::Loading => {
|
||||
set_private_value(scope, face, RESOLVER, resolver.into());
|
||||
// Retaining a pending promise keeps its native settlement endpoint
|
||||
// alive, including CSS-started loads. The JS heap owns this edge,
|
||||
// allowing an otherwise unreachable cycle to be collected.
|
||||
set_private_value(scope, promise.into(), PROMISE_OWNER, face.into());
|
||||
}
|
||||
}
|
||||
Some(promise)
|
||||
}
|
||||
|
||||
|
||||
@@ -108,37 +108,6 @@ impl DocumentRequestPolicySnapshot {
|
||||
Self::from_policies(enforce_policies, report_only_policies, reporting_endpoints)
|
||||
}
|
||||
|
||||
pub(crate) fn font_violation(
|
||||
&self,
|
||||
document_url: &Url,
|
||||
request_url: &Url,
|
||||
disposition: ContentSecurityPolicyDisposition,
|
||||
redirect_status: ContentSecurityPolicyRedirectStatus,
|
||||
) -> Option<DocumentContentSecurityPolicyViolation> {
|
||||
match disposition {
|
||||
ContentSecurityPolicyDisposition::Enforce => {
|
||||
document_url_policy_violation_from_document_policies(
|
||||
self.enforce_policies.clone(),
|
||||
document_url,
|
||||
None,
|
||||
request_url,
|
||||
ContentSecurityPolicyResourceKind::DocumentFont,
|
||||
redirect_status,
|
||||
disposition,
|
||||
)
|
||||
}
|
||||
ContentSecurityPolicyDisposition::Report => document_url_policy_violation(
|
||||
&self.report_only_policies,
|
||||
&self.reporting_endpoints,
|
||||
document_url,
|
||||
request_url,
|
||||
ContentSecurityPolicyResourceKind::DocumentFont,
|
||||
redirect_status,
|
||||
disposition,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn for_script_preload(
|
||||
mut self,
|
||||
metadata: crate::planning::ScriptFetchMetadata,
|
||||
@@ -337,6 +306,7 @@ impl DocumentRequestPolicySnapshot {
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn from_policy_container(policy: &DocumentPolicyContainer) -> Self {
|
||||
let mut enforce = policy.response_content_security_policies.clone();
|
||||
enforce.extend(policy.document_content_security_policies.iter().cloned());
|
||||
|
||||
@@ -1241,23 +1241,22 @@ impl PageScriptHost {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn record_font_face_fetch(
|
||||
&mut self,
|
||||
context: v8::Global<v8::Context>,
|
||||
execution_context: super::WindowExecutionContextBinding,
|
||||
resource_loader: &crate::network::context::DocumentResourceLoader,
|
||||
font: crate::types::PendingFontFaceFetch,
|
||||
owner: OwnerDispatchScope,
|
||||
registration: SubresourceFetchRegistration,
|
||||
dispatch: &crate::network_host::SubresourceRequestDispatch,
|
||||
network_partition_key: Option<String>,
|
||||
policy_context: crate::types::SubresourcePolicyContext,
|
||||
mut info: PendingSubresourceFetchInfo,
|
||||
) -> u64 {
|
||||
self.assign_pending_subresource_fetch_identity(&mut info);
|
||||
let internal_id = info.internal_id;
|
||||
let (load, request_origin) = self.require_document_resource_load_for_dispatch_scope(
|
||||
owner,
|
||||
info.resource_type,
|
||||
) -> Option<u64> {
|
||||
let load = resource_loader.register_load(
|
||||
ResourceLoadKind::Font,
|
||||
ResourceLoadDisposition::Ordinary,
|
||||
registration.cancel_handle(),
|
||||
);
|
||||
)?;
|
||||
self.assign_pending_subresource_fetch_identity(&mut info);
|
||||
let internal_id = info.internal_id;
|
||||
let dispatch = matches!(registration, SubresourceFetchRegistration::Intercepted)
|
||||
.then(|| Box::new(dispatch.clone()));
|
||||
self.record_subresource_admission(
|
||||
@@ -1274,20 +1273,18 @@ impl PageScriptHost {
|
||||
dispatch,
|
||||
info,
|
||||
load,
|
||||
execution_context: PendingSubresourceExecutionContext::adapter(owner, context),
|
||||
execution_context: PendingSubresourceExecutionContext::window(execution_context),
|
||||
credentials_mode: moli_fetch::RequestCredentialsMode::SameOrigin,
|
||||
request_mode: moli_fetch::RequestMode::Cors,
|
||||
network_partition_key,
|
||||
policy_context,
|
||||
continuation: PendingSubresourceContinuation::FontFace(Box::new(font)),
|
||||
request_origin,
|
||||
redirect_headers: None,
|
||||
deferred_request_started: false,
|
||||
blob_url_entry: None,
|
||||
},
|
||||
);
|
||||
self.note_subresource_activity();
|
||||
internal_id
|
||||
Some(internal_id)
|
||||
}
|
||||
|
||||
pub(crate) fn record_async_dictionary_fetch(
|
||||
|
||||
@@ -1213,35 +1213,6 @@ impl PageScriptHost {
|
||||
OwnerDispatchScope::Top
|
||||
}
|
||||
|
||||
pub(crate) fn font_request_allowed_by_csp(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
owner: OwnerDispatchScope,
|
||||
document_url: &url::Url,
|
||||
request_url: &url::Url,
|
||||
redirect_status: ContentSecurityPolicyRedirectStatus,
|
||||
) -> bool {
|
||||
let Some(policy) = self.document_connect_policy_snapshot_for_owner(owner) else {
|
||||
return false;
|
||||
};
|
||||
let mut allowed = true;
|
||||
for disposition in [
|
||||
ContentSecurityPolicyDisposition::Report,
|
||||
ContentSecurityPolicyDisposition::Enforce,
|
||||
] {
|
||||
if let Some(violation) =
|
||||
policy.font_violation(document_url, request_url, disposition, redirect_status)
|
||||
{
|
||||
let host_ptr = self as *mut Self;
|
||||
self.dispatch_content_security_policy_violation_event_for_owner_best_effort(
|
||||
scope, host_ptr, owner, &violation,
|
||||
);
|
||||
allowed &= disposition != ContentSecurityPolicyDisposition::Enforce;
|
||||
}
|
||||
}
|
||||
allowed
|
||||
}
|
||||
|
||||
pub(crate) fn check_document_connect_csp_for_owner<'s>(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::subresource::{PreparedSubresourceFetch, SubresourceFetchOptions};
|
||||
use super::*;
|
||||
use crate::{
|
||||
native_bridge::{PageScriptHost, WindowExecutionContextIdentity},
|
||||
types::{AsyncSubresourceFetchCompletion, PendingFontFaceFetch, SubresourceResourceType},
|
||||
types::{AsyncSubresourceFetchCompletion, PendingFontFaceFetch},
|
||||
};
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
|
||||
@@ -49,9 +49,9 @@ pub(crate) fn resolve_font_face_sources(
|
||||
|
||||
/// Explicit CSS Font Loading requests share document ownership, CORS and the
|
||||
/// renderer network queue with other resources. Never call page-defined fetch.
|
||||
pub(crate) fn start_font_face_fetch(
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
face: v8::Local<'_, v8::Object>,
|
||||
pub(crate) fn start_font_face_fetch<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
face: v8::Local<'s, v8::Object>,
|
||||
request_context: Option<WindowExecutionContextIdentity>,
|
||||
source: &str,
|
||||
) -> Result<()> {
|
||||
@@ -70,6 +70,15 @@ pub(crate) fn start_font_face_fetch(
|
||||
.filter(|identity| host.window_execution_context_identity_is_current(*identity))
|
||||
.context("resource request owner is stale")?;
|
||||
let owner = identity.dispatch_scope();
|
||||
let context = face
|
||||
.get_creation_context(scope)
|
||||
.context("FontFace creation realm is unavailable")?;
|
||||
let binding = crate::native_bridge::WindowExecutionContextBinding::new(
|
||||
identity.owner(),
|
||||
owner,
|
||||
identity.realm_token(),
|
||||
v8::Global::new(scope, context),
|
||||
);
|
||||
let resource_loader = host
|
||||
.document_resource_loader_for_dispatch_scope(owner)
|
||||
.context("Document resource loader is unavailable")?;
|
||||
@@ -114,15 +123,6 @@ pub(crate) fn start_font_face_fetch(
|
||||
moli_fetch::FetchUrlList::new(&request_url, &[])
|
||||
.validate_request_mode(moli_fetch::RequestMode::Cors, &environment.request_origin)
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
if matches!(request_url.scheme(), "http" | "https")
|
||||
&& !resource_loader
|
||||
.request_client()
|
||||
.optional_resource_fetch_enabled(SubresourceResourceType::Font)
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"FontFace requests are disabled by the resource policy"
|
||||
));
|
||||
}
|
||||
let font = PendingFontFaceFetch {
|
||||
face: v8::Global::new(scope, face),
|
||||
redirect_state: FetchCspRedirectState::new(&policy),
|
||||
@@ -138,16 +138,18 @@ pub(crate) fn start_font_face_fetch(
|
||||
request_url.clone(),
|
||||
SubresourceFetchOptions::FONT,
|
||||
);
|
||||
let internal_id = host.record_font_face_fetch(
|
||||
v8::Global::new(scope, scope.get_current_context()),
|
||||
font,
|
||||
owner,
|
||||
prepared.registration.clone(),
|
||||
&prepared.dispatch,
|
||||
prepared.network_partition_key.clone(),
|
||||
prepared.network_context.policy_context,
|
||||
prepared.pending_info.clone(),
|
||||
);
|
||||
let internal_id = host
|
||||
.record_font_face_fetch(
|
||||
binding,
|
||||
&resource_loader,
|
||||
font,
|
||||
prepared.registration.clone(),
|
||||
&prepared.dispatch,
|
||||
prepared.network_partition_key.clone(),
|
||||
prepared.network_context.policy_context,
|
||||
prepared.pending_info.clone(),
|
||||
)
|
||||
.context("FontFace Document was retired")?;
|
||||
// Local URL responses use the same resource completion task as network
|
||||
// responses, preserving the observable loading state before settlement.
|
||||
let blob = CapturedBlobUrl::capture(&request_url);
|
||||
|
||||
@@ -947,6 +947,12 @@ impl ScriptVm {
|
||||
),
|
||||
),
|
||||
PendingSubresourceContinuation::FontFace(face) => {
|
||||
crate::context_bootstrap::record_resource_performance_entry(
|
||||
scope,
|
||||
crate::context_bootstrap::ResourcePerformanceEntry::from_network_response(
|
||||
pending.info.url.as_str(), "css", None, &observable_response,
|
||||
),
|
||||
);
|
||||
let face = v8::Local::new(scope, &face.face);
|
||||
let bytes = ((200..300).contains(&response_status) && !opaque_response_blocked)
|
||||
.then(|| observable_response.body_bytes());
|
||||
|
||||
@@ -49,9 +49,31 @@ document.fonts.load('12px "Missing Face"').then(() => fontResult.push('WRONG set
|
||||
);
|
||||
}
|
||||
|
||||
fn complete_local_font_resources(
|
||||
vm: &mut ScriptVm,
|
||||
completions: &mut RendererResourceCompletionTestHarness,
|
||||
) {
|
||||
for _ in 0..16 {
|
||||
let Some(completion) = completions.pop_next_async_subresource_event() else {
|
||||
run_font_tasks(vm);
|
||||
return;
|
||||
};
|
||||
let activity = vm
|
||||
.complete_async_subresource_fetch_event_body(completion)
|
||||
.unwrap();
|
||||
vm.finish_async_subresource_body_checkpoint_for_test(activity)
|
||||
.unwrap();
|
||||
}
|
||||
panic!("local font resource tasks did not become idle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn font_face_valid_data_sources_register_and_unregister_real_font_bytes() {
|
||||
let mut vm = new_storage_test_vm("https://font-sources.test/");
|
||||
let mut completions = RendererResourceCompletionTestHarness::new();
|
||||
let mut vm = new_storage_test_vm_with_completion_sender(
|
||||
"https://font-sources.test/",
|
||||
completions.sender(),
|
||||
);
|
||||
let url = fixture_font_url();
|
||||
vm.eval(&format!(r#"
|
||||
globalThis.fontResult = [];
|
||||
@@ -60,6 +82,7 @@ document.fonts.add(face);
|
||||
fontResult.push(face.status, document.fonts.check('italic 12px "Actual Face", serif'));
|
||||
document.fonts.load('12px "Actual Face", serif').then(faces => fontResult.push(faces.length, faces[0] === face, face.status, document.fonts.check('12px "Actual Face"')));
|
||||
"#)).unwrap();
|
||||
complete_local_font_resources(&mut vm, &mut completions);
|
||||
assert_eq!(
|
||||
vm.eval("JSON.stringify(fontResult)").unwrap(),
|
||||
r#"["unloaded",false,1,true,"loaded",true]"#
|
||||
|
||||
@@ -39,7 +39,11 @@ fn font_set_queries_normalize_reversed_computed_descriptor_ranges() {
|
||||
|
||||
#[test]
|
||||
fn font_set_queries_resolve_css_calculations_in_requests_and_descriptors() {
|
||||
let mut vm = new_storage_test_vm("https://font-query-calculations.test/");
|
||||
let mut completions = RendererResourceCompletionTestHarness::new();
|
||||
let mut vm = new_storage_test_vm_with_completion_sender(
|
||||
"https://font-query-calculations.test/",
|
||||
completions.sender(),
|
||||
);
|
||||
let url = fixture_font_url();
|
||||
vm.eval(&format!(r#"
|
||||
const bytes=Uint8Array.from(atob('{}'),c=>c.charCodeAt(0));
|
||||
@@ -59,9 +63,10 @@ fn font_set_queries_resolve_css_calculations_in_requests_and_descriptors() {
|
||||
error=>calculations.push(error.name));
|
||||
}}
|
||||
"#,url.split_once(',').unwrap().1)).unwrap();
|
||||
complete_local_font_resources(&mut vm, &mut completions);
|
||||
assert_eq!(
|
||||
vm.eval("JSON.stringify(calculations)").unwrap(),
|
||||
r#"[false,false,true,"NetworkError","NetworkError",[1,true,"unloaded"]]"#
|
||||
r#"[false,false,true,[1,true,"unloaded"],"NetworkError","NetworkError"]"#
|
||||
);
|
||||
vm.eval(
|
||||
r#"
|
||||
@@ -72,6 +77,7 @@ fn font_set_queries_resolve_css_calculations_in_requests_and_descriptors() {
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
complete_local_font_resources(&mut vm, &mut completions);
|
||||
assert_eq!(
|
||||
vm.eval("JSON.stringify(widthCalculations)").unwrap(),
|
||||
r#"[false,"NetworkError"]"#
|
||||
@@ -80,7 +86,11 @@ fn font_set_queries_resolve_css_calculations_in_requests_and_descriptors() {
|
||||
|
||||
#[test]
|
||||
fn font_set_queries_filter_text_without_loading_unrelated_sources() {
|
||||
let mut vm = new_storage_test_vm("https://font-query-text.test/");
|
||||
let mut completions = RendererResourceCompletionTestHarness::new();
|
||||
let mut vm = new_storage_test_vm_with_completion_sender(
|
||||
"https://font-query-text.test/",
|
||||
completions.sender(),
|
||||
);
|
||||
vm.eval(
|
||||
r#"
|
||||
globalThis.face = new FontFace('ReviewProbe',
|
||||
@@ -97,6 +107,7 @@ fn font_set_queries_filter_text_without_loading_unrelated_sources() {
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
complete_local_font_resources(&mut vm, &mut completions);
|
||||
assert_eq!(
|
||||
vm.eval("JSON.stringify({...queryResults,status:face.status})")
|
||||
.unwrap(),
|
||||
@@ -109,6 +120,7 @@ fn font_set_queries_filter_text_without_loading_unrelated_sources() {
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
complete_local_font_resources(&mut vm, &mut completions);
|
||||
assert_eq!(
|
||||
vm.eval("JSON.stringify(matched)").unwrap(),
|
||||
r#"[false,"NetworkError"]"#
|
||||
@@ -117,7 +129,11 @@ fn font_set_queries_filter_text_without_loading_unrelated_sources() {
|
||||
|
||||
#[test]
|
||||
fn font_set_queries_select_weight_style_and_stretch_before_loading() {
|
||||
let mut vm = new_storage_test_vm("https://font-query-properties.test/");
|
||||
let mut completions = RendererResourceCompletionTestHarness::new();
|
||||
let mut vm = new_storage_test_vm_with_completion_sender(
|
||||
"https://font-query-properties.test/",
|
||||
completions.sender(),
|
||||
);
|
||||
let url = fixture_font_url();
|
||||
vm.eval(&format!(
|
||||
r#"
|
||||
@@ -143,6 +159,7 @@ fn font_set_queries_select_weight_style_and_stretch_before_loading() {
|
||||
url.split_once(',').unwrap().1
|
||||
))
|
||||
.unwrap();
|
||||
complete_local_font_resources(&mut vm, &mut completions);
|
||||
assert_eq!(
|
||||
vm.eval("JSON.stringify(queryResults)").unwrap(),
|
||||
r#"{"checks":[true,true,true],"loads":[[1,true,"unloaded"],[1,true,"unloaded"],[1,true,"unloaded"]]}"#
|
||||
@@ -154,6 +171,7 @@ fn font_set_queries_select_weight_style_and_stretch_before_loading() {
|
||||
document.fonts.load(query,'A').catch(e=>selected.push(e.name));
|
||||
}
|
||||
"#).unwrap();
|
||||
complete_local_font_resources(&mut vm, &mut completions);
|
||||
assert_eq!(
|
||||
vm.eval("JSON.stringify(selected)").unwrap(),
|
||||
r#"[false,false,false,"NetworkError","NetworkError","NetworkError"]"#
|
||||
|
||||
@@ -640,9 +640,22 @@ async fn font_set_finish_task_rechecks_fonts_started_before_dispatch() {
|
||||
firstReady.then(()=>readyResolved=true);
|
||||
globalThis.doneEvents=[];
|
||||
fonts.addEventListener('loadingdone',event=>doneEvents.push(event.fontfaces.map(face=>face.family).sort()));
|
||||
"#)).unwrap();
|
||||
// Complete the first source, leaving its FontFaceSet finish task queued.
|
||||
// Starting another face before dispatch must make that task recheck idle.
|
||||
let completion = completions.pop_next_async_subresource_event().unwrap();
|
||||
let activity = vm
|
||||
.complete_async_subresource_fetch_event_body(completion)
|
||||
.unwrap();
|
||||
vm.finish_async_subresource_body_checkpoint_for_test(activity)
|
||||
.unwrap();
|
||||
vm.eval(&format!(
|
||||
r#"
|
||||
globalThis.slow=new FontFace('Slow','url("{origin}/slow.woff2")');
|
||||
fonts.add(slow);slow.load();
|
||||
"#)).unwrap();
|
||||
"#
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
tokio::time::timeout(Duration::from_secs(2), requests.recv())
|
||||
.await
|
||||
|
||||
@@ -14,11 +14,10 @@ pub(super) fn order_font_data() -> (String, String) {
|
||||
)
|
||||
}
|
||||
|
||||
const ORDER_DOCUMENT: &str = "<!doctype html><html><head></head><body><span id='probe' style='display:inline-block;font:40px OrderFace'>AAAA</span><iframe id='frame'></iframe></body></html>";
|
||||
|
||||
pub(super) fn order_vm() -> StandaloneScriptVmHarness {
|
||||
let mut vm = new_parsed_test_vm(
|
||||
"https://font-selection-order.test/",
|
||||
"<!doctype html><html><head></head><body><span id='probe' style='display:inline-block;font:40px OrderFace'>AAAA</span><iframe id='frame'></iframe></body></html>",
|
||||
);
|
||||
let mut vm = new_parsed_test_vm("https://font-selection-order.test/", ORDER_DOCUMENT);
|
||||
vm.set_layout_policy(moli_page_types::LayoutPolicy::OnDemand);
|
||||
vm
|
||||
}
|
||||
@@ -281,9 +280,15 @@ fn font_face_selection_follows_owner_membership_instead_of_resource_id() {
|
||||
assert_eq!(width(&mut vm), "160");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manually_added_font_faces_take_priority_over_css_connected_faces() {
|
||||
let mut vm = order_vm();
|
||||
#[tokio::test]
|
||||
async fn manually_added_font_faces_take_priority_over_css_connected_faces() {
|
||||
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
|
||||
let (mut vm, mut completions) = new_parsed_test_vm_with_loader_and_resource_completion_queue(
|
||||
"https://font-selection-order.test/",
|
||||
ORDER_DOCUMENT,
|
||||
&loader,
|
||||
);
|
||||
vm.set_layout_policy(moli_page_types::LayoutPolicy::OnDemand);
|
||||
let (narrow, wide) = order_font_data();
|
||||
vm.eval(&format!(r#"
|
||||
const style=document.createElement('style');
|
||||
@@ -292,6 +297,7 @@ fn manually_added_font_faces_take_priority_over_css_connected_faces() {
|
||||
globalThis.narrow=[...document.fonts][0];
|
||||
narrow.load();
|
||||
"#)).unwrap();
|
||||
complete_local_font_resources(&mut vm, &mut completions);
|
||||
assert_eq!(vm.eval("narrow.status").unwrap(), "loaded");
|
||||
assert_eq!(
|
||||
vm.eval("String(probe.getBoundingClientRect().width)")
|
||||
|
||||
@@ -1755,7 +1755,9 @@ async fn font_face_string_sources_follow_load_state_and_connected_style_use() {
|
||||
globalThis.__fontFaceStringSourceProbe.local.afterDetachedStyle = local.status;
|
||||
(document.body || document.documentElement || document).appendChild(target);
|
||||
globalThis.__fontFaceStringSourceProbe.local.afterConnection = local.status;
|
||||
await Promise.allSettled([remoteLoaded, invalid.loaded, local.loaded]);
|
||||
const localLoad = document.fonts.load('16px MissingLocalFace');
|
||||
globalThis.__fontFaceStringSourceProbe.local.afterSetLoad = local.status;
|
||||
await Promise.allSettled([remoteLoaded, invalid.loaded, local.loaded, localLoad]);
|
||||
return JSON.stringify(globalThis.__fontFaceStringSourceProbe);
|
||||
})()
|
||||
"#,
|
||||
@@ -1764,7 +1766,7 @@ async fn font_face_string_sources_follow_load_state_and_connected_style_use() {
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
r#"{"remote":{"before":"unloaded","stablePromise":true,"loadReturnsLoaded":true,"after":"loading","settlement":"resolved-self"},"invalid":{"status":"error","settlement":"SyntaxError"},"local":{"beforeStyle":"unloaded","afterDetachedStyle":"unloaded","afterConnection":"loading","settlement":"NetworkError"}}"#
|
||||
r#"{"remote":{"before":"unloaded","stablePromise":true,"loadReturnsLoaded":true,"after":"loading","settlement":"resolved-self"},"invalid":{"status":"error","settlement":"SyntaxError"},"local":{"beforeStyle":"unloaded","afterDetachedStyle":"unloaded","afterConnection":"unloaded","settlement":"NetworkError","afterSetLoad":"error"}}"#
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
-52
@@ -53,56 +53,4 @@
|
||||
check(getComputedStyle(child).font === '', 'invalid substitution inherits non-initial adjustment');
|
||||
parent.remove();
|
||||
return true;
|
||||
})();
|
||||
|
||||
// Retain branch Typed OM assertions alongside main native CSSOM checks.
|
||||
(() => {
|
||||
const check = (ok, message) => { if (!ok) throw new Error(message); };
|
||||
for (const doc of [document, document.implementation.createHTMLDocument('')]) {
|
||||
const style = doc.createElement('div').style;
|
||||
style.cssText = 'font:16px serif;font-size-adjust:0';
|
||||
check(style.font === '', 'non-initial size adjustment prevents font serialization');
|
||||
style.font = '12px sans-serif';
|
||||
check(style.fontSizeAdjust === 'none', 'font resets size adjustment');
|
||||
check(style.font === '12px sans-serif', 'font serializes after reset');
|
||||
style.fontSizeAdjust = '0.5';
|
||||
style.setProperty('font', '16px serif', 'important');
|
||||
check(style.fontSizeAdjust === 'none', 'important font resets size adjustment');
|
||||
check(style.getPropertyPriority('font-size-adjust') === 'important', 'reset priority');
|
||||
}
|
||||
const parent = document.createElement('div');
|
||||
const child = document.createElement('div');
|
||||
parent.style.cssText = 'font:20px serif;font-size-adjust:0.75;--font:16px serif';
|
||||
parent.append(child); document.body.append(parent);
|
||||
const map = child.computedStyleMap();
|
||||
function adjusted(expected) {
|
||||
check(getComputedStyle(child).fontSizeAdjust === expected, 'computed size adjustment: ' + expected);
|
||||
check(String(map.get('font-size-adjust')) === expected, 'Typed OM size adjustment: ' + expected);
|
||||
}
|
||||
child.style.font = '16px serif';
|
||||
adjusted('none');
|
||||
const retained = Object.freeze(map.get('font'));
|
||||
child.style.fontSizeAdjust = '0';
|
||||
adjusted('0');
|
||||
check(child.style.font === '' && getComputedStyle(child).font === '', 'font cannot express size adjustment');
|
||||
check(map.get('font') === undefined && map.getAll('font').length === 0, 'unrepresentable Typed OM shorthand');
|
||||
child.style.font = '12px sans-serif';
|
||||
adjusted('none');
|
||||
check(String(retained) === '16px serif', 'retained font value');
|
||||
check(String(map.get('font')) === '12px sans-serif', 'map observes font reset');
|
||||
for (const keyword of ['initial', 'inherit', 'unset', 'revert', 'revert-layer']) {
|
||||
child.style.cssText = 'font:16px serif;font-size-adjust:0';
|
||||
child.style.font = keyword;
|
||||
check(child.style.fontSizeAdjust === keyword, 'font expands CSS-wide keyword: ' + keyword);
|
||||
adjusted(keyword === 'initial' ? 'none' : '0.75');
|
||||
}
|
||||
child.style.cssText = 'font-size-adjust:0;font:var(--font)';
|
||||
check(child.style.fontSizeAdjust === '', 'pending shorthand substitution');
|
||||
adjusted('none');
|
||||
check(getComputedStyle(child).font === '16px serif', 'valid substituted shorthand');
|
||||
child.style.font = 'var(--missing)';
|
||||
adjusted('0.75');
|
||||
check(getComputedStyle(child).font === '', 'invalid substitution inherits non-initial adjustment');
|
||||
parent.remove();
|
||||
return true;
|
||||
})()
|
||||
|
||||
+12
-5
@@ -4,10 +4,14 @@
|
||||
const child = document.createElement('div');
|
||||
parent.style.cssText = 'font-optical-sizing:none;font-variation-settings:"wght" 700, "wdth" 90, "wght" 600;--weight:650';
|
||||
parent.append(child); document.body.append(parent);
|
||||
const map = child.computedStyleMap();
|
||||
function computed(optical, variation) {
|
||||
const style = getComputedStyle(child);
|
||||
for (const [property, expected] of [['font-optical-sizing', optical], ['font-variation-settings', variation]]) {
|
||||
check(style.getPropertyValue(property) === expected, property + ': computed value');
|
||||
check(map.has(property), property + ': computed map exposure');
|
||||
check(String(map.get(property)) === expected, property + ': Typed OM value');
|
||||
check(map.getAll(property).length === 1, property + ': one computed value');
|
||||
}
|
||||
}
|
||||
for (const keyword of ['', 'inherit', 'unset', 'revert']) {
|
||||
@@ -22,13 +26,16 @@
|
||||
computed('none', '"wdth" 90, "wght" 600');
|
||||
child.style.cssText = 'font:16px serif;font-optical-sizing:none;font-variation-settings:"wght" 600';
|
||||
computed('none', '"wght" 600');
|
||||
check(child.style.font === '', 'font cannot express non-initial reset-only values');
|
||||
const optical = getComputedStyle(child).getPropertyValue('font-optical-sizing');
|
||||
const variation = getComputedStyle(child).getPropertyValue('font-variation-settings');
|
||||
check(child.style.font === '' && getComputedStyle(child).font === '', 'font cannot express non-initial reset-only values');
|
||||
const opticalText = getComputedStyle(child).getPropertyValue('font-optical-sizing');
|
||||
const variationText = getComputedStyle(child).getPropertyValue('font-variation-settings');
|
||||
const optical = Object.freeze(map.get('font-optical-sizing'));
|
||||
const variation = Object.freeze(map.get('font-variation-settings'));
|
||||
child.style.font = '16px serif';
|
||||
computed('auto', 'normal');
|
||||
check(child.style.font === '16px serif', 'font resets native values');
|
||||
check(String(optical) === 'none' && String(variation) === '"wght" 600', 'retained CSSOM strings');
|
||||
check(child.style.font === '16px serif' && getComputedStyle(child).font === '16px serif', 'font resets native values');
|
||||
check(String(optical) === 'none' && String(variation) === '"wght" 600', 'retained immutable values');
|
||||
check(opticalText === 'none' && variationText === '"wght" 600', 'retained CSSOM strings');
|
||||
const sheet = document.createElement('style');
|
||||
sheet.textContent = '@layer base { #font-target { font-optical-sizing:none;font-variation-settings:"wght" 400 } } #font-target { font-optical-sizing:auto;font-variation-settings:"wght" 550 }';
|
||||
document.head.append(sheet); child.id = 'font-target';
|
||||
|
||||
+7
-4
@@ -1,11 +1,11 @@
|
||||
(() => {
|
||||
const check = (ok, message) => { if (!ok) throw new Error(message); };
|
||||
const properties = [
|
||||
['font-optical-sizing', 'fontOpticalSizing', 'none'],
|
||||
['font-variation-settings', 'fontVariationSettings', '"wght" 700, "wdth" 90, "wght" 600'],
|
||||
['font-optical-sizing', 'fontOpticalSizing', 'none', CSSKeywordValue],
|
||||
['font-variation-settings', 'fontVariationSettings', '"wght" 700, "wdth" 90, "wght" 600', CSSStyleValue],
|
||||
];
|
||||
const documents = [document, document.implementation.createHTMLDocument('')];
|
||||
for (const [property, alias, value] of properties) {
|
||||
for (const [property, alias, value, constructor] of properties) {
|
||||
check(CSS.supports(property, value), property + ': native grammar');
|
||||
check(CSS.supports(property, 'var(--font-value)'), property + ': pending substitution');
|
||||
for (const doc of documents) {
|
||||
@@ -36,7 +36,10 @@
|
||||
check(CSS.supports(property, '/**/IN\\69 TIAL/**/'), property + ': tokenized support');
|
||||
check(CSS.supports(`(not (${property}: unsupported-value)) and (${property}: inherit)`), property + ': condition evaluation');
|
||||
}
|
||||
|
||||
const parsed = CSSStyleValue.parse(property, value);
|
||||
check(Object.getPrototypeOf(parsed) === constructor.prototype, property + ': Typed OM projection');
|
||||
check(String(parsed) === value, property + ': specified order and duplicates');
|
||||
check(CSSStyleValue.parseAll(property, value).length === 1, property + ': one property value');
|
||||
}
|
||||
return true;
|
||||
})()
|
||||
|
||||
Reference in New Issue
Block a user