Skip to content

Commit

Permalink
add fallback for monospace
Browse files Browse the repository at this point in the history
  • Loading branch information
Rishi Raj Jain committed Mar 14, 2024
1 parent 0e19ddc commit c27085c
Show file tree
Hide file tree
Showing 3 changed files with 918 additions and 913 deletions.
35 changes: 21 additions & 14 deletions packages/astro-font/font.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,23 @@ import type { Font } from 'fontkit'

// The font metadata of the fallback fonts, retrieved with fontkit on system font files
// The average width is calculated with the calcAverageWidth function below
const DEFAULT_SANS_SERIF_FONT = {
name: 'Arial',
azAvgWidth: 934.5116279069767,
unitsPerEm: 2048,
}

const DEFAULT_SERIF_FONT = {
name: 'Times New Roman',
azAvgWidth: 854.3953488372093,
unitsPerEm: 2048,
const fallbackFonts = {
serif: {
name: 'Times New Roman',
azAvgWidth: 854.3953488372093,
unitsPerEm: 2048,
},
monospace: {
name: 'Courier New',
azAvgWidth: 1145.9929435483877,
unitsPerEm: 2048,
},
'sans-serif': {
name: 'Arial',
azAvgWidth: 934.5116279069767,
unitsPerEm: 2048,
},
}

/**
Expand Down Expand Up @@ -69,17 +76,17 @@ function formatOverrideValue(val: number) {
* https://developer.chrome.com/blog/font-fallbacks/
* https://docs.google.com/document/d/e/2PACX-1vRsazeNirATC7lIj2aErSHpK26hZ6dA9GsQ069GEbq5fyzXEhXbvByoftSfhG82aJXmrQ_sJCPBqcx_/pub
*/
export function getFallbackMetricsFromFontFile(font: Font, category = 'serif') {
const fallbackFont = category === 'serif' ? DEFAULT_SERIF_FONT : DEFAULT_SANS_SERIF_FONT
export function getFallbackMetricsFromFontFile(font: Font, category: 'serif' | 'monospace' | 'sans-serif' = 'serif') {
const azAvgWidth = calcAverageWidth(font)
const fallbackFont = fallbackFonts[category]
const { ascent, descent, lineGap, unitsPerEm } = font
const fallbackFontAvgWidth = fallbackFont.azAvgWidth / fallbackFont.unitsPerEm
let sizeAdjust = azAvgWidth ? azAvgWidth / unitsPerEm / fallbackFontAvgWidth : 1
const sizeAdjust = azAvgWidth ? azAvgWidth / unitsPerEm / fallbackFontAvgWidth : 1
return {
fallbackFont: fallbackFont.name,
sizeAdjust: formatOverrideValue(sizeAdjust),
ascentOverride: formatOverrideValue(ascent / (unitsPerEm * sizeAdjust)),
descentOverride: formatOverrideValue(descent / (unitsPerEm * sizeAdjust)),
lineGapOverride: formatOverrideValue(lineGap / (unitsPerEm * sizeAdjust)),
fallbackFont: fallbackFont.name,
sizeAdjust: formatOverrideValue(sizeAdjust),
}
}
2 changes: 1 addition & 1 deletion packages/astro-font/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ interface Config {
fallbackName?: string
googleFontsURL?: string
cssVariable?: string | boolean
fallback: 'serif' | 'sans-serif'
fallback: 'serif' | 'sans-serif' | 'monospace'
}

export interface Props {
Expand Down

0 comments on commit c27085c

Please sign in to comment.