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

Catch errors when calculating avg font width (#43503)

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.

https://github.com/vercel/next.js/discussions/41745#discussioncomment-4245120 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)
parent 9159a6e7
...@@ -13,6 +13,7 @@ const DEFAULT_SERIF_FONT = { ...@@ -13,6 +13,7 @@ const DEFAULT_SERIF_FONT = {
} }
function calcAverageWidth(font: Font): number | undefined { function calcAverageWidth(font: Font): number | undefined {
try {
const avgCharacters = 'aaabcdeeeefghiijklmnnoopqrrssttuvwxyz ' const avgCharacters = 'aaabcdeeeefghiijklmnnoopqrrssttuvwxyz '
const hasAllChars = font const hasAllChars = font
.glyphsForString(avgCharacters) .glyphsForString(avgCharacters)
...@@ -26,6 +27,10 @@ function calcAverageWidth(font: Font): number | undefined { ...@@ -26,6 +27,10 @@ function calcAverageWidth(font: Font): number | undefined {
.map((glyph) => glyph.advanceWidth) .map((glyph) => glyph.advanceWidth)
const totalWidth = widths.reduce((sum, width) => sum + width, 0) const totalWidth = widths.reduce((sum, width) => sum + width, 0)
return totalWidth / widths.length return totalWidth / widths.length
} catch {
// Could not calculate average width from the font file, skip size-adjust
return undefined
}
} }
function formatOverrideValue(val: number) { function formatOverrideValue(val: number) {
......
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