diff --git a/draftlogs/8172_add.md b/draftlogs/8172_add.md new file mode 100644 index 00000000000..67aab5e972a --- /dev/null +++ b/draftlogs/8172_add.md @@ -0,0 +1 @@ +- Add `config.fonts`, which loads fonts before the graph draws and embeds them in exported images [[#8172](https://github.com/plotly/plotly.js/pull/8172)] diff --git a/lib/index.d.ts b/lib/index.d.ts index f0fb53d9b79..7d33e1b894b 100644 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -71,6 +71,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..7be171ac871 --- /dev/null +++ b/src/lib/font_faces.ts @@ -0,0 +1,432 @@ +'use strict'; + +import { encode } from 'base64-arraybuffer'; +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' +}; + +/** The characters that the XML serializer writes as named entities */ +const XML_ENTITIES: Record = { amp: '&', apos: "'", gt: '>', lt: '<', quot: '"' }; + +const ITEM_WARNING = + 'config.fonts: each item must have a *family* string and a *source*: ' + + 'the URL of a font file, a base64 data URL, an ArrayBuffer or a typed array.'; + +type Permission = 'embed' | 'forbid' | 'unknown'; +type Source = string | ArrayBuffer | ArrayBufferView; + +interface Face { + sourceKey: string; + key: string; + family: string; + weight: string; + style: string; + loading: Promise; + loaded: boolean; + settled: boolean; + permission: Permission; + bytes?: ArrayBuffer; + format?: string; + rule?: string; + warned?: boolean; +} + +// Faces by source key, then by family, weight and style. Two byte sources with equal bytes have the same key. +// A string source is its own key, so the cache finds the face of a long data URL without a copy of the URL. +const faces = new Map>(); +// The content keys of byte sources, so that each buffer gets one hash +const byteKeys = new WeakMap(); +// The values of config.fonts that produced a warning already +const warnedObjects = new WeakSet(); +const warnedValues = new Set(); + +/** + * Load the faces of `config.fonts` before the graph draws. + * A face that loads stays in the cache, and later graphs use it. + * If the download of a face fails, the face leaves the cache, and the next graph that draws tries the download again. + * A face whose font file cannot be decoded stays in the cache as failed, so the graph warns one time. + * + * @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 (fonts == null) return; + if (!Array.isArray(fonts)) { + warnOnce(fonts, 'config.fonts must be an array of objects with a *family* and a *source*.'); + return; + } + if (!fonts.length || typeof FontFace === 'undefined' || !document.fonts) return; + + const pending: Promise[] = []; + for (const font of fonts) { + const face = findFace(font, true); + if (!face) { + warnOnce(font, ITEM_WARNING); + 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 a `font-family` declaration of the SVG names its family. + * @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 ``); + 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 796fdd93ca9..0778cb409b2 100644 --- a/src/types/generated/schema.d.ts +++ b/src/types/generated/schema.d.ts @@ -16890,6 +16890,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. After a failed download, the next draw tries the download again. An export to *svg*, *pdf* or *eps* does not embed a font whose file forbids embedding. If plotly.js cannot read that permission, as in a WOFF2 file, the export embeds the font. + * @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..7542c026c86 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,216 @@ 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; + const fontBytes = () => Uint8Array.from(atob(testFonts.square.split(',')[1]), (c) => c.charCodeAt(0)); + + // Make fetch answer with the test font only when the test calls the returned function + const holdFetch = () => { + const answers = []; + spyOn(window, 'fetch').and.callFake( + () => new Promise((resolve) => answers.push(() => resolve(new Response(fontBytes())))) + ); + return () => answers.forEach((answer) => answer()); + }; + + 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'; + + Plotly.newPlot(gd, [{ y: [1, 2] }], layout(family), { fonts: [{ family, source: fontBytes() }] }) + .then(() => { + expect(titleWidth()).toBeCloseTo(100, 0); + }) + .then(done, done.fail); + }); + + it('should warn one time and draw with a fallback font if a font file cannot be decoded', (done) => { + spyOn(Lib, 'warn'); + const family = 'ConfigFontsBroken'; + const config = { fonts: [{ family, source: 'data:font/ttf;base64,AAAA' }] }; + const message = `Cannot load the font "${family}"`; + const warnings = () => Lib.warn.calls.allArgs().filter((args) => String(args[0]).includes(message)).length; + + Plotly.newPlot(gd, [{ y: [1, 2] }], layout(family), config) + .then(() => { + expect(gd.querySelector('.gtitle')).not.toBe(null); + expect(warnings()).toBe(1); + return Plotly.newPlot(gd, [{ y: [1, 2] }], layout(family), config); + }) + .then(() => { + expect(warnings()).toBe(1, 'the face stays failed'); + }) + .then(done, done.fail); + }); + + it('should not download a font file again if the file cannot be decoded', (done) => { + spyOn(Lib, 'warn'); + const family = 'ConfigFontsBadFile'; + const config = { fonts: [{ family, source: 'https://fonts.example.invalid/bad.ttf' }] }; + const message = `Cannot load the font "${family}"`; + const warnings = () => Lib.warn.calls.allArgs().filter((args) => String(args[0]).includes(message)).length; + spyOn(window, 'fetch').and.callFake(() => Promise.resolve(new Response(new Uint8Array([0, 1, 2, 3])))); + + Plotly.newPlot(gd, [{ y: [1, 2] }], layout(family), config) + .then(() => Plotly.newPlot(gd, [{ y: [1, 2] }], layout(family), config)) + .then(() => { + expect(window.fetch).toHaveBeenCalledTimes(1); + expect(warnings()).toBe(1); + }) + .then(done, done.fail); + }); + + it('should load a font in the next draw after a failed download', (done) => { + spyOn(Lib, 'warn'); + const family = 'ConfigFontsRetry'; + const config = { fonts: [{ family, source: 'https://fonts.example.invalid/retry.ttf' }] }; + let calls = 0; + spyOn(window, 'fetch').and.callFake(() => { + calls++; + if (calls === 1) return Promise.reject(new TypeError('Failed to fetch')); + return Promise.resolve(new Response(fontBytes())); + }); + + Plotly.newPlot(gd, [{ y: [1, 2] }], layout(family), config) + .then(() => { + expect(Lib.warn).toHaveBeenCalledWith(jasmine.stringMatching(`Cannot load the font "${family}"`)); + Plotly.purge(gd); + return Plotly.newPlot(gd, [{ y: [1, 2] }], layout(family), config); + }) + .then(() => { + expect(window.fetch).toHaveBeenCalledTimes(2); + expect(titleWidth()).toBeCloseTo(100, 0); + }) + .then(done, done.fail); + }); + + it('should stop a draw that waits for a font if the graph is purged during the wait', (done) => { + const family = 'ConfigFontsPurged'; + const answer = holdFetch(); + + const promise = Plotly.newPlot(gd, [{ y: [1, 2] }], layout(family), { + fonts: [{ family, source: 'https://fonts.example.invalid/purged.ttf' }] + }); + Plotly.purge(gd); + answer(); + + promise + .then((result) => { + expect(result).toBe(gd); + expect(gd.querySelector('.main-svg')).toBe(null, 'nothing drawn after the purge'); + }) + .then(done, done.fail); + }); + + it('should run a relayout that comes during the font wait after the draw', (done) => { + const family = 'ConfigFontsRelayout'; + const answer = holdFetch(); + + const plotted = Plotly.newPlot(gd, [{ x: [1, 2, 3], y: [1, 2, 3] }], layout(family), { + fonts: [{ family, source: 'https://fonts.example.invalid/relayout.ttf' }] + }); + const relaidOut = Plotly.relayout(gd, 'xaxis.range', [0, 4]); + answer(); + + Promise.all([plotted, relaidOut]) + .then(() => { + expect(gd._fullLayout.xaxis.range).toEqual([0, 4]); + expect(gd.querySelectorAll('.xtick').length).toBeGreaterThan(0); + expect(titleWidth()).toBeCloseTo(100, 0); + }) + .then(done, done.fail); + }); + + it('should not rebuild the plot when react gets the same font bytes in a new buffer', (done) => { + const family = 'ConfigFontsReactBytes'; + const config = () => ({ fonts: [{ family, source: fontBytes() }] }); + let paper; + + Plotly.newPlot(gd, [{ y: [1, 2] }], layout(family), config()) + .then(() => { + paper = gd.querySelector('.main-svg'); + return Plotly.react(gd, [{ y: [2, 1] }], layout(family), config()); + }) + .then(() => { + expect(gd.querySelector('.main-svg')).toBe(paper, 'react did not call newPlot'); + }) + .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.stringMatching('config\\.fonts'), item); + }) + .then(done, done.fail); + }); + + it('should warn about a fonts value that is not an array and about items without a usable source', (done) => { + spyOn(Lib, 'warn'); + const single = { family: 'ConfigFontsSingle', source: testFonts.square }; + const blobItem = { family: 'ConfigFontsBlob', source: new Blob([fontBytes()]) }; + + Plotly.newPlot(gd, [{ y: [1, 2] }], layout('Arial'), { fonts: single }) + .then(() => { + expect(Lib.warn).toHaveBeenCalledWith(jasmine.stringMatching('must be an array'), single); + return Plotly.newPlot(gd, [{ y: [1, 2] }], layout('Arial'), { + fonts: ['ConfigFontsString', blobItem] + }); + }) + .then(() => { + expect(Lib.warn).toHaveBeenCalledWith(jasmine.stringMatching('typed array'), 'ConfigFontsString'); + expect(Lib.warn).toHaveBeenCalledWith(jasmine.stringMatching('typed array'), blobItem); + }) + .then(done, done.fail); + }); + }); }); diff --git a/test/jasmine/tests/lib_test.js b/test/jasmine/tests/lib_test.js index 2551b3d7d12..bcd8d7b5b98 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; @@ -3386,6 +3387,45 @@ describe('Test lib.js:', function () { }); }); }); + + 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); + }); + }); }); describe('Queue', function () { diff --git a/test/jasmine/tests/plot_api_test.js b/test/jasmine/tests/plot_api_test.js index 40c75212cda..22c8b11760c 100644 --- a/test/jasmine/tests/plot_api_test.js +++ b/test/jasmine/tests/plot_api_test.js @@ -3144,6 +3144,16 @@ describe('plot_api helpers', function () { ).toBe(true); }); + it('Compares binary values by their bytes', () => { + const bytes = () => new Uint8Array([1, 2, 3]); + expect(helpers.collectionsAreEqual({ source: bytes() }, { source: bytes() })).toBe(true); + expect(helpers.collectionsAreEqual([bytes().buffer], [bytes().buffer])).toBe(true); + expect(helpers.collectionsAreEqual({ source: bytes() }, { source: new Uint8Array([1, 2, 4]) })).toBe(false); + expect(helpers.collectionsAreEqual({ source: bytes() }, { source: new Uint8Array([1, 2]) })).toBe(false); + const dataUrl = 'data:font/ttf;base64,AQID'; + expect(helpers.collectionsAreEqual({ source: bytes() }, { source: dataUrl })).toBe(false); + }); + it('Returns false for null values', () => { expect(helpers.collectionsAreEqual(null, null)).toBe(false); }); diff --git a/test/jasmine/tests/toimage_test.js b/test/jasmine/tests/toimage_test.js index 88dbe14b30f..a6bced3f1ef 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,139 @@ 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.stringMatching('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('embeds a font whose embedding permission cannot be read in svg exports', (done) => { + // Without DecompressionStream, plotly.js cannot read the compressed OS/2 table of a WOFF file + // Start the plot inside a promise, so that a synchronous error still restores the global + const decompressionStream = window.DecompressionStream; + window.DecompressionStream = undefined; + Promise.resolve() + .then(() => plot('ToImageFontsUnknown', testFonts.squareWoff)) + .finally(() => { + window.DecompressionStream = decompressionStream; + }) + .then(svgOf) + .then((svg) => { + expect(svg).toContain('data:font/woff;base64,'); + }) + .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); + }); + + it('embeds a font from an ArrayBuffer that the caller detaches after the draw', (done) => { + const buffer = Uint8Array.from(atob(testFonts.square.split(',')[1]), (c) => c.charCodeAt(0)).buffer; + plot('ToImageFontsDetached', buffer) + .then(() => { + structuredClone(buffer, { transfer: [buffer] }); + expect(buffer.byteLength).toBe(0, 'the buffer is detached'); + return svgOf(); + }) + .then((svg) => { + expect(svg).toContain('data:font/ttf;base64,'); + }) + .then(done, done.fail); + }); + + it('does not embed a font that no text of the graph uses', (done) => { + // The SVG holds the word 'legend' in class names, but no text uses the family 'Legend' + Plotly.newPlot( + gd, + [{ y: [1, 2] }, { y: [2, 1] }], + { width: 400, height: 300, font: { family: 'Arial' } }, + { fonts: [{ family: 'Legend', source: testFonts.square }] } + ) + .then(svgOf) + .then((svg) => { + expect(svg).toContain('legend'); + expect(svg).not.toContain('@font-face'); + }) + .then(done, done.fail); + }); + + it('embeds a font that a text span names in other letter case', (done) => { + const family = 'ToImage Fonts Span'; + Plotly.newPlot( + gd, + [{ y: [1, 2] }], + { + width: 400, + height: 300, + font: { family: 'Arial' }, + title: { text: `x ABCDE` } + }, + { fonts: [{ family, source: testFonts.square }] } + ) + .then(svgOf) + .then((svg) => { + expect(svg).toContain(`font-family:"${family}"`); + }) + .then(done, done.fail); + }); + + it('keeps the fonts in a snapshot clone', (done) => { + const fonts = [{ family: 'ToImageFontsClone', source: testFonts.square }]; + plot('ToImageFontsClone', testFonts.square) + .then(() => { + expect(Plotly.Snapshot.clone(gd, { format: 'png' }).config.fonts).toBe(gd._context.fonts); + expect(gd._context.fonts).toEqual(fonts); + }) + .then(done, done.fail); + }); + }); }); diff --git a/test/plot-schema.json b/test/plot-schema.json index 3e04122d215..33d17b44d54 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. After a failed download, the next draw tries the download again. An export to *svg*, *pdf* or *eps* does not embed a font whose file forbids embedding. If plotly.js cannot read that permission, as in a WOFF2 file, the export embeds the font.", + "dflt": [], + "valType": "any" + }, "frameMargins": { "description": "When `layout.autosize` is turned on, set the frame margins in fraction of the graph size.", "dflt": 0,