Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Issue #14 #74

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
84 changes: 84 additions & 0 deletions e2e-tests/development-runtime/cypress/integration/fonts.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,90 @@ describe(`fonts`, () => {
.and(`equal`, `400`);
});

it(`displays content with the self hosted font-style`, () => {
cy.getTestElement(`self-hosted-font`)
.should(`have.css`, `font-style`)
.and(`equal`, `normal`);
});

it(`displays content with the google font-family`, () => {
cy.getTestElement(`google-font`)
.should(`have.css`, `font-family`)
.and(`match`, /Roboto/);
});

it(`displays content with the google font-weight`, () => {
cy.getTestElement(`google-font`)
.should(`have.css`, `font-weight`)
.and(`equal`, `400`);
});

it(`displays content with the google font-style`, () => {
cy.getTestElement(`google-font`)
.should(`have.css`, `font-style`)
.and(`equal`, `normal`);
});

it(`displays content with the google2 font-family`, () => {
cy.getTestElement(`google2-font`)
.should(`have.css`, `font-family`)
.and(`match`, /Rubik/);
});

it(`displays content with the google2 font-weight`, () => {
cy.getTestElement(`google2-font`)
.should(`have.css`, `font-weight`)
.and(`equal`, `400`);
});

it(`displays content with the google2 font-style`, () => {
cy.getTestElement(`google2-font`)
.should(`have.css`, `font-style`)
.and(`equal`, `normal`);
});

it(`successfully generates CSS @font-face and it's descriptors for google`, () => {
cy.get(`head`)
.first()
.within(($head) => {
cy.get(`style`)
.should(`exist`)
.and(`contain`, `@font-face`)
.and(
`contain`,
`{font-display:swap;font-family:Rubik;font-style:normal;font-weight:300;src:url(/static/webfonts/s/rubik/v28/iJWZBXyIfDnIV5PNhY1KTN7Z-Yh-WYi1VQ.woff2) format("woff2"),url(/static/webfonts/s/rubik/v28/iJWZBXyIfDnIV5PNhY1KTN7Z-Yh-WYi1Uw.woff) format("woff")}`,
);
});
});

it(`successfully generates CSS @font-face and it's descriptors for google2`, () => {
cy.get(`head`)
.first()
.within(($head) => {
cy.get(`style`)
.should(`exist`)
.and(`contain`, `@font-face`)
.and(
`contain`,
`{font-display:swap;font-family:Rubik;font-style:normal;font-weight:300;src:url(/static/webfonts/s/rubik/v28/iJWZBXyIfDnIV5PNhY1KTN7Z-Yh-WYi1VQ.woff2) format("woff2"),url(/static/webfonts/s/rubik/v28/iJWZBXyIfDnIV5PNhY1KTN7Z-Yh-WYi1Uw.woff) format("woff")}`,
);
});
});

it(`successfully generates CSS @font-face and it's descriptors for self hosted`, () => {
cy.get(`head`)
.first()
.within(($head) => {
cy.get(`style`)
.should(`exist`)
.and(`contain`, `@font-face`)
.and(
`contain`,
`{font-display:swap;font-family:Open Sans;font-style:normal;font-weight:300;src:url(/static/webfonts/OpenSans300.woff2) format("woff2")}@font-face{font-display:swap;font-family:Open Sans;font-style:normal;font-weight:400;src:url(/static/webfonts/OpenSans400.woff2) format("woff2")}`,
);
});
});

