Skip to content

Commit

Permalink
feat(web-fonts): add fontshare provider (#1829)
Browse files Browse the repository at this point in the history
  • Loading branch information
catuhana committed Nov 2, 2022
1 parent c93b15d commit 2138013
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 1 deletion.
1 change: 1 addition & 0 deletions packages/preset-web-fonts/README.md
Expand Up @@ -71,6 +71,7 @@ Currently supported Providers:
- `none` - do nothing, treat the font as system font
- `google` - [Google Fonts](https://fonts.google.com/)
- `bunny` - [Privacy-Friendly Google Fonts](https://fonts.bunny.net/)
- `fontshare` - [Quality Font Service by ITF](https://www.fontshare.com/)

PR welcome to add more providers 🙌

Expand Down
2 changes: 2 additions & 0 deletions packages/preset-web-fonts/src/index.ts
Expand Up @@ -2,6 +2,7 @@ import type { Preset } from '@unocss/core'
import { toArray } from '@unocss/core'
import { BunnyFontsProvider } from './providers/bunny'
import { GoogleFontsProvider } from './providers/google'
import { FontshareProvider } from './providers/fontshare'
import { NoneProvider } from './providers/none'
import type { WebFontMeta, WebFontsOptions, WebFontsProviders } from './types'

Expand All @@ -24,6 +25,7 @@ export function normalizedFontMeta(meta: WebFontMeta | string, defaultProvider:
const providers = {
google: GoogleFontsProvider,
bunny: BunnyFontsProvider,
fontshare: FontshareProvider,
none: NoneProvider,
}

Expand Down
22 changes: 22 additions & 0 deletions packages/preset-web-fonts/src/providers/fontshare.ts
@@ -0,0 +1,22 @@
import type { Provider, WebFontsProviders } from '../types'

export const FontshareProvider: Provider = createFontshareProvider('fontshare', 'https://api.fontshare.com')

export function createFontshareProvider(name: WebFontsProviders, host: string): Provider {
return {
name,
getImportUrl(fonts) {
const strings = fonts.filter(f => f.provider === name).map((f) => {
let name = f.name.replace(/\s+/g, '-').toLocaleLowerCase()
if (f.weights?.length)
name += `@${f.weights.flatMap(w => f.italic ? Number(w) + 1 : w).sort().join()}`
else name += `@${f.italic ? 2 : 1}`
return `f[]=${name}`
}).join('&')
return `${host}/v2/css?${strings}&display=swap`
},
getFontName(font) {
return `"${font.name}"`
},
}
}
2 changes: 1 addition & 1 deletion packages/preset-web-fonts/src/types.ts
@@ -1,4 +1,4 @@
export type WebFontsProviders = 'google' | 'bunny' | 'none'
export type WebFontsProviders = 'google' | 'bunny' | 'fontshare' | 'none'

export interface WebFontMeta {
name: string
Expand Down

0 comments on commit 2138013

Please sign in to comment.