Skip to content

Commit

Permalink
⚡️ Prerender all fonts
Browse files Browse the repository at this point in the history
Co-authored-by: Rahul Tarak <[email protected]>
  • Loading branch information
wei and CryogenicPlanet committed Oct 22, 2020
1 parent 289dfbf commit 02c4499
Show file tree
Hide file tree
Showing 13 changed files with 1,571 additions and 71 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ git clone https://github.com/wei/socialify.git && cd socialify
mv .env.example .env

yarn install
yarn build
yarn dev
```

Expand Down
1,441 changes: 1,441 additions & 0 deletions common/fonts/devicon.css

Large diffs are not rendered by default.

15 changes: 15 additions & 0 deletions common/fonts/font.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* @jest-environment node
*/

import fontNames from './fonts.json'

import { Font } from '../types/configType'

describe('Verify Fonts', () => {
it('Check that all fonts exist', () => {
for (const item in Font) {
expect(item in fontNames).toBeTruthy()
}
})
})
8 changes: 8 additions & 0 deletions common/fonts/fonts.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"inter": "Inter",
"bitter": "Bitter",
"raleway": "Raleway",
"rokkitt": "Rokkitt",
"sourceCodePro": "Source Code Pro",
"koho": "KoHo"
}
22 changes: 21 additions & 1 deletion next.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,25 @@
const GoogleFontsPlugin = require('google-fonts-plugin')

const fontNames = require('./common/fonts/fonts.json')

module.exports = {
target: process.env.NETLIFY ? 'experimental-serverless-trace' : 'server',
target: 'experimental-serverless-trace',

webpack: config => {
config.plugins.push(
new GoogleFontsPlugin({
fonts: Object.values(fontNames).map(f => ({
family: f,
variants: ['200', '400', '500']
})),
filename: 'google-fonts.css',
formats: ['woff2']
})
)

return config
},

async rewrites() {
return [
{
Expand Down
8 changes: 3 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
"eslint-plugin-react": "^7.21.3",
"eslint-plugin-react-hooks": "^4.1.2",
"eslint-plugin-standard": "^4.0.1",
"google-fonts-plugin": "^5.0.2",
"graphql": "^15.3.0",
"graphql-compiler": "^1.7.0",
"husky": "^4.3.0",
Expand All @@ -92,9 +93,6 @@
]
},
"jest": {
"roots": [
"<rootDir>/src"
],
"collectCoverageFrom": [
"src/**/*.{js,jsx,ts,tsx}",
"!src/**/*.d.ts"
Expand All @@ -103,8 +101,8 @@
"<rootDir>/config/jest/setupTests.ts"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
"<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
"<rootDir>/**/__tests__/**/*.{js,jsx,ts,tsx}",
"<rootDir>/**/*.{spec,test}.{js,jsx,ts,tsx}"
],
"moduleNameMapper": {
"\\.(css|less)$": "identity-obj-proxy"
Expand Down
35 changes: 28 additions & 7 deletions pages/api/html.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { readFileSync } from 'fs'
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import { ServerStyleSheet } from 'styled-components'
Expand All @@ -11,16 +12,36 @@ import repoQuery from '../../common/relay/repoQuery'

import { repoQueryResponse } from '../../common/relay/__generated__/repoQuery.graphql'

import ConfigType, { OptionalConfigsKeys } from '../../common/types/configType'
import ConfigType, {
Font,
OptionalConfigsKeys
} from '../../common/types/configType'
import QueryType from '../../common/types/queryType'

import Card from '../../src/components/preview/card'
import { getOptionalConfig, defaultConfig } from '../../common/defaultConfig'

type Key = keyof typeof OptionalConfigsKeys

const cwd = process.cwd()

const devIconCSS = readFileSync(`${cwd}/common/fonts/devicon.css`).toString(
'utf-8'
)

const getGoogleFontCSS = (font: Font): string => {
const googleFontsCSS = readFileSync(`${cwd}/.next/google-fonts.css`).toString(
'utf-8'
)

return googleFontsCSS
.replace(/([{;])\n*\s*/g, '$1')
.split('\n')
.filter(f => f.startsWith(`@font-face {font-family: '${font}'`))
.join('\n')
}

export default async (req: NextApiRequest, res: NextApiResponse) => {
// 1. Get path and qs from req
const query = req.query as QueryType

const response = (await fetchQuery(enviornment, repoQuery, {
Expand Down Expand Up @@ -57,7 +78,6 @@ export default async (req: NextApiRequest, res: NextApiResponse) => {
}
}

// res.json({ query, config })
const sheet = new ServerStyleSheet()
const cardComponent = React.createElement(Card, config)
const cardHTMLMarkup = ReactDOMServer.renderToStaticMarkup(
Expand All @@ -68,7 +88,12 @@ export default async (req: NextApiRequest, res: NextApiResponse) => {
<html>
<meta charset="utf-8">
<title>Generated Image</title>
<link rel="icon" href="data:,">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
${devIconCSS}
${getGoogleFontCSS(config.font)}
</style>
${styleTags}
<body>
${cardHTMLMarkup}
Expand All @@ -79,8 +104,4 @@ export default async (req: NextApiRequest, res: NextApiResponse) => {
}
res.status(404).send('Not found')
}

// 4. render <Card config={config} /> into html
// 5. return
// 6. Add caching to graphql calls, convert relay to use get and api/graphql to use post and return cache headers
}
16 changes: 0 additions & 16 deletions src/components/preview/__snapshots__/card.test.tsx.snap
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,6 @@ exports[`Card #1 renders 1`] = `
}
}
>
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@200;400;500&display=swap"
rel="stylesheet"
/>
<link
href="https://cdn.jsdelivr.net/gh/devicons/devicon@master/devicon.min.css"
rel="stylesheet"
/>
<styled.div
className="card-logo-wrapper"
>
Expand Down Expand Up @@ -55,14 +47,6 @@ exports[`Card #2 renders 1`] = `
}
}
>
<link
href="https://fonts.googleapis.com/css2?family=KoHo:wght@200;400;500&display=swap"
rel="stylesheet"
/>
<link
href="https://cdn.jsdelivr.net/gh/devicons/devicon@master/devicon.min.css"
rel="stylesheet"
/>
<styled.div
className="card-logo-wrapper"
>
Expand Down
8 changes: 8 additions & 0 deletions src/components/preview/__snapshots__/preview.test.tsx.snap
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ exports[`Preview renders 1`] = `
className="preview-card-wrapper"
onClick={[Function]}
>
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@200;400;500&display=swap"
rel="stylesheet"
/>
<link
href="https://cdn.jsdelivr.net/gh/devicons/[email protected]/devicon.min.css"
rel="stylesheet"
/>
<Card
fileType="PNG"
font="Inter"
Expand Down
32 changes: 0 additions & 32 deletions src/components/preview/card.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,22 +27,6 @@ test('Card #1 renders', () => {
expect(card.hasClass('card-wrapper')).toBe(true)
expect(card.prop('style').fontFamily).toStrictEqual(config.font)
expect(card.hasClass(`theme-${config.theme.toLowerCase()}`)).toBe(true)
expect(
card.contains(
<link
href={`https://fonts.googleapis.com/css2?family=${config.font}:wght@200;400;500&display=swap`}
rel="stylesheet"
/>
)
).toBeTruthy()
expect(
card.contains(
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/gh/devicons/devicon@master/devicon.min.css"
/>
)
).toBeTruthy()
expect(card.find('.card-logo-wrapper i').length).toBe(1)
expect(
card.find('.card-logo-wrapper i').at(0).hasClass('devicon-github-plain')
Expand Down Expand Up @@ -98,22 +82,6 @@ test('Card #2 renders', () => {
expect(card.hasClass('card-wrapper')).toBe(true)
expect(card.prop('style').fontFamily).toStrictEqual(config.font)
expect(card.hasClass(`theme-${config.theme.toLowerCase()}`)).toBeTruthy()
expect(
card.contains(
<link
href={`https://fonts.googleapis.com/css2?family=${config.font}:wght@200;400;500&display=swap`}
rel="stylesheet"
/>
)
).toBeTruthy()
expect(
card.contains(
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/gh/devicons/devicon@master/devicon.min.css"
/>
)
).toBeTruthy()
expect(card.find('.card-name-name').text()).toStrictEqual(config.name)
expect(card.find('.card-logo-wrapper img').length).toBe(1)
expect(card.find('.card-logo-wrapper img').prop('src')).toBe(config.logo)
Expand Down
9 changes: 0 additions & 9 deletions src/components/preview/card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -128,15 +128,6 @@ const Card: React.FC<Configuration> = config => {
<CardWrapper
className={`card-wrapper theme-${config.theme.toLowerCase()}`}
style={{ fontFamily: config.font, backgroundImage: backgroundPattern }}>
<link
href={`https://fonts.googleapis.com/css2?family=${config.font}:wght@200;400;500&display=swap`}
rel="stylesheet"
/>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/gh/devicons/devicon@master/devicon.min.css"
/>

<CardLogoWrapper className="card-logo-wrapper">
{config.logo !== '' ? (
<img src={config.logo} alt="Custom logo"></img>
Expand Down
8 changes: 8 additions & 0 deletions src/components/preview/preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,14 @@ const Preview: React.FC = () => {
return (
<section className={styles['preview-wrapper']}>
<div className={styles['preview-card-wrapper']} onClick={copyImageUrl}>
<link
href={`https://fonts.googleapis.com/css2?family=${config.font}:wght@200;400;500&display=swap`}
rel="stylesheet"
/>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/gh/devicons/[email protected]/devicon.min.css"
/>
<Card {...config} />
<img
className={styles['preview-image-wrapper']}
Expand Down
39 changes: 38 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2373,6 +2373,13 @@ axe-core@^3.5.4:
resolved "https://registry.yarnpkg.com/axe-core/-/axe-core-3.5.5.tgz#84315073b53fa3c0c51676c588d59da09a192227"
integrity sha512-5P0QZ6J5xGikH780pghEdbEKijCTrruK9KxtPZCFWUpef0f6GipO+xEZ5GKCb020mmqgbiNO6TcA55CriL784Q==

axios@^0.19.0:
version "0.19.2"
resolved "https://registry.yarnpkg.com/axios/-/axios-0.19.2.tgz#3ea36c5d8818d0d5f8a8a97a6d36b86cdc00cb27"
integrity sha512-fjgm5MvRHLhx+osE2xoekY70AhARk3a6hkN+3Io1jc00jtquGvxYlKlsFUhmUET0V5te6CcZI7lcv2Ym61mjHA==
dependencies:
follow-redirects "1.5.10"

axobject-query@^2.1.2:
version "2.2.0"
resolved "https://registry.yarnpkg.com/axobject-query/-/axobject-query-2.2.0.tgz#943d47e10c0b704aa42275e20edf3722648989be"
Expand Down Expand Up @@ -3523,6 +3530,13 @@ debug@4, debug@^4.0.1, debug@^4.1.0, debug@^4.1.1:
dependencies:
ms "2.1.2"

debug@=3.1.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/debug/-/debug-3.1.0.tgz#5bb5a0672628b64149566ba16819e61518c67261"
integrity sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==
dependencies:
ms "2.0.0"

debug@^2.2.0, debug@^2.3.3, debug@^2.6.9:
version "2.6.9"
resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f"
Expand Down Expand Up @@ -4565,7 +4579,7 @@ fill-range@^7.0.1:
dependencies:
to-regex-range "^5.0.1"

[email protected]:
[email protected], find-cache-dir@^3.0.0:
version "3.3.1"
resolved "https://registry.yarnpkg.com/find-cache-dir/-/find-cache-dir-3.3.1.tgz#89b33fad4a4670daa94f855f7fbe31d6d84fe880"
integrity sha512-t2GDMt3oGC/v+BMwzmllWDuJF/xcDtE5j/fCGbqDD7OLuJkj0cfh1YSA5VKPvwMeLFLNDBkwOKZ2X85jGLVftQ==
Expand Down Expand Up @@ -4634,6 +4648,13 @@ flush-write-stream@^1.0.0:
inherits "^2.0.3"
readable-stream "^2.3.6"

[email protected]:
version "1.5.10"
resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.5.10.tgz#7b7a9f9aea2fdff36786a94ff643ed07f4ff5e2a"
integrity sha512-0V5l4Cizzvqt5D44aTXbFZz+FtyXV1vrDN6qrelxtfYQKW0KO0W2T/hkE8xvGa/540LkZlkaUjO4ailYTFtHVQ==
dependencies:
debug "=3.1.0"

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 Expand Up @@ -4838,6 +4859,15 @@ globby@^11.0.1:
merge2 "^1.3.0"
slash "^3.0.0"

google-fonts-plugin@^5.0.2:
version "5.0.2"
resolved "https://registry.yarnpkg.com/google-fonts-plugin/-/google-fonts-plugin-5.0.2.tgz#fb5d9f1758513006606badb81583c088592895cd"
integrity sha512-KYpJ9RbjIEmd5Q45GeNnsUyz4ca2R9L8GWZjbdnTWxOV+59Q300q2cFIcDtGpdkEjrh8ARVK9nOLAYRR9eAU4w==
dependencies:
axios "^0.19.0"
find-cache-dir "^3.0.0"
pkg-up "^3.1.0"

graceful-fs@^4.1.11, graceful-fs@^4.1.15, graceful-fs@^4.1.2, graceful-fs@^4.2.4:
version "4.2.4"
resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.4.tgz#2256bde14d3632958c465ebc96dc467ca07a29fb"
Expand Down Expand Up @@ -7181,6 +7211,13 @@ pkg-dir@^4.1.0, pkg-dir@^4.2.0:
dependencies:
find-up "^4.0.0"

pkg-up@^3.1.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/pkg-up/-/pkg-up-3.1.0.tgz#100ec235cc150e4fd42519412596a28512a0def5"
integrity sha512-nDywThFk1i4BQK4twPQ6TA4RT8bDY96yeuCVBWL3ePARCiEKDRSrNGbFIgUJpLp+XeIR65v8ra7WuJOFUBtkMA==
dependencies:
find-up "^3.0.0"

[email protected]:
version "1.3.3"
resolved "https://registry.yarnpkg.com/platform/-/platform-1.3.3.tgz#646c77011899870b6a0903e75e997e8e51da7461"
Expand Down

0 comments on commit 02c4499

Please sign in to comment.