Skip to content

Commit

Permalink
Merge pull request #297 from taylrj/add-font-face
Browse files Browse the repository at this point in the history
Add fontfaces and the use-font-face-observer hook
  • Loading branch information
taylrj authored Aug 10, 2022
2 parents 18008e6 + 6e69640 commit 2bbec6a
Show file tree
Hide file tree
Showing 7 changed files with 126 additions and 11 deletions.
26 changes: 22 additions & 4 deletions packages/core/src/constants/font.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,32 @@
const merriweather = 'merriweather'
const notoSerifTC = 'Noto Serif TC'
const serif = 'serif'
const rosario = 'rosario'
const notoSansTC = 'Noto Sans TC'
const sansSerif = 'sans-serif'

const fonts = {
merriweather,
notoSerifTC,
serif,
rosario,
notoSansTC,
sansSerif,
}

const fontWeight = {
extraLight: '100',
normal: '400',
bold: '700',
}

const fontFamily = {
title: 'merriweather, Noto Serif TC, serif',
default: 'rosario, Noto Sans TC, sans-serif',
title: `${merriweather}, ${notoSerifTC}, ${serif}`,
default: `${rosario}, ${notoSansTC}, ${sansSerif}`,
// use defaultFallback before ${notoSansTC} is fully loaded
defaultFallback: `${rosario}, ${sansSerif}`,
}

export default { fontWeight, fontFamily }
export default { fonts, fontWeight, fontFamily }

export { fontWeight, fontFamily }
export { fonts, fontWeight, fontFamily }
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import Tools from './aside/desktop-tools'
// constants
import themeConst from '../constants/theme'
import colorConst from '../constants/color'
import typography from '../constants/typography'
import { RELATED_POST_ANCHOR_ID } from '../constants/anchor'
// @twreporter
import mq from '@twreporter/core/lib/utils/media-query'
Expand All @@ -29,10 +28,6 @@ const _ = {
get,
}

const fontFamilyCss = css`
font-family: ${typography.font.family.default};
`

const shiftLeftCss = css`
position: relative;
/* 20px is border-(right|left) width of articlePage */
Expand Down Expand Up @@ -181,7 +176,6 @@ const RelatedBlock = styled.div`
`

const BackgroundBlock = styled(BorderBox)`
${fontFamilyCss}
${props => getBackgroundBlockStyles(props.theme.name)}
@media print {
Expand Down
1 change: 1 addition & 0 deletions packages/react-components/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"dependencies": {
"@twreporter/core": "^1.4.2",
"@twreporter/redux": "^7.2.2",
"fontfaceobserver-es": "^3.3.3",
"hoist-non-react-statics": "^2.3.1",
"lodash": "^4.0.0",
"memoize-one": "^5.0.5",
Expand Down
4 changes: 3 additions & 1 deletion packages/react-components/src/hook/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import useOutsideClick from './use-outside-click'
import useFontFaceObserver from './use-font-face-observer'

export { useOutsideClick }
export { useOutsideClick, useFontFaceObserver }

export default {
useOutsideClick,
useFontFaceObserver,
}
36 changes: 36 additions & 0 deletions packages/react-components/src/hook/use-font-face-observer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { useState, useEffect } from 'react'
import FontFaceObserver from 'fontfaceobserver-es'

const useFontFaceObserver = (fontFaces = [], callback) => {
const [isResolved, setIsResolved] = useState(false)
const fontFacesString = JSON.stringify(fontFaces)

useEffect(() => {
const promises = JSON.parse(fontFacesString).map(
({ family, weight, style, stretch }) =>
new FontFaceObserver(family, {
weight,
style,
stretch,
}).load('測試文字')
)

Promise.all(promises)
.then(() => {
if (typeof callback !== 'function') {
return
}
callback()
return setIsResolved(true)
})
.catch(e => {
// eslint-disable-next-line no-console
console.error(`An error occurred during font loading`)
console.log(e)
})
}, [fontFacesString, callback])

return isResolved
}

export default useFontFaceObserver
59 changes: 59 additions & 0 deletions packages/react-components/src/text/utils/webfonts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { fonts, fontWeight } from '@twreporter/core/lib/constants/font'
// lodash
import forEach from 'lodash/forEach'
import keys from 'lodash/keys'
import reduce from 'lodash/reduce'

const _ = {
forEach,
keys,
reduce,
}

const baseGCSDir = 'https://www.twreporter.org/assets/font/'
const fileExt = '.woff2'

const gcsFontFolder = {
[fonts.notoSansTC]: 'NotoSansTC',
}

const fontWeightKeys = _.keys(fontWeight)

// add @font-face to global style to use self-hosted font for performance reasons, to be more precise please check the issue below:
// https://twreporter-org.atlassian.net/browse/TWREPORTER-318?atlOrigin=eyJpIjoiNjg4OTQ2MWU2MGIxNGEzMGE0NDY2ZDNmZGRhOWExZDEiLCJwIjoiaiJ9
const getFontFaces = ({ font, folder }) => {
const fontFaceCSSTemplate = ({ fontWeightKey }) => `
@font-face {
font-family: "${font}";
font-weight: ${fontWeight[fontWeightKey]};
font-display: swap;
src: url("${baseGCSDir}${folder}/${fontWeightKey}${fileExt}");
}
`
return _.reduce(
fontWeightKeys,
(fontFaces, fontWeightKey) => {
return fontFaces + fontFaceCSSTemplate({ fontWeightKey })
},
''
)
}

const fontFaces = {
[fonts.notoSansTC]: getFontFaces({
font: fonts.notoSansTC,
folder: gcsFontFolder[fonts.notoSansTC],
}),
}

let fontGCSFiles = []

_.forEach(fontFaces, function(fontFace, font) {
_.forEach(fontWeightKeys, fontWeightKey => {
fontGCSFiles.push(
`${baseGCSDir}${gcsFontFolder[font]}/${fontWeightKey}${fileExt}`
)
})
})

export default { fontFaces, fontGCSFiles }
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -8862,6 +8862,11 @@ follow-redirects@^1.0.0:
dependencies:
debug "^3.2.6"

fontfaceobserver-es@^3.3.3:
version "3.3.3"
resolved "https://registry.yarnpkg.com/fontfaceobserver-es/-/fontfaceobserver-es-3.3.3.tgz#b8fa6b774592c53d4ff98b031f97f15f9bdc4d83"
integrity sha512-1EyweL1ryy0koZWk80Kr0UgWq9KhbOl2cD6x1O8BtFu0gNqCWIXK1lVFSUb37DI5FMn1m86I6X7N1JRBy8wVfw==

for-in@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80"
Expand Down

1 comment on commit 2bbec6a

@vercel
Copy link

@vercel vercel bot commented on 2bbec6a Aug 10, 2022

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.