2
0

🚸 (theme) Improve custom font flow by asking for font-face props directly

This commit is contained in:
Baptiste Arnaud
2024-02-27 11:28:37 +01:00
parent b9e54686d5
commit 33d0fcd842
6 changed files with 66 additions and 23 deletions

View File

@ -1,32 +1,44 @@
import { isEmpty } from '@typebot.io/lib'
import { isNotEmpty } from '@typebot.io/lib'
import { Font } from '@typebot.io/schemas'
import { defaultTheme } from '@typebot.io/schemas/features/typebot/theme/constants'
const googleFontCdnBaseUrl = 'https://fonts.bunny.net/css2'
const elementId = 'typebot-font'
export const injectFont = (font: Font) => {
const existingFont = document.getElementById('bot-font')
const existingFont = document.getElementById(elementId)
if (typeof font === 'string' || font.type === 'Google') {
const fontFamily =
(typeof font === 'string' ? font : font.family) ??
defaultTheme.general.font.family
if (existingFont?.getAttribute('href')?.includes(fontFamily)) return
existingFont?.remove()
const fontElement = document.createElement('link')
fontElement.href = `${googleFontCdnBaseUrl}?family=${fontFamily}:ital,wght@0,300;0,400;0,600;1,300;1,400;1,600&display=swap`
fontElement.rel = 'stylesheet'
fontElement.id = 'bot-font'
fontElement.id = elementId
document.head.appendChild(fontElement)
return
}
if (font.type === 'Custom') {
if (existingFont?.getAttribute('href') === font.url || isEmpty(font.url))
return
const fontElement = document.createElement('link')
fontElement.href = font.url
fontElement.rel = 'stylesheet'
fontElement.id = 'bot-font'
document.head.appendChild(fontElement)
if (isNotEmpty(font.css)) {
if (existingFont?.innerHTML === font.css) return
existingFont?.remove()
const style = document.createElement('style')
style.innerHTML = font.css
style.id = elementId
document.head.appendChild(style)
}
if (isNotEmpty(font.url)) {
if (existingFont?.getAttribute('href') === font.url) return
existingFont?.remove()
const fontElement = document.createElement('link')
fontElement.href = font.url
fontElement.rel = 'stylesheet'
fontElement.id = elementId
document.head.appendChild(fontElement)
}
}
}

View File

@ -47,7 +47,8 @@ export type GoogleFont = z.infer<typeof googleFontSchema>
const customFontSchema = z.object({
type: z.literal(fontTypes[1]),
family: z.string().optional(),
url: z.string().optional(),
css: z.string().optional(),
url: z.string().optional().describe('Deprecated, use `css` instead'),
})
export type CustomFont = z.infer<typeof customFontSchema>