elk/composables/fontSize.ts

40 lines
970 B
TypeScript
Raw Normal View History

2022-12-23 23:19:17 +00:00
import type { InjectionKey, Ref } from 'vue'
2022-12-23 22:47:13 +00:00
import { STORAGE_KEY_FONT_SIZE } from '~/constants'
2022-12-23 23:22:57 +00:00
const InjectionKeyFontSize = Symbol('fontSize') as InjectionKey<Ref<FontSize>>
const DEFAULT = 'md'
2022-12-23 22:47:13 +00:00
2022-12-23 23:22:57 +00:00
export type FontSize = 'xs' | 'sm' | 'md' | 'lg' | 'xl'
2022-12-23 23:19:17 +00:00
export function getFontSize() {
return inject(InjectionKeyFontSize)!
2022-12-23 22:47:13 +00:00
}
2022-12-23 23:22:57 +00:00
const fontSizeMap = {
2022-12-23 22:47:13 +00:00
xs: '13px',
sm: '14px',
md: '15px',
lg: '16px',
xl: '17px',
}
2022-12-23 23:19:17 +00:00
export async function setupFontSize() {
2022-12-23 23:22:57 +00:00
const fontSize = useCookie<FontSize>(STORAGE_KEY_FONT_SIZE, { default: () => DEFAULT })
2022-12-23 23:19:17 +00:00
getCurrentInstance()?.appContext.app.provide(InjectionKeyFontSize, fontSize)
if (!process.server) {
watchEffect(() => {
2022-12-23 23:22:57 +00:00
document.documentElement.style.setProperty('--font-size', fontSizeMap[fontSize.value || DEFAULT])
2022-12-23 23:19:17 +00:00
})
}
else {
useHead({
style: [
{
2022-12-23 23:22:57 +00:00
innerHTML: `:root { --font-size: ${fontSizeMap[fontSize.value || DEFAULT]}; }`,
2022-12-23 23:19:17 +00:00
},
],
})
}
2022-12-23 22:47:13 +00:00
}