Unverified Commit de4f197e authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

Turbopack `next/font`: Order weight variants numerically (#72043)

The Google fonts API requires this. Previously, `get_stylesheet_url`
trusted that the weight axis inputs were sorted correctly, which they
may not be.

This PR creates and uses two new enums:

- `FontAxesWeights`, to capture weights as ints, and moves the
responsibility of sorting weights into `get_stylesheet_url` itself.
- `VariantValue` to wrap each value for variants, as these can be either
a string (an expression representing a variable font weight range) or a
`u16`, representing a fixed font weight. This allows us to defer
stringifying these until format time while still comparing them for
ordering.

Test Plan: Added a unit test for `get_stylesheet_url`.


Closes PACK-3359
parent c32e2802
use std::cmp::Ordering;
use anyhow::{anyhow, bail, Context, Result};
use turbo_tasks::{fxindexset, FxIndexSet, RcStr};
use turbo_tasks::{FxIndexSet, RcStr};
use super::options::{FontData, FontWeights};
#[derive(Debug, PartialEq)]
#[derive(Debug, Default, PartialEq)]
pub(super) struct FontAxes {
pub(super) wght: FxIndexSet<RcStr>,
pub(super) wght: FontAxesWeights,
pub(super) ital: FxIndexSet<FontStyle>,
pub(super) variable_axes: Option<Vec<(RcStr, RcStr)>>,
}
#[derive(Debug, PartialEq, Eq, Hash)]
pub(super) enum FontAxesWeights {
Variable(Option<RcStr>),
Fixed(Vec<u16>),
}
impl Default for FontAxesWeights {
fn default() -> Self {
FontAxesWeights::Fixed(vec![])
}
}
#[derive(Debug, Default, PartialEq, Eq, Hash)]
pub(super) enum FontStyle {
Italic,
#[default]
Normal,
}
......@@ -83,28 +96,53 @@ pub(super) fn get_font_axes(
}
}
let wght = match weight_axis {
Some(weight_axis) => {
fxindexset! {weight_axis}
}
None => fxindexset! {},
};
Ok(FontAxes {
wght,
wght: FontAxesWeights::Variable(weight_axis),
ital,
variable_axes: Some(variable_axes),
})
}
FontWeights::Fixed(weights) => Ok(FontAxes {
wght: FxIndexSet::from_iter(weights.iter().map(|w| w.to_string().into())),
wght: FontAxesWeights::Fixed(weights.to_owned()),
ital,
variable_axes: None,
}),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum VariantValue {
String(RcStr),
U16(u16),
}
impl PartialOrd for VariantValue {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for VariantValue {
fn cmp(&self, other: &Self) -> Ordering {
match (self, other) {
(VariantValue::String(a), VariantValue::String(b)) => a.cmp(b),
(VariantValue::U16(a), VariantValue::U16(b)) => a.cmp(b),
(VariantValue::String(_), VariantValue::U16(_)) => Ordering::Less,
(VariantValue::U16(_), VariantValue::String(_)) => Ordering::Greater,
}
}
}
impl From<VariantValue> for RcStr {
fn from(val: VariantValue) -> Self {
match val {
VariantValue::String(s) => s,
VariantValue::U16(u) => u.to_string().into(),
}
}
}
// Derived from https://github.com/vercel/next.js/blob/9e098da0915a2a4581bebe2270953a1216be1ba4/packages/font/src/google/utils.ts#L128
pub(super) fn get_stylesheet_url(
root_url: &str,
......@@ -114,48 +152,66 @@ pub(super) fn get_stylesheet_url(
) -> Result<String> {
// Variants are all combinations of weight and style, each variant will result
// in a separate font file
let mut variants: Vec<Vec<(&str, &str)>> = vec![];
if axes.wght.is_empty() {
let mut variants: Vec<Vec<(&str, VariantValue)>> = vec![];
let weights = match &axes.wght {
FontAxesWeights::Variable(Some(wght)) => {
vec![VariantValue::String(wght.to_owned())]
}
FontAxesWeights::Variable(None) => {
vec![]
}
FontAxesWeights::Fixed(wghts) => {
let mut wghts = wghts.clone();
wghts.sort();
wghts.iter().map(|w| VariantValue::U16(*w)).collect()
}
};
if weights.is_empty() {
let mut variant = vec![];
if let Some(variable_axes) = &axes.variable_axes {
if !variable_axes.is_empty() {
for (key, val) in variable_axes {
variant.push((key.as_str(), &val[..]));
variant.push((key.as_str(), VariantValue::String(val.clone())));
}
variants.push(variant);
}
}
} else {
for wght in &axes.wght {
for wght in &weights {
if axes.ital.is_empty() {
let mut variant = vec![];
variant.push(("wght", &wght[..]));
variant.push(("wght", wght.clone()));
if let Some(variable_axes) = &axes.variable_axes {
for (key, val) in variable_axes {
variant.push((key, &val[..]));
variant.push((key, VariantValue::String(val.clone())));
}
}
variants.push(variant);
} else {
for ital in &axes.ital {
let mut variant = vec![];
let mut variant: Vec<(&str, VariantValue)> = vec![];
// If Normal is the only requested variant, it's safe to omit the ital axis
// entirely. Otherwise, include all variants.
if matches!(ital, FontStyle::Italic) || axes.ital.len() > 1 {
variant.push((
"ital",
match ital {
FontStyle::Normal => "0",
FontStyle::Italic => "1",
},
VariantValue::String(
match ital {
FontStyle::Normal => "0",
FontStyle::Italic => "1",
}
.into(),
),
));
}
variant.push(("wght", &wght[..]));
variant.push(("wght", wght.clone()));
if let Some(variable_axes) = &axes.variable_axes {
for (key, val) in variable_axes {
variant.push((key, &val[..]));
variant.push((key, VariantValue::String(val.clone())));
}
}
variants.push(variant);
......@@ -205,17 +261,25 @@ pub(super) fn get_stylesheet_url(
.map(|variant| {
variant
.iter()
.map(|pair| pair.1)
.collect::<Vec<&str>>()
.join(",")
.map(|pair| pair.1.clone())
.collect::<Vec<VariantValue>>()
})
.collect::<Vec<String>>();
.collect::<Vec<Vec<VariantValue>>>();
variant_values.sort();
// An encoding of the series of sorted variant values, with variants delimited
// by `;` and the values within a variant delimited by `,` e.g.
// `"0,10..100,500;1,10.100;500"`
let variant_values_str = variant_values.join(";");
let variant_values_str = variant_values
.iter()
.map(|v| {
v.iter()
.map(|vv| std::convert::Into::<RcStr>::into(vv.clone()))
.collect::<Vec<RcStr>>()
.join(",")
})
.collect::<Vec<String>>()
.join(";");
Ok(format!(
"{}?family={}:{}@{}&display={}",
......@@ -238,7 +302,7 @@ mod tests {
use super::get_font_axes;
use crate::next_font::google::{
options::{FontData, FontWeights},
util::{get_stylesheet_url, FontAxes, FontStyle},
util::{get_stylesheet_url, FontAxes, FontAxesWeights, FontStyle},
GOOGLE_FONTS_STYLESHEET_URL,
};
......@@ -325,7 +389,7 @@ mod tests {
&Some(vec!["slnt".into()]),
)?,
FontAxes {
wght: fxindexset! {"100..900".into()},
wght: FontAxesWeights::Variable(Some("100..900".into())),
ital: fxindexset! {},
variable_axes: Some(vec![("slnt".into(), "-10..0".into())])
}
......@@ -366,9 +430,9 @@ mod tests {
&Some(vec!["slnt".into()]),
)?,
FontAxes {
wght: fxindexset! {},
ital: fxindexset! {},
variable_axes: Some(vec![("slnt".into(), "-10..0".into())])
variable_axes: Some(vec![("slnt".into(), "-10..0".into())]),
wght: FontAxesWeights::Variable(None),
..Default::default()
}
);
Ok(())
......@@ -398,9 +462,8 @@ mod tests {
assert_eq!(
get_font_axes(&data, "Hind", &FontWeights::Fixed(vec![500]), &[], &None)?,
FontAxes {
wght: fxindexset! {"500".into()},
ital: fxindexset! {},
variable_axes: None
wght: FontAxesWeights::Fixed(vec![500]),
..Default::default()
}
);
Ok(())
......@@ -413,7 +476,7 @@ mod tests {
GOOGLE_FONTS_STYLESHEET_URL,
"Roboto Mono",
&FontAxes {
wght: fxindexset! {"500".into()},
wght: FontAxesWeights::Fixed(vec![500]),
ital: fxindexset! {FontStyle::Normal},
variable_axes: None
},
......@@ -432,7 +495,7 @@ mod tests {
GOOGLE_FONTS_STYLESHEET_URL,
"Roboto Serif",
&FontAxes {
wght: fxindexset! {"500".into()},
wght: FontAxesWeights::Fixed(vec![500]),
ital: fxindexset! {FontStyle::Normal},
variable_axes: Some(vec![
("GRAD".into(), "-50..100".into()),
......@@ -448,6 +511,25 @@ mod tests {
Ok(())
}
#[test]
fn test_stylesheet_url_sorts_weights_numerically() -> Result<()> {
assert_eq!(
get_stylesheet_url(
GOOGLE_FONTS_STYLESHEET_URL,
"Roboto Serif",
&FontAxes {
wght: FontAxesWeights::Fixed(vec![1000, 500, 200]),
ital: fxindexset! {FontStyle::Normal},
variable_axes: None
},
"optional"
)?,
"https://fonts.googleapis.com/css2?family=Roboto+Serif:wght@200;500;1000&display=optional"
);
Ok(())
}
#[test]
fn test_stylesheet_url_encodes_all_weight_ital_combinations() -> Result<()> {
assert_eq!(
......@@ -455,7 +537,7 @@ mod tests {
GOOGLE_FONTS_STYLESHEET_URL,
"Roboto Serif",
&FontAxes {
wght: fxindexset! {"500".into(), "300".into()},
wght: FontAxesWeights::Fixed(vec![500, 300]),
ital: fxindexset! {FontStyle::Normal, FontStyle::Italic},
variable_axes: Some(vec![
("GRAD".into(), "-50..100".into()),
......@@ -479,12 +561,11 @@ mod tests {
GOOGLE_FONTS_STYLESHEET_URL,
"Nabla",
&FontAxes {
wght: fxindexset! {},
ital: fxindexset! {},
variable_axes: Some(vec![
("EDPT".into(), "0..200".into()),
("EHLT".into(), "0..24".into()),
])
]),
..Default::default()
},
"optional"
)?,
......@@ -500,11 +581,7 @@ mod tests {
get_stylesheet_url(
GOOGLE_FONTS_STYLESHEET_URL,
"Nabla",
&FontAxes {
wght: fxindexset! {},
ital: fxindexset! {},
variable_axes: None,
},
&Default::default(),
"swap"
)?,
"https://fonts.googleapis.com/css2?family=Nabla&display=swap"
......@@ -520,9 +597,8 @@ mod tests {
GOOGLE_FONTS_STYLESHEET_URL,
"Nabla",
&FontAxes {
wght: fxindexset! {},
ital: fxindexset! {},
variable_axes: Some(vec![]),
..Default::default()
},
"swap"
)?,
......@@ -539,9 +615,8 @@ mod tests {
GOOGLE_FONTS_STYLESHEET_URL,
"Hind",
&FontAxes {
wght: fxindexset! {"500".into()},
ital: fxindexset! {},
variable_axes: None
wght: FontAxesWeights::Fixed(vec![500]),
..Default::default()
},
"optional"
)?,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment