Skip to content

Commit

Permalink
fix: Font resolution logic (#437)
Browse files Browse the repository at this point in the history
Closes #421.
  • Loading branch information
shuding authored Apr 7, 2023
1 parent 8d5c7a6 commit 104964b
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/font.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,16 +262,23 @@ export default class FontLoader {

const cachedFontResolver = new Map<number, opentype.Font | undefined>()
const resolveFont = (word: string, fallback = true) => {
const code = word.charCodeAt(0)
if (cachedFontResolver.has(code)) return cachedFontResolver.get(code)

const _fonts = [
...fonts,
...additionalFonts,
...specifiedLangFonts,
...(fallback ? nonSpecifiedLangFonts : []),
]

if (typeof word === 'undefined') {
if (fallback) {
return _fonts[_fonts.length - 1]
}
return undefined
}

const code = word.charCodeAt(0)
if (cachedFontResolver.has(code)) return cachedFontResolver.get(code)

const font = _fonts.find((_font, index) => {
return (
!!_font.charToGlyphIndex(word) ||
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
22 changes: 22 additions & 0 deletions test/language.test.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import { it, describe, expect } from 'vitest'

import { initFonts, toImage } from './utils.js'
import satori from '../src/index.js'

import { detectLanguageCode } from '../src/language.js'

let fonts
initFonts((f) => (fonts = f))

describe('detectLanguageCode', () => {
it('should detect emoji', async () => {
expect(detectLanguageCode('🔺')).toBe('emoji')
Expand Down Expand Up @@ -91,4 +97,20 @@ describe('detectLanguageCode', () => {
it('should detect symbol', async () => {
expect(detectLanguageCode('☻')).toBe('symbol')
})

it('should not crash when rendering Arabic letters', async () => {
const svg = await satori(
<div
style={{
width: '100%',
height: '100%',
background: 'white',
}}
>
سلام
</div>,
{ width: 100, height: 100, fonts }
)
expect(toImage(svg, 100)).toMatchImageSnapshot()
})
})

1 comment on commit 104964b

@vercel
Copy link

@vercel vercel bot commented on 104964b Apr 7, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.