Unverified Commit df8dde77 authored by Hannes Bornö's avatar Hannes Bornö Committed by GitHub

Refactoring in @next/font (#43848)

Some refactoring, renaming and fixed comments in @next/font

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [ ]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent 589f090d
...@@ -5,7 +5,6 @@ import { calculateSizeAdjustValues } from 'next/dist/server/font-utils' ...@@ -5,7 +5,6 @@ import { calculateSizeAdjustValues } from 'next/dist/server/font-utils'
import * as Log from 'next/dist/build/output/log' import * as Log from 'next/dist/build/output/log'
// @ts-ignore // @ts-ignore
import chalk from 'next/dist/compiled/chalk' import chalk from 'next/dist/compiled/chalk'
// @ts-ignore
import { import {
fetchCSSFromGoogleFonts, fetchCSSFromGoogleFonts,
fetchFontFile, fetchFontFile,
...@@ -94,6 +93,17 @@ const downloadGoogleFonts: FontLoader = async ({ ...@@ -94,6 +93,17 @@ const downloadGoogleFonts: FontLoader = async ({
} }
} }
const result = {
fallbackFonts: fallback,
weight:
weights.length === 1 && weights[0] !== 'variable'
? weights[0]
: undefined,
style: styles.length === 1 ? styles[0] : undefined,
variable,
adjustFontFallback: adjustFontFallbackMetrics,
}
try { try {
const hasCachedCSS = cssCache.has(url) const hasCachedCSS = cssCache.has(url)
let fontFaceDeclarations = hasCachedCSS let fontFaceDeclarations = hasCachedCSS
...@@ -156,7 +166,7 @@ const downloadGoogleFonts: FontLoader = async ({ ...@@ -156,7 +166,7 @@ const downloadGoogleFonts: FontLoader = async ({
} }
const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(googleFontFileUrl)![1] const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(googleFontFileUrl)![1]
// Emit font file to .next/static/fonts // Emit font file to .next/static/media
const selfHostedFileUrl = emitFontFile( const selfHostedFileUrl = emitFontFile(
fontFileBuffer, fontFileBuffer,
ext, ext,
...@@ -180,15 +190,8 @@ const downloadGoogleFonts: FontLoader = async ({ ...@@ -180,15 +190,8 @@ const downloadGoogleFonts: FontLoader = async ({
} }
return { return {
...result,
css: updatedCssResponse, css: updatedCssResponse,
fallbackFonts: fallback,
weight:
weights.length === 1 && weights[0] !== 'variable'
? weights[0]
: undefined,
style: styles.length === 1 ? styles[0] : undefined,
variable,
adjustFontFallback: adjustFontFallbackMetrics,
} }
} catch (err) { } catch (err) {
loaderContext.cacheable(false) loaderContext.cacheable(false)
...@@ -213,14 +216,8 @@ const downloadGoogleFonts: FontLoader = async ({ ...@@ -213,14 +216,8 @@ const downloadGoogleFonts: FontLoader = async ({
css += '\n}' css += '\n}'
return { return {
...result,
css, css,
fallbackFonts: fallback,
weight:
weights.length === 1 && weights[0] !== 'variable'
? weights[0]
: undefined,
style: styles.length === 1 ? styles[0] : undefined,
variable,
} }
} else { } else {
throw err throw err
......
...@@ -4,7 +4,7 @@ import { webpack } from 'next/dist/compiled/webpack/webpack' ...@@ -4,7 +4,7 @@ import { webpack } from 'next/dist/compiled/webpack/webpack'
import { loader, plugin } from '../../helpers' import { loader, plugin } from '../../helpers'
import { ConfigurationContext, ConfigurationFn, pipe } from '../../utils' import { ConfigurationContext, ConfigurationFn, pipe } from '../../utils'
import { getCssModuleLoader, getGlobalCssLoader } from './loaders' import { getCssModuleLoader, getGlobalCssLoader } from './loaders'
import { getFontLoader } from './loaders/font-loader' import { getNextFontLoader } from './loaders/next-font'
import { import {
getCustomDocumentError, getCustomDocumentError,
getGlobalImportError, getGlobalImportError,
...@@ -188,7 +188,6 @@ export const css = curry(async function css( ...@@ -188,7 +188,6 @@ export const css = curry(async function css(
]) ])
: undefined : undefined
// Font loaders cannot be imported in _document.
fontLoaders?.forEach(([fontLoaderPath, fontLoaderOptions]) => { fontLoaders?.forEach(([fontLoaderPath, fontLoaderOptions]) => {
// Matches the resolved font loaders noop files to run next-font-loader // Matches the resolved font loaders noop files to run next-font-loader
fns.push( fns.push(
...@@ -197,7 +196,11 @@ export const css = curry(async function css( ...@@ -197,7 +196,11 @@ export const css = curry(async function css(
markRemovable({ markRemovable({
sideEffects: false, sideEffects: false,
test: fontLoaderPath, test: fontLoaderPath,
use: getFontLoader(ctx, lazyPostCSSInitializer, fontLoaderOptions), use: getNextFontLoader(
ctx,
lazyPostCSSInitializer,
fontLoaderOptions
),
}), }),
], ],
}) })
......
...@@ -3,7 +3,7 @@ import { ConfigurationContext } from '../../../utils' ...@@ -3,7 +3,7 @@ import { ConfigurationContext } from '../../../utils'
import { getClientStyleLoader } from './client' import { getClientStyleLoader } from './client'
import { cssFileResolve } from './file-resolve' import { cssFileResolve } from './file-resolve'
export function getFontLoader( export function getNextFontLoader(
ctx: ConfigurationContext, ctx: ConfigurationContext,
postcss: any, postcss: any,
fontLoaderOptions: any fontLoaderOptions: any
......
...@@ -4,7 +4,7 @@ import { promises as fs } from 'fs' ...@@ -4,7 +4,7 @@ import { promises as fs } from 'fs'
import path from 'path' import path from 'path'
import chalk from 'next/dist/compiled/chalk' import chalk from 'next/dist/compiled/chalk'
import loaderUtils from 'next/dist/compiled/loader-utils3' import loaderUtils from 'next/dist/compiled/loader-utils3'
import postcssFontLoaderPlugn from './postcss-font-loader' import postcssNextFontPlugin from './postcss-next-font'
import { promisify } from 'util' import { promisify } from 'util'
import { CONFIG_FILES } from '../../../../shared/lib/constants' import { CONFIG_FILES } from '../../../../shared/lib/constants'
...@@ -110,7 +110,7 @@ export default async function nextFontLoader(this: any) { ...@@ -110,7 +110,7 @@ export default async function nextFontLoader(this: any) {
) )
// Add CSS classes, exports and make the font-family localy scoped by turning it unguessable // Add CSS classes, exports and make the font-family localy scoped by turning it unguessable
const result = await postcss( const result = await postcss(
postcssFontLoaderPlugn({ postcssNextFontPlugin({
exports, exports,
fontFamilyHash, fontFamilyHash,
fallbackFonts, fallbackFonts,
......
import type { AdjustFontFallback } from '../../../../font' import type { AdjustFontFallback } from '../../../../font'
import postcss, { Declaration } from 'postcss' import postcss, { Declaration } from 'postcss'
const postcssFontLoaderPlugn = ({ const postcssNextFontPlugin = ({
exports, exports,
fontFamilyHash, fontFamilyHash,
fallbackFonts = [], fallbackFonts = [],
...@@ -19,7 +19,7 @@ const postcssFontLoaderPlugn = ({ ...@@ -19,7 +19,7 @@ const postcssFontLoaderPlugn = ({
style?: string style?: string
}) => { }) => {
return { return {
postcssPlugin: 'postcss-font-loader', postcssPlugin: 'postcss-next-font',
Once(root: any) { Once(root: any) {
let fontFamily: string | undefined let fontFamily: string | undefined
...@@ -32,7 +32,7 @@ const postcssFontLoaderPlugn = ({ ...@@ -32,7 +32,7 @@ const postcssFontLoaderPlugn = ({
return `'__${family.replace(/ /g, '_')}_${fontFamilyHash}'` return `'__${family.replace(/ /g, '_')}_${fontFamilyHash}'`
} }
// Hash font-family name // Hash font-family names
for (const node of root.nodes) { for (const node of root.nodes) {
if (node.type === 'atrule' && node.name === 'font-face') { if (node.type === 'atrule' && node.name === 'font-face') {
const familyNode = node.nodes.find( const familyNode = node.nodes.find(
...@@ -118,6 +118,7 @@ const postcssFontLoaderPlugn = ({ ...@@ -118,6 +118,7 @@ const postcssFontLoaderPlugn = ({
...(adjustFontFallbackFamily ? [adjustFontFallbackFamily] : []), ...(adjustFontFallbackFamily ? [adjustFontFallbackFamily] : []),
...fallbackFonts, ...fallbackFonts,
].join(', ') ].join(', ')
// Add class with family, weight and style // Add class with family, weight and style
const classRule = new postcss.Rule({ selector: '.className' }) const classRule = new postcss.Rule({ selector: '.className' })
classRule.nodes = [ classRule.nodes = [
...@@ -171,6 +172,6 @@ const postcssFontLoaderPlugn = ({ ...@@ -171,6 +172,6 @@ const postcssFontLoaderPlugn = ({
} }
} }
postcssFontLoaderPlugn.postcss = true postcssNextFontPlugin.postcss = true
export default postcssFontLoaderPlugn export default postcssNextFontPlugin
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