From 5421178d9eeba97232090f2ed89f6a8d7db19c48 Mon Sep 17 00:00:00 2001 From: Sergey Plotnikov <6223985+nul0m@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:05:19 +0100 Subject: [PATCH 1/6] Add config.fonts to load font files before the first draw and embed them in exports Text that plotly.js measures before a web font loads keeps the size of the fallback font, so titles, legends and margins do not fit the final text. An exported SVG cannot use the fonts of the page, so the exported text shows a fallback font. config.fonts gives plotly.js the font data, as a URL, a base64 data URL or the bytes. plotly.js loads these faces before it measures text. SVG exports embed the faces that the image uses, if the font file permits embedding. See #8056. --- draftlogs/0000_add.md | 1 + lib/index.d.ts | 1 + src/lib/font_faces.ts | 340 +++++++++++++++++++++++++++++ src/plot_api/plot_api.js | 14 +- src/plot_api/plot_config.js | 16 ++ src/snapshot/tosvg.js | 5 + src/types/core/config.d.ts | 29 ++- src/types/generated/schema.d.ts | 5 + test/jasmine/assets/test_fonts.js | 18 ++ test/jasmine/tests/config_test.js | 87 ++++++++ test/jasmine/tests/lib_test.js | 40 ++++ test/jasmine/tests/toimage_test.js | 60 +++++ test/plot-schema.json | 5 + 13 files changed, 616 insertions(+), 5 deletions(-) create mode 100644 draftlogs/0000_add.md create mode 100644 src/lib/font_faces.ts create mode 100644 test/jasmine/assets/test_fonts.js diff --git a/draftlogs/0000_add.md b/draftlogs/0000_add.md new file mode 100644 index 00000000000..4aa8d2b6533 --- /dev/null +++ b/draftlogs/0000_add.md @@ -0,0 +1 @@ +- Add `config.fonts`, which loads fonts before the graph draws and embeds them in exported images [[#0000](https://github.com/plotly/plotly.js/pull/0000)], with thanks to @nul0m for the contribution! diff --git a/lib/index.d.ts b/lib/index.d.ts index 583bd7811a3..df831b49a7c 100644 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -69,6 +69,7 @@ export type { export type { Config, DownloadImgopts, + FontSource, ToImageButtonOptions, ToImgopts } from '../src/types/core/config'; diff --git a/src/lib/font_faces.ts b/src/lib/font_faces.ts new file mode 100644 index 00000000000..0d076ff5a62 --- /dev/null +++ b/src/lib/font_faces.ts @@ -0,0 +1,340 @@ +'use strict'; + +import * as Lib from './index'; +import type { FontSource } from '../types/core/config'; + +// lib/index.js builds its exports at run time, so TypeScript cannot type them. +// Read warn at call time, so that a spy on Lib.warn sees the warnings. +const warn = (...args: unknown[]) => (Lib as unknown as { warn: (...a: unknown[]) => void }).warn(...args); + +/** Time limit for the download of one font file, in milliseconds */ +const DOWNLOAD_TIMEOUT = 10000; + +/** Export formats that put the font bytes in a file that the user keeps */ +const DOCUMENT_FORMATS = ['svg', 'pdf', 'eps']; + +/** The tag of the OpenType table that holds the embedding permission, 'OS/2' */ +const OS2_TAG = 0x4f532f32; + +/** Font container formats by the first four bytes of the file */ +const SIGNATURES: Record = { + 0x00010000: 'truetype', + 0x74727565: 'truetype', + 0x4f54544f: 'opentype', + 0x774f4646: 'woff', + 0x774f4632: 'woff2' +}; + +const MIME_TYPES: Record = { + truetype: 'font/ttf', + opentype: 'font/otf', + woff: 'font/woff', + woff2: 'font/woff2' +}; + +type Permission = 'embed' | 'forbid' | 'unknown'; +type Source = string | ArrayBuffer | ArrayBufferView; + +interface Face { + family: string; + weight: string; + style: string; + loading: Promise; + loaded: boolean; + settled: boolean; + permission: Permission; + bytes?: ArrayBuffer; + format?: string; + rule?: string; + warned?: boolean; +} + +// Faces by descriptors and source. Two byte sources with equal bytes are the same source. +const faces = new Map(); +// The content keys of byte sources, so that each buffer gets one hash +const byteKeys = new WeakMap(); +// Items of config.fonts that produced a warning already +const warnedItems = new WeakSet(); + +/** + * Load the faces of `config.fonts` before the graph draws. + * Each face downloads and loads one time. Later graphs use the same face. + * + * @param fonts - the `fonts` value of the graph config + * @returns undefined if no face must load. Otherwise a promise that resolves after the faces load or fail. + * The promise resolves to true if a face loaded during the wait. + * A face that fails produces a warning. The promise does not reject. + */ +export function loadFonts(fonts: unknown): Promise | undefined { + if (!Array.isArray(fonts) || !fonts.length) return; + if (typeof FontFace === 'undefined' || !document.fonts) return; + + const pending: Promise[] = []; + for (const font of fonts) { + const face = findFace(font, true); + if (!face) { + if (font && typeof font === 'object' && !warnedItems.has(font)) { + warnedItems.add(font); + warn('config.fonts: each item must have a *family* string and a *source*.', font); + } + continue; + } + if (!face.settled) pending.push(face.loading); + } + if (!pending.length) return; + + return Promise.all(pending).then((loaded) => loaded.indexOf(true) !== -1); +} + +/** + * Make the `@font-face` rules that embed the faces of `config.fonts` in an exported SVG. + * An SVG image cannot use the fonts of the page, so the SVG must hold the font bytes. + * + * @param fonts - the `fonts` value of the graph config + * @param svg - the serialized SVG. A face gets a rule only if the SVG names its family. + * @param format - the export format. For *svg*, *pdf* and *eps*, a face gets a rule only if + * its font file permits embedding. + * @returns the CSS text for a ``); + return s; }; diff --git a/src/types/core/config.d.ts b/src/types/core/config.d.ts index f705374e90f..d514bddabbc 100644 --- a/src/types/core/config.d.ts +++ b/src/types/core/config.d.ts @@ -3,7 +3,7 @@ * * This file overlays a small hand-written interface on the schema-derived * `ConfigBase` to build `Config`. Most fields come straight from the schema. - * The overrides cover the five fields whose schema `valType` is `any`. Those + * The overrides cover the six fields whose schema `valType` is `any`. Those * fields accept a function value, an arbitrary-key map, or a structure too * irregular for the schema to model. */ @@ -50,14 +50,33 @@ export interface DownloadImgopts extends Omit { filename?: string; } +// --------------------------------------------------------------------------- +// Fonts +// --------------------------------------------------------------------------- + +/** + * One font face for `config.fonts`. plotly.js loads the face before the graph + * draws, and embeds it in exported images. + */ +export interface FontSource { + /** The family name that the figure uses in its `font.family` values */ + family: string; + /** The URL of a font file, a base64 data URL, or the font bytes */ + source: string | ArrayBuffer | ArrayBufferView; + /** The weight of the face, as in a CSS `@font-face` rule. The default is `'normal'`. */ + weight?: number | string; + /** The style of the face: `'normal'`, `'italic'` or `'oblique'`. The default is `'normal'`. */ + style?: string; +} + // --------------------------------------------------------------------------- // Config - hybrid (schema-derived + hand-written overrides) // --------------------------------------------------------------------------- /** - * Hand-written overrides for the five `schema.config` fields whose `valType` - * is `any`. These fields accept functions or arbitrary-key maps, which the - * JSON schema cannot describe. + * Hand-written overrides for the six `schema.config` fields whose `valType` + * is `any`. These fields accept functions, arbitrary-key maps or binary data, + * which the JSON schema cannot describe. */ interface ConfigOverrides { /** Override the background color with a static color name, or with a function that runs on each render */ @@ -70,6 +89,8 @@ interface ConfigOverrides { modeBarButtonsToRemove?: ModeBarDefaultButtons[]; /** Localization definitions under a locale id key, for example `'en-US'` or `'fr'` */ locales?: Record; format?: Record }>; + /** Fonts to load before the graph draws, and to embed in exported images */ + fonts?: FontSource[]; } /** diff --git a/src/types/generated/schema.d.ts b/src/types/generated/schema.d.ts index 6d1004a24f6..c7816cfc6bb 100644 --- a/src/types/generated/schema.d.ts +++ b/src/types/generated/schema.d.ts @@ -16863,6 +16863,11 @@ export interface ConfigBase { * @default false */ fillFrame?: boolean; + /** + * Sets the fonts that plotly.js loads before it draws the graph, and embeds in exported images. Each item is an object with a *family* string and a *source*, and an optional *weight* and *style* as in a CSS `@font-face` rule. The *source* is the URL of a font file, a base64 data URL, or the font bytes in an `ArrayBuffer` or a typed array. plotly.js measures text only after the fonts load. If a font does not load in 10 seconds, plotly.js logs a warning and draws with a fallback font. An export to *svg*, *pdf* or *eps* embeds a font only if the font file permits embedding. plotly.js cannot read that permission in a WOFF2 file, so these exports do not embed WOFF2 fonts. + * @default [] + */ + fonts?: any; /** * When `layout.autosize` is turned on, set the frame margins in fraction of the graph size. * @default 0 diff --git a/test/jasmine/assets/test_fonts.js b/test/jasmine/assets/test_fonts.js new file mode 100644 index 00000000000..5f7ea525c8a --- /dev/null +++ b/test/jasmine/assets/test_fonts.js @@ -0,0 +1,18 @@ +'use strict'; + +// Synthetic test fonts. Each character is a square glyph with an advance width of 1 em, +// so text of n characters at a font size of s px measures n * s px. +// The files differ only in the fsType field of the OS/2 table: 0 permits embedding, and 2 forbids it. +// The WOFF files compress their OS/2 table. +// Made with fontTools: FontBuilder(1000, isTTF=True), glyphs .notdef, space and square (a 800 x 700 box), +// cmap U+0020 to space and U+0021-U+007E and U+2212 to square, every advance width 1000, +// setupOS2(fsType=0 or 2), then flavor 'woff' for the WOFF files. +module.exports = { + square: 'data:font/ttf;base64,AAEAAAAKAIAAAwAgT1MvMkU8Z5YAAAEoAAAAYGNtYXBEk+ALAAABkAAAAPpnbHlm383fzAAAApQAAAA0aGVhZDDl6PIAAACsAAAANmhoZWEHCgOGAAAA5AAAACRobXR4A+gAyAAAAYgAAAAIbG9jYQANACcAAAKMAAAACG1heHAABQAGAAABCAAAACBuYW1lLbx8DAAAAsgAAACBcG9zdGft13cAAANMAAAALwABAAAAAQAALzPHnV8PPPUAAwPoAAAAAObz0qsAAAAA5vPSqwBkAAADhAK8AAAAAwACAAAAAAAAAAEAAAMg/zgAAAPoAGQAZAOEAAEAAAAAAAAAAAAAAAAAAAABAAEAAAADAAQAAQAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAwPoAZAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAQAAAAAAAAAAAPz8/PwAAACAiEgMg/zgAAAMgAMgAAAAAAAAAAAAAAAAAAAAgAAAD6ABkAAAAZAAAAAIAAAADAAAAFAADAAEAAAAUAAQA5gAAAAYABAABAAIAfiIS//8AAAAgIhL//wAA3fAAAQAGAAAAAAABAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAAAAAA0ADQAaAAEAZAAAA4QCvAADAAAzESERZAMgArz9RAAAAQBkAAADhAK8AAMAADMRIRFkAyACvP1EAAAAAAQANgABAAAAAAABABIAAAABAAAAAAACAAcAEgADAAEECQABACQAGQADAAEECQACAA4APVBsb3RseSBUZXN0IFNxdWFyZVJlZ3VsYXIAUABsAG8AdABsAHkAIABUAGUAcwB0ACAAUwBxAHUAYQByAGUAUgBlAGcAdQBsAGEAcgAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAADAQIGc3F1YXJlAA==', + squareRestricted: + 'data:font/ttf;base64,AAEAAAAKAIAAAwAgT1MvMkU+Z5YAAAEoAAAAYGNtYXBEk+ALAAABkAAAAPpnbHlm383fzAAAApQAAAA0aGVhZDDl6PIAAACsAAAANmhoZWEHCgOGAAAA5AAAACRobXR4A+gAyAAAAYgAAAAIbG9jYQANACcAAAKMAAAACG1heHAABQAGAAABCAAAACBuYW1lLbx8DAAAAsgAAACBcG9zdGft13cAAANMAAAALwABAAAAAQAALy/HnV8PPPUAAwPoAAAAAObz0qsAAAAA5vPSqwBkAAADhAK8AAAAAwACAAAAAAAAAAEAAAMg/zgAAAPoAGQAZAOEAAEAAAAAAAAAAAAAAAAAAAABAAEAAAADAAQAAQAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAwPoAZAABQACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAQAAAAAAAAAAAPz8/PwAAACAiEgMg/zgAAAMgAMgAAAAAAAAAAAAAAAAAAAAgAAAD6ABkAAAAZAAAAAIAAAADAAAAFAADAAEAAAAUAAQA5gAAAAYABAABAAIAfiIS//8AAAAgIhL//wAA3fAAAQAGAAAAAAABAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAAAAAA0ADQAaAAEAZAAAA4QCvAADAAAzESERZAMgArz9RAAAAQBkAAADhAK8AAMAADMRIRFkAyACvP1EAAAAAAQANgABAAAAAAABABIAAAABAAAAAAACAAcAEgADAAEECQABACQAGQADAAEECQACAA4APVBsb3RseSBUZXN0IFNxdWFyZVJlZ3VsYXIAUABsAG8AdABsAHkAIABUAGUAcwB0ACAAUwBxAHUAYQByAGUAUgBlAGcAdQBsAGEAcgAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAADAQIGc3F1YXJlAA==', + squareWoff: + 'data:font/woff;base64,d09GRgABAAAAAAKEAAoAAAAAA3wAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABZAAAAC8AAABgRTxnlmNtYXAAAAGcAAAANgAAAPpEk+ALZ2x5ZgAAAdwAAAAlAAAANN/N38xoZWFkAAAA9AAAADYAAAA2MOXo8mhoZWEAAAEsAAAAHgAAACQHCgOGaG10eAAAAZQAAAAIAAAACAPoAMhsb2NhAAAB1AAAAAgAAAAIAA0AJ21heHAAAAFMAAAAGAAAACAABQAGbmFtZQAAAgQAAABnAAAAgS28fAxwb3N0AAACbAAAABgAAAAvZ+3XdwABAAAAAQAALzPHnV8PPPUAAwPoAAAAAObz0qsAAAAA5vPSqwBkAAADhAK8AAAAAwACAAAAAAAAeJxjYGRgYFb4bwEkXzCkMKQwtzAARVAAIwBbAQOYAAB4nGNgZGBgYGZgYQDRDAxMDGgAAAEtAAx4nGNgZn7BOIGBlYEYwAjEDjCOPRAAKQUlIWaF/xYMDMwKDCfQ1CswMAAA+xsFewAD6ABkAAAAZHicY2BgYGJgYGAGYhEgyQimWRieAWk2IM0IlK1TEvr/H8hXgNB3PwBF2RhAACQ7ZCEAzzoIvAAAAAAADQANABp4nGNgZEhhYGBuYdrDwMzAYCyoKJjCrMC0568LAwNOGQDYEglTAAAAeJwtiDEKgDAQBCcqiI2FnV0K32DnH0TzgRTB5kCMSeHvvYgDu+ws0DBjKBiGrwsVrVqNaTp9JsZ/V/Qsq5xJHuvCnex+ZR/DFo4sPrIinCTtB4sjcKtZdi4ynqjPpjnUpPgLtDAUZgB4nGNgYsAPmEGYkYmtuLA0sSgVAAo9AqM=', + squareRestrictedWoff: + 'data:font/woff;base64,d09GRgABAAAAAAKEAAoAAAAAA3wAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABZAAAADAAAABgRT5nlmNtYXAAAAGcAAAANgAAAPpEk+ALZ2x5ZgAAAdwAAAAlAAAANN/N38xoZWFkAAAA9AAAADYAAAA2MOXo8mhoZWEAAAEsAAAAHgAAACQHCgOGaG10eAAAAZQAAAAIAAAACAPoAMhsb2NhAAAB1AAAAAgAAAAIAA0AJ21heHAAAAFMAAAAGAAAACAABQAGbmFtZQAAAgQAAABnAAAAgS28fAxwb3N0AAACbAAAABgAAAAvZ+3XdwABAAAAAQAALy/HnV8PPPUAAwPoAAAAAObz0qsAAAAA5vPSqwBkAAADhAK8AAAAAwACAAAAAAAAeJxjYGRgYFb4bwEkXzCkMKQwtzAARVAAIwBbAQOYAAB4nGNgZGBgYGZgYQDRDAxMDGgAAAEtAAx4nGNgZn7BOIGBlYGJgTBgBGIHGMceCICUgpIQs8J/CwYGZgWGE2jqFRgYAPvJBX0D6ABkAAAAZHicY2BgYGJgYGAGYhEgyQimWRieAWk2IM0IlK1TEvr/H8hXgNB3PwBF2RhAACQ7ZCEAzzoIvAAAAAAADQANABp4nGNgZEhhYGBuYdrDwMzAYCyoKJjCrMC0568LAwNOGQDYEglTAAAAeJwtiDEKgDAQBCcqiI2FnV0K32DnH0TzgRTB5kCMSeHvvYgDu+ws0DBjKBiGrwsVrVqNaTp9JsZ/V/Qsq5xJHuvCnex+ZR/DFo4sPrIinCTtB4sjcKtZdi4ynqjPpjnUpPgLtDAUZgB4nGNgYsAPmEGYkYmtuLA0sSgVAAo9AqM=' +}; diff --git a/test/jasmine/tests/config_test.js b/test/jasmine/tests/config_test.js index 6055da55216..ed98741ba5d 100644 --- a/test/jasmine/tests/config_test.js +++ b/test/jasmine/tests/config_test.js @@ -11,6 +11,7 @@ var click = require('../assets/click'); var mouseEvent = require('../assets/mouse_event'); var failTest = require('../assets/fail_test'); var delay = require('../assets/delay'); +const testFonts = require('../assets/test_fonts'); var RESIZE_DELAY = 300; @@ -1040,4 +1041,90 @@ describe('config argument', function() { .then(done, done.fail); }); }); + + describe('fonts:', () => { + let gd; + + beforeEach(() => { + gd = createGraphDiv(); + }); + + afterEach(destroyGraphDiv); + + // Each glyph of the test font is 1 em wide, so the title 'ABCDE' at 20px measures 100px + const layout = (family) => ({ + width: 400, + height: 300, + font: { family: `${family}, Arial` }, + title: { text: 'ABCDE', font: { size: 20 } } + }); + const titleWidth = () => gd.querySelector('.gtitle').getBoundingClientRect().width; + + it('should load the fonts before the graph draws', (done) => { + const family = 'ConfigFontsLoad'; + const promise = Plotly.newPlot(gd, [{ y: [1, 2] }], layout(family), { + fonts: [{ family, source: testFonts.square }] + }); + expect(gd.querySelector('.gtitle')).toBe(null, 'no title before the font loads'); + + promise + .then(() => { + expect(titleWidth()).toBeCloseTo(100, 0); + expect(document.fonts.check(`20px ${family}`)).toBe(true); + }) + .then(done, done.fail); + }); + + it('should draw synchronously when the fonts loaded before', (done) => { + const family = 'ConfigFontsCache'; + const config = { fonts: [{ family, source: testFonts.square }] }; + + Plotly.newPlot(gd, [{ y: [1, 2] }], layout(family), config) + .then(() => { + Plotly.purge(gd); + const promise = Plotly.newPlot(gd, [{ y: [1, 2] }], layout(family), config); + expect(gd.querySelector('.gtitle')).not.toBe(null, 'title drawn without a wait'); + expect(titleWidth()).toBeCloseTo(100, 0); + return promise; + }) + .then(done, done.fail); + }); + + it('should accept the font bytes in a typed array', (done) => { + const family = 'ConfigFontsBytes'; + const binary = atob(testFonts.square.split(',')[1]); + const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0)); + + Plotly.newPlot(gd, [{ y: [1, 2] }], layout(family), { fonts: [{ family, source: bytes }] }) + .then(() => { + expect(titleWidth()).toBeCloseTo(100, 0); + }) + .then(done, done.fail); + }); + + it('should warn and draw with a fallback font if a font does not load', (done) => { + spyOn(Lib, 'warn'); + const family = 'ConfigFontsBroken'; + + Plotly.newPlot(gd, [{ y: [1, 2] }], layout(family), { + fonts: [{ family, source: 'data:font/ttf;base64,AAAA' }] + }) + .then(() => { + expect(gd.querySelector('.gtitle')).not.toBe(null); + expect(Lib.warn).toHaveBeenCalledWith(jasmine.stringContaining(`Cannot load the font "${family}"`)); + }) + .then(done, done.fail); + }); + + it('should warn about an item without a family', (done) => { + spyOn(Lib, 'warn'); + const item = { source: testFonts.square }; + + Plotly.newPlot(gd, [{ y: [1, 2] }], layout('ConfigFontsNoFamily'), { fonts: [item] }) + .then(() => { + expect(Lib.warn).toHaveBeenCalledWith(jasmine.stringContaining('config.fonts'), item); + }) + .then(done, done.fail); + }); + }); }); diff --git a/test/jasmine/tests/lib_test.js b/test/jasmine/tests/lib_test.js index 6f59958da97..dd4a1177a1f 100644 --- a/test/jasmine/tests/lib_test.js +++ b/test/jasmine/tests/lib_test.js @@ -1,6 +1,7 @@ var Lib = require('../../../src/lib'); var setCursor = require('../../../src/lib/setcursor'); var overrideCursor = require('../../../src/lib/override_cursor'); +const { readEmbeddingPermission } = require('../../../src/lib/font_faces'); var config = require('../../../src/plot_api/plot_config').dfltConfig; var d3Select = require('../../strict-d3').select; @@ -3434,4 +3435,43 @@ describe('Queue', function () { }) .then(done, done.fail); }); + + describe('readEmbeddingPermission', () => { + // A minimal TrueType file with one OS/2 table that holds only fsType + const sfnt = (fsType) => { + const view = new DataView(new ArrayBuffer(38)); + view.setUint32(0, 0x00010000); + view.setUint16(4, 1); + view.setUint32(12, 0x4f532f32); + view.setUint32(20, 28); + view.setUint16(36, fsType); + return view.buffer; + }; + const read = (files) => Promise.all(files.map(readEmbeddingPermission)); + + it('permits embedding for installable, preview, editable and legacy fonts', (done) => { + read([0x0000, 0x0004, 0x0008, 0x0006].map(sfnt)) + .then((permissions) => { + expect(permissions).toEqual(['embed', 'embed', 'embed', 'embed']); + }) + .then(done, done.fail); + }); + + it('forbids embedding for restricted and bitmap-only fonts', (done) => { + read([0x0002, 0x0102, 0x0200].map(sfnt)) + .then((permissions) => { + expect(permissions).toEqual(['forbid', 'forbid', 'forbid']); + }) + .then(done, done.fail); + }); + + it('cannot read the permission of a WOFF2 file or a truncated file', (done) => { + const woff2 = new Uint8Array([0x77, 0x4f, 0x46, 0x32, 0, 0, 0, 0]).buffer; + read([woff2, sfnt(0).slice(0, 20)]) + .then((permissions) => { + expect(permissions).toEqual(['unknown', 'unknown']); + }) + .then(done, done.fail); + }); + }); }); diff --git a/test/jasmine/tests/toimage_test.js b/test/jasmine/tests/toimage_test.js index 88dbe14b30f..8ac56730ff7 100644 --- a/test/jasmine/tests/toimage_test.js +++ b/test/jasmine/tests/toimage_test.js @@ -5,6 +5,8 @@ function b64encodeTypedArray(typedArray) { var Plotly = require('../../../lib/index'); var Lib = require('../../../src/lib'); +const toSVG = require('../../../src/snapshot/tosvg'); +const testFonts = require('../assets/test_fonts'); var d3Select = require('../../strict-d3').select; var createGraphDiv = require('../assets/create_graph_div'); @@ -647,4 +649,62 @@ describe('Plotly.toImage', function () { .then(done, done.fail); }); }); + + describe('with config.fonts', () => { + const plot = (family, source) => + Plotly.newPlot( + gd, + [{ y: [1, 2] }], + { width: 400, height: 300, font: { family: `${family}, Arial` }, title: { text: 'ABCDE' } }, + { fonts: [{ family, source }] } + ); + const svgOf = () => Plotly.toImage(gd, { format: 'svg', imageDataOnly: true }); + + it('embeds the fonts that the graph uses in svg exports', (done) => { + const family = 'ToImageFonts'; + plot(family, testFonts.square) + .then(svgOf) + .then((svg) => { + expect(svg).toContain('@font-face'); + expect(svg).toContain(`font-family:"${family}"`); + expect(svg).toContain('data:font/ttf;base64,'); + }) + .then(done, done.fail); + }); + + it('does not embed a font that forbids embedding in svg exports', (done) => { + spyOn(Lib, 'warn'); + const family = 'ToImageFontsRestricted'; + plot(family, testFonts.squareRestricted) + .then(svgOf) + .then((svg) => { + expect(svg).not.toContain('@font-face'); + expect(Lib.warn).toHaveBeenCalledWith(jasmine.stringContaining('forbids embedding')); + }) + .then(done, done.fail); + }); + + it('embeds a font that forbids embedding in raster exports', (done) => { + // A raster export keeps the pixels of the text, not the font + plot('ToImageFontsRaster', testFonts.squareRestricted) + .then(() => { + expect(toSVG(gd, 'png')).toContain('@font-face'); + }) + .then(done, done.fail); + }); + + it('reads the embedding permission of a WOFF file with a compressed OS/2 table', (done) => { + plot('ToImageFontsWoff', testFonts.squareWoff) + .then(svgOf) + .then((svg) => { + expect(svg).toContain('data:font/woff;base64,'); + return plot('ToImageFontsWoffRestricted', testFonts.squareRestrictedWoff); + }) + .then(svgOf) + .then((svg) => { + expect(svg).not.toContain('@font-face'); + }) + .then(done, done.fail); + }); + }); }); diff --git a/test/plot-schema.json b/test/plot-schema.json index cd4ad209bb2..79ff7a714a9 100644 --- a/test/plot-schema.json +++ b/test/plot-schema.json @@ -215,6 +215,11 @@ "dflt": false, "valType": "boolean" }, + "fonts": { + "description": "Sets the fonts that plotly.js loads before it draws the graph, and embeds in exported images. Each item is an object with a *family* string and a *source*, and an optional *weight* and *style* as in a CSS `@font-face` rule. The *source* is the URL of a font file, a base64 data URL, or the font bytes in an `ArrayBuffer` or a typed array. plotly.js measures text only after the fonts load. If a font does not load in 10 seconds, plotly.js logs a warning and draws with a fallback font. An export to *svg*, *pdf* or *eps* embeds a font only if the font file permits embedding. plotly.js cannot read that permission in a WOFF2 file, so these exports do not embed WOFF2 fonts.", + "dflt": [], + "valType": "any" + }, "frameMargins": { "description": "When `layout.autosize` is turned on, set the frame margins in fraction of the graph size.", "dflt": 0, From 1859211cb47c58d79cd641fcd9ba6ec11a372c98 Mon Sep 17 00:00:00 2001 From: Sergey Plotnikov <6223985+nul0m@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:08:08 +0100 Subject: [PATCH 2/6] Use jasmine.stringMatching in the config.fonts tests The repository uses jasmine 3.5, which has no jasmine.stringContaining. --- test/jasmine/tests/config_test.js | 4 ++-- test/jasmine/tests/toimage_test.js | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/jasmine/tests/config_test.js b/test/jasmine/tests/config_test.js index ed98741ba5d..464930237de 100644 --- a/test/jasmine/tests/config_test.js +++ b/test/jasmine/tests/config_test.js @@ -1111,7 +1111,7 @@ describe('config argument', function() { }) .then(() => { expect(gd.querySelector('.gtitle')).not.toBe(null); - expect(Lib.warn).toHaveBeenCalledWith(jasmine.stringContaining(`Cannot load the font "${family}"`)); + expect(Lib.warn).toHaveBeenCalledWith(jasmine.stringMatching(`Cannot load the font "${family}"`)); }) .then(done, done.fail); }); @@ -1122,7 +1122,7 @@ describe('config argument', function() { Plotly.newPlot(gd, [{ y: [1, 2] }], layout('ConfigFontsNoFamily'), { fonts: [item] }) .then(() => { - expect(Lib.warn).toHaveBeenCalledWith(jasmine.stringContaining('config.fonts'), item); + expect(Lib.warn).toHaveBeenCalledWith(jasmine.stringMatching('config\\.fonts'), item); }) .then(done, done.fail); }); diff --git a/test/jasmine/tests/toimage_test.js b/test/jasmine/tests/toimage_test.js index 8ac56730ff7..486e2516b5e 100644 --- a/test/jasmine/tests/toimage_test.js +++ b/test/jasmine/tests/toimage_test.js @@ -679,7 +679,7 @@ describe('Plotly.toImage', function () { .then(svgOf) .then((svg) => { expect(svg).not.toContain('@font-face'); - expect(Lib.warn).toHaveBeenCalledWith(jasmine.stringContaining('forbids embedding')); + expect(Lib.warn).toHaveBeenCalledWith(jasmine.stringMatching('forbids embedding')); }) .then(done, done.fail); }); From dfd728a4e4d47748fce70522f766fc025ce0b0f0 Mon Sep 17 00:00:00 2001 From: Sergey Plotnikov <6223985+nul0m@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:03:54 +0100 Subject: [PATCH 3/6] Embed fonts with an unreadable permission, and load failed fonts again in the next draw plotly.js cannot read the embedding permission of a WOFF2 file, because browsers have no Brotli decoder. Before this change, svg, pdf and eps exports refused every WOFF2 face, so the exported text showed a fallback font. Now an export refuses a face only if the font file forbids embedding. A face that failed to load stayed in the cache for the life of the page. Thus a short network fault removed the font from all later graphs. Now the cache forgets a failed face, and the next draw tries the font again. See #8056. --- draftlogs/0000_add.md | 2 +- src/lib/font_faces.ts | 21 ++++++++-------- src/plot_api/plot_config.js | 5 ++-- src/types/generated/schema.d.ts | 2 +- test/jasmine/tests/config_test.js | 39 +++++++++++++++++++++++++++--- test/jasmine/tests/toimage_test.js | 15 ++++++++++++ test/plot-schema.json | 2 +- 7 files changed, 67 insertions(+), 19 deletions(-) diff --git a/draftlogs/0000_add.md b/draftlogs/0000_add.md index 4aa8d2b6533..6610456b55f 100644 --- a/draftlogs/0000_add.md +++ b/draftlogs/0000_add.md @@ -1 +1 @@ -- Add `config.fonts`, which loads fonts before the graph draws and embeds them in exported images [[#0000](https://github.com/plotly/plotly.js/pull/0000)], with thanks to @nul0m for the contribution! +- Add `config.fonts`, which loads fonts before the graph draws and embeds them in exported images [[#0000](https://github.com/plotly/plotly.js/pull/0000)] diff --git a/src/lib/font_faces.ts b/src/lib/font_faces.ts index 0d076ff5a62..28d29bb1790 100644 --- a/src/lib/font_faces.ts +++ b/src/lib/font_faces.ts @@ -36,6 +36,7 @@ type Permission = 'embed' | 'forbid' | 'unknown'; type Source = string | ArrayBuffer | ArrayBufferView; interface Face { + key: string; family: string; weight: string; style: string; @@ -58,7 +59,8 @@ const warnedItems = new WeakSet(); /** * Load the faces of `config.fonts` before the graph draws. - * Each face downloads and loads one time. Later graphs use the same face. + * A face that loads stays in the cache, and later graphs use it. + * A face that fails leaves the cache, so that the next graph that draws tries it again. * * @param fonts - the `fonts` value of the graph config * @returns undefined if no face must load. Otherwise a promise that resolves after the faces load or fail. @@ -92,8 +94,8 @@ export function loadFonts(fonts: unknown): Promise | undefined { * * @param fonts - the `fonts` value of the graph config * @param svg - the serialized SVG. A face gets a rule only if the SVG names its family. - * @param format - the export format. For *svg*, *pdf* and *eps*, a face gets a rule only if - * its font file permits embedding. + * @param format - the export format. For *svg*, *pdf* and *eps*, a face gets no rule if + * its font file forbids embedding. A face whose permission cannot be read gets a rule. * @returns the CSS text for a `