Skip to content

Commit

Permalink
Catch errors when calculating avg font width (#43503)
Browse files Browse the repository at this point in the history
When calculating the avg width it's possible for `fontkit` to throw if it can't get the width of the glyphs for a font file. In that case skip the `size-adjust` property and use the other overrides.

#41745 (comment) here's an example of an error thrown by fontkit.

## 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)
  • Loading branch information
hanneslund committed Nov 29, 2022
1 parent 9159a6e commit fdff88b
Showing 1 changed file with 18 additions and 13 deletions.
31 changes: 18 additions & 13 deletions packages/font/src/utils.ts
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

0 comments on commit fdff88b

Please sign in to comment.