Skip to content

Commit

Permalink
fix: font store load method skip loading (#1909)
Browse files Browse the repository at this point in the history
  • Loading branch information
diegomura authored Jul 2, 2022
1 parent d011983 commit 3acf53b
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/cuddly-dolls-burn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@react-pdf/font': patch
---

fix: font store load method skip loading
13 changes: 8 additions & 5 deletions packages/font/src/font.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,11 @@ class FontSource {
this.fontWeight = fontWeight || 400;

this.data = null;
this.loading = false;
this.options = options;
this.loadResultPromise = null;
}

async load() {
this.loading = true;

async _load() {
const { postscriptName } = this.options;

if (isDataUrl(this.src)) {
Expand All @@ -78,8 +76,13 @@ class FontSource {
),
);
}
}

this.loading = false;
async load() {
if (this.loadResultPromise === null) {
this.loadResultPromise = this._load();
}
return this.loadResultPromise;
}
}

Expand Down
4 changes: 1 addition & 3 deletions packages/font/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,7 @@ function FontStore() {
const f = this.getFont(descriptor);

// We cache the font to avoid fetching it many times
if (!f.data && !f.loading) {
await f.load();
}
await f.load();
};

this.reset = () => {
Expand Down
41 changes: 41 additions & 0 deletions packages/font/tests/font.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const path = require('path');
const fontkit = require('@react-pdf/fontkit');
const { default: FontStore } = require('../src/index');

global.BROWSER = false;

describe('FontStore', () => {
test('load method will wait for font loaded when parallel execution', async () => {
const openSpy = jest.spyOn(fontkit.default, 'open');
const fontStore = new FontStore();
const fontFamily = '思源';
fontStore.register({
family: fontFamily, // assume this is a chinese font
fonts: [
{
src: path.join(__dirname, '../../examples/public/Roboto-Bold.ttf'),
},
],
});

const getFontSource = () =>
fontStore.getRegisteredFonts()[fontFamily].sources[0];

const getFontData = () => getFontSource().data;

const makeSureFontLoadedAfterLoad = async () => {
expect(getFontData()).toBeNull();
await fontStore.load({
fontFamily,
});
expect(getFontData()).not.toBeNull();
};
return Promise.all([
makeSureFontLoadedAfterLoad(),
makeSureFontLoadedAfterLoad(),
]).then(() => {
// call load method twice but just call file open method once
expect(openSpy.mock.calls).toHaveLength(1);
});
});
});

0 comments on commit 3acf53b

Please sign in to comment.