mirror of
https://github.com/lexmount/moli.git
synced 2026-11-25 08:02:28 +00:00
fix(fonts): include resolved fallback sources in CSS resource identity
Hash the complete resolved source list with ordered, typed and length-delimited entries. Preserve identity convergence between native and import-response projections. Add distinct-base fallback identity checks and a browser contract with identical external stylesheet text, separate font requests and opposite narrow/wide geometry in both declaration orders. Validation: cargo fmt --all; strict workspace Clippy; cargo nextest run --no-fail-fast (20593 tests run: 20593 passed (9 slow), 18 skipped).
This commit is contained in:
@@ -6,6 +6,7 @@ from typing import Any
|
||||
from ..assertions import assert_equal, record_contract
|
||||
from ..config import REPO_ROOT
|
||||
from .font_face_css_order import run_css_font_order_contract, run_projected_local_font_order_contract
|
||||
from .font_face_fallback_identity import run_font_fallback_identity_contract
|
||||
from .font_face_matching import run_font_matching_contract
|
||||
|
||||
|
||||
@@ -14,6 +15,7 @@ async def run_font_face_payload_group(
|
||||
fixture: str,
|
||||
results: list[dict[str, Any]],
|
||||
) -> None:
|
||||
await run_font_fallback_identity_contract(browser, results)
|
||||
await run_css_font_order_contract(browser, results)
|
||||
await run_projected_local_font_order_contract(browser, results)
|
||||
context = await browser.new_context()
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from typing import Any
|
||||
|
||||
from ..assertions import assert_equal, record_contract
|
||||
from ..config import REPO_ROOT
|
||||
|
||||
|
||||
async def run_font_fallback_identity_contract(browser: Any, results: list[dict[str, Any]]) -> None:
|
||||
fixtures = REPO_ROOT / "moli-layout/tests/fixtures"
|
||||
fonts = {name: (fixtures / f"moli-ahem-{width}.ttf").read_bytes()
|
||||
for name, width in [("a", "narrow"), ("b", "wide")]}
|
||||
requests: list[str] = []
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_GET(self) -> None:
|
||||
requests.append(self.path)
|
||||
if self.path.endswith("style.css"):
|
||||
body = b"@font-face{font-family:FallbackIdentity;src:url(data:font/woff2;base64,YmFk),url(font.ttf)}"
|
||||
content_type = "text/css"
|
||||
elif self.path.endswith("font.ttf"):
|
||||
body = fonts[self.path.split("/")[-2]]
|
||||
content_type = "font/ttf"
|
||||
else:
|
||||
body = b"<!doctype html><html><head></head><body></body></html>"
|
||||
content_type = "text/html"
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *_: Any) -> None:
|
||||
pass
|
||||
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
observed = []
|
||||
try:
|
||||
for index, order in enumerate([["a", "b"], ["b", "a"]]):
|
||||
context = await browser.new_context()
|
||||
try:
|
||||
page = await context.new_page()
|
||||
await page.goto(f"http://127.0.0.1:{server.server_port}/round-{index}/page", wait_until="load")
|
||||
observed.append(await page.evaluate("""async order => {
|
||||
const target=document.createElement('span');
|
||||
target.textContent='AAAA';
|
||||
target.style.cssText='display:inline-block;font:40px FallbackIdentity';
|
||||
document.body.append(target);
|
||||
const widths=[], counts=[];
|
||||
for (const directory of order) {
|
||||
const link=document.createElement('link');link.rel='stylesheet';
|
||||
link.href=directory+'/style.css';
|
||||
const loaded=new Promise((resolve,reject)=>{link.onload=resolve;link.onerror=reject});
|
||||
document.head.append(link);await loaded;
|
||||
const faces=[...document.fonts].filter(face=>face.family==='FallbackIdentity');
|
||||
counts.push(faces.length);
|
||||
await Promise.all(faces.map(face=>face.load()));
|
||||
widths.push(target.getBoundingClientRect().width);
|
||||
}
|
||||
return {widths,counts};
|
||||
}""", order))
|
||||
finally:
|
||||
await context.close()
|
||||
finally:
|
||||
await asyncio.to_thread(server.shutdown)
|
||||
server.server_close()
|
||||
thread.join()
|
||||
assert_equal(observed, [{"widths": [80, 160], "counts": [1, 2]},
|
||||
{"widths": [160, 80], "counts": [1, 2]}],
|
||||
"relative fallbacks in identical stylesheet text keep independent resources")
|
||||
font_requests = sorted(path for path in requests if path.endswith("font.ttf"))
|
||||
assert_equal(font_requests, [f"/round-{index}/{directory}/font.ttf"
|
||||
for index in range(2) for directory in ["a", "b"]],
|
||||
"each stylesheet requests its own resolved fallback")
|
||||
record_contract(results, "font_face_resolved_fallback_identity",
|
||||
contract="Font resource identity includes the ordered resolved fallback list.",
|
||||
source="CSS Fonts source fallback and stylesheet URL resolution",
|
||||
commands=["Runtime.evaluate"], observed={"geometry": observed, "requests": font_requests})
|
||||
@@ -215,11 +215,20 @@ fn stylesheet_web_font_resource_with_descriptor(
|
||||
// projections of the same parsed rule (the import response and the later
|
||||
// retained style world) must converge on one slot. Conversely, identical
|
||||
// relative declarations parsed under different stylesheet bases must not
|
||||
// alias, so identity includes the resolved request URL.
|
||||
let mut slot_material = Vec::with_capacity(request_url.as_str().len() + css_text.len() + 1);
|
||||
slot_material.extend_from_slice(request_url.as_str().as_bytes());
|
||||
slot_material.push(0);
|
||||
// alias, so identity includes every resolved fallback, its kind and order.
|
||||
// Length-prefix strings so source boundaries cannot collide.
|
||||
let mut slot_material = Vec::new();
|
||||
slot_material.extend_from_slice(&(css_text.len() as u64).to_le_bytes());
|
||||
slot_material.extend_from_slice(css_text.as_bytes());
|
||||
for source in &sources {
|
||||
let (kind, value) = match source {
|
||||
moli_css_parse::CssFontSource::Local(value) => (0, value),
|
||||
moli_css_parse::CssFontSource::Url(value) => (1, value),
|
||||
};
|
||||
slot_material.push(kind);
|
||||
slot_material.extend_from_slice(&(value.len() as u64).to_le_bytes());
|
||||
slot_material.extend_from_slice(value.as_bytes());
|
||||
}
|
||||
let slot = format!("stylesheet-font:{}", sha256_hex(&slot_material));
|
||||
StylesheetLoadBlockingResource::font(
|
||||
request_url,
|
||||
@@ -486,6 +495,46 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn font_slot_includes_every_resolved_fallback_in_source_order() {
|
||||
use moli_css_parse::CssFontSource::{Local, Url as SourceUrl};
|
||||
let css =
|
||||
"@font-face{font-family:Fallback;src:url(data:font/woff2;base64,YmFk),url(font.woff2)}";
|
||||
let first = stylesheet_web_font_resource(
|
||||
css,
|
||||
&Url::parse("https://example.test/a/style.css").unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let second = stylesheet_web_font_resource(
|
||||
css,
|
||||
&Url::parse("https://example.test/b/style.css").unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(first.request_url(), second.request_url());
|
||||
assert_ne!(
|
||||
first.web_font().unwrap().slot(),
|
||||
second.web_font().unwrap().slot()
|
||||
);
|
||||
let slot = |sources| {
|
||||
stylesheet_web_font_resource_with_resolved_sources(css, sources)
|
||||
.unwrap()
|
||||
.web_font()
|
||||
.unwrap()
|
||||
.slot()
|
||||
.to_owned()
|
||||
};
|
||||
let url = "https://example.test/font.woff2".to_owned();
|
||||
let other = "https://example.test/other.woff2".to_owned();
|
||||
assert_ne!(
|
||||
slot(vec![SourceUrl(url.clone()), SourceUrl(other.clone())]),
|
||||
slot(vec![SourceUrl(other.clone()), SourceUrl(url.clone())]),
|
||||
);
|
||||
assert_ne!(
|
||||
slot(vec![SourceUrl(url.clone()), Local(other.clone())]),
|
||||
slot(vec![SourceUrl(url), SourceUrl(other)]),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_blocking_font_selection_ignores_image_and_unrelated_bits() {
|
||||
let css = r#"
|
||||
|
||||
Reference in New Issue
Block a user