Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Catch errors when calculating avg font width #43503

Merged
merged 2 commits into from
Nov 29, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 18 additions & 13 deletions packages/font/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,24 @@ const DEFAULT_SERIF_FONT = {
}

function calcAverageWidth(font: Font): number | undefined {
const avgCharacters = 'aaabcdeeeefghiijklmnnoopqrrssttuvwxyz '
const hasAllChars = font
.glyphsForString(avgCharacters)
.flatMap((glyph) => glyph.codePoints)
.every((codePoint) => font.hasGlyphForCodePoint(codePoint))

if (!hasAllChars) return undefined

const widths = font
.glyphsForString(avgCharacters)
.map((glyph) => glyph.advanceWidth)
const totalWidth = widths.reduce((sum, width) => sum + width, 0)
return totalWidth / widths.length
try {
const avgCharacters = 'aaabcdeeeefghiijklmnnoopqrrssttuvwxyz '
const hasAllChars = font
.glyphsForString(avgCharacters)
.flatMap((glyph) => glyph.codePoints)
.every((codePoint) => font.hasGlyphForCodePoint(codePoint))

if (!hasAllChars) return undefined

const widths = font
.glyphsForString(avgCharacters)
.map((glyph) => glyph.advanceWidth)
const totalWidth = widths.reduce((sum, width) => sum + width, 0)
return totalWidth / widths.length
} catch {
// Could not calculate average width from the font file, skip size-adjust
return undefined
}
}

function formatOverrideValue(val: number) {
Expand Down