Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(fonts): preserve generic families in font-set queries

ldm06c4cdafc20ab
diff --git a/moli-css-parse/src/font_face.rs b/moli-css-parse/src/font_face.rs
index e94599c8f..c494c07bf 100644
--- a/moli-css-parse/src/font_face.rs
+++ b/moli-css-parse/src/font_face.rs
@@ -71,10 +71,18 @@ pub fn legacy_variations_font_format(format: &str) -> Option<&str> {
.filter(|format| matches!(*format, "woff" | "woff2" | "truetype" | "opentype"))
}
+/// A decoded family name or a generic selected by the CSS parser. Quoting a
+/// generic keyword makes it a named family rather than a generic fallback.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum CssFontFamily {
+ Named(String),
+ Generic(style::values::computed::font::GenericFontFamily),
+}
+
#[derive(Clone, Debug)]
pub struct CssFontShorthand {
pub family_css: String,
- pub families: Vec<String>,
+ pub families: Vec<CssFontFamily>,
pub size: String,
pub style: String,
pub weight: String,
@@ -85,8 +93,10 @@ pub struct CssFontShorthand {
/// multi-word families and fallback lists. No guessed last-whitespace token.
pub fn parse_font_shorthand(value: &str) -> Option<CssFontShorthand> {
use style::{
+ parser::Parse,
properties::{PropertyId, parse_property_declaration_list},
stylesheets::CssRuleType,
+ values::computed::font::SingleFontFamily,
};
use style_traits::CssStringWriter;
if crate::escape_top_level_semicolons(value) != value
@@ -111,11 +121,12 @@ pub fn parse_font_shorthand(value: &str) -> Option<CssFontShorthand> {
}
let families = Parser::new(&family_css)
.parse_comma_separated(|p| {
- let mut parts = Vec::new();
- while !p.is_exhausted() {
- parts.push(p.expect_ident_or_string()?.to_string());
- }
- Ok::<_, cssparser::ParseError<()>>(parts.join(" "))
+ SingleFontFamily::parse(context, p).map(|family| match family {
+ SingleFontFamily::FamilyName(name) => {
+ CssFontFamily::Named(name.name.to_string())
+ }
+ SingleFontFamily::Generic(generic) => CssFontFamily::Generic(generic),
+ })
})
.ok()?;
Some(CssFontShorthand {
@@ -239,12 +250,43 @@ mod tests {
);
}
+ #[test]
+ fn font_shorthand_distinguishes_quoted_and_escaped_generic_keywords() {
+ use super::{CssFontFamily, parse_font_shorthand};
+ use style::values::computed::font::GenericFontFamily;
+ for keyword in ["serif", "SeRiF", r"s\65 rif"] {
+ let font = parse_font_shorthand(&format!("16px {keyword}")).unwrap();
+ assert_eq!(
+ font.families,
+ [CssFontFamily::Generic(GenericFontFamily::Serif)]
+ );
+ }
+ for name in [r#""serif""#, r#""s\65 rif""#, "Named serif"] {
+ let font = parse_font_shorthand(&format!("16px {name}")).unwrap();
+ let expected = if name == "Named serif" {
+ "Named serif"
+ } else {
+ "serif"
+ };
+ assert_eq!(font.families, [CssFontFamily::Named(expected.into())]);
+ }
+ }
+
#[test]
fn font_shorthand_uses_stylo_validation_and_keeps_all_families() {
let font =
super::parse_font_shorthand("italic bold 10.5px/1.2 \"A B\", Another Face, serif")
.unwrap();
- assert_eq!(font.families, ["A B", "Another Face", "serif"]);
+ assert_eq!(
+ font.families,
+ [
+ super::CssFontFamily::Named("A B".into()),
+ super::CssFontFamily::Named("Another Face".into()),
+ super::CssFontFamily::Generic(
+ style::values::computed::font::GenericFontFamily::Serif
+ ),
+ ]
+ );
assert_eq!(font.size, "10.5px");
assert_eq!(font.style, "italic");
for invalid in [
diff --git a/moli-css-parse/src/lib.rs b/moli-css-parse/src/lib.rs
index 627f64258..d1bf9546e 100644
--- a/moli-css-parse/src/lib.rs
+++ b/moli-css-parse/src/lib.rs
@@ -21,9 +21,10 @@ pub use color::{
};
pub use declaration::{CssDeclaration, DeclarationParseOptions, parse_declaration_list};
pub use font_face::{
- CssFontFace, CssFontShorthand, CssFontSource, font_load_query_contains_css_wide_keyword,
- font_load_query_family, font_load_query_is_valid, legacy_variations_font_format,
- normalize_font_face_src, parse_font_face_sources, parse_font_faces, parse_font_shorthand,
+ CssFontFace, CssFontFamily, CssFontShorthand, CssFontSource,
+ font_load_query_contains_css_wide_keyword, font_load_query_family, font_load_query_is_valid,
+ legacy_variations_font_format, normalize_font_face_src, parse_font_face_sources,
+ parse_font_faces, parse_font_shorthand,
};
pub use font_palette::{
CssFontPaletteValuesProperty, parse_font_palette_values_property_with_stylo,
diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/query.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/query.rs
index dbe6a2794..0616d0b79 100644
--- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/query.rs
+++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/query.rs
@@ -51,6 +51,9 @@ pub(super) fn font_face_set_matching_faces_array<'s>(
let text = text.chars().collect::<Vec<_>>();
let mut matching = Vec::new();
for family in query.families {
+ let moli_css_parse::CssFontFamily::Named(family) = family else {
+ continue;
+ };
let family_faces = candidates
.iter()
.filter(|face| family.eq_ignore_ascii_case(&face.family))
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/matching.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/matching.rs
index d9bef7225..0cc62694b 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/matching.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/matching.rs
@@ -228,3 +228,34 @@ fn font_set_queries_match_unicode_scalars_and_preserve_family_list_order() {
"[true,false,2,true,true]"
);
}
+
+#[test]
+fn font_query_generic_families_do_not_match_named_font_faces() {
+ for generic in ["serif", "sans-serif", "monospace", "system-ui"] {
+ let mut vm = new_storage_test_vm("https://font-matching.test/");
+ vm.eval(&format!(r#"
+ globalThis.face=new FontFace('{generic}','url(data:font/ttf;base64,AA==)');
+ face.loaded.catch(()=>{{}});document.fonts.add(face);
+ globalThis.results=[];
+ document.fonts.load('16px {generic}','A').then(faces=>results.push(faces.length),error=>results.push(error.name));
+ "#)).unwrap();
+ assert_eq!(
+ vm.eval(&format!("document.fonts.check('16px {generic}','A')"))
+ .unwrap(),
+ "true",
+ "{generic}"
+ );
+ assert_eq!(
+ vm.eval("JSON.stringify(results)").unwrap(),
+ "[0]",
+ "{generic}"
+ );
+ assert_eq!(vm.eval("face.status").unwrap(), "unloaded", "{generic}");
+ vm.eval(&format!(r#"document.fonts.load('16px "{generic}"','A').then(faces=>results.push(faces.length),error=>results.push(error.name))"#)).unwrap();
+ assert_eq!(
+ vm.eval("JSON.stringify(results)").unwrap(),
+ r#"[0,"NetworkError"]"#
+ );
+ assert_eq!(vm.eval("face.status").unwrap(), "error");
+ }
+}