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

next/font/local prep: compartmentalize next/font/google (#47213)

This PR is largely preparation work for next/font/local by
compartmentalizing and modularizing existing pieces of next/font/google.
It:

* Renames the top level directory to `next_font`
* Places next/font/google-specific code into `next_font/google`
* Extracts common structures and methods into top-level
`font_fallback.rs`, `stylesheet.rs`, `util.rs`, etc.
* Updates visibility of structures and functions to use `pub(super)`
within `next/font/google`

---------
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent fd0e8134
...@@ -16,7 +16,7 @@ mod next_client_chunks; ...@@ -16,7 +16,7 @@ mod next_client_chunks;
mod next_client_component; mod next_client_component;
pub mod next_config; pub mod next_config;
mod next_edge; mod next_edge;
mod next_font_google; mod next_font;
pub mod next_image; pub mod next_image;
mod next_import_map; mod next_import_map;
mod next_route_matcher; mod next_route_matcher;
......
use anyhow::Result;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use turbo_tasks::{
primitives::{StringVc, StringsVc},
trace::TraceRawVcs,
};
pub(crate) struct DefaultFallbackFont {
pub name: String,
pub az_avg_width: f64,
pub units_per_em: u32,
}
// From https://github.com/vercel/next.js/blob/a3893bf69c83fb08e88c87bf8a21d987a0448c8e/packages/font/src/utils.ts#L4
pub(crate) static DEFAULT_SANS_SERIF_FONT: Lazy<DefaultFallbackFont> =
Lazy::new(|| DefaultFallbackFont {
name: "Arial".to_owned(),
az_avg_width: 934.5116279069767,
units_per_em: 2048,
});
pub(crate) 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(shared)]
pub(crate) struct AutomaticFontFallback {
pub scoped_font_family: StringVc,
pub local_font_family: StringVc,
pub adjustment: Option<FontAdjustment>,
}
#[turbo_tasks::value(shared)]
pub(crate) enum FontFallback {
Automatic(AutomaticFontFallbackVc),
/// There was an issue preparing the font fallback. 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),
}
#[turbo_tasks::value(transparent)]
pub(crate) struct FontFallbacks(Vec<FontFallback>);
#[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 {}
use std::collections::HashMap; use std::collections::HashMap;
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_tasks::{ use turbo_tasks::{
primitives::{StringVc, StringsVc, U32Vc}, primitives::{StringVc, StringsVc, U32Vc},
...@@ -10,48 +9,22 @@ use turbo_tasks::{ ...@@ -10,48 +9,22 @@ use turbo_tasks::{
use turbo_tasks_fs::FileSystemPathVc; use turbo_tasks_fs::FileSystemPathVc;
use turbopack_core::issue::IssueSeverity; use turbopack_core::issue::IssueSeverity;
use super::{get_scoped_font_family, options::NextFontGoogleOptionsVc, FontFamilyType}; use super::options::NextFontGoogleOptionsVc;
use crate::{next_font_google::issue::NextFontIssue, util::load_next_json}; use crate::{
next_font::{
struct DefaultFallbackFont { font_fallback::{
name: String, AutomaticFontFallback, FontAdjustment, FontFallback, FontFallbackVc,
az_avg_width: f64, DEFAULT_SANS_SERIF_FONT, DEFAULT_SERIF_FONT,
units_per_em: u32, },
} issue::NextFontIssue,
util::{get_scoped_font_family, FontFamilyType},
// 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 { util::load_next_json,
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)] #[derive(Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub(crate) struct FontMetricsMapEntry { pub(super) struct FontMetricsMapEntry {
category: String, category: String,
ascent: i32, ascent: i32,
descent: i32, descent: i32,
...@@ -61,28 +34,16 @@ pub(crate) struct FontMetricsMapEntry { ...@@ -61,28 +34,16 @@ pub(crate) struct FontMetricsMapEntry {
} }
#[derive(Deserialize)] #[derive(Deserialize)]
pub(crate) struct FontMetricsMap(pub HashMap<String, FontMetricsMapEntry>); pub(super) 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)] #[derive(Debug, PartialEq, Serialize, Deserialize, TraceRawVcs)]
pub(crate) struct Font { pub(super) struct Font {
pub font_family: String, pub font_family: String,
pub adjustment: Option<FontAdjustment>, pub adjustment: Option<FontAdjustment>,
} }
#[turbo_tasks::function] #[turbo_tasks::function]
pub(crate) async fn get_font_fallback( pub(super) async fn get_font_fallback(
context: FileSystemPathVc, context: FileSystemPathVc,
options_vc: NextFontGoogleOptionsVc, options_vc: NextFontGoogleOptionsVc,
request_hash: U32Vc, request_hash: U32Vc,
...@@ -106,7 +67,7 @@ pub(crate) async fn get_font_fallback( ...@@ -106,7 +67,7 @@ pub(crate) async fn get_font_fallback(
AutomaticFontFallback { AutomaticFontFallback {
scoped_font_family: get_scoped_font_family( scoped_font_family: get_scoped_font_family(
FontFamilyType::Fallback.cell(), FontFamilyType::Fallback.cell(),
options_vc, options_vc.font_family(),
request_hash, request_hash,
), ),
local_font_family: StringVc::cell(fallback.font_family), local_font_family: StringVc::cell(fallback.font_family),
...@@ -189,7 +150,7 @@ mod tests { ...@@ -189,7 +150,7 @@ mod tests {
use turbo_tasks_fs::json::parse_json_with_source_context; use turbo_tasks_fs::json::parse_json_with_source_context;
use super::{FontAdjustment, FontMetricsMap}; use super::{FontAdjustment, FontMetricsMap};
use crate::next_font_google::font_fallback::{lookup_fallback, Font}; use crate::next_font::google::font_fallback::{lookup_fallback, Font};
#[test] #[test]
fn test_fallback_from_metrics_sans_serif() -> Result<()> { fn test_fallback_from_metrics_sans_serif() -> Result<()> {
......
...@@ -2,11 +2,10 @@ use anyhow::{bail, Context, Result}; ...@@ -2,11 +2,10 @@ use anyhow::{bail, Context, Result};
use indexmap::IndexMap; use indexmap::IndexMap;
use indoc::formatdoc; use indoc::formatdoc;
use turbo_tasks::{ use turbo_tasks::{
primitives::{OptionStringVc, OptionU16Vc, StringVc, U32Vc}, primitives::{OptionStringVc, StringVc, U32Vc},
Value, Value,
}; };
use turbo_tasks_fs::{json::parse_json_with_source_context, FileContent, FileSystemPathVc}; use turbo_tasks_fs::{json::parse_json_with_source_context, FileContent, FileSystemPathVc};
use turbo_tasks_hash::hash_xxh3_hash64;
use turbopack_core::{ use turbopack_core::{
resolve::{ resolve::{
options::{ options::{
...@@ -22,26 +21,25 @@ use turbopack_core::{ ...@@ -22,26 +21,25 @@ use turbopack_core::{
use turbopack_node::execution_context::ExecutionContextVc; use turbopack_node::execution_context::ExecutionContextVc;
use self::{ use self::{
font_fallback::{get_font_fallback, FontFallback, FontFallbackVc}, font_fallback::get_font_fallback,
options::{FontWeights, NextFontGoogleOptionsVc}, options::{options_from_request, FontDataEntry, FontWeights, NextFontGoogleOptionsVc},
stylesheet::build_stylesheet, stylesheet::build_stylesheet,
util::{get_scoped_font_family, FontFamilyType},
};
use crate::{
embed_js::next_js_file_path,
next_font_google::{
options::FontDataEntry,
util::{get_font_axes, get_stylesheet_url}, util::{get_font_axes, get_stylesheet_url},
};
use super::{
font_fallback::{FontFallback, FontFallbackVc},
util::{
get_request_hash, get_request_id, get_scoped_font_family, FontCssProperties,
FontCssPropertiesVc, FontFamilyType,
}, },
util::load_next_json,
}; };
use crate::{embed_js::next_js_file_path, util::load_next_json};
pub(crate) mod font_fallback; pub mod font_fallback;
pub(crate) mod issue; pub mod options;
pub(crate) mod options; pub mod request;
pub(crate) mod request; pub mod stylesheet;
pub(crate) mod stylesheet; pub mod util;
pub(crate) mod util;
pub const GOOGLE_FONTS_STYLESHEET_URL: &str = "https://fonts.googleapis.com/css2"; pub const GOOGLE_FONTS_STYLESHEET_URL: &str = "https://fonts.googleapis.com/css2";
...@@ -87,7 +85,7 @@ impl ImportMappingReplacement for NextFontGoogleReplacer { ...@@ -87,7 +85,7 @@ impl ImportMappingReplacement for NextFontGoogleReplacer {
let properties = get_font_css_properties(options, fallback, request_hash).await?; let properties = get_font_css_properties(options, fallback, request_hash).await?;
let js_asset = VirtualAssetVc::new( let js_asset = VirtualAssetVc::new(
next_js_file_path("internal/font/google") next_js_file_path("internal/font/google")
.join(&format!("{}.js", get_request_id(*query_vc, font_data).await?)), .join(&format!("{}.js", get_request_id(options.font_family(), request_hash).await?)),
FileContent::Content( FileContent::Content(
formatdoc!( formatdoc!(
r#" r#"
...@@ -112,6 +110,7 @@ impl ImportMappingReplacement for NextFontGoogleReplacer { ...@@ -112,6 +110,7 @@ impl ImportMappingReplacement for NextFontGoogleReplacer {
properties properties
.weight .weight
.await? .await?
.as_ref()
.map(|w| format!("fontWeight: {},\n", w)) .map(|w| format!("fontWeight: {},\n", w))
.unwrap_or_else(|| "".to_owned()), .unwrap_or_else(|| "".to_owned()),
properties properties
...@@ -169,11 +168,14 @@ impl ImportMappingReplacement for NextFontGoogleCssModuleReplacer { ...@@ -169,11 +168,14 @@ impl ImportMappingReplacement for NextFontGoogleCssModuleReplacer {
let options = font_options_from_query_map(*query_vc, font_data); let options = font_options_from_query_map(*query_vc, font_data);
let stylesheet_url = get_stylesheet_url_from_options(options, font_data); let stylesheet_url = get_stylesheet_url_from_options(options, font_data);
let request_hash = get_request_hash(*query_vc); let request_hash = get_request_hash(*query_vc);
let scoped_font_family = let scoped_font_family = get_scoped_font_family(
get_scoped_font_family(FontFamilyType::WebFont.cell(), options, request_hash); FontFamilyType::WebFont.cell(),
options.font_family(),
request_hash,
);
let css_virtual_path = next_js_file_path("internal/font/google").join(&format!( let css_virtual_path = next_js_file_path("internal/font/google").join(&format!(
"/{}.module.css", "/{}.module.css",
get_request_id(*query_vc, font_data).await? get_request_id(options.font_family(), request_hash).await?
)); ));
// When running Next.js integration tests, use the mock data available in // When running Next.js integration tests, use the mock data available in
...@@ -220,7 +222,7 @@ impl ImportMappingReplacement for NextFontGoogleCssModuleReplacer { ...@@ -220,7 +222,7 @@ impl ImportMappingReplacement for NextFontGoogleCssModuleReplacer {
let stylesheet = match stylesheet_str { let stylesheet = match stylesheet_str {
Some(s) => Some( Some(s) => Some(
update_stylesheet(s, options, scoped_font_family) update_google_stylesheet(s, options, scoped_font_family)
.await? .await?
.clone_value(), .clone_value(),
), ),
...@@ -258,7 +260,7 @@ async fn load_font_data(project_root: FileSystemPathVc) -> Result<FontDataVc> { ...@@ -258,7 +260,7 @@ async fn load_font_data(project_root: FileSystemPathVc) -> Result<FontDataVc> {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
async fn update_stylesheet( async fn update_google_stylesheet(
stylesheet: StringVc, stylesheet: StringVc,
options: NextFontGoogleOptionsVc, options: NextFontGoogleOptionsVc,
scoped_font_family: StringVc, scoped_font_family: StringVc,
...@@ -271,34 +273,6 @@ async fn update_stylesheet( ...@@ -271,34 +273,6 @@ async fn update_stylesheet(
))) )))
} }
#[turbo_tasks::function]
async fn get_request_id(query_vc: QueryMapVc, font_data: FontDataVc) -> Result<StringVc> {
let options = font_options_from_query_map(query_vc, font_data).await?;
Ok(StringVc::cell(format!(
"{}_{:x?}",
options.font_family.to_lowercase().replace(' ', "_"),
get_request_hash(query_vc).await?,
)))
}
#[turbo_tasks::function]
async fn get_request_hash(query_vc: QueryMapVc) -> Result<U32Vc> {
let query = &*query_vc.await?;
let query = query.as_ref().context("Query map must be present")?;
let mut to_hash = vec![];
for (k, v) in query {
to_hash.push(k);
to_hash.push(v);
}
Ok(U32Vc::cell(
// Truncate the has to u32. These hashes are ultimately displayed as 8-character
// hexadecimal values.
hash_xxh3_hash64(to_hash) as u32,
))
}
#[turbo_tasks::function] #[turbo_tasks::function]
async fn get_stylesheet_url_from_options( async fn get_stylesheet_url_from_options(
options: NextFontGoogleOptionsVc, options: NextFontGoogleOptionsVc,
...@@ -331,14 +305,6 @@ async fn get_stylesheet_url_from_options( ...@@ -331,14 +305,6 @@ async fn get_stylesheet_url_from_options(
)?)) )?))
} }
#[turbo_tasks::value(transparent)]
pub(crate) struct FontCssProperties {
font_family: StringVc,
weight: OptionU16Vc,
style: OptionStringVc,
variable: OptionStringVc,
}
#[turbo_tasks::function] #[turbo_tasks::function]
async fn get_font_css_properties( async fn get_font_css_properties(
options_vc: NextFontGoogleOptionsVc, options_vc: NextFontGoogleOptionsVc,
...@@ -346,10 +312,14 @@ async fn get_font_css_properties( ...@@ -346,10 +312,14 @@ async fn get_font_css_properties(
request_hash: U32Vc, request_hash: U32Vc,
) -> Result<FontCssPropertiesVc> { ) -> Result<FontCssPropertiesVc> {
let options = &*options_vc.await?; let options = &*options_vc.await?;
let scoped_font_family = let scoped_font_family = &*get_scoped_font_family(
&*get_scoped_font_family(FontFamilyType::WebFont.cell(), options_vc, request_hash).await?; FontFamilyType::WebFont.cell(),
options_vc.font_family(),
request_hash,
)
.await?;
let mut font_families = vec![scoped_font_family.clone()]; let mut font_families = vec![format!("'{}'", scoped_font_family.clone())];
let font_fallback = &*font_fallback.await?; let font_fallback = &*font_fallback.await?;
match font_fallback { match font_fallback {
FontFallback::Manual(fonts) => { FontFallback::Manual(fonts) => {
...@@ -357,26 +327,16 @@ async fn get_font_css_properties( ...@@ -357,26 +327,16 @@ async fn get_font_css_properties(
} }
FontFallback::Automatic(fallback) => { FontFallback::Automatic(fallback) => {
let fallback = &*fallback.await?; let fallback = &*fallback.await?;
font_families.push((*fallback.scoped_font_family.await?).clone()); font_families.push(format!("'{}'", *fallback.scoped_font_family.await?));
} }
FontFallback::Error => {} FontFallback::Error => {}
} }
if let Some(fallback) = &options.fallback {
font_families.extend_from_slice(fallback);
}
Ok(FontCssPropertiesVc::cell(FontCssProperties { Ok(FontCssPropertiesVc::cell(FontCssProperties {
font_family: StringVc::cell( font_family: StringVc::cell(font_families.join(", ")),
font_families weight: OptionStringVc::cell(match &options.weights {
.iter()
.map(|f| format!("'{}'", f))
.collect::<Vec<String>>()
.join(", "),
),
weight: OptionU16Vc::cell(match &options.weights {
FontWeights::Variable => None, FontWeights::Variable => None,
FontWeights::Fixed(weights) => weights.first().cloned(), FontWeights::Fixed(weights) => weights.first().map(|w| w.to_string()),
}), }),
style: OptionStringVc::cell(options.styles.first().cloned()), style: OptionStringVc::cell(options.styles.first().cloned()),
variable: OptionStringVc::cell(options.variable.clone()), variable: OptionStringVc::cell(options.variable.clone()),
...@@ -403,7 +363,7 @@ async fn font_options_from_query_map( ...@@ -403,7 +363,7 @@ async fn font_options_from_query_map(
bail!("Expected one entry"); bail!("Expected one entry");
}; };
self::options::options_from_request(&parse_json_with_source_context(json)?, &*font_data.await?) options_from_request(&parse_json_with_source_context(json)?, &*font_data.await?)
.map(|o| NextFontGoogleOptionsVc::new(Value::new(o))) .map(|o| NextFontGoogleOptionsVc::new(Value::new(o)))
} }
......
use anyhow::{anyhow, Context, Result}; use anyhow::{anyhow, Context, Result};
use indexmap::{indexset, IndexMap, IndexSet}; use indexmap::{indexset, IndexMap, IndexSet};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, Value}; use turbo_tasks::{primitives::StringVc, trace::TraceRawVcs, Value};
use super::request::{NextFontRequest, OneOrManyStrings}; use super::request::{NextFontRequest, OneOrManyStrings};
const ALLOWED_DISPLAY_VALUES: &[&str] = &["auto", "block", "swap", "fallback", "optional"]; const ALLOWED_DISPLAY_VALUES: &[&str] = &["auto", "block", "swap", "fallback", "optional"];
pub(crate) type FontData = IndexMap<String, FontDataEntry>; pub(super) type FontData = IndexMap<String, FontDataEntry>;
#[turbo_tasks::value(serialization = "auto_for_input")] #[turbo_tasks::value(serialization = "auto_for_input")]
#[derive(Clone, Debug, PartialOrd, Ord, Hash)] #[derive(Clone, Debug, PartialOrd, Ord, Hash)]
pub(crate) struct NextFontGoogleOptions { pub(super) struct NextFontGoogleOptions {
/// Name of the requested font from Google. Contains literal spaces. /// Name of the requested font from Google. Contains literal spaces.
pub font_family: String, pub font_family: String,
pub weights: FontWeights, pub weights: FontWeights,
...@@ -21,6 +21,8 @@ pub(crate) struct NextFontGoogleOptions { ...@@ -21,6 +21,8 @@ pub(crate) struct NextFontGoogleOptions {
pub selected_variable_axes: Option<Vec<String>>, pub selected_variable_axes: Option<Vec<String>>,
pub fallback: Option<Vec<String>>, pub fallback: Option<Vec<String>>,
pub adjust_font_fallback: bool, pub adjust_font_fallback: bool,
/// An optional name for a css custom property (css variable) that applies
/// the font family when used.
pub variable: Option<String>, pub variable: Option<String>,
pub subsets: Option<Vec<String>>, pub subsets: Option<Vec<String>>,
} }
...@@ -31,18 +33,23 @@ impl NextFontGoogleOptionsVc { ...@@ -31,18 +33,23 @@ impl NextFontGoogleOptionsVc {
pub fn new(options: Value<NextFontGoogleOptions>) -> NextFontGoogleOptionsVc { pub fn new(options: Value<NextFontGoogleOptions>) -> NextFontGoogleOptionsVc {
Self::cell(options.into_value()) Self::cell(options.into_value())
} }
#[turbo_tasks::function]
pub async fn font_family(self) -> Result<StringVc> {
Ok(StringVc::cell((*self.await?.font_family).to_owned()))
}
} }
#[derive( #[derive(
Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, TraceRawVcs, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, TraceRawVcs,
)] )]
pub(crate) enum FontWeights { pub(super) enum FontWeights {
Variable, Variable,
Fixed(Vec<u16>), Fixed(Vec<u16>),
} }
#[derive(Debug, PartialEq, Eq, Deserialize, Serialize, TraceRawVcs)] #[derive(Debug, PartialEq, Eq, Deserialize, Serialize, TraceRawVcs)]
pub(crate) struct FontDataEntry { pub(super) struct FontDataEntry {
pub weights: Vec<String>, pub weights: Vec<String>,
pub styles: Vec<String>, pub styles: Vec<String>,
pub axes: Option<Vec<Axis>>, pub axes: Option<Vec<Axis>>,
...@@ -50,7 +57,7 @@ pub(crate) struct FontDataEntry { ...@@ -50,7 +57,7 @@ pub(crate) struct FontDataEntry {
#[derive(Debug, PartialEq, Deserialize, Serialize, TraceRawVcs)] #[derive(Debug, PartialEq, Deserialize, Serialize, TraceRawVcs)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub(crate) struct Axis { pub(super) struct Axis {
pub tag: String, pub tag: String,
pub min: f64, pub min: f64,
pub max: f64, pub max: f64,
...@@ -61,7 +68,7 @@ impl Eq for Axis {} ...@@ -61,7 +68,7 @@ impl Eq for Axis {}
// Transforms the request fields to a struct suitable for making requests to // Transforms the request fields to a struct suitable for making requests to
// Google Fonts. Similar to next/font/google's validateData: // Google Fonts. Similar to next/font/google's validateData:
// https://github.com/vercel/next.js/blob/28454c6ddbc310419467e5415aee26e48d079b46/packages/font/src/google/utils.ts#L22 // https://github.com/vercel/next.js/blob/28454c6ddbc310419467e5415aee26e48d079b46/packages/font/src/google/utils.ts#L22
pub(crate) fn options_from_request( pub(super) fn options_from_request(
request: &NextFontRequest, request: &NextFontRequest,
data: &IndexMap<String, FontDataEntry>, data: &IndexMap<String, FontDataEntry>,
) -> Result<NextFontGoogleOptions> { ) -> Result<NextFontGoogleOptions> {
...@@ -194,7 +201,7 @@ mod tests { ...@@ -194,7 +201,7 @@ mod tests {
use turbo_tasks_fs::json::parse_json_with_source_context; use turbo_tasks_fs::json::parse_json_with_source_context;
use super::{options_from_request, FontDataEntry, NextFontGoogleOptions}; use super::{options_from_request, FontDataEntry, NextFontGoogleOptions};
use crate::next_font_google::{options::FontWeights, request::NextFontRequest}; use crate::next_font::google::{options::FontWeights, request::NextFontRequest};
#[test] #[test]
fn test_errors_on_unknown_font() -> Result<()> { fn test_errors_on_unknown_font() -> Result<()> {
......
...@@ -5,15 +5,13 @@ use serde::Deserialize; ...@@ -5,15 +5,13 @@ use serde::Deserialize;
/// `next/font/google/target.css?{"path": "index.js", "import": "Inter"...` /// `next/font/google/target.css?{"path": "index.js", "import": "Inter"...`
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct NextFontRequest { pub(super) struct NextFontRequest {
pub path: String,
pub import: String, pub import: String,
pub arguments: Vec<NextFontRequestArguments>, pub arguments: Vec<NextFontRequestArguments>,
pub variable_name: String,
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
pub struct NextFontRequestArguments { pub(super) struct NextFontRequestArguments {
pub weight: Option<OneOrManyStrings>, pub weight: Option<OneOrManyStrings>,
pub subsets: Option<Vec<String>>, pub subsets: Option<Vec<String>>,
pub style: Option<OneOrManyStrings>, pub style: Option<OneOrManyStrings>,
...@@ -29,7 +27,7 @@ pub struct NextFontRequestArguments { ...@@ -29,7 +27,7 @@ pub struct NextFontRequestArguments {
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
#[serde(untagged)] #[serde(untagged)]
pub enum OneOrManyStrings { pub(super) enum OneOrManyStrings {
One(String), One(String),
Many(Vec<String>), Many(Vec<String>),
} }
......
...@@ -2,13 +2,11 @@ use anyhow::Result; ...@@ -2,13 +2,11 @@ use anyhow::Result;
use indoc::formatdoc; use indoc::formatdoc;
use turbo_tasks::primitives::{OptionStringVc, StringVc}; use turbo_tasks::primitives::{OptionStringVc, StringVc};
use super::{ use super::FontCssPropertiesVc;
font_fallback::{FontFallback, FontFallbackVc}, use crate::next_font::{font_fallback::FontFallbackVc, stylesheet::build_fallback_definition};
FontCssProperties, FontCssPropertiesVc,
};
#[turbo_tasks::function] #[turbo_tasks::function]
pub(crate) async fn build_stylesheet( pub(super) async fn build_stylesheet(
base_stylesheet: OptionStringVc, base_stylesheet: OptionStringVc,
font_css_properties: FontCssPropertiesVc, font_css_properties: FontCssPropertiesVc,
font_fallback: FontFallbackVc, font_fallback: FontFallbackVc,
...@@ -17,53 +15,16 @@ pub(crate) async fn build_stylesheet( ...@@ -17,53 +15,16 @@ pub(crate) async fn build_stylesheet(
let mut stylesheet = base_stylesheet let mut stylesheet = base_stylesheet
.as_ref() .as_ref()
.map_or_else(|| "".to_owned(), |s| s.to_owned()); .map_or_else(|| "".to_owned(), |s| s.to_owned());
if let Some(definition) = build_fallback_definition(&*font_fallback.await?).await? { if let Some(definition) = &*build_fallback_definition(font_fallback).await? {
stylesheet.push_str(&definition); stylesheet.push_str(definition);
} }
stylesheet.push_str(&build_font_class_rules(&*font_css_properties.await?).await?); stylesheet.push_str(&build_font_class_rules(font_css_properties).await?);
Ok(StringVc::cell(stylesheet)) Ok(StringVc::cell(stylesheet))
} }
async fn build_fallback_definition(fallback: &FontFallback) -> Result<Option<String>> { #[turbo_tasks::function]
match fallback { async fn build_font_class_rules(properties: FontCssPropertiesVc) -> Result<StringVc> {
FontFallback::Error => Ok(None), let properties = &*properties.await?;
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 font_family = &*properties.font_family.await?;
let mut result = formatdoc!( let mut result = formatdoc!(
...@@ -77,6 +38,7 @@ async fn build_font_class_rules(properties: &FontCssProperties) -> Result<String ...@@ -77,6 +38,7 @@ async fn build_font_class_rules(properties: &FontCssProperties) -> Result<String
properties properties
.weight .weight
.await? .await?
.as_ref()
.map(|w| format!("font-weight: {};\n", w)) .map(|w| format!("font-weight: {};\n", w))
.unwrap_or_else(|| "".to_owned()), .unwrap_or_else(|| "".to_owned()),
properties properties
...@@ -97,12 +59,7 @@ async fn build_font_class_rules(properties: &FontCssProperties) -> Result<String ...@@ -97,12 +59,7 @@ async fn build_font_class_rules(properties: &FontCssProperties) -> Result<String
variable, variable,
font_family, font_family,
)) ))
//
} }
Ok(result) Ok(StringVc::cell(result))
}
fn format_fixed_percentage(value: f64) -> String {
format!("{:.2}", value * 100.0)
} }
...@@ -2,54 +2,24 @@ use std::cmp::Ordering; ...@@ -2,54 +2,24 @@ use std::cmp::Ordering;
use anyhow::{anyhow, bail, Context, Result}; use anyhow::{anyhow, bail, Context, Result};
use indexmap::{indexset, IndexSet}; use indexmap::{indexset, IndexSet};
use turbo_tasks::primitives::{StringVc, U32Vc};
use super::options::{FontData, FontWeights, NextFontGoogleOptionsVc}; use super::options::{FontData, FontWeights};
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub(crate) struct FontAxes { pub(super) struct FontAxes {
pub(crate) wght: IndexSet<String>, pub(super) wght: IndexSet<String>,
pub(crate) ital: IndexSet<FontItal>, pub(super) ital: IndexSet<FontStyle>,
pub(crate) variable_axes: Option<Vec<(String, String)>>, pub(super) variable_axes: Option<Vec<(String, String)>>,
} }
#[derive(Debug, PartialEq, Eq, Hash)] #[derive(Debug, PartialEq, Eq, Hash)]
pub(crate) enum FontItal { pub(super) enum FontStyle {
Italic, Italic,
Normal, 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 // Derived from https://github.com/vercel/next.js/blob/9e098da0915a2a4581bebe2270953a1216be1ba4/packages/font/src/google/utils.ts#L232
pub(crate) fn get_font_axes( pub(super) fn get_font_axes(
font_data: &FontData, font_data: &FontData,
font_family: &str, font_family: &str,
weights: &FontWeights, weights: &FontWeights,
...@@ -66,10 +36,10 @@ pub(crate) fn get_font_axes( ...@@ -66,10 +36,10 @@ pub(crate) fn get_font_axes(
let has_normal = styles.contains(&"normal".to_owned()); let has_normal = styles.contains(&"normal".to_owned());
let mut set = IndexSet::new(); let mut set = IndexSet::new();
if has_normal { if has_normal {
set.insert(FontItal::Normal); set.insert(FontStyle::Normal);
} }
if has_italic { if has_italic {
set.insert(FontItal::Italic); set.insert(FontStyle::Italic);
} }
set set
}; };
...@@ -134,7 +104,7 @@ pub(crate) fn get_font_axes( ...@@ -134,7 +104,7 @@ pub(crate) fn get_font_axes(
} }
// Derived from https://github.com/vercel/next.js/blob/9e098da0915a2a4581bebe2270953a1216be1ba4/packages/font/src/google/utils.ts#L128 // Derived from https://github.com/vercel/next.js/blob/9e098da0915a2a4581bebe2270953a1216be1ba4/packages/font/src/google/utils.ts#L128
pub(crate) fn get_stylesheet_url( pub(super) fn get_stylesheet_url(
root_url: &str, root_url: &str,
font_family: &str, font_family: &str,
axes: &FontAxes, axes: &FontAxes,
...@@ -170,12 +140,12 @@ pub(crate) fn get_stylesheet_url( ...@@ -170,12 +140,12 @@ pub(crate) fn get_stylesheet_url(
// If Normal is the only requested variant, it's safe to omit the ital axis // If Normal is the only requested variant, it's safe to omit the ital axis
// entirely. Otherwise, include all variants. // entirely. Otherwise, include all variants.
if matches!(ital, FontItal::Italic) || axes.ital.len() > 1 { if matches!(ital, FontStyle::Italic) || axes.ital.len() > 1 {
variant.push(( variant.push((
"ital", "ital",
match ital { match ital {
FontItal::Normal => "0", FontStyle::Normal => "0",
FontItal::Italic => "1", FontStyle::Italic => "1",
}, },
)); ));
} }
...@@ -264,9 +234,9 @@ mod tests { ...@@ -264,9 +234,9 @@ mod tests {
use turbo_tasks_fs::json::parse_json_with_source_context; use turbo_tasks_fs::json::parse_json_with_source_context;
use super::get_font_axes; use super::get_font_axes;
use crate::next_font_google::{ use crate::next_font::google::{
options::{FontData, FontWeights}, options::{FontData, FontWeights},
util::{get_stylesheet_url, FontAxes, FontItal}, util::{get_stylesheet_url, FontAxes, FontStyle},
GOOGLE_FONTS_STYLESHEET_URL, GOOGLE_FONTS_STYLESHEET_URL,
}; };
...@@ -442,7 +412,7 @@ mod tests { ...@@ -442,7 +412,7 @@ mod tests {
"Roboto Mono", "Roboto Mono",
&FontAxes { &FontAxes {
wght: indexset! {"500".to_owned()}, wght: indexset! {"500".to_owned()},
ital: indexset! {FontItal::Normal}, ital: indexset! {FontStyle::Normal},
variable_axes: None variable_axes: None
}, },
"optional" "optional"
...@@ -461,7 +431,7 @@ mod tests { ...@@ -461,7 +431,7 @@ mod tests {
"Roboto Serif", "Roboto Serif",
&FontAxes { &FontAxes {
wght: indexset! {"500".to_owned()}, wght: indexset! {"500".to_owned()},
ital: indexset! {FontItal::Normal}, ital: indexset! {FontStyle::Normal},
variable_axes: Some(vec![ variable_axes: Some(vec![
("GRAD".to_owned(), "-50..100".to_owned()), ("GRAD".to_owned(), "-50..100".to_owned()),
("opsz".to_owned(), "8..144".to_owned()), ("opsz".to_owned(), "8..144".to_owned()),
...@@ -484,7 +454,7 @@ mod tests { ...@@ -484,7 +454,7 @@ mod tests {
"Roboto Serif", "Roboto Serif",
&FontAxes { &FontAxes {
wght: indexset! {"500".to_owned(), "300".to_owned()}, wght: indexset! {"500".to_owned(), "300".to_owned()},
ital: indexset! {FontItal::Normal, FontItal::Italic}, ital: indexset! {FontStyle::Normal, FontStyle::Italic},
variable_axes: Some(vec![ variable_axes: Some(vec![
("GRAD".to_owned(), "-50..100".to_owned()), ("GRAD".to_owned(), "-50..100".to_owned()),
("opsz".to_owned(), "8..144".to_owned()), ("opsz".to_owned(), "8..144".to_owned()),
......
pub(crate) mod font_fallback;
pub(crate) mod google;
pub(crate) mod issue;
pub(crate) mod stylesheet;
pub(crate) mod util;
use anyhow::Result;
use indoc::formatdoc;
use turbo_tasks::primitives::OptionStringVc;
use super::font_fallback::{FontFallback, FontFallbackVc};
/// Builds `@font-face` stylesheet definition for a given FontFallback
#[turbo_tasks::function]
pub(crate) async fn build_fallback_definition(fallback: FontFallbackVc) -> Result<OptionStringVc> {
Ok(OptionStringVc::cell(match *fallback.await? {
FontFallback::Error => None,
FontFallback::Manual(_) => 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)
),
};
Some(formatdoc!(
r#"
@font-face {{
font-family: '{}';
src: local("{}");
{}
}}
"#,
fallback.scoped_font_family.await?,
fallback.local_font_family.await?,
override_properties
))
}
}))
}
fn format_fixed_percentage(value: f64) -> String {
format!("{:.2}", value * 100.0)
}
use anyhow::{Context, Result};
use turbo_tasks::primitives::{OptionStringVc, StringVc, U32Vc};
use turbo_tasks_hash::hash_xxh3_hash64;
use turbopack_core::resolve::pattern::QueryMapVc;
#[turbo_tasks::value(shared)]
pub(crate) struct FontCssProperties {
pub font_family: StringVc,
pub weight: OptionStringVc,
pub style: OptionStringVc,
pub variable: OptionStringVc,
}
#[turbo_tasks::function]
pub(crate) async fn get_request_hash(query_vc: QueryMapVc) -> Result<U32Vc> {
let query = &*query_vc.await?;
let query = query.as_ref().context("Query map must be present")?;
let mut to_hash = vec![];
for (k, v) in query {
to_hash.push(k);
to_hash.push(v);
}
Ok(U32Vc::cell(
// Truncate the has to u32. These hashes are ultimately displayed as 8-character
// hexadecimal values.
hash_xxh3_hash64(to_hash) as u32,
))
}
#[turbo_tasks::value(shared)]
pub(crate) enum FontFamilyType {
WebFont,
Fallback,
}
#[turbo_tasks::function]
pub(crate) async fn get_scoped_font_family(
ty: FontFamilyTypeVc,
font_family_name: StringVc,
request_hash: U32Vc,
) -> Result<StringVc> {
let hash = {
let mut hash = format!("{:x?}", request_hash.await?);
hash.truncate(6);
hash
};
let font_family_base = font_family_name.await?.replace(' ', "_");
let font_family_name = match &*ty.await? {
FontFamilyType::WebFont => font_family_base,
FontFamilyType::Fallback => format!("{}_Fallback", font_family_base),
};
Ok(StringVc::cell(format!("__{}_{}", font_family_name, hash)))
}
#[turbo_tasks::function]
pub async fn get_request_id(font_family: StringVc, request_hash: U32Vc) -> Result<StringVc> {
Ok(StringVc::cell(format!(
"{}_{:x?}",
font_family.await?.to_lowercase().replace(' ', "_"),
request_hash.await?
)))
}
...@@ -22,7 +22,7 @@ use crate::{ ...@@ -22,7 +22,7 @@ use crate::{
embed_js::{next_js_fs, VIRTUAL_PACKAGE_NAME}, embed_js::{next_js_fs, VIRTUAL_PACKAGE_NAME},
next_client::context::ClientContextType, next_client::context::ClientContextType,
next_config::NextConfigVc, next_config::NextConfigVc,
next_font_google::{NextFontGoogleCssModuleReplacerVc, NextFontGoogleReplacerVc}, next_font::google::{NextFontGoogleCssModuleReplacerVc, NextFontGoogleReplacerVc},
next_server::context::ServerContextType, next_server::context::ServerContextType,
}; };
......
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