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;
mod next_client_component;
pub mod next_config;
mod next_edge;
mod next_font_google;
mod next_font;
pub mod next_image;
mod next_import_map;
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 anyhow::{Context, Result};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use turbo_tasks::{
primitives::{StringVc, StringsVc, U32Vc},
......@@ -10,48 +9,22 @@ use turbo_tasks::{
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),
}
use super::options::NextFontGoogleOptionsVc;
use crate::{
next_font::{
font_fallback::{
AutomaticFontFallback, FontAdjustment, FontFallback, FontFallbackVc,
DEFAULT_SANS_SERIF_FONT, DEFAULT_SERIF_FONT,
},
issue::NextFontIssue,
util::{get_scoped_font_family, FontFamilyType},
},
util::load_next_json,
};
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct FontMetricsMapEntry {
pub(super) struct FontMetricsMapEntry {
category: String,
ascent: i32,
descent: i32,
......@@ -61,28 +34,16 @@ pub(crate) struct FontMetricsMapEntry {
}
#[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 {}
pub(super) struct FontMetricsMap(pub HashMap<String, FontMetricsMapEntry>);
#[derive(Debug, PartialEq, Serialize, Deserialize, TraceRawVcs)]
pub(crate) struct Font {
pub(super) struct Font {
pub font_family: String,
pub adjustment: Option<FontAdjustment>,
}
#[turbo_tasks::function]
pub(crate) async fn get_font_fallback(
pub(super) async fn get_font_fallback(
context: FileSystemPathVc,
options_vc: NextFontGoogleOptionsVc,
request_hash: U32Vc,
......@@ -106,7 +67,7 @@ pub(crate) async fn get_font_fallback(
AutomaticFontFallback {
scoped_font_family: get_scoped_font_family(
FontFamilyType::Fallback.cell(),
options_vc,
options_vc.font_family(),
request_hash,
),
local_font_family: StringVc::cell(fallback.font_family),
......@@ -189,7 +150,7 @@ mod tests {
use turbo_tasks_fs::json::parse_json_with_source_context;
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]
fn test_fallback_from_metrics_sans_serif() -> Result<()> {
......
......@@ -2,11 +2,10 @@ use anyhow::{bail, Context, Result};
use indexmap::IndexMap;
use indoc::formatdoc;
use turbo_tasks::{
primitives::{OptionStringVc, OptionU16Vc, StringVc, U32Vc},
primitives::{OptionStringVc, 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::{
resolve::{
options::{
......@@ -22,26 +21,25 @@ use turbopack_core::{
use turbopack_node::execution_context::ExecutionContextVc;
use self::{
font_fallback::{get_font_fallback, FontFallback, FontFallbackVc},
options::{FontWeights, NextFontGoogleOptionsVc},
font_fallback::get_font_fallback,
options::{options_from_request, FontDataEntry, FontWeights, NextFontGoogleOptionsVc},
stylesheet::build_stylesheet,
util::{get_scoped_font_family, FontFamilyType},
util::{get_font_axes, get_stylesheet_url},
};
use crate::{
embed_js::next_js_file_path,
next_font_google::{
options::FontDataEntry,
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(crate) mod issue;
pub(crate) mod options;
pub(crate) mod request;
pub(crate) mod stylesheet;
pub(crate) mod util;
pub mod font_fallback;
pub mod options;
pub mod request;
pub mod stylesheet;
pub mod util;
pub const GOOGLE_FONTS_STYLESHEET_URL: &str = "https://fonts.googleapis.com/css2";
......@@ -87,7 +85,7 @@ impl ImportMappingReplacement for NextFontGoogleReplacer {
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, font_data).await?)),
.join(&format!("{}.js", get_request_id(options.font_family(), request_hash).await?)),
FileContent::Content(
formatdoc!(
r#"
......@@ -112,6 +110,7 @@ impl ImportMappingReplacement for NextFontGoogleReplacer {
properties
.weight
.await?
.as_ref()
.map(|w| format!("fontWeight: {},\n", w))
.unwrap_or_else(|| "".to_owned()),
properties
......@@ -169,11 +168,14 @@ impl ImportMappingReplacement for NextFontGoogleCssModuleReplacer {
let options = font_options_from_query_map(*query_vc, font_data);
let stylesheet_url = get_stylesheet_url_from_options(options, font_data);
let request_hash = get_request_hash(*query_vc);
let scoped_font_family =
get_scoped_font_family(FontFamilyType::WebFont.cell(), options, request_hash);
let scoped_font_family = get_scoped_font_family(
FontFamilyType::WebFont.cell(),
options.font_family(),
request_hash,
);
let css_virtual_path = next_js_file_path("internal/font/google").join(&format!(
"/{}.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
......@@ -220,7 +222,7 @@ impl ImportMappingReplacement for NextFontGoogleCssModuleReplacer {
let stylesheet = match stylesheet_str {
Some(s) => Some(
update_stylesheet(s, options, scoped_font_family)
update_google_stylesheet(s, options, scoped_font_family)
.await?
.clone_value(),
),
......@@ -258,7 +260,7 @@ async fn load_font_data(project_root: FileSystemPathVc) -> Result<FontDataVc> {
}
#[turbo_tasks::function]
async fn update_stylesheet(
async fn update_google_stylesheet(
stylesheet: StringVc,
options: NextFontGoogleOptionsVc,
scoped_font_family: StringVc,
......@@ -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]
async fn get_stylesheet_url_from_options(
options: NextFontGoogleOptionsVc,
......@@ -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]
async fn get_font_css_properties(
options_vc: NextFontGoogleOptionsVc,
......@@ -346,10 +312,14 @@ async fn get_font_css_properties(
request_hash: U32Vc,
) -> Result<FontCssPropertiesVc> {
let options = &*options_vc.await?;
let scoped_font_family =
&*get_scoped_font_family(FontFamilyType::WebFont.cell(), options_vc, request_hash).await?;
let scoped_font_family = &*get_scoped_font_family(
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?;
match font_fallback {
FontFallback::Manual(fonts) => {
......@@ -357,26 +327,16 @@ async fn get_font_css_properties(
}
FontFallback::Automatic(fallback) => {
let fallback = &*fallback.await?;
font_families.push((*fallback.scoped_font_family.await?).clone());
font_families.push(format!("'{}'", *fallback.scoped_font_family.await?));
}
FontFallback::Error => {}
}
if let Some(fallback) = &options.fallback {
font_families.extend_from_slice(fallback);
}
Ok(FontCssPropertiesVc::cell(FontCssProperties {
font_family: StringVc::cell(
font_families
.iter()
.map(|f| format!("'{}'", f))
.collect::<Vec<String>>()
.join(", "),
),
weight: OptionU16Vc::cell(match &options.weights {
font_family: StringVc::cell(font_families.join(", ")),
weight: OptionStringVc::cell(match &options.weights {
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()),
variable: OptionStringVc::cell(options.variable.clone()),
......@@ -403,7 +363,7 @@ async fn font_options_from_query_map(
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)))
}
......
use anyhow::{anyhow, Context, Result};
use indexmap::{indexset, IndexMap, IndexSet};
use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, Value};
use turbo_tasks::{primitives::StringVc, trace::TraceRawVcs, Value};
use super::request::{NextFontRequest, OneOrManyStrings};
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")]
#[derive(Clone, Debug, PartialOrd, Ord, Hash)]
pub(crate) struct NextFontGoogleOptions {
pub(super) struct NextFontGoogleOptions {
/// Name of the requested font from Google. Contains literal spaces.
pub font_family: String,
pub weights: FontWeights,
......@@ -21,6 +21,8 @@ pub(crate) struct NextFontGoogleOptions {
pub selected_variable_axes: Option<Vec<String>>,
pub fallback: Option<Vec<String>>,
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 subsets: Option<Vec<String>>,
}
......@@ -31,18 +33,23 @@ impl NextFontGoogleOptionsVc {
pub fn new(options: Value<NextFontGoogleOptions>) -> NextFontGoogleOptionsVc {
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(
Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, TraceRawVcs,
)]
pub(crate) enum FontWeights {
pub(super) enum FontWeights {
Variable,
Fixed(Vec<u16>),
}
#[derive(Debug, PartialEq, Eq, Deserialize, Serialize, TraceRawVcs)]
pub(crate) struct FontDataEntry {
pub(super) struct FontDataEntry {
pub weights: Vec<String>,
pub styles: Vec<String>,
pub axes: Option<Vec<Axis>>,
......@@ -50,7 +57,7 @@ pub(crate) struct FontDataEntry {
#[derive(Debug, PartialEq, Deserialize, Serialize, TraceRawVcs)]
#[serde(rename_all = "camelCase")]
pub(crate) struct Axis {
pub(super) struct Axis {
pub tag: String,
pub min: f64,
pub max: f64,
......@@ -61,7 +68,7 @@ impl Eq for Axis {}
// 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(crate) fn options_from_request(
pub(super) fn options_from_request(
request: &NextFontRequest,
data: &IndexMap<String, FontDataEntry>,
) -> Result<NextFontGoogleOptions> {
......@@ -194,7 +201,7 @@ mod tests {
use turbo_tasks_fs::json::parse_json_with_source_context;
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]
fn test_errors_on_unknown_font() -> Result<()> {
......
......@@ -5,15 +5,13 @@ use serde::Deserialize;
/// `next/font/google/target.css?{"path": "index.js", "import": "Inter"...`
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NextFontRequest {
pub path: String,
pub(super) struct NextFontRequest {
pub import: String,
pub arguments: Vec<NextFontRequestArguments>,
pub variable_name: String,
}
#[derive(Debug, Deserialize)]
pub struct NextFontRequestArguments {
pub(super) struct NextFontRequestArguments {
pub weight: Option<OneOrManyStrings>,
pub subsets: Option<Vec<String>>,
pub style: Option<OneOrManyStrings>,
......@@ -29,7 +27,7 @@ pub struct NextFontRequestArguments {
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum OneOrManyStrings {
pub(super) enum OneOrManyStrings {
One(String),
Many(Vec<String>),
}
......
......@@ -2,13 +2,11 @@ use anyhow::Result;
use indoc::formatdoc;
use turbo_tasks::primitives::{OptionStringVc, StringVc};
use super::{
font_fallback::{FontFallback, FontFallbackVc},
FontCssProperties, FontCssPropertiesVc,
};
use super::FontCssPropertiesVc;
use crate::next_font::{font_fallback::FontFallbackVc, stylesheet::build_fallback_definition};
#[turbo_tasks::function]
pub(crate) async fn build_stylesheet(
pub(super) async fn build_stylesheet(
base_stylesheet: OptionStringVc,
font_css_properties: FontCssPropertiesVc,
font_fallback: FontFallbackVc,
......@@ -17,53 +15,16 @@ pub(crate) async fn build_stylesheet(
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);
if let Some(definition) = &*build_fallback_definition(font_fallback).await? {
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))
}
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> {
#[turbo_tasks::function]
async fn build_font_class_rules(properties: FontCssPropertiesVc) -> Result<StringVc> {
let properties = &*properties.await?;
let font_family = &*properties.font_family.await?;
let mut result = formatdoc!(
......@@ -77,6 +38,7 @@ async fn build_font_class_rules(properties: &FontCssProperties) -> Result<String
properties
.weight
.await?
.as_ref()
.map(|w| format!("font-weight: {};\n", w))
.unwrap_or_else(|| "".to_owned()),
properties
......@@ -97,12 +59,7 @@ async fn build_font_class_rules(properties: &FontCssProperties) -> Result<String
variable,
font_family,
))
//
}
Ok(result)
}
fn format_fixed_percentage(value: f64) -> String {
format!("{:.2}", value * 100.0)
Ok(StringVc::cell(result))
}
......@@ -2,54 +2,24 @@ 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, NextFontGoogleOptionsVc};
use super::options::{FontData, FontWeights};
#[derive(Debug, PartialEq)]
pub(crate) struct FontAxes {
pub(crate) wght: IndexSet<String>,
pub(crate) ital: IndexSet<FontItal>,
pub(crate) variable_axes: Option<Vec<(String, String)>>,
pub(super) struct FontAxes {
pub(super) wght: IndexSet<String>,
pub(super) ital: IndexSet<FontStyle>,
pub(super) variable_axes: Option<Vec<(String, String)>>,
}
#[derive(Debug, PartialEq, Eq, Hash)]
pub(crate) enum FontItal {
pub(super) enum FontStyle {
Italic,
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(
pub(super) fn get_font_axes(
font_data: &FontData,
font_family: &str,
weights: &FontWeights,
......@@ -66,10 +36,10 @@ pub(crate) fn get_font_axes(
let has_normal = styles.contains(&"normal".to_owned());
let mut set = IndexSet::new();
if has_normal {
set.insert(FontItal::Normal);
set.insert(FontStyle::Normal);
}
if has_italic {
set.insert(FontItal::Italic);
set.insert(FontStyle::Italic);
}
set
};
......@@ -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
pub(crate) fn get_stylesheet_url(
pub(super) fn get_stylesheet_url(
root_url: &str,
font_family: &str,
axes: &FontAxes,
......@@ -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
// 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((
"ital",
match ital {
FontItal::Normal => "0",
FontItal::Italic => "1",
FontStyle::Normal => "0",
FontStyle::Italic => "1",
},
));
}
......@@ -264,9 +234,9 @@ mod tests {
use turbo_tasks_fs::json::parse_json_with_source_context;
use super::get_font_axes;
use crate::next_font_google::{
use crate::next_font::google::{
options::{FontData, FontWeights},
util::{get_stylesheet_url, FontAxes, FontItal},
util::{get_stylesheet_url, FontAxes, FontStyle},
GOOGLE_FONTS_STYLESHEET_URL,
};
......@@ -442,7 +412,7 @@ mod tests {
"Roboto Mono",
&FontAxes {
wght: indexset! {"500".to_owned()},
ital: indexset! {FontItal::Normal},
ital: indexset! {FontStyle::Normal},
variable_axes: None
},
"optional"
......@@ -461,7 +431,7 @@ mod tests {
"Roboto Serif",
&FontAxes {
wght: indexset! {"500".to_owned()},
ital: indexset! {FontItal::Normal},
ital: indexset! {FontStyle::Normal},
variable_axes: Some(vec![
("GRAD".to_owned(), "-50..100".to_owned()),
("opsz".to_owned(), "8..144".to_owned()),
......@@ -484,7 +454,7 @@ mod tests {
"Roboto Serif",
&FontAxes {
wght: indexset! {"500".to_owned(), "300".to_owned()},
ital: indexset! {FontItal::Normal, FontItal::Italic},
ital: indexset! {FontStyle::Normal, FontStyle::Italic},
variable_axes: Some(vec![
("GRAD".to_owned(), "-50..100".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::{
embed_js::{next_js_fs, VIRTUAL_PACKAGE_NAME},
next_client::context::ClientContextType,
next_config::NextConfigVc,
next_font_google::{NextFontGoogleCssModuleReplacerVc, NextFontGoogleReplacerVc},
next_font::google::{NextFontGoogleCssModuleReplacerVc, NextFontGoogleReplacerVc},
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