it(`successfully loads fonts`, () => {
cy.document().its(`fonts.status`).should(`equal`, `loaded`);
});
Expand Down
18 changes: 18 additions & 0 deletions e2e-tests/development-runtime/src/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,24 @@ export default function App() {
>
Static Font Example
</Typography>
<Typography
variant="p"
component="p"
fontFamily="Roboto"
fontWeight={400}
data-testid="google-font"
>
Google Font Example
</Typography>
<Typography
variant="p"
component="p"
fontFamily="Rubik"
fontWeight={400}
data-testid="google2-font"
>
Google2 Font Example
</Typography>
<Link to="/about" color="secondary">
Go to the about page
</Link>
Expand Down
11 changes: 6 additions & 5 deletions gatsby-plugin-webfonts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ module.exports = {

## Self Hosted Fonts

Add your own self hosted font files. The plugin will handle the imports & preloading. Strategy is always `selfHosted`, subsets are already defined within your font file.
Add your own self hosted font files. The plugin will handle the imports & preloading. Strategy is always `selfHosted`, subsets are already defined within your font file, preconnect is unnecessary as the fonts will be served from your already connected host.

```javascript
module.exports = {
Expand All @@ -224,10 +224,10 @@ module.exports = {
urls: {
// src attributes
// path relative to gatsby project root
woff2: `/examplePath/filename.woff2`,
woff: `/examplePath/filename.woff`,
otf: `/examplePath/filename.otf`,
ttf: `/examplePath/filename.ttf`,
woff2: `/fonts/filename.woff2`,
woff: `/fonts/filename.woff`,
otf: `/fonts/filename.otf`,
ttf: `/fonts/filename.ttf`,
},
fontStyle: "light",
fontWeight: 300,
Expand All @@ -240,6 +240,7 @@ module.exports = {
};
```

Just put your font files in your desired location and include that location in the `urls` as per the above example.
As per gatsby docs it is recommended not to put fonts in the `/static` directory. This plugin will automatically be copy them across to `/public/webfonts/selfHosted`.

## License
Expand Down
58 changes: 28 additions & 30 deletions gatsby-plugin-webfonts/src/modules/selfHosted.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,41 +14,39 @@ export default function selfHosted(
const getFontFace = async (font) => {
const { family, urls, ...cssProperties } = createFontOptions(font);

const src = Object.entries(urls).map(([format, url]) => {
const sourcePath = path.join(directory, url);
if (!existsSync(sourcePath)) {
reporter.panicOnBuild(
`Specified selfHosted font file missing: "${sourcePath}"`,
);
return ``;
}
const src = Object.entries(urls)
.map(([format, url]) => {
const sourcePath = path.join(directory, url);
if (!existsSync(sourcePath)) {
reporter.panicOnBuild(
`Specified selfHosted font file missing: "${sourcePath}"`,
);
return ``;
}

const fileName = path.basename(url);
const cssDir = path.join(
pathPrefix ? pathPrefix : `/`,
`static`,
`webfonts`,
);
const fileName = path.basename(url);
const cssDir = path.join(
pathPrefix ? pathPrefix : `/`,
`static`,
`webfonts`,
);

if (!existsSync(cacheFolder)) {
mkdirSync(cacheFolder, { recursive: true }, (err) => {
reporter.error(err);
});
}
if (!existsSync(cacheFolder)) {
mkdirSync(cacheFolder, { recursive: true }, reporter.error);
}

const outputPath = path.join(cacheFolder, fileName);
const outputPath = path.join(cacheFolder, fileName);

copyFileSync(
sourcePath,
outputPath,
constants.COPYFILE_FICLONE,
(err) => {
reporter.error(err);
},
);
copyFileSync(
sourcePath,
outputPath,
constants.COPYFILE_FICLONE,
reporter.error,
);

return `url("${cssDir}/${fileName}") format("${format}")`;
});
return `url("${cssDir}/${fileName}") format("${format}")`;
})
.join(`, `);

const { css } = await postcss().process(cssProperties, {
parser: postcssJs,
Expand Down
11 changes: 8 additions & 3 deletions gatsby-plugin-webfonts/src/modules/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,15 @@ import postcssJs from "postcss-js";
function fontFaceReducer(fontDisplay = `swap`, useMerge) {
return (acc, obj) => {
if (useMerge) {
const { fontFamily, fontStyle, fontWeight } = obj;
const srcs = obj.src.split(`,`);

const index = acc.findIndex((element) => {
return element.src.split(`,`)[0] === srcs[0];
return (
element.fontFamily === fontFamily &&
element.fontWeight === fontWeight &&
element.fontStyle === fontStyle
);
});

if (index > -1) {
Expand All @@ -24,13 +29,13 @@ function fontFaceReducer(fontDisplay = `swap`, useMerge) {

obj.fontDisplay = fontDisplay;
acc.push(obj);

return acc;
};
}

export async function parseCss(cssString, { fontDisplay = `swap`, useMerge }) {
const root = postcss.parse(cssString);

const cssObject = postcssJs.objectify(root);

if (cssObject[`@font-face`]) {
Expand Down Expand Up @@ -102,7 +107,7 @@ export async function encodeFonts(css) {
const fontsEncoded = await Promise.all(
fontUrls.map(async (fontUrl) => {
const font = await downloadFont(fontUrl);
const format = path.extname(fontUrl).substr(1);
const format = path.extname(fontUrl).substring(1);
return `"data:application/x-font-${format};base64,${Buffer.from(
font,
`binary`,
Expand Down