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

next/font: Generate fallback fonts (vercel/turbo#4086)

This:
* Generates and uses definitions for fallback system fonts to use in
place of user fonts, or as they are loading.
* Reads the font metrics file from the `next` package directly relative
to the user's app.
* Fixes a bug where `adjust_font_fallback` defaulted to `false` instead
of `true`.
* Begins to refactor next/font code to be more modular in anticipation
of `next/font/local` support.
* Changes `handle_resolve_error` to take an origin `FileSystemPathVc`
instead of a `ResolveOriginVc` as this is all it used, and a resolve
origin isn't always available.
parent 8c9ae939
use std::collections::HashMap;
use anyhow::{Context, Result};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use turbo_tasks::{
primitives::{StringVc, StringsVc, U32Vc},
trace::TraceRawVcs,
};
use turbo_tasks_fs::FileSystemPathVc;
use turbopack_core::issue::IssueSeverity;
use super::{get_scoped_font_family, options::NextFontGoogleOptionsVc, FontFamilyType};
use crate::{next_font_google::issue::NextFontIssue, util::load_next_json};
struct DefaultFallbackFont {
name: String,
az_avg_width: f64,
units_per_em: u32,
}
// From https://github.com/vercel/next.js/blob/a3893bf69c83fb08e88c87bf8a21d987a0448c8e/packages/font/src/utils.ts#L4
static DEFAULT_SANS_SERIF_FONT: Lazy<DefaultFallbackFont> = Lazy::new(|| DefaultFallbackFont {
name: "Arial".to_owned(),
az_avg_width: 934.5116279069767,
units_per_em: 2048,
});
static DEFAULT_SERIF_FONT: Lazy<DefaultFallbackFont> = Lazy::new(|| DefaultFallbackFont {
name: "Times New Roman".to_owned(),
az_avg_width: 854.3953488372093,
units_per_em: 2048,
});
#[turbo_tasks::value(transparent)]
pub(crate) struct AutomaticFontFallback {
pub scoped_font_family: StringVc,
pub local_font_family: StringVc,
pub adjustment: Option<FontAdjustment>,
}
#[turbo_tasks::value(transparent)]
pub(crate) enum FontFallback {
Automatic(AutomaticFontFallbackVc),
/// There was an issue loading the font metrics data. Since resolving the
/// font css cannot fail, proper Errors cannot be returned. Emit an issue,
/// return this and omit fallback information instead.
Error,
Manual(StringsVc),
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct FontMetricsMapEntry {
category: String,
ascent: i32,
descent: i32,
line_gap: u32,
units_per_em: u32,
az_avg_width: f64,
}
#[derive(Deserialize)]
pub(crate) struct FontMetricsMap(pub HashMap<String, FontMetricsMapEntry>);
#[derive(Debug, PartialEq, Serialize, Deserialize, TraceRawVcs)]
pub(crate) struct FontAdjustment {
pub ascent: f64,
pub descent: f64,
pub line_gap: f64,
pub size_adjust: f64,
}
// Necessary since floating points in this struct don't implement Eq, but it's
// required for turbo tasks values.
impl Eq for FontAdjustment {}
#[derive(Debug, PartialEq, Serialize, Deserialize, TraceRawVcs)]
pub(crate) struct Font {
pub font_family: String,
pub adjustment: Option<FontAdjustment>,
}
#[turbo_tasks::function]
pub(crate) async fn get_font_fallback(
context: FileSystemPathVc,
options_vc: NextFontGoogleOptionsVc,
request_hash: U32Vc,
) -> Result<FontFallbackVc> {
let options = options_vc.await?;
Ok(match &options.fallback {
Some(fallback) => FontFallback::Manual(StringsVc::cell(fallback.clone())).cell(),
None => {
let metrics_json =
load_next_json(context, "/dist/server/google-font-metrics.json").await;
match metrics_json {
Ok(metrics_json) => {
let fallback = lookup_fallback(
&options.font_family,
metrics_json,
options.adjust_font_fallback,
);
match fallback {
Ok(fallback) => FontFallback::Automatic(
AutomaticFontFallback {
scoped_font_family: get_scoped_font_family(
FontFamilyType::Fallback.cell(),
options_vc,
request_hash,
),
local_font_family: StringVc::cell(fallback.font_family),
adjustment: fallback.adjustment,
}
.cell(),
)
.cell(),
Err(_) => {
NextFontIssue {
path: context,
title: StringVc::cell(format!(
"Failed to find font override values for font `{}`",
&options.font_family,
)),
description: StringVc::cell(
"Skipping generating a fallback font.".to_owned(),
),
severity: IssueSeverity::Warning.cell(),
}
.cell()
.as_issue()
.emit();
FontFallback::Error.cell()
}
}
}
Err(_) => FontFallback::Error.cell(),
}
}
})
}
fn lookup_fallback(
font_family: &str,
font_metrics_map: FontMetricsMap,
adjust: bool,
) -> Result<Font> {
let metrics = font_metrics_map
.0
.get(font_family)
.context("Font not found in metrics")?;
let fallback = if metrics.category == "serif" {
&DEFAULT_SERIF_FONT
} else {
&DEFAULT_SANS_SERIF_FONT
};
let metrics = if adjust {
// Derived from
// https://github.com/vercel/next.js/blob/a3893bf69c83fb08e88c87bf8a21d987a0448c8e/packages/next/src/server/font-utils.ts#L121
let main_font_avg_width = metrics.az_avg_width / metrics.units_per_em as f64;
let fallback_font_avg_width = fallback.az_avg_width / fallback.units_per_em as f64;
let size_adjust = main_font_avg_width / fallback_font_avg_width;
let ascent = metrics.ascent as f64 / (metrics.units_per_em as f64 * size_adjust);
let descent = metrics.descent as f64 / (metrics.units_per_em as f64 * size_adjust);
let line_gap = metrics.line_gap as f64 / (metrics.units_per_em as f64 * size_adjust);
Some(FontAdjustment {
ascent,
descent,
line_gap,
size_adjust,
})
} else {
None
};
Ok(Font {
font_family: fallback.name.clone(),
adjustment: metrics,
})
}
#[cfg(test)]
mod tests {
use anyhow::Result;
use turbo_tasks_fs::json::parse_json_with_source_context;
use super::{FontAdjustment, FontMetricsMap};
use crate::next_font_google::font_fallback::{lookup_fallback, Font};
#[test]
fn test_fallback_from_metrics_sans_serif() -> Result<()> {
let font_metrics: FontMetricsMap = parse_json_with_source_context(
r#"
{
"Inter": {
"category": "sans-serif",
"ascent": 2728,
"descent": -680,
"lineGap": 0,
"xAvgCharWidth": 1838,
"unitsPerEm": 2816,
"azAvgWidth": 1383.0697674418604
}
}
"#,
)?;
assert_eq!(
lookup_fallback("Inter", font_metrics, true)?,
Font {
font_family: "Arial".to_owned(),
adjustment: Some(FontAdjustment {
ascent: 0.9000259575934895,
descent: -0.2243466463209578,
line_gap: 0.0,
size_adjust: 1.0763578448229054
})
}
);
Ok(())
}
#[test]
fn test_fallback_from_metrics_serif() -> Result<()> {
let font_metrics: FontMetricsMap = parse_json_with_source_context(
r#"
{
"Roboto Slab": {
"category": "serif",
"ascent": 2146,
"descent": -555,
"lineGap": 0,
"xAvgCharWidth": 1239,
"unitsPerEm": 2048,
"azAvgWidth": 1005.6279069767442
}
}
"#,
)?;
assert_eq!(
lookup_fallback("Roboto Slab", font_metrics, true)?,
Font {
font_family: "Times New Roman".to_owned(),
adjustment: Some(FontAdjustment {
ascent: 0.8902691493151913,
descent: -0.23024202137461844,
line_gap: 0.0,
size_adjust: 1.1770053621492147
})
}
);
Ok(())
}
}
use turbo_tasks::primitives::StringVc;
use turbo_tasks_fs::FileSystemPathVc;
use turbopack_core::issue::{Issue, IssueSeverityVc, IssueVc};
#[turbo_tasks::value(shared)]
pub(crate) struct NextFontIssue {
pub(crate) path: FileSystemPathVc,
pub(crate) title: StringVc,
pub(crate) description: StringVc,
pub(crate) severity: IssueSeverityVc,
}
#[turbo_tasks::value_impl]
impl Issue for NextFontIssue {
#[turbo_tasks::function]
fn category(&self) -> StringVc {
StringVc::cell("other".to_string())
}
#[turbo_tasks::function]
fn severity(&self) -> IssueSeverityVc {
self.severity
}
#[turbo_tasks::function]
fn context(&self) -> FileSystemPathVc {
self.path
}
#[turbo_tasks::function]
fn title(&self) -> StringVc {
self.title
}
#[turbo_tasks::function]
fn description(&self) -> StringVc {
self.description
}
}
......@@ -2,7 +2,10 @@ use anyhow::{bail, Context, Result};
use indexmap::IndexMap;
use indoc::formatdoc;
use once_cell::sync::Lazy;
use turbo_tasks::primitives::{OptionStringVc, OptionU16Vc, StringVc, U32Vc};
use turbo_tasks::{
primitives::{OptionStringVc, OptionU16Vc, StringVc, U32Vc},
Value,
};
use turbo_tasks_fs::{json::parse_json_with_source_context, FileContent, FileSystemPathVc};
use turbo_tasks_hash::hash_xxh3_hash64;
use turbopack_core::{
......@@ -19,7 +22,12 @@ use turbopack_core::{
};
use turbopack_node::execution_context::ExecutionContextVc;
use self::options::FontWeights;
use self::{
font_fallback::{get_font_fallback, FontFallback, FontFallbackVc},
options::{FontWeights, NextFontGoogleOptionsVc},
stylesheet::build_stylesheet,
util::{get_scoped_font_family, FontFamilyType},
};
use crate::{
embed_js::next_js_file_path,
next_font_google::{
......@@ -28,9 +36,12 @@ use crate::{
},
};
pub(crate) mod font_fallback;
pub(crate) mod issue;
pub(crate) mod options;
pub(crate) mod request;
mod util;
pub(crate) mod stylesheet;
pub(crate) mod util;
pub const GOOGLE_FONTS_STYLESHEET_URL: &str = "https://fonts.googleapis.com/css2";
static FONT_DATA: Lazy<FontData> = Lazy::new(|| {
......@@ -40,7 +51,7 @@ static FONT_DATA: Lazy<FontData> = Lazy::new(|| {
type FontData = IndexMap<String, FontDataEntry>;
#[turbo_tasks::value(shared)]
pub struct NextFontGoogleReplacer {
pub(crate) struct NextFontGoogleReplacer {
project_path: FileSystemPathVc,
}
......@@ -72,8 +83,9 @@ impl ImportMappingReplacement for NextFontGoogleReplacer {
let query = &*query_vc.await?;
let options = font_options_from_query_map(*query_vc);
let properties =
get_font_css_properties(get_scoped_font_family(*query_vc), options).await?;
let request_hash = get_request_hash(*query_vc);
let fallback = get_font_fallback(self.project_path, options, request_hash);
let properties = get_font_css_properties(options, fallback, request_hash).await?;
let js_asset = VirtualAssetVc::new(
next_js_file_path("internal/font/google")
.join(&format!("{}.js", get_request_id(*query_vc).await?)),
......@@ -157,7 +169,9 @@ impl ImportMappingReplacement for NextFontGoogleCssModuleReplacer {
let options = font_options_from_query_map(*query_vc);
let stylesheet_url = get_stylesheet_url_from_options(options);
let scoped_font_family = get_scoped_font_family(*query_vc);
let request_hash = get_request_hash(*query_vc);
let scoped_font_family =
get_scoped_font_family(FontFamilyType::WebFont.cell(), options, request_hash);
let css_virtual_path = next_js_file_path("internal/font/google")
.join(&format!("/{}.module.css", get_request_id(*query_vc).await?));
......@@ -212,42 +226,16 @@ impl ImportMappingReplacement for NextFontGoogleCssModuleReplacer {
None => None,
};
let properties = get_font_css_properties(scoped_font_family, options).await?;
let font_family = properties.font_family.await?;
let font_fallback = get_font_fallback(self.project_path, options, request_hash);
let css_asset = VirtualAssetVc::new(
css_virtual_path,
FileContent::Content(
formatdoc!(
r#"
{}
.className {{
font-family: {};
{}{}
}}
{}
"#,
stylesheet.unwrap_or_else(|| "".to_owned()),
font_family,
properties
.weight
.await?
.map(|w| format!("font-weight: {};\n", w))
.unwrap_or_else(|| "".to_owned()),
properties
.style
.await?
.as_ref()
.map(|s| format!("font-style: {};\n", s))
.unwrap_or_else(|| "".to_owned()),
properties
.variable
.await?
.as_ref()
.map(|v| { format!(".variable {{ {}: {}; }} ", v, *font_family) })
.unwrap_or_else(|| "".to_owned())
build_stylesheet(
OptionStringVc::cell(stylesheet),
get_font_css_properties(options, font_fallback, request_hash),
font_fallback,
)
.await?
.into(),
)
.into(),
......@@ -271,22 +259,6 @@ async fn update_stylesheet(
)))
}
#[turbo_tasks::function]
async fn get_scoped_font_family(query_vc: QueryMapVc) -> Result<StringVc> {
let options = font_options_from_query_map(query_vc).await?;
let hash = {
let mut hash = format!("{:x?}", *get_request_hash(query_vc).await?);
hash.truncate(6);
hash
};
Ok(StringVc::cell(format!(
"__{}_{}",
options.font_family.replace(' ', "_"),
hash
)))
}
#[turbo_tasks::function]
async fn get_request_id(query_vc: QueryMapVc) -> Result<StringVc> {
let options = font_options_from_query_map(query_vc).await?;
......@@ -345,10 +317,7 @@ async fn get_stylesheet_url_from_options(options: NextFontGoogleOptionsVc) -> Re
}
#[turbo_tasks::value(transparent)]
struct NextFontGoogleOptions(self::options::NextFontGoogleOptions);
#[turbo_tasks::value(transparent)]
struct FontCssProperties {
pub(crate) struct FontCssProperties {
font_family: StringVc,
weight: OptionU16Vc,
style: OptionStringVc,
......@@ -357,13 +326,27 @@ struct FontCssProperties {
#[turbo_tasks::function]
async fn get_font_css_properties(
scoped_font_family: StringVc,
options: NextFontGoogleOptionsVc,
options_vc: NextFontGoogleOptionsVc,
font_fallback: FontFallbackVc,
request_hash: U32Vc,
) -> Result<FontCssPropertiesVc> {
let options = &*options.await?;
let scoped_font_family = &*scoped_font_family.await?;
let options = &*options_vc.await?;
let scoped_font_family =
&*get_scoped_font_family(FontFamilyType::WebFont.cell(), options_vc, request_hash).await?;
let mut font_families = vec![scoped_font_family.clone()];
let font_fallback = &*font_fallback.await?;
match font_fallback {
FontFallback::Manual(fonts) => {
font_families.extend_from_slice(&fonts.await?);
}
FontFallback::Automatic(fallback) => {
let fallback = &*fallback.await?;
font_families.push((*fallback.scoped_font_family.await?).clone());
}
FontFallback::Error => {}
}
if let Some(fallback) = &options.fallback {
font_families.extend_from_slice(fallback);
}
......@@ -403,7 +386,7 @@ async fn font_options_from_query_map(query: QueryMapVc) -> Result<NextFontGoogle
};
self::options::options_from_request(&parse_json_with_source_context(json)?, &FONT_DATA)
.map(NextFontGoogleOptionsVc::cell)
.map(|o| NextFontGoogleOptionsVc::new(Value::new(o)))
}
#[cfg(feature = "__internal_nextjs_integration_test")]
......
use anyhow::{anyhow, Context, Result};
use indexmap::{indexset, IndexMap, IndexSet};
use serde::{Deserialize, Serialize};
use turbo_tasks::trace::TraceRawVcs;
use turbo_tasks::{trace::TraceRawVcs, Value};
use super::request::{NextFontRequest, OneOrManyStrings};
const ALLOWED_DISPLAY_VALUES: &[&str] = &["auto", "block", "swap", "fallback", "optional"];
pub type FontData = IndexMap<String, FontDataEntry>;
pub(crate) type FontData = IndexMap<String, FontDataEntry>;
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs)]
pub struct NextFontGoogleOptions {
#[turbo_tasks::value(serialization = "auto_for_input")]
#[derive(Clone, Debug, PartialOrd, Ord, Hash)]
pub(crate) struct NextFontGoogleOptions {
/// Name of the requested font from Google. Contains literal spaces.
pub font_family: String,
pub weights: FontWeights,
pub styles: IndexSet<String>,
pub styles: Vec<String>,
pub display: String,
pub preload: bool,
pub selected_variable_axes: Option<Vec<String>>,
......@@ -24,14 +25,24 @@ pub struct NextFontGoogleOptions {
pub subsets: Option<Vec<String>>,
}
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs)]
pub enum FontWeights {
#[turbo_tasks::value_impl]
impl NextFontGoogleOptionsVc {
#[turbo_tasks::function]
pub fn new(options: Value<NextFontGoogleOptions>) -> NextFontGoogleOptionsVc {
Self::cell(options.into_value())
}
}
#[derive(
Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, TraceRawVcs,
)]
pub(crate) enum FontWeights {
Variable,
Fixed(IndexSet<u16>),
Fixed(Vec<u16>),
}
#[derive(Debug, Deserialize)]
pub struct FontDataEntry {
pub(crate) struct FontDataEntry {
pub weights: Vec<String>,
pub styles: Vec<String>,
pub axes: Option<Vec<Axis>>,
......@@ -39,17 +50,16 @@ pub struct FontDataEntry {
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Axis {
pub(crate) struct Axis {
pub tag: String,
pub min: f64,
pub max: f64,
pub default_value: f64,
}
// Transforms the request fields to a struct suitable for making requests to
// Google Fonts. Similar to next/font/google's validateData:
// https://github.com/vercel/next.js/blob/28454c6ddbc310419467e5415aee26e48d079b46/packages/font/src/google/utils.ts#L22
pub fn options_from_request(
pub(crate) fn options_from_request(
request: &NextFontRequest,
data: &IndexMap<String, FontDataEntry>,
) -> Result<NextFontGoogleOptions> {
......@@ -77,11 +87,11 @@ pub fn options_from_request(
let mut styles = argument
.and_then(|argument| {
argument.style.as_ref().map(|w| match w {
OneOrManyStrings::One(one) => indexset! {one.to_owned()},
OneOrManyStrings::Many(many) => IndexSet::from_iter(many.iter().cloned()),
OneOrManyStrings::One(one) => vec![one.to_owned()],
OneOrManyStrings::Many(many) => many.clone(),
})
})
.unwrap_or_else(IndexSet::new);
.unwrap_or_default();
let weights = if requested_weights.is_empty() {
if !font_data.weights.contains(&"variable".to_owned()) {
......@@ -115,9 +125,9 @@ pub fn options_from_request(
}
}
let mut weights = indexset! {};
let mut weights = vec![];
for weight in requested_weights {
weights.insert(weight.parse()?);
weights.push(weight.parse()?);
}
FontWeights::Fixed(weights)
......@@ -125,9 +135,9 @@ pub fn options_from_request(
if styles.is_empty() {
if font_data.styles.len() == 1 {
styles.insert(font_data.styles[0].clone());
styles.push(font_data.styles[0].clone());
} else {
styles.insert("normal".to_owned());
styles.push("normal".to_owned());
}
}
......@@ -169,7 +179,7 @@ pub fn options_from_request(
preload: argument.map(|a| a.preload).unwrap_or(true),
selected_variable_axes: argument.and_then(|a| a.axes.clone()),
fallback: argument.and_then(|a| a.fallback.clone()),
adjust_font_fallback: argument.map(|a| a.adjust_font_fallback).unwrap_or(false),
adjust_font_fallback: argument.map(|a| a.adjust_font_fallback).unwrap_or(true),
variable: argument.and_then(|a| a.variable.clone()),
subsets: argument.and_then(|a| a.subsets.clone()),
})
......@@ -178,7 +188,7 @@ pub fn options_from_request(
#[cfg(test)]
mod tests {
use anyhow::Result;
use indexmap::{indexset, IndexMap};
use indexmap::IndexMap;
use turbo_tasks_fs::json::parse_json_with_source_context;
use super::{options_from_request, FontDataEntry, NextFontGoogleOptions};
......@@ -246,12 +256,12 @@ mod tests {
NextFontGoogleOptions {
font_family: "ABeeZee".to_owned(),
weights: FontWeights::Variable,
styles: indexset! {"normal".to_owned()},
styles: vec!["normal".to_owned()],
display: "swap".to_owned(),
preload: true,
selected_variable_axes: None,
fallback: None,
adjust_font_fallback: false,
adjust_font_fallback: true,
variable: None,
subsets: None,
},
......@@ -400,7 +410,7 @@ mod tests {
)?;
let options = options_from_request(&request, &data)?;
assert_eq!(options.styles, indexset! {"italic".to_owned()});
assert_eq!(options.styles, vec!["italic".to_owned()]);
Ok(())
}
......@@ -432,7 +442,7 @@ mod tests {
)?;
let options = options_from_request(&request, &data)?;
assert_eq!(options.styles, indexset! {"normal".to_owned()});
assert_eq!(options.styles, vec!["normal".to_owned()]);
Ok(())
}
......
......@@ -22,7 +22,7 @@ pub struct NextFontRequestArguments {
pub preload: bool,
pub axes: Option<Vec<String>>,
pub fallback: Option<Vec<String>>,
#[serde(default)]
#[serde(default = "default_adjust_font_fallback")]
pub adjust_font_fallback: bool,
pub variable: Option<String>,
}
......@@ -33,3 +33,7 @@ pub enum OneOrManyStrings {
One(String),
Many(Vec<String>),
}
fn default_adjust_font_fallback() -> bool {
true
}
use anyhow::Result;
use indoc::formatdoc;
use turbo_tasks::primitives::{OptionStringVc, StringVc};
use super::{
font_fallback::{FontFallback, FontFallbackVc},
FontCssProperties, FontCssPropertiesVc,
};
#[turbo_tasks::function]
pub(crate) async fn build_stylesheet(
base_stylesheet: OptionStringVc,
font_css_properties: FontCssPropertiesVc,
font_fallback: FontFallbackVc,
) -> Result<StringVc> {
let base_stylesheet = &*base_stylesheet.await?;
let mut stylesheet = base_stylesheet
.as_ref()
.map_or_else(|| "".to_owned(), |s| s.to_owned());
if let Some(definition) = build_fallback_definition(&*font_fallback.await?).await? {
stylesheet.push_str(&definition);
}
stylesheet.push_str(&build_font_class_rules(&*font_css_properties.await?).await?);
Ok(StringVc::cell(stylesheet))
}
async fn build_fallback_definition(fallback: &FontFallback) -> Result<Option<String>> {
match fallback {
FontFallback::Error => Ok(None),
FontFallback::Manual(_) => Ok(None),
FontFallback::Automatic(fallback) => {
let fallback = fallback.await?;
let override_properties = match &fallback.adjustment {
None => "".to_owned(),
Some(adjustment) => formatdoc!(
r#"
ascent-override: {}%;
descent-override: {}%;
line-gap-override: {}%;
size-adjust: {}%;
"#,
format_fixed_percentage(adjustment.ascent),
format_fixed_percentage(adjustment.descent.abs()),
format_fixed_percentage(adjustment.line_gap),
format_fixed_percentage(adjustment.size_adjust)
),
};
Ok(Some(formatdoc!(
r#"
@font-face {{
font-family: '{}';
src: local("{}");
{}
}}
"#,
fallback.scoped_font_family.await?,
fallback.local_font_family.await?,
override_properties
)))
}
}
}
async fn build_font_class_rules(properties: &FontCssProperties) -> Result<String> {
let font_family = &*properties.font_family.await?;
let mut result = formatdoc!(
r#"
.className {{
font-family: {};
{}{}
}}
"#,
font_family,
properties
.weight
.await?
.map(|w| format!("font-weight: {};\n", w))
.unwrap_or_else(|| "".to_owned()),
properties
.style
.await?
.as_ref()
.map(|s| format!("font-style: {};\n", s))
.unwrap_or_else(|| "".to_owned()),
);
if let Some(variable) = &*properties.variable.await? {
result.push_str(&formatdoc!(
r#"
.variable {{
{}: {};
}}
"#,
variable,
font_family,
))
//
}
Ok(result)
}
fn format_fixed_percentage(value: f64) -> String {
format!("{:.2}", value * 100.0)
}
......@@ -2,8 +2,9 @@ use std::cmp::Ordering;
use anyhow::{anyhow, bail, Context, Result};
use indexmap::{indexset, IndexSet};
use turbo_tasks::primitives::{StringVc, U32Vc};
use super::options::{FontData, FontWeights};
use super::options::{FontData, FontWeights, NextFontGoogleOptionsVc};
#[derive(Debug, PartialEq)]
pub(crate) struct FontAxes {
......@@ -18,12 +19,41 @@ pub(crate) enum FontItal {
Normal,
}
#[turbo_tasks::value(shared)]
pub(crate) enum FontFamilyType {
WebFont,
Fallback,
}
#[turbo_tasks::function]
pub(crate) async fn get_scoped_font_family(
ty: FontFamilyTypeVc,
options: NextFontGoogleOptionsVc,
request_hash: U32Vc,
) -> Result<StringVc> {
let options = options.await?;
let hash = {
let mut hash = format!("{:x?}", request_hash.await?);
hash.truncate(6);
hash
};
let font_family_base = options.font_family.replace(' ', "_");
let ty = &*ty.await?;
let font_family = match ty {
FontFamilyType::WebFont => font_family_base,
FontFamilyType::Fallback => format!("{}_Fallback", font_family_base),
};
Ok(StringVc::cell(format!("__{}_{}", font_family, hash)))
}
// Derived from https://github.com/vercel/next.js/blob/9e098da0915a2a4581bebe2270953a1216be1ba4/packages/font/src/google/utils.ts#L232
pub(crate) fn get_font_axes(
font_data: &FontData,
font_family: &str,
weights: &FontWeights,
styles: &IndexSet<String>,
styles: &[String],
selected_variable_axes: &Option<Vec<String>>,
) -> Result<FontAxes> {
let all_axes = &font_data
......@@ -32,8 +62,8 @@ pub(crate) fn get_font_axes(
.axes;
let ital = {
let has_italic = styles.contains("italic");
let has_normal = styles.contains("normal");
let has_italic = styles.contains(&"italic".to_owned());
let has_normal = styles.contains(&"normal".to_owned());
let mut set = IndexSet::new();
if has_normal {
set.insert(FontItal::Normal);
......@@ -253,13 +283,7 @@ mod tests {
"#,
)?;
match get_font_axes(
&data,
"foobar",
&FontWeights::Variable,
&indexset! {},
&None,
) {
match get_font_axes(&data, "foobar", &FontWeights::Variable, &[], &None) {
Ok(_) => panic!(),
Err(err) => {
assert_eq!(err.to_string(), "Font family not found")
......@@ -281,13 +305,7 @@ mod tests {
"#,
)?;
match get_font_axes(
&data,
"ABeeZee",
&FontWeights::Variable,
&indexset! {},
&None,
) {
match get_font_axes(&data, "ABeeZee", &FontWeights::Variable, &[], &None) {
Ok(_) => panic!(),
Err(err) => {
assert_eq!(err.to_string(), "Font ABeeZee has no definable `axes`")
......@@ -331,7 +349,7 @@ mod tests {
&data,
"Inter",
&FontWeights::Variable,
&indexset! {},
&[],
&Some(vec!["slnt".to_owned()]),
)?,
FontAxes {
......@@ -372,7 +390,7 @@ mod tests {
&data,
"Inter",
&FontWeights::Variable,
&indexset! {},
&[],
&Some(vec!["slnt".to_owned()]),
)?,
FontAxes {
......@@ -406,13 +424,7 @@ mod tests {
)?;
assert_eq!(
get_font_axes(
&data,
"Hind",
&FontWeights::Fixed(indexset! {500}),
&indexset! {},
&None
)?,
get_font_axes(&data, "Hind", &FontWeights::Fixed(vec![500]), &[], &None)?,
FontAxes {
wght: indexset! {"500".to_owned()},
ital: indexset! {},
......
use anyhow::{anyhow, bail, Result};
use serde::{Deserialize, Serialize};
use anyhow::{anyhow, bail, Context, Result};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use swc_core::ecma::ast::Program;
use turbo_tasks::{primitives::StringVc, trace::TraceRawVcs, ValueToString};
use turbo_tasks_fs::FileSystemPathVc;
use turbo_tasks::{primitives::StringVc, trace::TraceRawVcs, Value, ValueToString};
use turbo_tasks_fs::{json::parse_json_rope_with_source_context, FileContent, FileSystemPathVc};
use turbopack::condition::ContextCondition;
use turbopack_core::{
asset::{Asset, AssetVc},
ident::AssetIdentVc,
issue::{Issue, IssueSeverity, IssueSeverityVc, IssueVc},
reference_type::{EcmaScriptModulesReferenceSubType, ReferenceType},
resolve::{
self, handle_resolve_error, node::node_cjs_resolve_options, parse::RequestVc,
pattern::QueryMapVc, PrimaryResolveResult,
},
};
use turbopack_ecmascript::{
analyzer::{JsValue, ObjectPart},
......@@ -293,3 +298,46 @@ fn parse_config_from_js_value(module_asset: AssetVc, value: &JsValue) -> NextSou
config
}
pub async fn load_next_json<T: DeserializeOwned>(
context: FileSystemPathVc,
path: &str,
) -> Result<T> {
let request = RequestVc::module(
"next".to_owned(),
Value::new(path.to_string().into()),
QueryMapVc::cell(None),
);
let resolve_options = node_cjs_resolve_options(context.root());
let resolve_result = handle_resolve_error(
resolve::resolve(context, request, resolve_options),
Value::new(ReferenceType::EcmaScriptModules(
EcmaScriptModulesReferenceSubType::Undefined,
)),
context,
request,
resolve_options,
)
.await?;
let resolve_result = &*resolve_result.await?;
let primary = resolve_result
.primary
.first()
.context("Unable to resolve primary asset")?;
let PrimaryResolveResult::Asset(metrics_asset) = primary else {
bail!("Expected to find asset");
};
let content = &*metrics_asset.content().file_content().await?;
let FileContent::Content(file) = content else {
bail!("Expected file content for metrics data");
};
let result: T = parse_json_rope_with_source_context(file.content())?;
Ok(result)
}
......@@ -17,7 +17,7 @@ function runTests() {
expect(interNoArgs).toEqual({
className: "className__inter_34ab8b4d__7bdff866",
style: {
fontFamily: "'__Inter_34ab8b'",
fontFamily: "'__Inter_34ab8b', '__Inter_Fallback_34ab8b'",
fontStyle: "normal",
},
});
......
......@@ -20,7 +20,7 @@ function runTests() {
expect(interNoArgs).toEqual({
className: "className__inter_34ab8b4d__7bdff866",
style: {
fontFamily: "'__Inter_34ab8b'",
fontFamily: "'__Inter_34ab8b', '__Inter_Fallback_34ab8b'",
fontStyle: "normal",
},
});
......@@ -29,7 +29,9 @@ function runTests() {
it("includes a rule styling the exported className", async () => {
const matchingRule = await getRuleMatchingClassName(interNoArgs.className);
expect(matchingRule).toBeTruthy();
expect(matchingRule.style.fontFamily).toEqual("__Inter_34ab8b");
expect(matchingRule.style.fontFamily).toEqual(
"__Inter_34ab8b, __Inter_Fallback_34ab8b"
);
expect(matchingRule.style.fontStyle).toEqual("normal");
});
......@@ -37,7 +39,7 @@ function runTests() {
expect(interWithVariableName).toEqual({
className: "className__inter_c6e282f1__e152ac0c",
style: {
fontFamily: "'__Inter_c6e282'",
fontFamily: "'__Inter_c6e282', '__Inter_Fallback_c6e282'",
fontStyle: "normal",
},
variable: "variable__inter_c6e282f1__e152ac0c",
......@@ -47,7 +49,7 @@ function runTests() {
interWithVariableName.variable
);
expect(matchingRule.styleMap.get("--my-font").toString().trim()).toBe(
'"__Inter_c6e282"'
'"__Inter_c6e282", "__Inter_Fallback_c6e282"'
);
});
}
......
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