|
|
import { nextFontError } from '../next-font-error' |
|
|
|
|
|
const NORMAL_WEIGHT = 400 |
|
|
const BOLD_WEIGHT = 700 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function getWeightNumber(weight: string) { |
|
|
return weight === 'normal' |
|
|
? NORMAL_WEIGHT |
|
|
: weight === 'bold' |
|
|
? BOLD_WEIGHT |
|
|
: Number(weight) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function getDistanceFromNormalWeight(weight?: string) { |
|
|
if (!weight) return 0 |
|
|
|
|
|
|
|
|
const [firstWeight, secondWeight] = weight |
|
|
.trim() |
|
|
.split(/ +/) |
|
|
.map(getWeightNumber) |
|
|
|
|
|
if (Number.isNaN(firstWeight) || Number.isNaN(secondWeight)) { |
|
|
nextFontError( |
|
|
`Invalid weight value in src array: \`${weight}\`.\nExpected \`normal\`, \`bold\` or a number.` |
|
|
) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
if (!secondWeight) { |
|
|
return firstWeight - NORMAL_WEIGHT |
|
|
} |
|
|
|
|
|
|
|
|
if (firstWeight <= NORMAL_WEIGHT && secondWeight >= NORMAL_WEIGHT) { |
|
|
return 0 |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
const firstWeightDistance = firstWeight - NORMAL_WEIGHT |
|
|
const secondWeightDistance = secondWeight - NORMAL_WEIGHT |
|
|
if (Math.abs(firstWeightDistance) < Math.abs(secondWeightDistance)) { |
|
|
return firstWeightDistance |
|
|
} |
|
|
return secondWeightDistance |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function pickFontFileForFallbackGeneration< |
|
|
T extends { style?: string; weight?: string }, |
|
|
>(fontFiles: T[]): T { |
|
|
return fontFiles.reduce((usedFontFile, currentFontFile) => { |
|
|
if (!usedFontFile) return currentFontFile |
|
|
|
|
|
const usedFontDistance = getDistanceFromNormalWeight(usedFontFile.weight) |
|
|
const currentFontDistance = getDistanceFromNormalWeight( |
|
|
currentFontFile.weight |
|
|
) |
|
|
|
|
|
|
|
|
if ( |
|
|
usedFontDistance === currentFontDistance && |
|
|
(typeof currentFontFile.style === 'undefined' || |
|
|
currentFontFile.style === 'normal') |
|
|
) { |
|
|
return currentFontFile |
|
|
} |
|
|
|
|
|
const absUsedDistance = Math.abs(usedFontDistance) |
|
|
const absCurrentDistance = Math.abs(currentFontDistance) |
|
|
|
|
|
|
|
|
if (absCurrentDistance < absUsedDistance) return currentFontFile |
|
|
|
|
|
|
|
|
if ( |
|
|
absUsedDistance === absCurrentDistance && |
|
|
currentFontDistance < usedFontDistance |
|
|
) { |
|
|
return currentFontFile |
|
|
} |
|
|
|
|
|
return usedFontFile |
|
|
}) |
|
|
} |
|
|
|