Skip to content

Commit b2aa6c2

Browse files
committed
Use promises for tracking font loading because of Safari limitations
1 parent aa44890 commit b2aa6c2

7 files changed

Lines changed: 123 additions & 33 deletions

File tree

‎src/lib/font_family_names.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
'use strict';
2+
3+
/**
4+
* Split a CSS `font-family` value into lowercase family names without quotes.
5+
*
6+
* @param value - A `font-family` value, such as `"Open Sans", verdana, sans-serif`
7+
* @returns The family names in order. A comma inside quotes stays part of its name.
8+
*/
9+
export function fontFamilyNames(value: string): string[] {
10+
return (value.match(/"[^"]*"|'[^']*'|[^,]+/g) || []).map((name) =>
11+
name
12+
.trim()
13+
.replace(/^["']|["']$/g, '')
14+
.toLowerCase()
15+
);
16+
}

‎src/lib/index.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,8 @@ lib.cleanNumber = require('./clean_number').default;
219219

220220
lib.slugify = require('./slugify');
221221

222+
lib.fontFamilyNames = require('./font_family_names').fontFamilyNames;
223+
222224
lib.ensureNumber = function ensureNumber(v) {
223225
if (!isNumeric(v)) return BADNUM;
224226
v = Number(v);

‎src/plot_api/plot_api.js‎

Lines changed: 37 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -198,27 +198,8 @@ function _doPlot(gd, data, layout, config) {
198198
Lib.clearResponsive(gd);
199199
}
200200

201-
// A plot that draws before its web font loads measures its text with the fallback font.
202-
// Save the callback that clears the listener for teardown in `Plots.purge`.
203-
if (!gd._clearFontListener && document.fonts) {
204-
const onLoadingDone = (event) => {
205-
const families = event.fontfaces.map((face) => face.family.replace(/["']/g, '').toLowerCase());
206-
if (!families.length) return;
207-
208-
// Clear size cache to force new measurement with loaded fonts
209-
Drawing.savedBBoxes = {};
210-
211-
for (const node of gd.querySelectorAll('[style*="font-family"]')) {
212-
const fontFamily = node.style.fontFamily.toLowerCase();
213-
if (families.some((family) => fontFamily.includes(family))) {
214-
exports._doPlot(gd);
215-
return;
216-
}
217-
}
218-
};
219-
document.fonts.addEventListener('loadingdone', onLoadingDone);
220-
gd._clearFontListener = () => document.fonts.removeEventListener('loadingdone', onLoadingDone);
221-
}
201+
// Text measured while one of these faces loads uses the fallback font
202+
const unloadedFaces = document.fonts ? [...document.fonts].filter((face) => face.status !== 'loaded') : [];
222203

223204
/*
224205
* start async-friendly code - now we're actually drawing things
@@ -430,11 +411,46 @@ function _doPlot(gd, data, layout, config) {
430411
if (!plotDone || !plotDone.then) plotDone = Promise.resolve();
431412

432413
return plotDone.then(function () {
414+
redrawAfterFontLoads(gd, unloadedFaces);
433415
emitAfterPlot(gd);
434416
return gd;
435417
});
436418
}
437419

420+
/**
421+
* Redraw a plot after the web fonts that its text uses finish loading.
422+
*
423+
* A plot that draws before its web font loads measures its text with the fallback font.
424+
* The redraw happens after the draw that calls this function, once every face of a used family
425+
* that started or finished loading during the draw settles. A face that fails to load still settles.
426+
* A later draw or `Plots.purge` cancels a pending redraw.
427+
*
428+
* @param gd - The graph div that finished a draw
429+
* @param unloadedFaces - The faces in `document.fonts` that were not loaded when the draw started
430+
*/
431+
async function redrawAfterFontLoads(gd, unloadedFaces) {
432+
// The draw started these loads, or they finished during the draw
433+
const changedFaces = unloadedFaces.filter((face) => ['loaded', 'loading'].includes(face.status));
434+
if (!changedFaces.length) return;
435+
436+
const usedFamilies = new Set();
437+
for (const node of gd.querySelectorAll('[style*="font-family"]')) {
438+
for (const family of Lib.fontFamilyNames(node.style.fontFamily)) usedFamilies.add(family);
439+
}
440+
const faces = changedFaces.filter((face) => usedFamilies.has(Lib.fontFamilyNames(face.family)[0]));
441+
if (!faces.length) return;
442+
443+
const token = {};
444+
gd._fontLoadToken = token;
445+
await Promise.all(faces.map((face) => face.loaded.catch(() => {})));
446+
if (gd._fontLoadToken !== token) return;
447+
delete gd._fontLoadToken;
448+
449+
// Clear size cache to force new measurement with loaded fonts
450+
Drawing.savedBBoxes = {};
451+
exports._doPlot(gd);
452+
}
453+
438454
function emitAfterPlot(gd) {
439455
var fullLayout = gd._fullLayout;
440456

‎src/plots/plots.js‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1470,9 +1470,8 @@ plots.purge = function(gd) {
14701470
// remove responsive handler
14711471
Lib.clearResponsive(gd);
14721472

1473-
// Remove web font handler
1474-
gd._clearFontListener?.();
1475-
delete gd._clearFontListener;
1473+
// Cancel the pending redraw for web fonts
1474+
delete gd._fontLoadToken;
14761475

14771476
// data and layout
14781477
delete gd.data;

‎src/types/core/graph-div.internal.d.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,14 @@ export interface GraphContext extends Partial<Config> {
2828
* This is an HTMLDivElement with additional Plotly-specific properties.
2929
*/
3030
export interface GraphDiv extends HTMLDivElement {
31-
/** Removes the listener that redraws the plot when a web font it uses finishes loading */
32-
_clearFontListener?: () => void;
3331
/** Removes the listener that resizes the plot when `config.responsive` is on */
3432
_clearResponsive?: () => void;
3533
/** Resolved configuration plus internal context. */
3634
_context?: GraphContext;
3735
/** True while an inline edit is in progress (e.g. axis title rename). */
3836
_editing?: boolean;
37+
/** Identifies the pending redraw for web fonts. A later draw or a purge replaces or deletes the token. */
38+
_fontLoadToken?: object;
3939
/** Trace data after defaults are applied. */
4040
_fullData?: FullData[];
4141
/** Layout after defaults are applied. */

‎test/jasmine/tests/lib_test.js‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1996,6 +1996,45 @@ describe('Test lib.js:', function () {
19961996
});
19971997
});
19981998

1999+
describe('fontFamilyNames', () => {
2000+
it('should split a font stack into lowercase names', () => {
2001+
expect(Lib.fontFamilyNames('"Open Sans", verdana, Arial, sans-serif')).toEqual([
2002+
'open sans',
2003+
'verdana',
2004+
'arial',
2005+
'sans-serif'
2006+
]);
2007+
});
2008+
2009+
it('should return a single unquoted name', () => {
2010+
expect(Lib.fontFamilyNames('ReproMono')).toEqual(['repromono']);
2011+
});
2012+
2013+
it('should strip double and single quotes', () => {
2014+
expect(Lib.fontFamilyNames(`"Open Sans", 'Fira Code'`)).toEqual(['open sans', 'fira code']);
2015+
});
2016+
2017+
it('should keep a comma inside quotes as part of the name', () => {
2018+
expect(Lib.fontFamilyNames('"Foo, Bar", serif')).toEqual(['foo, bar', 'serif']);
2019+
expect(Lib.fontFamilyNames(`'Foo, Bar', serif`)).toEqual(['foo, bar', 'serif']);
2020+
});
2021+
2022+
it('should keep a longer name whole instead of matching a shorter one', () => {
2023+
expect(Lib.fontFamilyNames('"Open Sans Condensed", sans-serif')).toEqual([
2024+
'open sans condensed',
2025+
'sans-serif'
2026+
]);
2027+
});
2028+
2029+
it('should ignore spaces around names', () => {
2030+
expect(Lib.fontFamilyNames(' "Open Sans" , verdana ')).toEqual(['open sans', 'verdana']);
2031+
});
2032+
2033+
it('should return an empty array for an empty value', () => {
2034+
expect(Lib.fontFamilyNames('')).toEqual([]);
2035+
});
2036+
});
2037+
19992038
describe('isPlotDiv', function () {
20002039
it('should work on plain objects', function () {
20012040
expect(Lib.isPlotDiv({})).toBe(false);

‎test/jasmine/tests/plot_api_test.js‎

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3327,9 +3327,10 @@ describe('web font loading', () => {
33273327
});
33283328

33293329
// Each test adds a new family, so that no earlier measurement can be in the bBox cache
3330-
const addFace = () => {
3331-
face = new FontFace(`PlotlyTestFont${++faceCount}`, `url(${fontUrl})`);
3330+
const addFace = (name = `PlotlyTestFont${++faceCount}`) => {
3331+
face = new FontFace(name, `url(${fontUrl})`);
33323332
document.fonts.add(face);
3333+
// The family comes back as CSS, with quotes when the name needs them
33333334
return face.family;
33343335
};
33353336

@@ -3364,6 +3365,23 @@ describe('web font loading', () => {
33643365
.then(done, done.fail);
33653366
});
33663367

3368+
it('should redraw a plot whose quoted font family contains a comma', (done) => {
3369+
const fig = makeFigure(addFace(`PlotlyTest, Font${++faceCount}`));
3370+
let widthBeforeLoad;
3371+
3372+
Plotly.newPlot(gd, fig.data, fig.layout)
3373+
.then(() => {
3374+
expect(face.status).not.toBe('loaded');
3375+
widthBeforeLoad = legendWidth(gd);
3376+
return new Promise((resolve) => gd.once('plotly_afterplot', resolve));
3377+
})
3378+
.then(() => {
3379+
expect(face.status).toBe('loaded');
3380+
expect(legendWidth(gd)).not.toBe(widthBeforeLoad);
3381+
})
3382+
.then(done, done.fail);
3383+
});
3384+
33673385
it('should not redraw a plot that does not use the loaded font', (done) => {
33683386
addFace();
33693387
const fig = makeFigure('Arial');
@@ -3373,7 +3391,7 @@ describe('web font loading', () => {
33733391
spyOn(plotApi, '_doPlot').and.callThrough();
33743392
return face.load();
33753393
})
3376-
// The `loadingdone` event can fire after the load promise resolves
3394+
// `document.fonts.ready` can resolve after the load promise
33773395
.then(() => new Promise((resolve) => setTimeout(resolve, 100)))
33783396
.then(() => {
33793397
expect(plotApi._doPlot).not.toHaveBeenCalled();
@@ -3392,7 +3410,7 @@ describe('web font loading', () => {
33923410
spyOn(plotApi, '_doPlot').and.callThrough();
33933411
return face.loaded;
33943412
})
3395-
// The `loadingdone` event can fire after the load promise resolves
3413+
// `document.fonts.ready` can resolve after the load promise
33963414
.then(() => new Promise((resolve) => setTimeout(resolve, 100)))
33973415
.then(() => {
33983416
expect(plotApi._doPlot).toHaveBeenCalledTimes(1);
@@ -3406,15 +3424,15 @@ describe('web font loading', () => {
34063424
Plotly.newPlot(gd, fig.data, fig.layout)
34073425
.then(() => {
34083426
expect(face.status).not.toBe('loaded');
3409-
expect(gd._clearFontListener).toEqual(jasmine.any(Function));
3427+
expect(gd._fontLoadToken).toBeDefined();
34103428

34113429
Plotly.purge(gd);
3412-
expect(gd._clearFontListener).toBeUndefined();
3430+
expect(gd._fontLoadToken).toBeUndefined();
34133431

34143432
spyOn(plotApi, '_doPlot').and.callThrough();
34153433
return face.loaded;
34163434
})
3417-
// The `loadingdone` event can fire after the load promise resolves
3435+
// `document.fonts.ready` can resolve after the load promise
34183436
.then(() => new Promise((resolve) => setTimeout(resolve, 100)))
34193437
.then(() => {
34203438
expect(plotApi._doPlot).not.toHaveBeenCalled();

0 commit comments

Comments
 (0)