├── .gitignore ├── .npmignore ├── .travis.yml ├── LICENSE ├── README.md ├── bower.json ├── dist ├── fontfaceobserver.cjs.js ├── fontfaceobserver.esm.js └── fontfaceobserver.umd.js ├── docs ├── FontFaceObserver.html ├── Ruler.html ├── Ruler.js.html ├── fonts │ ├── OpenSans-Bold-webfont.eot │ ├── OpenSans-Bold-webfont.svg │ ├── OpenSans-Bold-webfont.woff │ ├── OpenSans-BoldItalic-webfont.eot │ ├── OpenSans-BoldItalic-webfont.svg │ ├── OpenSans-BoldItalic-webfont.woff │ ├── OpenSans-Italic-webfont.eot │ ├── OpenSans-Italic-webfont.svg │ ├── OpenSans-Italic-webfont.woff │ ├── OpenSans-Light-webfont.eot │ ├── OpenSans-Light-webfont.svg │ ├── OpenSans-Light-webfont.woff │ ├── OpenSans-LightItalic-webfont.eot │ ├── OpenSans-LightItalic-webfont.svg │ ├── OpenSans-LightItalic-webfont.woff │ ├── OpenSans-Regular-webfont.eot │ ├── OpenSans-Regular-webfont.svg │ └── OpenSans-Regular-webfont.woff ├── global.html ├── index.html ├── index.js.html ├── scripts │ ├── linenumber.js │ └── prettify │ │ ├── Apache-License-2.0.txt │ │ ├── lang-css.js │ │ └── prettify.js └── styles │ ├── jsdoc-default.css │ ├── prettify-jsdoc.css │ └── prettify-tomorrow.css ├── package-lock.json ├── package.json ├── rollup.config.js ├── src ├── dom.js ├── index.js ├── ruler.js └── types.d.ts └── test ├── assets ├── index.html ├── late.css ├── sourcesanspro-regular.eot ├── sourcesanspro-regular.ttf ├── sourcesanspro-regular.woff ├── subset.eot ├── subset.ttf └── subset.woff ├── index.html ├── observer-test.js └── ruler-test.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | lib 3 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | test 2 | docs 3 | bower.json 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | 3 | language: node_js 4 | 5 | node_js: 6 | - '8' 7 | - '9' 8 | - '10' 9 | - '11' 10 | 11 | matrix: 12 | fast_finish: true 13 | 14 | cache: 15 | directories: 16 | - node_modules 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014 - Bram Stein 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions 6 | are met: 7 | 8 | 1. Redistributions of source code must retain the above copyright 9 | notice, this list of conditions and the following disclaimer. 10 | 2. Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED 15 | WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 16 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO 17 | EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 18 | INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 19 | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 20 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 21 | OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 22 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 23 | EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Font Face Observer 2 | 3 | [![Build Status](https://travis-ci.org/dmnsgn/fontfaceobserver.svg?branch=master)](https://travis-ci.org/dmnsgn/fontfaceobserver) 4 | [![npm version](https://badge.fury.io/js/fontfaceobserver.svg)](https://www.npmjs.com/package/fontfaceobserver-es) 5 | [![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier) 6 | 7 | > Font Face Observer is a small `@font-face` loader and monitor (3.5KB minified and 1.3KB gzipped) compatible with any webfont service. It will monitor when a webfont is loaded and notify you. It does not limit you in any way in where, when, or how you load your webfonts. Unlike the [Web Font Loader](https://github.com/typekit/webfontloader) Font Face Observer uses scroll events to detect font loads efficiently and with minimum overhead. 8 | 9 | ## Documentation 10 | 11 | For details on how to use, check out the [documentation](https://dmnsgn.github.io/fontfaceobserver/). 12 | 13 | ## Installation 14 | 15 | Font Face Observer comes with three bundles: 16 | 17 | * A CommonJS bundle (`dist/fontfaceobserver.cjs.js`) for use in NodeJS: 18 | 19 | ```shell 20 | npm install fontfaceobserver-es 21 | ``` 22 | 23 | ```js 24 | var FontFaceObserver = require("fontfaceobserver-es"); 25 | 26 | var font = new FontFaceObserver("My Family"); 27 | 28 | font.load().then(function() { 29 | console.log("My Family has loaded"); 30 | }); 31 | ``` 32 | 33 | * An ES module bundle (`dist/fontfaceobserver.esm.js`) for the above and also directly in the browser: 34 | 35 | ```html 36 | 37 | ``` 38 | 39 | ```js 40 | import FontFaceObserver from "fontfaceobserver-es"; 41 | 42 | const font = new FontFaceObserver("My Family"); 43 | 44 | font.load().then(function() { 45 | console.log("My Family has loaded"); 46 | }); 47 | ``` 48 | 49 | * A UMD build (`dist/fontfaceobserver.umd.js`) mainly for browser without ES module support: 50 | 51 | ```js 52 | 53 | 60 | ``` 61 | 62 | You'll need to include the required Polyfill for Promise support. See [babel-polyfill](https://babeljs.io/docs/usage/polyfill/) and [core-js](https://github.com/zloirock/core-js#commonjs). 63 | 64 | ## Usage 65 | 66 | Include your `@font-face` rules as usual. Fonts can be supplied by either a font service such as [Google Fonts](http://www.google.com/fonts), [Typekit](http://typekit.com), and [Webtype](http://webtype.com) or be self-hosted. You can set up monitoring for a single font family at a time: 67 | 68 | ```js 69 | const font = new FontFaceObserver("My Family", { 70 | weight: 400 71 | }); 72 | 73 | font.load().then( 74 | function() { 75 | console.log("Font is available"); 76 | }, 77 | function() { 78 | console.log("Font is not available"); 79 | } 80 | ); 81 | ``` 82 | 83 | The `FontFaceObserver` constructor takes two arguments: the font-family name (required) and an object describing the variation (optional). The object can contain `weight`, `style`, and `stretch` properties. If a property is not present it will default to `normal`. To start loading the font, call the `load` method. It'll immediately return a new Promise that resolves when the font is loaded and rejected when the font fails to load. 84 | 85 | If your font doesn't contain at least the latin "BESbwy" characters you must pass a custom test string to the `load` method. 86 | 87 | ```js 88 | const font = new FontFaceObserver("My Family"); 89 | 90 | font.load("中国").then( 91 | function() { 92 | console.log("Font is available"); 93 | }, 94 | function() { 95 | console.log("Font is not available"); 96 | } 97 | ); 98 | ``` 99 | 100 | The default timeout for giving up on font loading is 3 seconds. You can increase or decrease this by passing a number of milliseconds as the second parameter to the `load` method. 101 | 102 | ```js 103 | var font = new FontFaceObserver("My Family"); 104 | 105 | font.load(null, 5000).then( 106 | function() { 107 | console.log("Font is available"); 108 | }, 109 | function() { 110 | console.log("Font is not available after waiting 5 seconds"); 111 | } 112 | ); 113 | ``` 114 | 115 | Multiple fonts can be loaded by creating a `FontFaceObserver` instance for each. 116 | 117 | ```js 118 | var fontA = new FontFaceObserver("Family A"); 119 | var fontB = new FontFaceObserver("Family B"); 120 | 121 | fontA.load().then(function() { 122 | console.log("Family A is available"); 123 | }); 124 | 125 | fontB.load().then(function() { 126 | console.log("Family B is available"); 127 | }); 128 | ``` 129 | 130 | You may also load both at the same time, rather than loading each individually. 131 | 132 | ```js 133 | var fontA = new FontFaceObserver("Family A"); 134 | var fontB = new FontFaceObserver("Family B"); 135 | 136 | Promise.all([fontA.load(), fontB.load()]).then(function() { 137 | console.log("Family A & B have loaded"); 138 | }); 139 | ``` 140 | 141 | If you are working with a large number of fonts, you may decide to create `FontFaceObserver` instances dynamically: 142 | 143 | ```js 144 | // An example collection of font data with additional metadata, 145 | // in this case “color.” 146 | var exampleFontData = { 147 | 'Family A': { weight: 400, color: 'red' }, 148 | 'Family B': { weight: 400, color: 'orange' }, 149 | 'Family C': { weight: 900, color: 'yellow' }, 150 | // Etc. 151 | }; 152 | 153 | var observers = []; 154 | 155 | // Make one observer for each font, 156 | // by iterating over the data we already have 157 | Object.keys(exampleFontData).forEach(function(family) { 158 | var data = exampleFontData[family]; 159 | var obs = new FontFaceObserver(family, data); 160 | observers.push(obs.load()); 161 | }); 162 | 163 | Promise.all(observers) 164 | .then(function(fonts) { 165 | fonts.forEach(function(font) { 166 | console.log(font.family + ' ' + font.weight + ' ' + 'loaded'); 167 | 168 | // Map the result of the Promise back to our existing data, 169 | // to get the other properties we need. 170 | console.log(exampleFontData[font.family].color); 171 | }); 172 | }) 173 | .catch(function(err) { 174 | console.warn('Some critical font are not available:', err); 175 | }); 176 | ``` 177 | 178 | The following example emulates FOUT with Font Face Observer for `My Family`. 179 | 180 | ```js 181 | var font = new FontFaceObserver("My Family"); 182 | 183 | font.load().then(function() { 184 | document.documentElement.className += " fonts-loaded"; 185 | }); 186 | ``` 187 | 188 | ```css 189 | .fonts-loaded { 190 | body { 191 | font-family: My Family, sans-serif; 192 | } 193 | } 194 | ``` 195 | 196 | ## Browser support 197 | 198 | FontFaceObserver has been tested and works on the following browsers: 199 | 200 | * Chrome (desktop & Android) 201 | * Firefox 202 | * Opera 203 | * Safari (desktop & iOS) 204 | * IE8+ 205 | * Android WebKit 206 | 207 | ## License 208 | 209 | Font Face Observer is licensed under the BSD License. Copyright 2014-2017 Bram Stein and Damien Seguin. All rights reserved. 210 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fontfaceobserver-es", 3 | "description": "Fast and simple web font loading.", 4 | "main": "dist/fontfaceobserver.umd.js", 5 | "authors": [ 6 | "Bram Stein (http://www.bramstein.com/)", 7 | "Damien Seguin (https://dmnsgn.me/)" 8 | ], 9 | "license": "BSD-3-Clause", 10 | "keywords": [ 11 | "fontloader", 12 | "fonts", 13 | "font", 14 | "font-face", 15 | "web", 16 | "font", 17 | "font", 18 | "load", 19 | "font", 20 | "events" 21 | ], 22 | "homepage": "https://github.com/dmnsgn/fontfaceobserver" 23 | } 24 | -------------------------------------------------------------------------------- /dist/fontfaceobserver.cjs.js: -------------------------------------------------------------------------------- 1 | "use strict";function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n 1 && arguments[1] !== undefined ? arguments[1] : {}; 367 | 368 | _classCallCheck(this, FontFaceObserver); 369 | 370 | this.family = family; 371 | this.style = descriptors.style || "normal"; 372 | this.weight = descriptors.weight || "normal"; 373 | this.stretch = descriptors.stretch || "normal"; 374 | return this; 375 | } 376 | /** 377 | * @param {string=} text Optional test string to use for detecting if a font 378 | * is available. 379 | * @param {number=} timeout Optional timeout for giving up on font load 380 | * detection and rejecting the promise (defaults to 3 seconds). 381 | * @return {Promise.} 382 | */ 383 | 384 | 385 | _createClass(FontFaceObserver, [{ 386 | key: "load", 387 | value: function load(text, timeout) { 388 | var that = this; 389 | var testString = text || "BESbswy"; 390 | var timeoutId = 0; 391 | var timeoutValue = timeout || FontFaceObserver.DEFAULT_TIMEOUT; 392 | var start = that.getTime(); 393 | return new Promise(function (resolve, reject) { 394 | if (FontFaceObserver.supportsNativeFontLoading() && !FontFaceObserver.hasSafari10Bug()) { 395 | var loader = new Promise(function (resolve, reject) { 396 | var check = function check() { 397 | var now = that.getTime(); 398 | 399 | if (now - start >= timeoutValue) { 400 | reject(new Error("" + timeoutValue + "ms timeout exceeded")); 401 | } else { 402 | document.fonts.load(that.getStyle('"' + that["family"] + '"'), testString).then(function (fonts) { 403 | if (fonts.length >= 1) { 404 | resolve(); 405 | } else { 406 | setTimeout(check, 25); 407 | } 408 | }, reject); 409 | } 410 | }; 411 | 412 | check(); 413 | }); 414 | var timer = new Promise(function (resolve, reject) { 415 | timeoutId = setTimeout(function () { 416 | reject(new Error("" + timeoutValue + "ms timeout exceeded")); 417 | }, timeoutValue); 418 | }); 419 | Promise.race([timer, loader]).then(function () { 420 | clearTimeout(timeoutId); 421 | resolve(that); 422 | }, reject); 423 | } else { 424 | onReady(function () { 425 | var rulerA = new Ruler(testString); 426 | var rulerB = new Ruler(testString); 427 | var rulerC = new Ruler(testString); 428 | var widthA = -1; 429 | var widthB = -1; 430 | var widthC = -1; 431 | var fallbackWidthA = -1; 432 | var fallbackWidthB = -1; 433 | var fallbackWidthC = -1; 434 | var container = document.createElement("div"); 435 | /** 436 | * @private 437 | */ 438 | 439 | function removeContainer() { 440 | if (container.parentNode !== null) { 441 | container.parentNode.removeChild(container); 442 | } 443 | } 444 | /** 445 | * @private 446 | * 447 | * If metric compatible fonts are detected, one of the widths will be 448 | * -1. This is because a metric compatible font won't trigger a scroll 449 | * event. We work around this by considering a font loaded if at least 450 | * two of the widths are the same. Because we have three widths, this 451 | * still prevents false positives. 452 | * 453 | * Cases: 454 | * 1) Font loads: both a, b and c are called and have the same value. 455 | * 2) Font fails to load: resize callback is never called and timeout 456 | * happens. 457 | * 3) WebKit bug: both a, b and c are called and have the same value, 458 | * but the values are equal to one of the last resort fonts, we 459 | * ignore this and continue waiting until we get new values (or a 460 | * timeout). 461 | */ 462 | 463 | 464 | function check() { 465 | if (widthA != -1 && widthB != -1 || widthA != -1 && widthC != -1 || widthB != -1 && widthC != -1) { 466 | if (widthA == widthB || widthA == widthC || widthB == widthC) { 467 | // All values are the same, so the browser has most likely 468 | // loaded the web font 469 | if (FontFaceObserver.hasWebKitFallbackBug()) { 470 | // Except if the browser has the WebKit fallback bug, in which 471 | // case we check to see if all values are set to one of the 472 | // last resort fonts. 473 | if (widthA == fallbackWidthA && widthB == fallbackWidthA && widthC == fallbackWidthA || widthA == fallbackWidthB && widthB == fallbackWidthB && widthC == fallbackWidthB || widthA == fallbackWidthC && widthB == fallbackWidthC && widthC == fallbackWidthC) { 474 | // The width we got matches some of the known last resort 475 | // fonts, so let's assume we're dealing with the last resort 476 | // font. 477 | return; 478 | } 479 | } 480 | 481 | removeContainer(); 482 | clearTimeout(timeoutId); 483 | resolve(that); 484 | } 485 | } 486 | } // This ensures the scroll direction is correct. 487 | 488 | 489 | container.dir = "ltr"; 490 | rulerA.setFont(that.getStyle("sans-serif")); 491 | rulerB.setFont(that.getStyle("serif")); 492 | rulerC.setFont(that.getStyle("monospace")); 493 | container.appendChild(rulerA.getElement()); 494 | container.appendChild(rulerB.getElement()); 495 | container.appendChild(rulerC.getElement()); 496 | document.body.appendChild(container); 497 | fallbackWidthA = rulerA.getWidth(); 498 | fallbackWidthB = rulerB.getWidth(); 499 | fallbackWidthC = rulerC.getWidth(); 500 | 501 | function checkForTimeout() { 502 | var now = that.getTime(); 503 | 504 | if (now - start >= timeoutValue) { 505 | removeContainer(); 506 | reject(new Error("" + timeoutValue + "ms timeout exceeded")); 507 | } else { 508 | var hidden = document["hidden"]; 509 | 510 | if (hidden === true || hidden === undefined) { 511 | widthA = rulerA.getWidth(); 512 | widthB = rulerB.getWidth(); 513 | widthC = rulerC.getWidth(); 514 | check(); 515 | } 516 | 517 | timeoutId = setTimeout(checkForTimeout, 50); 518 | } 519 | } 520 | 521 | checkForTimeout(); 522 | rulerA.onResize(function (width) { 523 | widthA = width; 524 | check(); 525 | }); 526 | rulerA.setFont(that.getStyle('"' + that["family"] + '",sans-serif')); 527 | rulerB.onResize(function (width) { 528 | widthB = width; 529 | check(); 530 | }); 531 | rulerB.setFont(that.getStyle('"' + that["family"] + '",serif')); 532 | rulerC.onResize(function (width) { 533 | widthC = width; 534 | check(); 535 | }); 536 | rulerC.setFont(that.getStyle('"' + that["family"] + '",monospace')); 537 | }); 538 | } 539 | }); 540 | } 541 | /** 542 | * @private 543 | * 544 | * @param {string} family 545 | * @return {string} 546 | */ 547 | 548 | }, { 549 | key: "getStyle", 550 | value: function getStyle(family) { 551 | return [this.style, this.weight, FontFaceObserver.supportStretch() ? this.stretch : "", "100px", family].join(" "); 552 | } 553 | /** 554 | * @private 555 | * 556 | * @return {number} 557 | */ 558 | 559 | }, { 560 | key: "getTime", 561 | value: function getTime() { 562 | return new Date().getTime(); 563 | } 564 | }]); 565 | 566 | return FontFaceObserver; 567 | }(); 568 | 569 | _defineProperty(FontFaceObserver, "Ruler", Ruler); 570 | 571 | _defineProperty(FontFaceObserver, "HAS_WEBKIT_FALLBACK_BUG", null); 572 | 573 | _defineProperty(FontFaceObserver, "HAS_SAFARI_10_BUG", null); 574 | 575 | _defineProperty(FontFaceObserver, "SUPPORTS_STRETCH", null); 576 | 577 | _defineProperty(FontFaceObserver, "SUPPORTS_NATIVE_FONT_LOADING", null); 578 | 579 | _defineProperty(FontFaceObserver, "DEFAULT_TIMEOUT", 3000); 580 | 581 | export default FontFaceObserver; 582 | -------------------------------------------------------------------------------- /dist/fontfaceobserver.umd.js: -------------------------------------------------------------------------------- 1 | !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).FontFaceObserver=t()}(this,function(){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){for(var n=0;n 2 | 3 | 4 | 5 | JSDoc: Class: FontFaceObserver 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Class: FontFaceObserver

21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 |
30 | 31 |

FontFaceObserver(family, descriptors)

32 | 33 |
Class for FontFaceObserver.
34 | 35 | 36 |
37 | 38 |
39 |
40 | 41 | 42 | 43 | 44 |

Constructor

45 | 46 | 47 | 48 |

new FontFaceObserver(family, descriptors)

49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 |
Parameters:
64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 122 | 123 | 124 | 125 | 126 | 127 | 130 | 131 | 132 | 133 | 134 |
NameTypeDescription
family 92 | 93 | 94 | string 95 | 96 | 97 | 98 | font-family name (required)
descriptors 115 | 116 | 117 | Descriptors 118 | 119 | 120 | 121 | an object describing the variation 128 | (optional). The object can contain `weight`, `style`, and `stretch` 129 | properties. If a property is not present it will default to `normal`.
135 | 136 | 137 | 138 | 139 | 140 | 141 |
142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 |
Source:
169 |
172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 |
180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 |
200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 |

Members

215 | 216 | 217 | 218 |

DEFAULT_TIMEOUT :number

219 | 220 | 221 | 222 | 223 | 224 | 225 |
Type:
226 |
    227 |
  • 228 | 229 | number 230 | 231 | 232 |
  • 233 |
234 | 235 | 236 | 237 | 238 | 239 |
240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 |
Source:
267 |
270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 |
278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 |

HAS_SAFARI_10_BUG :null|boolean

287 | 288 | 289 | 290 | 291 | 292 | 293 |
Type:
294 |
    295 |
  • 296 | 297 | null 298 | | 299 | 300 | boolean 301 | 302 | 303 |
  • 304 |
305 | 306 | 307 | 308 | 309 | 310 |
311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 |
Source:
338 |
341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 |
349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 |

HAS_WEBKIT_FALLBACK_BUG :null|boolean

358 | 359 | 360 | 361 | 362 | 363 | 364 |
Type:
365 |
    366 |
  • 367 | 368 | null 369 | | 370 | 371 | boolean 372 | 373 | 374 |
  • 375 |
376 | 377 | 378 | 379 | 380 | 381 |
382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 |
Source:
409 |
412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 |
420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 |

SUPPORTS_NATIVE_FONT_LOADING :null|boolean

429 | 430 | 431 | 432 | 433 | 434 | 435 |
Type:
436 |
    437 |
  • 438 | 439 | null 440 | | 441 | 442 | boolean 443 | 444 | 445 |
  • 446 |
447 | 448 | 449 | 450 | 451 | 452 |
453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 |
Source:
480 |
483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 |
491 | 492 | 493 | 494 | 495 | 496 | 497 | 498 | 499 |

SUPPORTS_STRETCH :null|boolean

500 | 501 | 502 | 503 | 504 | 505 | 506 |
Type:
507 |
    508 |
  • 509 | 510 | null 511 | | 512 | 513 | boolean 514 | 515 | 516 |
  • 517 |
518 | 519 | 520 | 521 | 522 | 523 |
524 | 525 | 526 | 527 | 528 | 529 | 530 | 531 | 532 | 533 | 534 | 535 | 536 | 537 | 538 | 539 | 540 | 541 | 542 | 543 | 544 | 545 | 546 | 547 | 548 | 549 | 550 |
Source:
551 |
554 | 555 | 556 | 557 | 558 | 559 | 560 | 561 |
562 | 563 | 564 | 565 | 566 | 567 | 568 | 569 | 570 | 571 | 572 |

Methods

573 | 574 | 575 | 576 | 577 | 578 | 579 | 580 |

(static) getNavigatorVendor() → {string}

581 | 582 | 583 | 584 | 585 | 586 | 587 | 588 | 589 | 590 | 591 | 592 | 593 | 594 | 595 | 596 | 597 | 598 | 599 |
600 | 601 | 602 | 603 | 604 | 605 | 606 | 607 | 608 | 609 | 610 | 611 | 612 | 613 | 614 | 615 | 616 | 617 | 618 | 619 | 620 | 621 | 622 | 623 | 624 | 625 | 626 |
Source:
627 |
630 | 631 | 632 | 633 | 634 | 635 | 636 | 637 |
638 | 639 | 640 | 641 | 642 | 643 | 644 | 645 | 646 | 647 | 648 | 649 | 650 | 651 |
Returns:
652 | 653 | 654 | 655 | 656 |
657 |
658 | Type 659 |
660 |
661 | 662 | string 663 | 664 | 665 |
666 |
667 | 668 | 669 | 670 | 671 | 672 | 673 | 674 | 675 | 676 | 677 | 678 | 679 | 680 |

(static) getUserAgent() → {string}

681 | 682 | 683 | 684 | 685 | 686 | 687 | 688 | 689 | 690 | 691 | 692 | 693 | 694 | 695 | 696 | 697 | 698 | 699 |
700 | 701 | 702 | 703 | 704 | 705 | 706 | 707 | 708 | 709 | 710 | 711 | 712 | 713 | 714 | 715 | 716 | 717 | 718 | 719 | 720 | 721 | 722 | 723 | 724 | 725 | 726 |
Source:
727 |
730 | 731 | 732 | 733 | 734 | 735 | 736 | 737 |
738 | 739 | 740 | 741 | 742 | 743 | 744 | 745 | 746 | 747 | 748 | 749 | 750 | 751 |
Returns:
752 | 753 | 754 | 755 | 756 |
757 |
758 | Type 759 |
760 |
761 | 762 | string 763 | 764 | 765 |
766 |
767 | 768 | 769 | 770 | 771 | 772 | 773 | 774 | 775 | 776 | 777 | 778 | 779 | 780 |

(static) hasSafari10Bug() → {boolean}

781 | 782 | 783 | 784 | 785 | 786 | 787 |
788 | Returns true if the browser has the Safari 10 bugs. The native font load 789 | API in Safari 10 has two bugs that cause the document.fonts.load and 790 | FontFace.prototype.load methods to return promises that don't reliably get 791 | settled. 792 | 793 | The bugs are described in more detail here: 794 | - https://bugs.webkit.org/show_bug.cgi?id=165037 795 | - https://bugs.webkit.org/show_bug.cgi?id=164902 796 | 797 | If the browser is made by Apple, and has native font loading support, it is 798 | potentially affected. But the API was fixed around AppleWebKit version 603, 799 | so any newer versions that that does not contain the bug. 800 |
801 | 802 | 803 | 804 | 805 | 806 | 807 | 808 | 809 | 810 | 811 | 812 | 813 | 814 |
815 | 816 | 817 | 818 | 819 | 820 | 821 | 822 | 823 | 824 | 825 | 826 | 827 | 828 | 829 | 830 | 831 | 832 | 833 | 834 | 835 | 836 | 837 | 838 | 839 | 840 | 841 |
Source:
842 |
845 | 846 | 847 | 848 | 849 | 850 | 851 | 852 |
853 | 854 | 855 | 856 | 857 | 858 | 859 | 860 | 861 | 862 | 863 | 864 | 865 | 866 |
Returns:
867 | 868 | 869 | 870 | 871 |
872 |
873 | Type 874 |
875 |
876 | 877 | boolean 878 | 879 | 880 |
881 |
882 | 883 | 884 | 885 | 886 | 887 | 888 | 889 | 890 | 891 | 892 | 893 | 894 | 895 |

(static) hasWebKitFallbackBug() → {boolean}

896 | 897 | 898 | 899 | 900 | 901 | 902 |
903 | Returns true if this browser is WebKit and it has the fallback bug which is 904 | present in WebKit 536.11 and earlier. 905 |
906 | 907 | 908 | 909 | 910 | 911 | 912 | 913 | 914 | 915 | 916 | 917 | 918 | 919 |
920 | 921 | 922 | 923 | 924 | 925 | 926 | 927 | 928 | 929 | 930 | 931 | 932 | 933 | 934 | 935 | 936 | 937 | 938 | 939 | 940 | 941 | 942 | 943 | 944 | 945 | 946 |
Source:
947 |
950 | 951 | 952 | 953 | 954 | 955 | 956 | 957 |
958 | 959 | 960 | 961 | 962 | 963 | 964 | 965 | 966 | 967 | 968 | 969 | 970 | 971 |
Returns:
972 | 973 | 974 | 975 | 976 |
977 |
978 | Type 979 |
980 |
981 | 982 | boolean 983 | 984 | 985 |
986 |
987 | 988 | 989 | 990 | 991 | 992 | 993 | 994 | 995 | 996 | 997 | 998 | 999 | 1000 |

(static) supportsNativeFontLoading() → {boolean}

1001 | 1002 | 1003 | 1004 | 1005 | 1006 | 1007 |
1008 | Returns true if the browser supports the native font loading API. 1009 |
1010 | 1011 | 1012 | 1013 | 1014 | 1015 | 1016 | 1017 | 1018 | 1019 | 1020 | 1021 | 1022 | 1023 |
1024 | 1025 | 1026 | 1027 | 1028 | 1029 | 1030 | 1031 | 1032 | 1033 | 1034 | 1035 | 1036 | 1037 | 1038 | 1039 | 1040 | 1041 | 1042 | 1043 | 1044 | 1045 | 1046 | 1047 | 1048 | 1049 | 1050 |
Source:
1051 |
1054 | 1055 | 1056 | 1057 | 1058 | 1059 | 1060 | 1061 |
1062 | 1063 | 1064 | 1065 | 1066 | 1067 | 1068 | 1069 | 1070 | 1071 | 1072 | 1073 | 1074 | 1075 |
Returns:
1076 | 1077 | 1078 | 1079 | 1080 |
1081 |
1082 | Type 1083 |
1084 |
1085 | 1086 | boolean 1087 | 1088 | 1089 |
1090 |
1091 | 1092 | 1093 | 1094 | 1095 | 1096 | 1097 | 1098 | 1099 | 1100 | 1101 | 1102 | 1103 | 1104 |

(static) supportStretch() → {boolean}

1105 | 1106 | 1107 | 1108 | 1109 | 1110 | 1111 |
1112 | Returns true if the browser supports font-style in the font short-hand 1113 | syntax. 1114 |
1115 | 1116 | 1117 | 1118 | 1119 | 1120 | 1121 | 1122 | 1123 | 1124 | 1125 | 1126 | 1127 | 1128 |
1129 | 1130 | 1131 | 1132 | 1133 | 1134 | 1135 | 1136 | 1137 | 1138 | 1139 | 1140 | 1141 | 1142 | 1143 | 1144 | 1145 | 1146 | 1147 | 1148 | 1149 | 1150 | 1151 | 1152 | 1153 | 1154 | 1155 |
Source:
1156 |
1159 | 1160 | 1161 | 1162 | 1163 | 1164 | 1165 | 1166 |
1167 | 1168 | 1169 | 1170 | 1171 | 1172 | 1173 | 1174 | 1175 | 1176 | 1177 | 1178 | 1179 | 1180 |
Returns:
1181 | 1182 | 1183 | 1184 | 1185 |
1186 |
1187 | Type 1188 |
1189 |
1190 | 1191 | boolean 1192 | 1193 | 1194 |
1195 |
1196 | 1197 | 1198 | 1199 | 1200 | 1201 | 1202 | 1203 | 1204 | 1205 | 1206 | 1207 | 1208 | 1209 |

load(textopt, timeoutopt) → {Promise.<FontFaceObserver>}

1210 | 1211 | 1212 | 1213 | 1214 | 1215 | 1216 | 1217 | 1218 | 1219 | 1220 | 1221 | 1222 | 1223 | 1224 |
Parameters:
1225 | 1226 | 1227 | 1228 | 1229 | 1230 | 1231 | 1232 | 1233 | 1234 | 1235 | 1236 | 1237 | 1238 | 1239 | 1240 | 1241 | 1242 | 1243 | 1244 | 1245 | 1246 | 1247 | 1248 | 1249 | 1250 | 1251 | 1252 | 1253 | 1254 | 1262 | 1263 | 1264 | 1273 | 1274 | 1275 | 1276 | 1277 | 1279 | 1280 | 1281 | 1282 | 1283 | 1284 | 1285 | 1286 | 1287 | 1288 | 1296 | 1297 | 1298 | 1307 | 1308 | 1309 | 1310 | 1311 | 1313 | 1314 | 1315 | 1316 | 1317 |
NameTypeAttributesDescription
text 1255 | 1256 | 1257 | string 1258 | 1259 | 1260 | 1261 | 1265 | 1266 | <optional>
1267 | 1268 | 1269 | 1270 | 1271 | 1272 |
Optional test string to use for detecting if a font 1278 | is available.
timeout 1289 | 1290 | 1291 | number 1292 | 1293 | 1294 | 1295 | 1299 | 1300 | <optional>
1301 | 1302 | 1303 | 1304 | 1305 | 1306 |
Optional timeout for giving up on font load 1312 | detection and rejecting the promise (defaults to 3 seconds).
1318 | 1319 | 1320 | 1321 | 1322 | 1323 | 1324 |
1325 | 1326 | 1327 | 1328 | 1329 | 1330 | 1331 | 1332 | 1333 | 1334 | 1335 | 1336 | 1337 | 1338 | 1339 | 1340 | 1341 | 1342 | 1343 | 1344 | 1345 | 1346 | 1347 | 1348 | 1349 | 1350 | 1351 |
Source:
1352 |
1355 | 1356 | 1357 | 1358 | 1359 | 1360 | 1361 | 1362 |
1363 | 1364 | 1365 | 1366 | 1367 | 1368 | 1369 | 1370 | 1371 | 1372 | 1373 | 1374 | 1375 | 1376 |
Returns:
1377 | 1378 | 1379 | 1380 | 1381 |
1382 |
1383 | Type 1384 |
1385 |
1386 | 1387 | Promise.<FontFaceObserver> 1388 | 1389 | 1390 |
1391 |
1392 | 1393 | 1394 | 1395 | 1396 | 1397 | 1398 | 1399 | 1400 | 1401 | 1402 | 1403 | 1404 | 1405 |
1406 | 1407 |
1408 | 1409 | 1410 | 1411 | 1412 |
1413 | 1414 | 1417 | 1418 |
1419 | 1420 |
1421 | Documentation generated by JSDoc 3.5.5 on Mon Jun 22 2020 13:41:52 GMT+0100 (British Summer Time) 1422 |
1423 | 1424 | 1425 | 1426 | 1427 | -------------------------------------------------------------------------------- /docs/Ruler.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Class: Ruler 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Class: Ruler

21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 |
30 | 31 |

Ruler(text)

32 | 33 | 34 |
35 | 36 |
37 |
38 | 39 | 40 | 41 | 42 | 43 | 44 |

new Ruler(text)

45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 |
Parameters:
60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 |
NameTypeDescription
text 88 | 89 | 90 | string 91 | 92 | 93 | 94 |
106 | 107 | 108 | 109 | 110 | 111 | 112 |
113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 |
Source:
140 |
143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 |
151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 |
171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 |

Methods

188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 |

getElement() → {Element}

196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 |
215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 |
Source:
242 |
245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 |
253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 |
Returns:
267 | 268 | 269 | 270 | 271 |
272 |
273 | Type 274 |
275 |
276 | 277 | Element 278 | 279 | 280 |
281 |
282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 |

getWidth() → {number}

296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 |
315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 |
Source:
342 |
345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 |
353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 |
Returns:
367 | 368 | 369 | 370 | 371 |
372 |
373 | Type 374 |
375 |
376 | 377 | number 378 | 379 | 380 |
381 |
382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 |

onResize(callback)

396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 |
Parameters:
411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 |
NameTypeDescription
callback 439 | 440 | 441 | function 442 | 443 | 444 | 445 |
457 | 458 | 459 | 460 | 461 | 462 | 463 |
464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 |
Source:
491 |
494 | 495 | 496 | 497 | 498 | 499 | 500 | 501 |
502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 | 520 | 521 | 522 | 523 | 524 | 525 | 526 |

setFont(font)

527 | 528 | 529 | 530 | 531 | 532 | 533 | 534 | 535 | 536 | 537 | 538 | 539 | 540 | 541 |
Parameters:
542 | 543 | 544 | 545 | 546 | 547 | 548 | 549 | 550 | 551 | 552 | 553 | 554 | 555 | 556 | 557 | 558 | 559 | 560 | 561 | 562 | 563 | 564 | 565 | 566 | 567 | 568 | 569 | 577 | 578 | 579 | 580 | 581 | 582 | 583 | 584 | 585 | 586 | 587 |
NameTypeDescription
font 570 | 571 | 572 | string 573 | 574 | 575 | 576 |
588 | 589 | 590 | 591 | 592 | 593 | 594 |
595 | 596 | 597 | 598 | 599 | 600 | 601 | 602 | 603 | 604 | 605 | 606 | 607 | 608 | 609 | 610 | 611 | 612 | 613 | 614 | 615 | 616 | 617 | 618 | 619 | 620 | 621 |
Source:
622 |
625 | 626 | 627 | 628 | 629 | 630 | 631 | 632 |
633 | 634 | 635 | 636 | 637 | 638 | 639 | 640 | 641 | 642 | 643 | 644 | 645 | 646 | 647 | 648 | 649 | 650 | 651 | 652 | 653 | 654 | 655 | 656 | 657 |

setWidth(width)

658 | 659 | 660 | 661 | 662 | 663 | 664 | 665 | 666 | 667 | 668 | 669 | 670 | 671 | 672 |
Parameters:
673 | 674 | 675 | 676 | 677 | 678 | 679 | 680 | 681 | 682 | 683 | 684 | 685 | 686 | 687 | 688 | 689 | 690 | 691 | 692 | 693 | 694 | 695 | 696 | 697 | 698 | 699 | 700 | 708 | 709 | 710 | 711 | 712 | 713 | 714 | 715 | 716 | 717 | 718 |
NameTypeDescription
width 701 | 702 | 703 | string 704 | 705 | 706 | 707 |
719 | 720 | 721 | 722 | 723 | 724 | 725 |
726 | 727 | 728 | 729 | 730 | 731 | 732 | 733 | 734 | 735 | 736 | 737 | 738 | 739 | 740 | 741 | 742 | 743 | 744 | 745 | 746 | 747 | 748 | 749 | 750 | 751 | 752 |
Source:
753 |
756 | 757 | 758 | 759 | 760 | 761 | 762 | 763 |
764 | 765 | 766 | 767 | 768 | 769 | 770 | 771 | 772 | 773 | 774 | 775 | 776 | 777 | 778 | 779 | 780 | 781 | 782 | 783 | 784 | 785 | 786 | 787 | 788 |
789 | 790 |
791 | 792 | 793 | 794 | 795 |
796 | 797 | 800 | 801 |
802 | 803 |
804 | Documentation generated by JSDoc 3.5.5 on Mon Jun 22 2020 13:41:52 GMT+0100 (British Summer Time) 805 |
806 | 807 | 808 | 809 | 810 | -------------------------------------------------------------------------------- /docs/Ruler.js.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Source: ruler.js 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Source: ruler.js

21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 |
29 |
const styles = {
 30 |   maxWidth: "none",
 31 |   display: "inline-block",
 32 |   position: "absolute",
 33 |   height: "100%",
 34 |   width: "100%",
 35 |   overflow: "scroll",
 36 |   fontSize: "16px"
 37 | };
 38 | 
 39 | const collapsibleInnerStyles = {
 40 |   display: "inline-block",
 41 |   height: "200%",
 42 |   width: "200%",
 43 |   fontSize: "16px",
 44 |   maxWidth: "none"
 45 | };
 46 | 
 47 | const fontStyle = {
 48 |   maxWidth: "none",
 49 |   minWidth: "20px",
 50 |   minHeight: "20px",
 51 |   display: "inline-block",
 52 |   overflow: "hidden",
 53 |   position: "absolute",
 54 |   width: "auto",
 55 |   margin: "0",
 56 |   padding: "0",
 57 |   top: "-999px",
 58 |   whiteSpace: "nowrap",
 59 |   fontSynthesis: "none"
 60 | };
 61 | 
 62 | class Ruler {
 63 |   /**
 64 |    *
 65 |    * @param {string} text
 66 |    */
 67 |   constructor(text) {
 68 |     this.element = document.createElement("div");
 69 |     this.element.setAttribute("aria-hidden", "true");
 70 | 
 71 |     this.element.appendChild(document.createTextNode(text));
 72 | 
 73 |     this.collapsible = document.createElement("span");
 74 |     this.expandable = document.createElement("span");
 75 |     this.collapsibleInner = document.createElement("span");
 76 |     this.expandableInner = document.createElement("span");
 77 | 
 78 |     this.lastOffsetWidth = -1;
 79 | 
 80 |     Object.assign(this.collapsible.style, styles);
 81 |     Object.assign(this.expandable.style, styles);
 82 |     Object.assign(this.expandableInner.style, styles);
 83 |     Object.assign(this.collapsibleInner.style, collapsibleInnerStyles);
 84 | 
 85 |     this.collapsible.appendChild(this.collapsibleInner);
 86 |     this.expandable.appendChild(this.expandableInner);
 87 | 
 88 |     this.element.appendChild(this.collapsible);
 89 |     this.element.appendChild(this.expandable);
 90 |   }
 91 | 
 92 |   /**
 93 |    * @return {Element}
 94 |    */
 95 |   getElement() {
 96 |     return this.element;
 97 |   }
 98 | 
 99 |   /**
100 |    * @param {string} font
101 |    */
102 |   setFont(font) {
103 |     Object.assign(this.element.style, { ...fontStyle, font });
104 |   }
105 | 
106 |   /**
107 |    * @return {number}
108 |    */
109 |   getWidth() {
110 |     return this.element.offsetWidth;
111 |   }
112 | 
113 |   /**
114 |    * @param {string} width
115 |    */
116 |   setWidth(width) {
117 |     this.element.style.width = width + "px";
118 |   }
119 | 
120 |   /**
121 |    * @private
122 |    *
123 |    * @return {boolean}
124 |    */
125 |   reset() {
126 |     const offsetWidth = this.getWidth();
127 |     const width = offsetWidth + 100;
128 | 
129 |     this.expandableInner.style.width = width + "px";
130 |     this.expandable.scrollLeft = width;
131 |     this.collapsible.scrollLeft = this.collapsible.scrollWidth + 100;
132 | 
133 |     if (this.lastOffsetWidth !== offsetWidth) {
134 |       this.lastOffsetWidth = offsetWidth;
135 |       return true;
136 |     } else {
137 |       return false;
138 |     }
139 |   }
140 | 
141 |   /**
142 |    * @private
143 |    * @param {function(number)} callback
144 |    */
145 |   onScroll(callback) {
146 |     if (this.reset() && this.element.parentNode !== null) {
147 |       callback(this.lastOffsetWidth);
148 |     }
149 |   }
150 | 
151 |   /**
152 |    * @param {function(number)} callback
153 |    */
154 |   onResize(callback) {
155 |     var that = this;
156 | 
157 |     function onScroll() {
158 |       that.onScroll(callback);
159 |     }
160 | 
161 |     this.collapsible.addEventListener("scroll", onScroll);
162 |     this.expandable.addEventListener("scroll", onScroll);
163 |     this.reset();
164 |   }
165 | }
166 | 
167 | export default Ruler;
168 | 
169 |
170 |
171 | 172 | 173 | 174 | 175 |
176 | 177 | 180 | 181 |
182 | 183 |
184 | Documentation generated by JSDoc 3.5.5 on Mon Jun 22 2020 13:41:52 GMT+0100 (British Summer Time) 185 |
186 | 187 | 188 | 189 | 190 | 191 | -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Bold-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmnsgn/fontfaceobserver/6c12e94a086c011f1e1447e79031c3de6ee5ec2a/docs/fonts/OpenSans-Bold-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Bold-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmnsgn/fontfaceobserver/6c12e94a086c011f1e1447e79031c3de6ee5ec2a/docs/fonts/OpenSans-Bold-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-BoldItalic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmnsgn/fontfaceobserver/6c12e94a086c011f1e1447e79031c3de6ee5ec2a/docs/fonts/OpenSans-BoldItalic-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-BoldItalic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmnsgn/fontfaceobserver/6c12e94a086c011f1e1447e79031c3de6ee5ec2a/docs/fonts/OpenSans-BoldItalic-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Italic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmnsgn/fontfaceobserver/6c12e94a086c011f1e1447e79031c3de6ee5ec2a/docs/fonts/OpenSans-Italic-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Italic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmnsgn/fontfaceobserver/6c12e94a086c011f1e1447e79031c3de6ee5ec2a/docs/fonts/OpenSans-Italic-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Light-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmnsgn/fontfaceobserver/6c12e94a086c011f1e1447e79031c3de6ee5ec2a/docs/fonts/OpenSans-Light-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Light-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmnsgn/fontfaceobserver/6c12e94a086c011f1e1447e79031c3de6ee5ec2a/docs/fonts/OpenSans-Light-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-LightItalic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmnsgn/fontfaceobserver/6c12e94a086c011f1e1447e79031c3de6ee5ec2a/docs/fonts/OpenSans-LightItalic-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-LightItalic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmnsgn/fontfaceobserver/6c12e94a086c011f1e1447e79031c3de6ee5ec2a/docs/fonts/OpenSans-LightItalic-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Regular-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmnsgn/fontfaceobserver/6c12e94a086c011f1e1447e79031c3de6ee5ec2a/docs/fonts/OpenSans-Regular-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Regular-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmnsgn/fontfaceobserver/6c12e94a086c011f1e1447e79031c3de6ee5ec2a/docs/fonts/OpenSans-Regular-webfont.woff -------------------------------------------------------------------------------- /docs/global.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Global 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Global

21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 |
30 | 31 |

32 | 33 | 34 |
35 | 36 |
37 |
38 | 39 | 40 | 41 | 42 | 43 | 44 |
45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 |
78 | 79 | 80 | 81 | 82 |
83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 |

Type Definitions

102 | 103 | 104 | 105 |

Descriptors

106 | 107 | 108 | 109 | 110 | 111 | 112 |
Type:
113 |
    114 |
  • 115 | 116 | Object 117 | 118 | 119 |
  • 120 |
121 | 122 | 123 | 124 | 125 | 126 |
Properties:
127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 |
NameTypeDescription
style 156 | 157 | 158 | string 159 | | 160 | 161 | undefined 162 | 163 | 164 | 165 |
weight 182 | 183 | 184 | string 185 | | 186 | 187 | undefined 188 | 189 | 190 | 191 |
stretch 208 | 209 | 210 | string 211 | | 212 | 213 | undefined 214 | 215 | 216 | 217 |
229 | 230 | 231 | 232 | 233 |
234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 |
Source:
261 |
264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 |
272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 |
283 | 284 |
285 | 286 | 287 | 288 | 289 |
290 | 291 | 294 | 295 |
296 | 297 |
298 | Documentation generated by JSDoc 3.5.5 on Mon Jun 22 2020 13:41:52 GMT+0100 (British Summer Time) 299 |
300 | 301 | 302 | 303 | 304 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Home 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Home

21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 |

30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 |
46 |

Font Face Observer

Build Status 47 | npm version 48 | styled with prettier

49 |
50 |

Font Face Observer is a small @font-face loader and monitor (3.5KB minified and 1.3KB gzipped) compatible with any webfont service. It will monitor when a webfont is loaded and notify you. It does not limit you in any way in where, when, or how you load your webfonts. Unlike the Web Font Loader Font Face Observer uses scroll events to detect font loads efficiently and with minimum overhead.

51 |
52 |

Documentation

For details on how to use, check out the documentation.

53 |

Installation

Font Face Observer comes with three bundles:

54 |
    55 |
  • A CommonJS bundle (dist/fontfaceobserver.cjs.js) for use in NodeJS:
  • 56 |
57 |
npm install fontfaceobserver-es
var FontFaceObserver = require("fontfaceobserver-es");
 58 | 
 59 | var font = new FontFaceObserver("My Family");
 60 | 
 61 | font.load().then(function() {
 62 |   console.log("My Family has loaded");
 63 | });
    64 |
  • An ES module bundle (dist/fontfaceobserver.esm.js) for the above and also directly in the browser:
  • 65 |
66 |
<script type="module" src="https://unpkg.com/fontfaceobserver-es@3.0.0/dist/fontfaceobserver.esm.js"></script>
import FontFaceObserver from "fontfaceobserver-es";
 67 | 
 68 | const font = new FontFaceObserver("My Family");
 69 | 
 70 | font.load().then(function() {
 71 |   console.log("My Family has loaded");
 72 | });
    73 |
  • A UMD build (dist/fontfaceobserver.umd.js) mainly for browser without ES module support:
  • 74 |
75 |
<script src="https://unpkg.com/fontfaceobserver-es@3.0.0/dist/fontfaceobserver.umd.js"></script>
 76 | <script>
 77 | const font = new FontFaceObserver("My Family");
 78 | 
 79 | font.load().then(function() {
 80 |   console.log("My Family has loaded");
 81 | });
 82 | </script>

You'll need to include the required Polyfill for Promise support. See babel-polyfill and core-js.

83 |

Usage

Include your @font-face rules as usual. Fonts can be supplied by either a font service such as Google Fonts, Typekit, and Webtype or be self-hosted. You can set up monitoring for a single font family at a time:

84 |
const font = new FontFaceObserver("My Family", {
 85 |   weight: 400
 86 | });
 87 | 
 88 | font.load().then(
 89 |   function() {
 90 |     console.log("Font is available");
 91 |   },
 92 |   function() {
 93 |     console.log("Font is not available");
 94 |   }
 95 | );

The FontFaceObserver constructor takes two arguments: the font-family name (required) and an object describing the variation (optional). The object can contain weight, style, and stretch properties. If a property is not present it will default to normal. To start loading the font, call the load method. It'll immediately return a new Promise that resolves when the font is loaded and rejected when the font fails to load.

96 |

If your font doesn't contain at least the latin "BESbwy" characters you must pass a custom test string to the load method.

97 |
const font = new FontFaceObserver("My Family");
 98 | 
 99 | font.load("中国").then(
100 |   function() {
101 |     console.log("Font is available");
102 |   },
103 |   function() {
104 |     console.log("Font is not available");
105 |   }
106 | );

The default timeout for giving up on font loading is 3 seconds. You can increase or decrease this by passing a number of milliseconds as the second parameter to the load method.

107 |
var font = new FontFaceObserver("My Family");
108 | 
109 | font.load(null, 5000).then(
110 |   function() {
111 |     console.log("Font is available");
112 |   },
113 |   function() {
114 |     console.log("Font is not available after waiting 5 seconds");
115 |   }
116 | );

Multiple fonts can be loaded by creating a FontFaceObserver instance for each.

117 |
var fontA = new FontFaceObserver("Family A");
118 | var fontB = new FontFaceObserver("Family B");
119 | 
120 | fontA.load().then(function() {
121 |   console.log("Family A is available");
122 | });
123 | 
124 | fontB.load().then(function() {
125 |   console.log("Family B is available");
126 | });

You may also load both at the same time, rather than loading each individually.

127 |
var fontA = new FontFaceObserver("Family A");
128 | var fontB = new FontFaceObserver("Family B");
129 | 
130 | Promise.all([fontA.load(), fontB.load()]).then(function() {
131 |   console.log("Family A & B have loaded");
132 | });

If you are working with a large number of fonts, you may decide to create FontFaceObserver instances dynamically:

133 |
// An example collection of font data with additional metadata,
134 | // in this case “color.”
135 | var exampleFontData = {
136 |   'Family A': { weight: 400, color: 'red' },
137 |   'Family B': { weight: 400, color: 'orange' },
138 |   'Family C': { weight: 900, color: 'yellow' },
139 |   // Etc.
140 | };
141 | 
142 | var observers = [];
143 | 
144 | // Make one observer for each font,
145 | // by iterating over the data we already have
146 | Object.keys(exampleFontData).forEach(function(family) {
147 |   var data = exampleFontData[family];
148 |   var obs = new FontFaceObserver(family, data);
149 |   observers.push(obs.load());
150 | });
151 | 
152 | Promise.all(observers)
153 |   .then(function(fonts) {
154 |     fonts.forEach(function(font) {
155 |       console.log(font.family + ' ' + font.weight + ' ' + 'loaded');
156 | 
157 |       // Map the result of the Promise back to our existing data,
158 |       // to get the other properties we need.
159 |       console.log(exampleFontData[font.family].color);
160 |     });
161 |   })
162 |   .catch(function(err) {
163 |     console.warn('Some critical font are not available:', err);
164 |   });

The following example emulates FOUT with Font Face Observer for My Family.

165 |
var font = new FontFaceObserver("My Family");
166 | 
167 | font.load().then(function() {
168 |   document.documentElement.className += " fonts-loaded";
169 | });
.fonts-loaded {
170 |   body {
171 |     font-family: My Family, sans-serif;
172 |   }
173 | }

Browser support

FontFaceObserver has been tested and works on the following browsers:

174 |
    175 |
  • Chrome (desktop & Android)
  • 176 |
  • Firefox
  • 177 |
  • Opera
  • 178 |
  • Safari (desktop & iOS)
  • 179 |
  • IE8+
  • 180 |
  • Android WebKit
  • 181 |
182 |

License

Font Face Observer is licensed under the BSD License. Copyright 2014-2017 Bram Stein and Damien Seguin. All rights reserved.

183 |
184 | 185 | 186 | 187 | 188 | 189 | 190 |
191 | 192 | 195 | 196 |
197 | 198 |
199 | Documentation generated by JSDoc 3.5.5 on Mon Jun 22 2020 13:41:52 GMT+0100 (British Summer Time) 200 |
201 | 202 | 203 | 204 | 205 | -------------------------------------------------------------------------------- /docs/index.js.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Source: index.js 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Source: index.js

21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 |
29 |
import Ruler from "./ruler.js";
 30 | import { onReady } from "./dom.js";
 31 | 
 32 | /** Class for FontFaceObserver. */
 33 | class FontFaceObserver {
 34 |   static Ruler = Ruler;
 35 | 
 36 |   /**
 37 |    * @type {null|boolean}
 38 |    */
 39 |   static HAS_WEBKIT_FALLBACK_BUG = null;
 40 | 
 41 |   /**
 42 |    * @type {null|boolean}
 43 |    */
 44 |   static HAS_SAFARI_10_BUG = null;
 45 | 
 46 |   /**
 47 |    * @type {null|boolean}
 48 |    */
 49 |   static SUPPORTS_STRETCH = null;
 50 | 
 51 |   /**
 52 |    * @type {null|boolean}
 53 |    */
 54 |   static SUPPORTS_NATIVE_FONT_LOADING = null;
 55 | 
 56 |   /**
 57 |    * @type {number}
 58 |    */
 59 |   static DEFAULT_TIMEOUT = 3000;
 60 | 
 61 |   /**
 62 |    * @return {string}
 63 |    */
 64 |   static getUserAgent() {
 65 |     return window.navigator.userAgent;
 66 |   }
 67 | 
 68 |   /**
 69 |    * @return {string}
 70 |    */
 71 |   static getNavigatorVendor() {
 72 |     return window.navigator.vendor;
 73 |   }
 74 | 
 75 |   /**
 76 |    * Returns true if this browser is WebKit and it has the fallback bug which is
 77 |    * present in WebKit 536.11 and earlier.
 78 |    *
 79 |    * @return {boolean}
 80 |    */
 81 |   static hasWebKitFallbackBug() {
 82 |     if (FontFaceObserver.HAS_WEBKIT_FALLBACK_BUG === null) {
 83 |       const match = /AppleWebKit\/([0-9]+)(?:\.([0-9]+))/.exec(
 84 |         FontFaceObserver.getUserAgent()
 85 |       );
 86 | 
 87 |       FontFaceObserver.HAS_WEBKIT_FALLBACK_BUG =
 88 |         !!match &&
 89 |         (parseInt(match[1], 10) < 536 ||
 90 |           (parseInt(match[1], 10) === 536 && parseInt(match[2], 10) <= 11));
 91 |     }
 92 |     return FontFaceObserver.HAS_WEBKIT_FALLBACK_BUG;
 93 |   }
 94 | 
 95 |   /**
 96 |    * Returns true if the browser has the Safari 10 bugs. The native font load
 97 |    * API in Safari 10 has two bugs that cause the document.fonts.load and
 98 |    * FontFace.prototype.load methods to return promises that don't reliably get
 99 |    * settled.
100 |    *
101 |    * The bugs are described in more detail here:
102 |    *  - https://bugs.webkit.org/show_bug.cgi?id=165037
103 |    *  - https://bugs.webkit.org/show_bug.cgi?id=164902
104 |    *
105 |    * If the browser is made by Apple, and has native font loading support, it is
106 |    * potentially affected. But the API was fixed around AppleWebKit version 603,
107 |    * so any newer versions that that does not contain the bug.
108 |    *
109 |    * @return {boolean}
110 |    */
111 |   static hasSafari10Bug() {
112 |     if (FontFaceObserver.HAS_SAFARI_10_BUG === null) {
113 |       if (
114 |         FontFaceObserver.supportsNativeFontLoading() &&
115 |         /Apple/.test(FontFaceObserver.getNavigatorVendor())
116 |       ) {
117 |         const match = /AppleWebKit\/([0-9]+)(?:\.([0-9]+))(?:\.([0-9]+))/.exec(
118 |           FontFaceObserver.getUserAgent()
119 |         );
120 | 
121 |         FontFaceObserver.HAS_SAFARI_10_BUG =
122 |           !!match && parseInt(match[1], 10) < 603;
123 |       } else {
124 |         FontFaceObserver.HAS_SAFARI_10_BUG = false;
125 |       }
126 |     }
127 |     return FontFaceObserver.HAS_SAFARI_10_BUG;
128 |   }
129 | 
130 |   /**
131 |    * Returns true if the browser supports the native font loading API.
132 |    *
133 |    * @return {boolean}
134 |    */
135 |   static supportsNativeFontLoading() {
136 |     if (FontFaceObserver.SUPPORTS_NATIVE_FONT_LOADING === null) {
137 |       FontFaceObserver.SUPPORTS_NATIVE_FONT_LOADING = !!document["fonts"];
138 |     }
139 |     return FontFaceObserver.SUPPORTS_NATIVE_FONT_LOADING;
140 |   }
141 | 
142 |   /**
143 |    * Returns true if the browser supports font-style in the font short-hand
144 |    * syntax.
145 |    *
146 |    * @return {boolean}
147 |    */
148 |   static supportStretch() {
149 |     if (FontFaceObserver.SUPPORTS_STRETCH === null) {
150 |       const div = document.createElement("div");
151 | 
152 |       try {
153 |         div.style.font = "condensed 100px sans-serif";
154 |       } catch (e) {}
155 |       FontFaceObserver.SUPPORTS_STRETCH = div.style.font !== "";
156 |     }
157 | 
158 |     return FontFaceObserver.SUPPORTS_STRETCH;
159 |   }
160 | 
161 |   /**
162 |    * @typedef {Object} Descriptors
163 |    * @property {string|undefined} style
164 |    * @property {string|undefined} weight
165 |    * @property {string|undefined} stretch
166 |    */
167 |   /**
168 |    *
169 |    * @param {string} family font-family name (required)
170 |    * @param {Descriptors} descriptors an object describing the variation
171 |    * (optional). The object can contain `weight`, `style`, and `stretch`
172 |    * properties. If a property is not present it will default to `normal`.
173 |    */
174 |   constructor(family, descriptors = {}) {
175 |     this.family = family;
176 | 
177 |     this.style = descriptors.style || "normal";
178 |     this.weight = descriptors.weight || "normal";
179 |     this.stretch = descriptors.stretch || "normal";
180 | 
181 |     return this;
182 |   }
183 | 
184 |   /**
185 |    * @param {string=} text Optional test string to use for detecting if a font
186 |    * is available.
187 |    * @param {number=} timeout Optional timeout for giving up on font load
188 |    * detection and rejecting the promise (defaults to 3 seconds).
189 |    * @return {Promise.<FontFaceObserver>}
190 |    */
191 |   load(text, timeout) {
192 |     const that = this;
193 |     const testString = text || "BESbswy";
194 |     let timeoutId = 0;
195 |     const timeoutValue = timeout || FontFaceObserver.DEFAULT_TIMEOUT;
196 |     const start = that.getTime();
197 | 
198 |     return new Promise(function(resolve, reject) {
199 |       if (
200 |         FontFaceObserver.supportsNativeFontLoading() &&
201 |         !FontFaceObserver.hasSafari10Bug()
202 |       ) {
203 |         const loader = new Promise(function(resolve, reject) {
204 |           const check = function() {
205 |             const now = that.getTime();
206 | 
207 |             if (now - start >= timeoutValue) {
208 |               reject(new Error("" + timeoutValue + "ms timeout exceeded"));
209 |             } else {
210 |               document.fonts
211 |                 .load(that.getStyle('"' + that["family"] + '"'), testString)
212 |                 .then(function(fonts) {
213 |                   if (fonts.length >= 1) {
214 |                     resolve();
215 |                   } else {
216 |                     setTimeout(check, 25);
217 |                   }
218 |                 }, reject);
219 |             }
220 |           };
221 |           check();
222 |         });
223 | 
224 |         const timer = new Promise(function(resolve, reject) {
225 |           timeoutId = setTimeout(function() {
226 |             reject(new Error("" + timeoutValue + "ms timeout exceeded"));
227 |           }, timeoutValue);
228 |         });
229 | 
230 |         Promise.race([timer, loader]).then(function() {
231 |           clearTimeout(timeoutId);
232 |           resolve(that);
233 |         }, reject);
234 |       } else {
235 |         onReady(function() {
236 |           const rulerA = new Ruler(testString);
237 |           const rulerB = new Ruler(testString);
238 |           const rulerC = new Ruler(testString);
239 | 
240 |           let widthA = -1;
241 |           let widthB = -1;
242 |           let widthC = -1;
243 | 
244 |           let fallbackWidthA = -1;
245 |           let fallbackWidthB = -1;
246 |           let fallbackWidthC = -1;
247 | 
248 |           const container = document.createElement("div");
249 | 
250 |           /**
251 |            * @private
252 |            */
253 |           function removeContainer() {
254 |             if (container.parentNode !== null) {
255 |               container.parentNode.removeChild(container);
256 |             }
257 |           }
258 | 
259 |           /**
260 |            * @private
261 |            *
262 |            * If metric compatible fonts are detected, one of the widths will be
263 |            * -1. This is because a metric compatible font won't trigger a scroll
264 |            * event. We work around this by considering a font loaded if at least
265 |            * two of the widths are the same. Because we have three widths, this
266 |            * still prevents false positives.
267 |            *
268 |            * Cases:
269 |            * 1) Font loads: both a, b and c are called and have the same value.
270 |            * 2) Font fails to load: resize callback is never called and timeout
271 |            *    happens.
272 |            * 3) WebKit bug: both a, b and c are called and have the same value,
273 |            *    but the values are equal to one of the last resort fonts, we
274 |            *    ignore this and continue waiting until we get new values (or a
275 |            *    timeout).
276 |            */
277 |           function check() {
278 |             if (
279 |               (widthA != -1 && widthB != -1) ||
280 |               (widthA != -1 && widthC != -1) ||
281 |               (widthB != -1 && widthC != -1)
282 |             ) {
283 |               if (widthA == widthB || widthA == widthC || widthB == widthC) {
284 |                 // All values are the same, so the browser has most likely
285 |                 // loaded the web font
286 | 
287 |                 if (FontFaceObserver.hasWebKitFallbackBug()) {
288 |                   // Except if the browser has the WebKit fallback bug, in which
289 |                   // case we check to see if all values are set to one of the
290 |                   // last resort fonts.
291 | 
292 |                   if (
293 |                     (widthA == fallbackWidthA &&
294 |                       widthB == fallbackWidthA &&
295 |                       widthC == fallbackWidthA) ||
296 |                     (widthA == fallbackWidthB &&
297 |                       widthB == fallbackWidthB &&
298 |                       widthC == fallbackWidthB) ||
299 |                     (widthA == fallbackWidthC &&
300 |                       widthB == fallbackWidthC &&
301 |                       widthC == fallbackWidthC)
302 |                   ) {
303 |                     // The width we got matches some of the known last resort
304 |                     // fonts, so let's assume we're dealing with the last resort
305 |                     // font.
306 |                     return;
307 |                   }
308 |                 }
309 |                 removeContainer();
310 |                 clearTimeout(timeoutId);
311 |                 resolve(that);
312 |               }
313 |             }
314 |           }
315 | 
316 |           // This ensures the scroll direction is correct.
317 |           container.dir = "ltr";
318 | 
319 |           rulerA.setFont(that.getStyle("sans-serif"));
320 |           rulerB.setFont(that.getStyle("serif"));
321 |           rulerC.setFont(that.getStyle("monospace"));
322 | 
323 |           container.appendChild(rulerA.getElement());
324 |           container.appendChild(rulerB.getElement());
325 |           container.appendChild(rulerC.getElement());
326 | 
327 |           document.body.appendChild(container);
328 | 
329 |           fallbackWidthA = rulerA.getWidth();
330 |           fallbackWidthB = rulerB.getWidth();
331 |           fallbackWidthC = rulerC.getWidth();
332 | 
333 |           function checkForTimeout() {
334 |             const now = that.getTime();
335 | 
336 |             if (now - start >= timeoutValue) {
337 |               removeContainer();
338 |               reject(new Error("" + timeoutValue + "ms timeout exceeded"));
339 |             } else {
340 |               const hidden = document["hidden"];
341 |               if (hidden === true || hidden === undefined) {
342 |                 widthA = rulerA.getWidth();
343 |                 widthB = rulerB.getWidth();
344 |                 widthC = rulerC.getWidth();
345 |                 check();
346 |               }
347 |               timeoutId = setTimeout(checkForTimeout, 50);
348 |             }
349 |           }
350 | 
351 |           checkForTimeout();
352 | 
353 |           rulerA.onResize(function(width) {
354 |             widthA = width;
355 |             check();
356 |           });
357 | 
358 |           rulerA.setFont(that.getStyle('"' + that["family"] + '",sans-serif'));
359 | 
360 |           rulerB.onResize(function(width) {
361 |             widthB = width;
362 |             check();
363 |           });
364 | 
365 |           rulerB.setFont(that.getStyle('"' + that["family"] + '",serif'));
366 | 
367 |           rulerC.onResize(function(width) {
368 |             widthC = width;
369 |             check();
370 |           });
371 | 
372 |           rulerC.setFont(that.getStyle('"' + that["family"] + '",monospace'));
373 |         });
374 |       }
375 |     });
376 |   }
377 | 
378 |   /**
379 |    * @private
380 |    *
381 |    * @param {string} family
382 |    * @return {string}
383 |    */
384 |   getStyle(family) {
385 |     return [
386 |       this.style,
387 |       this.weight,
388 |       FontFaceObserver.supportStretch() ? this.stretch : "",
389 |       "100px",
390 |       family
391 |     ].join(" ");
392 |   }
393 |   /**
394 |    * @private
395 |    *
396 |    * @return {number}
397 |    */
398 |   getTime() {
399 |     return new Date().getTime();
400 |   }
401 | }
402 | 
403 | export default FontFaceObserver;
404 | 
405 |
406 |
407 | 408 | 409 | 410 | 411 |
412 | 413 | 416 | 417 |
418 | 419 |
420 | Documentation generated by JSDoc 3.5.5 on Mon Jun 22 2020 13:41:52 GMT+0100 (British Summer Time) 421 |
422 | 423 | 424 | 425 | 426 | 427 | -------------------------------------------------------------------------------- /docs/scripts/linenumber.js: -------------------------------------------------------------------------------- 1 | /*global document */ 2 | (function() { 3 | var source = document.getElementsByClassName('prettyprint source linenums'); 4 | var i = 0; 5 | var lineNumber = 0; 6 | var lineId; 7 | var lines; 8 | var totalLines; 9 | var anchorHash; 10 | 11 | if (source && source[0]) { 12 | anchorHash = document.location.hash.substring(1); 13 | lines = source[0].getElementsByTagName('li'); 14 | totalLines = lines.length; 15 | 16 | for (; i < totalLines; i++) { 17 | lineNumber++; 18 | lineId = 'line' + lineNumber; 19 | lines[i].id = lineId; 20 | if (lineId === anchorHash) { 21 | lines[i].className += ' selected'; 22 | } 23 | } 24 | } 25 | })(); 26 | -------------------------------------------------------------------------------- /docs/scripts/prettify/Apache-License-2.0.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /docs/scripts/prettify/lang-css.js: -------------------------------------------------------------------------------- 1 | PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\f\r ]+/,null," \t\r\n "]],[["str",/^"(?:[^\n\f\r"\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*"/,null],["str",/^'(?:[^\n\f\r'\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*'/,null],["lang-css-str",/^url\(([^"')]*)\)/i],["kwd",/^(?:url|rgb|!important|@import|@page|@media|@charset|inherit)(?=[^\w-]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*)\s*:/i],["com",/^\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//],["com", 2 | /^(?:<\!--|--\>)/],["lit",/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],["lit",/^#[\da-f]{3,6}/i],["pln",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i],["pun",/^[^\s\w"']+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[["kwd",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[["str",/^[^"')]+/]]),["css-str"]); 3 | -------------------------------------------------------------------------------- /docs/scripts/prettify/prettify.js: -------------------------------------------------------------------------------- 1 | var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; 2 | (function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= 3 | [],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;ci[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), 9 | l=[],p={},d=0,g=e.length;d=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, 10 | q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, 11 | q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, 12 | "");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), 13 | a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} 14 | for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], 18 | "catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], 19 | H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], 20 | J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ 21 | I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), 22 | ["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", 23 | /^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), 24 | ["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", 25 | hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p=0){var k=k.match(g),f,b;if(b= 26 | !k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p th:last-child { border-right: 1px solid #ddd; } 224 | 225 | .ancestors, .attribs { color: #999; } 226 | .ancestors a, .attribs a 227 | { 228 | color: #999 !important; 229 | text-decoration: none; 230 | } 231 | 232 | .clear 233 | { 234 | clear: both; 235 | } 236 | 237 | .important 238 | { 239 | font-weight: bold; 240 | color: #950B02; 241 | } 242 | 243 | .yes-def { 244 | text-indent: -1000px; 245 | } 246 | 247 | .type-signature { 248 | color: #aaa; 249 | } 250 | 251 | .name, .signature { 252 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 253 | } 254 | 255 | .details { margin-top: 14px; border-left: 2px solid #DDD; } 256 | .details dt { width: 120px; float: left; padding-left: 10px; padding-top: 6px; } 257 | .details dd { margin-left: 70px; } 258 | .details ul { margin: 0; } 259 | .details ul { list-style-type: none; } 260 | .details li { margin-left: 30px; padding-top: 6px; } 261 | .details pre.prettyprint { margin: 0 } 262 | .details .object-value { padding-top: 0; } 263 | 264 | .description { 265 | margin-bottom: 1em; 266 | margin-top: 1em; 267 | } 268 | 269 | .code-caption 270 | { 271 | font-style: italic; 272 | font-size: 107%; 273 | margin: 0; 274 | } 275 | 276 | .prettyprint 277 | { 278 | border: 1px solid #ddd; 279 | width: 80%; 280 | overflow: auto; 281 | } 282 | 283 | .prettyprint.source { 284 | width: inherit; 285 | } 286 | 287 | .prettyprint code 288 | { 289 | font-size: 100%; 290 | line-height: 18px; 291 | display: block; 292 | padding: 4px 12px; 293 | margin: 0; 294 | background-color: #fff; 295 | color: #4D4E53; 296 | } 297 | 298 | .prettyprint code span.line 299 | { 300 | display: inline-block; 301 | } 302 | 303 | .prettyprint.linenums 304 | { 305 | padding-left: 70px; 306 | -webkit-user-select: none; 307 | -moz-user-select: none; 308 | -ms-user-select: none; 309 | user-select: none; 310 | } 311 | 312 | .prettyprint.linenums ol 313 | { 314 | padding-left: 0; 315 | } 316 | 317 | .prettyprint.linenums li 318 | { 319 | border-left: 3px #ddd solid; 320 | } 321 | 322 | .prettyprint.linenums li.selected, 323 | .prettyprint.linenums li.selected * 324 | { 325 | background-color: lightyellow; 326 | } 327 | 328 | .prettyprint.linenums li * 329 | { 330 | -webkit-user-select: text; 331 | -moz-user-select: text; 332 | -ms-user-select: text; 333 | user-select: text; 334 | } 335 | 336 | .params .name, .props .name, .name code { 337 | color: #4D4E53; 338 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 339 | font-size: 100%; 340 | } 341 | 342 | .params td.description > p:first-child, 343 | .props td.description > p:first-child 344 | { 345 | margin-top: 0; 346 | padding-top: 0; 347 | } 348 | 349 | .params td.description > p:last-child, 350 | .props td.description > p:last-child 351 | { 352 | margin-bottom: 0; 353 | padding-bottom: 0; 354 | } 355 | 356 | .disabled { 357 | color: #454545; 358 | } 359 | -------------------------------------------------------------------------------- /docs/styles/prettify-jsdoc.css: -------------------------------------------------------------------------------- 1 | /* JSDoc prettify.js theme */ 2 | 3 | /* plain text */ 4 | .pln { 5 | color: #000000; 6 | font-weight: normal; 7 | font-style: normal; 8 | } 9 | 10 | /* string content */ 11 | .str { 12 | color: #006400; 13 | font-weight: normal; 14 | font-style: normal; 15 | } 16 | 17 | /* a keyword */ 18 | .kwd { 19 | color: #000000; 20 | font-weight: bold; 21 | font-style: normal; 22 | } 23 | 24 | /* a comment */ 25 | .com { 26 | font-weight: normal; 27 | font-style: italic; 28 | } 29 | 30 | /* a type name */ 31 | .typ { 32 | color: #000000; 33 | font-weight: normal; 34 | font-style: normal; 35 | } 36 | 37 | /* a literal value */ 38 | .lit { 39 | color: #006400; 40 | font-weight: normal; 41 | font-style: normal; 42 | } 43 | 44 | /* punctuation */ 45 | .pun { 46 | color: #000000; 47 | font-weight: bold; 48 | font-style: normal; 49 | } 50 | 51 | /* lisp open bracket */ 52 | .opn { 53 | color: #000000; 54 | font-weight: bold; 55 | font-style: normal; 56 | } 57 | 58 | /* lisp close bracket */ 59 | .clo { 60 | color: #000000; 61 | font-weight: bold; 62 | font-style: normal; 63 | } 64 | 65 | /* a markup tag name */ 66 | .tag { 67 | color: #006400; 68 | font-weight: normal; 69 | font-style: normal; 70 | } 71 | 72 | /* a markup attribute name */ 73 | .atn { 74 | color: #006400; 75 | font-weight: normal; 76 | font-style: normal; 77 | } 78 | 79 | /* a markup attribute value */ 80 | .atv { 81 | color: #006400; 82 | font-weight: normal; 83 | font-style: normal; 84 | } 85 | 86 | /* a declaration */ 87 | .dec { 88 | color: #000000; 89 | font-weight: bold; 90 | font-style: normal; 91 | } 92 | 93 | /* a variable name */ 94 | .var { 95 | color: #000000; 96 | font-weight: normal; 97 | font-style: normal; 98 | } 99 | 100 | /* a function name */ 101 | .fun { 102 | color: #000000; 103 | font-weight: bold; 104 | font-style: normal; 105 | } 106 | 107 | /* Specify class=linenums on a pre to get line numbering */ 108 | ol.linenums { 109 | margin-top: 0; 110 | margin-bottom: 0; 111 | } 112 | -------------------------------------------------------------------------------- /docs/styles/prettify-tomorrow.css: -------------------------------------------------------------------------------- 1 | /* Tomorrow Theme */ 2 | /* Original theme - https://github.com/chriskempson/tomorrow-theme */ 3 | /* Pretty printing styles. Used with prettify.js. */ 4 | /* SPAN elements with the classes below are added by prettyprint. */ 5 | /* plain text */ 6 | .pln { 7 | color: #4d4d4c; } 8 | 9 | @media screen { 10 | /* string content */ 11 | .str { 12 | color: #718c00; } 13 | 14 | /* a keyword */ 15 | .kwd { 16 | color: #8959a8; } 17 | 18 | /* a comment */ 19 | .com { 20 | color: #8e908c; } 21 | 22 | /* a type name */ 23 | .typ { 24 | color: #4271ae; } 25 | 26 | /* a literal value */ 27 | .lit { 28 | color: #f5871f; } 29 | 30 | /* punctuation */ 31 | .pun { 32 | color: #4d4d4c; } 33 | 34 | /* lisp open bracket */ 35 | .opn { 36 | color: #4d4d4c; } 37 | 38 | /* lisp close bracket */ 39 | .clo { 40 | color: #4d4d4c; } 41 | 42 | /* a markup tag name */ 43 | .tag { 44 | color: #c82829; } 45 | 46 | /* a markup attribute name */ 47 | .atn { 48 | color: #f5871f; } 49 | 50 | /* a markup attribute value */ 51 | .atv { 52 | color: #3e999f; } 53 | 54 | /* a declaration */ 55 | .dec { 56 | color: #f5871f; } 57 | 58 | /* a variable name */ 59 | .var { 60 | color: #c82829; } 61 | 62 | /* a function name */ 63 | .fun { 64 | color: #4271ae; } } 65 | /* Use higher contrast and text-weight for printable form. */ 66 | @media print, projection { 67 | .str { 68 | color: #060; } 69 | 70 | .kwd { 71 | color: #006; 72 | font-weight: bold; } 73 | 74 | .com { 75 | color: #600; 76 | font-style: italic; } 77 | 78 | .typ { 79 | color: #404; 80 | font-weight: bold; } 81 | 82 | .lit { 83 | color: #044; } 84 | 85 | .pun, .opn, .clo { 86 | color: #440; } 87 | 88 | .tag { 89 | color: #006; 90 | font-weight: bold; } 91 | 92 | .atn { 93 | color: #404; } 94 | 95 | .atv { 96 | color: #060; } } 97 | /* Style */ 98 | /* 99 | pre.prettyprint { 100 | background: white; 101 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 102 | font-size: 12px; 103 | line-height: 1.5; 104 | border: 1px solid #ccc; 105 | padding: 10px; } 106 | */ 107 | 108 | /* Specify class=linenums on a pre to get line numbering */ 109 | ol.linenums { 110 | margin-top: 0; 111 | margin-bottom: 0; } 112 | 113 | /* IE indents via margin-left */ 114 | li.L0, 115 | li.L1, 116 | li.L2, 117 | li.L3, 118 | li.L4, 119 | li.L5, 120 | li.L6, 121 | li.L7, 122 | li.L8, 123 | li.L9 { 124 | /* */ } 125 | 126 | /* Alternate shading for lines */ 127 | li.L1, 128 | li.L3, 129 | li.L5, 130 | li.L7, 131 | li.L9 { 132 | /* */ } 133 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fontfaceobserver-es", 3 | "version": "3.3.3", 4 | "description": "Detect if web fonts are available", 5 | "directories": { 6 | "test": "test" 7 | }, 8 | "repository": { 9 | "type": "git", 10 | "url": "git+https://github.com/dmnsgn/fontfaceobserver.git" 11 | }, 12 | "bugs": { 13 | "url": "https://github.com/dmnsgn/fontfaceobserver/issues" 14 | }, 15 | "homepage": "https://fontfaceobserver.com/", 16 | "main": "dist/fontfaceobserver.cjs.js", 17 | "browser": "dist/fontfaceobserver.umd.js", 18 | "module": "dist/fontfaceobserver.esm.js", 19 | "types": "src/types.d.ts", 20 | "keywords": [ 21 | "fontloader", 22 | "fonts", 23 | "font", 24 | "font-face", 25 | "web font", 26 | "font load", 27 | "font events" 28 | ], 29 | "files": [ 30 | "dist/fontfaceobserver.cjs.js", 31 | "dist/fontfaceobserver.esm.js", 32 | "dist/fontfaceobserver.umd.js", 33 | "src/*.js", 34 | "src/*.ts" 35 | ], 36 | "author": "Bram Stein (http://www.bramstein.com/)", 37 | "contributors": [ 38 | "Damien Seguin (https://dmnsgn.me/)" 39 | ], 40 | "license": "BSD-3-Clause", 41 | "devDependencies": { 42 | "@babel/core": "^7.3.4", 43 | "@babel/plugin-proposal-class-properties": "^7.3.4", 44 | "@babel/plugin-proposal-object-rest-spread": "^7.3.4", 45 | "@babel/preset-env": "^7.3.4", 46 | "babel-eslint": "^10.0.1", 47 | "babel-polyfill": "^6.26.0", 48 | "eslint": "^5.15.2", 49 | "eslint-config-prettier": "^4.1.0", 50 | "eslint-plugin-prettier": "^3.0.1", 51 | "jsdoc": "^3.5.5", 52 | "mocha": "^6.0.2", 53 | "mocha-phantomjs-core": "^2.1.2", 54 | "phantomjs-prebuilt": "^2.1.16", 55 | "prettier": "^1.16.4", 56 | "rollup": "^1.6.0", 57 | "rollup-plugin-babel": "^4.3.2", 58 | "rollup-plugin-commonjs": "^9.2.1", 59 | "rollup-plugin-node-resolve": "^4.0.1", 60 | "rollup-plugin-uglify": "^6.0.2", 61 | "sinon": "^7.2.7", 62 | "unexpected": "^11.2.0" 63 | }, 64 | "scripts": { 65 | "dev": "rollup -c -w -m inline --environment NODE_ENV:development", 66 | "build": "rollup -c --environment NODE_ENV:production", 67 | "clean": "rm -rf dist && rm -rf docs", 68 | "lint": "eslint 'src/**/*.js'", 69 | "docs": "jsdoc ./src --destination docs --readme README.md", 70 | "preversion": "npm test && npm run lint", 71 | "version": "npm run build && npm run docs && git add -A", 72 | "postversion": "git push && git push --tags && npm publish", 73 | "test": "npx phantomjs ./node_modules/mocha-phantomjs-core/mocha-phantomjs-core.js test/index.html spec" 74 | }, 75 | "eslintConfig": { 76 | "parser": "babel-eslint", 77 | "extends": [ 78 | "prettier" 79 | ], 80 | "plugins": [ 81 | "prettier" 82 | ], 83 | "rules": { 84 | "prettier/prettier": "error" 85 | }, 86 | "parserOptions": { 87 | "ecmaVersion": 2019, 88 | "sourceType": "module" 89 | } 90 | }, 91 | "eslintIgnore": [ 92 | "node_modules" 93 | ] 94 | } 95 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import resolve from "rollup-plugin-node-resolve"; 2 | import commonjs from "rollup-plugin-commonjs"; 3 | import babel from "rollup-plugin-babel"; 4 | import { uglify } from "rollup-plugin-uglify"; 5 | import pkg from "./package.json"; 6 | 7 | const copyright = "© Bram Stein - Damien Seguin. License: BSD-3-Clause"; 8 | const banner = `/* Font Face Observer v${pkg.version} - ${copyright} */`; 9 | 10 | const babelCommonOptions = { 11 | exclude: ["node_modules/**"], 12 | plugins: [ 13 | "@babel/plugin-proposal-class-properties", 14 | "@babel/plugin-proposal-object-rest-spread" 15 | ] 16 | }; 17 | 18 | const isDev = process.env.NODE_ENV === "development"; 19 | 20 | export default [ 21 | { 22 | input: "src/index.js", 23 | plugins: [ 24 | resolve(), 25 | babel({ 26 | ...babelCommonOptions, 27 | presets: [ 28 | [ 29 | "@babel/preset-env", 30 | { 31 | targets: { 32 | browsers: ["ie >= 8"] 33 | }, 34 | modules: false 35 | } 36 | ] 37 | ] 38 | }), 39 | commonjs(), 40 | isDev ? 0 : uglify() 41 | ].filter(Boolean), 42 | output: { 43 | banner, 44 | name: "FontFaceObserver", 45 | file: pkg.browser, 46 | format: "umd" 47 | } 48 | }, 49 | { 50 | input: "src/index.js", 51 | plugins: [ 52 | babel({ 53 | ...babelCommonOptions, 54 | presets: [ 55 | [ 56 | "@babel/preset-env", 57 | { 58 | targets: { 59 | browsers: ["last 2 versions"] 60 | }, 61 | modules: false 62 | } 63 | ] 64 | ] 65 | }), 66 | isDev ? 0 : uglify() 67 | ].filter(Boolean), 68 | output: { 69 | banner, 70 | file: pkg.main, 71 | format: "cjs" 72 | } 73 | }, 74 | { 75 | input: "src/index.js", 76 | plugins: [ 77 | babel({ 78 | ...babelCommonOptions, 79 | presets: [ 80 | [ 81 | "@babel/preset-env", 82 | { 83 | targets: { 84 | browsers: ["last 2 versions"] 85 | }, 86 | modules: false 87 | } 88 | ] 89 | ] 90 | }) 91 | ], 92 | output: { 93 | banner, 94 | format: "es", 95 | file: pkg.module 96 | } 97 | } 98 | ]; 99 | -------------------------------------------------------------------------------- /src/dom.js: -------------------------------------------------------------------------------- 1 | export function onReady(callback) { 2 | document.body 3 | ? callback() 4 | : document.addEventListener 5 | ? document.addEventListener("DOMContentLoaded", function c() { 6 | document.removeEventListener("DOMContentLoaded", c); 7 | callback(); 8 | }) 9 | : document.attachEvent("onreadystatechange", function k() { 10 | if ( 11 | "interactive" == document.readyState || 12 | "complete" == document.readyState 13 | ) 14 | document.detachEvent("onreadystatechange", k), callback(); 15 | }); 16 | } 17 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import Ruler from "./ruler.js"; 2 | import { onReady } from "./dom.js"; 3 | 4 | /** Class for FontFaceObserver. */ 5 | class FontFaceObserver { 6 | static Ruler = Ruler; 7 | 8 | /** 9 | * @type {null|boolean} 10 | */ 11 | static HAS_WEBKIT_FALLBACK_BUG = null; 12 | 13 | /** 14 | * @type {null|boolean} 15 | */ 16 | static HAS_SAFARI_10_BUG = null; 17 | 18 | /** 19 | * @type {null|boolean} 20 | */ 21 | static SUPPORTS_STRETCH = null; 22 | 23 | /** 24 | * @type {null|boolean} 25 | */ 26 | static SUPPORTS_NATIVE_FONT_LOADING = null; 27 | 28 | /** 29 | * @type {number} 30 | */ 31 | static DEFAULT_TIMEOUT = 3000; 32 | 33 | /** 34 | * @return {string} 35 | */ 36 | static getUserAgent() { 37 | return window.navigator.userAgent; 38 | } 39 | 40 | /** 41 | * @return {string} 42 | */ 43 | static getNavigatorVendor() { 44 | return window.navigator.vendor; 45 | } 46 | 47 | /** 48 | * Returns true if this browser is WebKit and it has the fallback bug which is 49 | * present in WebKit 536.11 and earlier. 50 | * 51 | * @return {boolean} 52 | */ 53 | static hasWebKitFallbackBug() { 54 | if (FontFaceObserver.HAS_WEBKIT_FALLBACK_BUG === null) { 55 | const match = /AppleWebKit\/([0-9]+)(?:\.([0-9]+))/.exec( 56 | FontFaceObserver.getUserAgent() 57 | ); 58 | 59 | FontFaceObserver.HAS_WEBKIT_FALLBACK_BUG = 60 | !!match && 61 | (parseInt(match[1], 10) < 536 || 62 | (parseInt(match[1], 10) === 536 && parseInt(match[2], 10) <= 11)); 63 | } 64 | return FontFaceObserver.HAS_WEBKIT_FALLBACK_BUG; 65 | } 66 | 67 | /** 68 | * Returns true if the browser has the Safari 10 bugs. The native font load 69 | * API in Safari 10 has two bugs that cause the document.fonts.load and 70 | * FontFace.prototype.load methods to return promises that don't reliably get 71 | * settled. 72 | * 73 | * The bugs are described in more detail here: 74 | * - https://bugs.webkit.org/show_bug.cgi?id=165037 75 | * - https://bugs.webkit.org/show_bug.cgi?id=164902 76 | * 77 | * If the browser is made by Apple, and has native font loading support, it is 78 | * potentially affected. But the API was fixed around AppleWebKit version 603, 79 | * so any newer versions that that does not contain the bug. 80 | * 81 | * @return {boolean} 82 | */ 83 | static hasSafari10Bug() { 84 | if (FontFaceObserver.HAS_SAFARI_10_BUG === null) { 85 | if ( 86 | FontFaceObserver.supportsNativeFontLoading() && 87 | /Apple/.test(FontFaceObserver.getNavigatorVendor()) 88 | ) { 89 | const match = /AppleWebKit\/([0-9]+)(?:\.([0-9]+))(?:\.([0-9]+))/.exec( 90 | FontFaceObserver.getUserAgent() 91 | ); 92 | 93 | FontFaceObserver.HAS_SAFARI_10_BUG = 94 | !!match && parseInt(match[1], 10) < 603; 95 | } else { 96 | FontFaceObserver.HAS_SAFARI_10_BUG = false; 97 | } 98 | } 99 | return FontFaceObserver.HAS_SAFARI_10_BUG; 100 | } 101 | 102 | /** 103 | * Returns true if the browser supports the native font loading API. 104 | * 105 | * @return {boolean} 106 | */ 107 | static supportsNativeFontLoading() { 108 | if (FontFaceObserver.SUPPORTS_NATIVE_FONT_LOADING === null) { 109 | FontFaceObserver.SUPPORTS_NATIVE_FONT_LOADING = !!document["fonts"]; 110 | } 111 | return FontFaceObserver.SUPPORTS_NATIVE_FONT_LOADING; 112 | } 113 | 114 | /** 115 | * Returns true if the browser supports font-style in the font short-hand 116 | * syntax. 117 | * 118 | * @return {boolean} 119 | */ 120 | static supportStretch() { 121 | if (FontFaceObserver.SUPPORTS_STRETCH === null) { 122 | const div = document.createElement("div"); 123 | 124 | try { 125 | div.style.font = "condensed 100px sans-serif"; 126 | } catch (e) {} 127 | FontFaceObserver.SUPPORTS_STRETCH = div.style.font !== ""; 128 | } 129 | 130 | return FontFaceObserver.SUPPORTS_STRETCH; 131 | } 132 | 133 | /** 134 | * @typedef {Object} Descriptors 135 | * @property {string|undefined} style 136 | * @property {string|undefined} weight 137 | * @property {string|undefined} stretch 138 | */ 139 | /** 140 | * 141 | * @param {string} family font-family name (required) 142 | * @param {Descriptors} descriptors an object describing the variation 143 | * (optional). The object can contain `weight`, `style`, and `stretch` 144 | * properties. If a property is not present it will default to `normal`. 145 | */ 146 | constructor(family, descriptors = {}) { 147 | this.family = family; 148 | 149 | this.style = descriptors.style || "normal"; 150 | this.weight = descriptors.weight || "normal"; 151 | this.stretch = descriptors.stretch || "normal"; 152 | 153 | return this; 154 | } 155 | 156 | /** 157 | * @param {string=} text Optional test string to use for detecting if a font 158 | * is available. 159 | * @param {number=} timeout Optional timeout for giving up on font load 160 | * detection and rejecting the promise (defaults to 3 seconds). 161 | * @return {Promise.} 162 | */ 163 | load(text, timeout) { 164 | const that = this; 165 | const testString = text || "BESbswy"; 166 | let timeoutId = 0; 167 | const timeoutValue = timeout || FontFaceObserver.DEFAULT_TIMEOUT; 168 | const start = that.getTime(); 169 | 170 | return new Promise(function(resolve, reject) { 171 | if ( 172 | FontFaceObserver.supportsNativeFontLoading() && 173 | !FontFaceObserver.hasSafari10Bug() 174 | ) { 175 | const loader = new Promise(function(resolve, reject) { 176 | const check = function() { 177 | const now = that.getTime(); 178 | 179 | if (now - start >= timeoutValue) { 180 | reject(new Error("" + timeoutValue + "ms timeout exceeded")); 181 | } else { 182 | document.fonts 183 | .load(that.getStyle('"' + that["family"] + '"'), testString) 184 | .then(function(fonts) { 185 | if (fonts.length >= 1) { 186 | resolve(); 187 | } else { 188 | setTimeout(check, 25); 189 | } 190 | }, reject); 191 | } 192 | }; 193 | check(); 194 | }); 195 | 196 | const timer = new Promise(function(resolve, reject) { 197 | timeoutId = setTimeout(function() { 198 | reject(new Error("" + timeoutValue + "ms timeout exceeded")); 199 | }, timeoutValue); 200 | }); 201 | 202 | Promise.race([timer, loader]).then(function() { 203 | clearTimeout(timeoutId); 204 | resolve(that); 205 | }, reject); 206 | } else { 207 | onReady(function() { 208 | const rulerA = new Ruler(testString); 209 | const rulerB = new Ruler(testString); 210 | const rulerC = new Ruler(testString); 211 | 212 | let widthA = -1; 213 | let widthB = -1; 214 | let widthC = -1; 215 | 216 | let fallbackWidthA = -1; 217 | let fallbackWidthB = -1; 218 | let fallbackWidthC = -1; 219 | 220 | const container = document.createElement("div"); 221 | 222 | /** 223 | * @private 224 | */ 225 | function removeContainer() { 226 | if (container.parentNode !== null) { 227 | container.parentNode.removeChild(container); 228 | } 229 | } 230 | 231 | /** 232 | * @private 233 | * 234 | * If metric compatible fonts are detected, one of the widths will be 235 | * -1. This is because a metric compatible font won't trigger a scroll 236 | * event. We work around this by considering a font loaded if at least 237 | * two of the widths are the same. Because we have three widths, this 238 | * still prevents false positives. 239 | * 240 | * Cases: 241 | * 1) Font loads: both a, b and c are called and have the same value. 242 | * 2) Font fails to load: resize callback is never called and timeout 243 | * happens. 244 | * 3) WebKit bug: both a, b and c are called and have the same value, 245 | * but the values are equal to one of the last resort fonts, we 246 | * ignore this and continue waiting until we get new values (or a 247 | * timeout). 248 | */ 249 | function check() { 250 | if ( 251 | (widthA != -1 && widthB != -1) || 252 | (widthA != -1 && widthC != -1) || 253 | (widthB != -1 && widthC != -1) 254 | ) { 255 | if (widthA == widthB || widthA == widthC || widthB == widthC) { 256 | // All values are the same, so the browser has most likely 257 | // loaded the web font 258 | 259 | if (FontFaceObserver.hasWebKitFallbackBug()) { 260 | // Except if the browser has the WebKit fallback bug, in which 261 | // case we check to see if all values are set to one of the 262 | // last resort fonts. 263 | 264 | if ( 265 | (widthA == fallbackWidthA && 266 | widthB == fallbackWidthA && 267 | widthC == fallbackWidthA) || 268 | (widthA == fallbackWidthB && 269 | widthB == fallbackWidthB && 270 | widthC == fallbackWidthB) || 271 | (widthA == fallbackWidthC && 272 | widthB == fallbackWidthC && 273 | widthC == fallbackWidthC) 274 | ) { 275 | // The width we got matches some of the known last resort 276 | // fonts, so let's assume we're dealing with the last resort 277 | // font. 278 | return; 279 | } 280 | } 281 | removeContainer(); 282 | clearTimeout(timeoutId); 283 | resolve(that); 284 | } 285 | } 286 | } 287 | 288 | // This ensures the scroll direction is correct. 289 | container.dir = "ltr"; 290 | 291 | rulerA.setFont(that.getStyle("sans-serif")); 292 | rulerB.setFont(that.getStyle("serif")); 293 | rulerC.setFont(that.getStyle("monospace")); 294 | 295 | container.appendChild(rulerA.getElement()); 296 | container.appendChild(rulerB.getElement()); 297 | container.appendChild(rulerC.getElement()); 298 | 299 | document.body.appendChild(container); 300 | 301 | fallbackWidthA = rulerA.getWidth(); 302 | fallbackWidthB = rulerB.getWidth(); 303 | fallbackWidthC = rulerC.getWidth(); 304 | 305 | function checkForTimeout() { 306 | const now = that.getTime(); 307 | 308 | if (now - start >= timeoutValue) { 309 | removeContainer(); 310 | reject(new Error("" + timeoutValue + "ms timeout exceeded")); 311 | } else { 312 | const hidden = document["hidden"]; 313 | if (hidden === true || hidden === undefined) { 314 | widthA = rulerA.getWidth(); 315 | widthB = rulerB.getWidth(); 316 | widthC = rulerC.getWidth(); 317 | check(); 318 | } 319 | timeoutId = setTimeout(checkForTimeout, 50); 320 | } 321 | } 322 | 323 | checkForTimeout(); 324 | 325 | rulerA.onResize(function(width) { 326 | widthA = width; 327 | check(); 328 | }); 329 | 330 | rulerA.setFont(that.getStyle('"' + that["family"] + '",sans-serif')); 331 | 332 | rulerB.onResize(function(width) { 333 | widthB = width; 334 | check(); 335 | }); 336 | 337 | rulerB.setFont(that.getStyle('"' + that["family"] + '",serif')); 338 | 339 | rulerC.onResize(function(width) { 340 | widthC = width; 341 | check(); 342 | }); 343 | 344 | rulerC.setFont(that.getStyle('"' + that["family"] + '",monospace')); 345 | }); 346 | } 347 | }); 348 | } 349 | 350 | /** 351 | * @private 352 | * 353 | * @param {string} family 354 | * @return {string} 355 | */ 356 | getStyle(family) { 357 | return [ 358 | this.style, 359 | this.weight, 360 | FontFaceObserver.supportStretch() ? this.stretch : "", 361 | "100px", 362 | family 363 | ].join(" "); 364 | } 365 | /** 366 | * @private 367 | * 368 | * @return {number} 369 | */ 370 | getTime() { 371 | return new Date().getTime(); 372 | } 373 | } 374 | 375 | export default FontFaceObserver; 376 | -------------------------------------------------------------------------------- /src/ruler.js: -------------------------------------------------------------------------------- 1 | const styles = { 2 | maxWidth: "none", 3 | display: "inline-block", 4 | position: "absolute", 5 | height: "100%", 6 | width: "100%", 7 | overflow: "scroll", 8 | fontSize: "16px" 9 | }; 10 | 11 | const collapsibleInnerStyles = { 12 | display: "inline-block", 13 | height: "200%", 14 | width: "200%", 15 | fontSize: "16px", 16 | maxWidth: "none" 17 | }; 18 | 19 | const fontStyle = { 20 | maxWidth: "none", 21 | minWidth: "20px", 22 | minHeight: "20px", 23 | display: "inline-block", 24 | overflow: "hidden", 25 | position: "absolute", 26 | width: "auto", 27 | margin: "0", 28 | padding: "0", 29 | top: "-999px", 30 | whiteSpace: "nowrap", 31 | fontSynthesis: "none" 32 | }; 33 | 34 | class Ruler { 35 | /** 36 | * 37 | * @param {string} text 38 | */ 39 | constructor(text) { 40 | this.element = document.createElement("div"); 41 | this.element.setAttribute("aria-hidden", "true"); 42 | 43 | this.element.appendChild(document.createTextNode(text)); 44 | 45 | this.collapsible = document.createElement("span"); 46 | this.expandable = document.createElement("span"); 47 | this.collapsibleInner = document.createElement("span"); 48 | this.expandableInner = document.createElement("span"); 49 | 50 | this.lastOffsetWidth = -1; 51 | 52 | Object.assign(this.collapsible.style, styles); 53 | Object.assign(this.expandable.style, styles); 54 | Object.assign(this.expandableInner.style, styles); 55 | Object.assign(this.collapsibleInner.style, collapsibleInnerStyles); 56 | 57 | this.collapsible.appendChild(this.collapsibleInner); 58 | this.expandable.appendChild(this.expandableInner); 59 | 60 | this.element.appendChild(this.collapsible); 61 | this.element.appendChild(this.expandable); 62 | } 63 | 64 | /** 65 | * @return {Element} 66 | */ 67 | getElement() { 68 | return this.element; 69 | } 70 | 71 | /** 72 | * @param {string} font 73 | */ 74 | setFont(font) { 75 | Object.assign(this.element.style, { ...fontStyle, font }); 76 | } 77 | 78 | /** 79 | * @return {number} 80 | */ 81 | getWidth() { 82 | return this.element.offsetWidth; 83 | } 84 | 85 | /** 86 | * @param {string} width 87 | */ 88 | setWidth(width) { 89 | this.element.style.width = width + "px"; 90 | } 91 | 92 | /** 93 | * @private 94 | * 95 | * @return {boolean} 96 | */ 97 | reset() { 98 | const offsetWidth = this.getWidth(); 99 | const width = offsetWidth + 100; 100 | 101 | this.expandableInner.style.width = width + "px"; 102 | this.expandable.scrollLeft = width; 103 | this.collapsible.scrollLeft = this.collapsible.scrollWidth + 100; 104 | 105 | if (this.lastOffsetWidth !== offsetWidth) { 106 | this.lastOffsetWidth = offsetWidth; 107 | return true; 108 | } else { 109 | return false; 110 | } 111 | } 112 | 113 | /** 114 | * @private 115 | * @param {function(number)} callback 116 | */ 117 | onScroll(callback) { 118 | if (this.reset() && this.element.parentNode !== null) { 119 | callback(this.lastOffsetWidth); 120 | } 121 | } 122 | 123 | /** 124 | * @param {function(number)} callback 125 | */ 126 | onResize(callback) { 127 | var that = this; 128 | 129 | function onScroll() { 130 | that.onScroll(callback); 131 | } 132 | 133 | this.collapsible.addEventListener("scroll", onScroll); 134 | this.expandable.addEventListener("scroll", onScroll); 135 | this.reset(); 136 | } 137 | } 138 | 139 | export default Ruler; 140 | -------------------------------------------------------------------------------- /src/types.d.ts: -------------------------------------------------------------------------------- 1 | declare namespace FontFaceObserver { 2 | interface FontVariant { 3 | weight?: number | string; 4 | style?: string; 5 | stretch?: string; 6 | } 7 | } 8 | 9 | declare class FontFaceObserver { 10 | /** 11 | * Creates a new FontFaceObserver. 12 | * @param fontFamilyName Name of the font family to observe. 13 | * @param variant Description of the font variant to observe. If a property is not present it will default to normal. 14 | */ 15 | constructor(fontFamilyName: string, variant?: FontFaceObserver.FontVariant); 16 | 17 | /** 18 | * Starts observing the loading of the specified font. Immediately returns a new Promise that resolves when the font is available and rejected when the font is not available. 19 | * @param testString If your font doesn't contain latin characters you can pass a custom test string. 20 | * @param timeout The default timeout for giving up on font loading is 3 seconds. You can increase or decrease this by passing a number of milliseconds. 21 | */ 22 | load(testString?: string, timeout?: number): Promise; 23 | } 24 | 25 | declare module "fontfaceobserver-es" { 26 | export = FontFaceObserver; 27 | } 28 | -------------------------------------------------------------------------------- /test/assets/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | hello 7 | 8 | 9 | -------------------------------------------------------------------------------- /test/assets/late.css: -------------------------------------------------------------------------------- 1 | @font-face { font-family: observer-test9; src: url(sourcesanspro-regular.woff) format('woff'), url(sourcesanspro-regular.ttf) format('truetype'); } 2 | -------------------------------------------------------------------------------- /test/assets/sourcesanspro-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmnsgn/fontfaceobserver/6c12e94a086c011f1e1447e79031c3de6ee5ec2a/test/assets/sourcesanspro-regular.eot -------------------------------------------------------------------------------- /test/assets/sourcesanspro-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmnsgn/fontfaceobserver/6c12e94a086c011f1e1447e79031c3de6ee5ec2a/test/assets/sourcesanspro-regular.ttf -------------------------------------------------------------------------------- /test/assets/sourcesanspro-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmnsgn/fontfaceobserver/6c12e94a086c011f1e1447e79031c3de6ee5ec2a/test/assets/sourcesanspro-regular.woff -------------------------------------------------------------------------------- /test/assets/subset.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmnsgn/fontfaceobserver/6c12e94a086c011f1e1447e79031c3de6ee5ec2a/test/assets/subset.eot -------------------------------------------------------------------------------- /test/assets/subset.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmnsgn/fontfaceobserver/6c12e94a086c011f1e1447e79031c3de6ee5ec2a/test/assets/subset.ttf -------------------------------------------------------------------------------- /test/assets/subset.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmnsgn/fontfaceobserver/6c12e94a086c011f1e1447e79031c3de6ee5ec2a/test/assets/subset.woff -------------------------------------------------------------------------------- /test/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | FontFaceObserver 6 | 7 | 8 | 73 | 74 | 75 |
76 | 77 | 78 | 79 | 80 | 81 | 82 | 87 | 88 | 89 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /test/observer-test.js: -------------------------------------------------------------------------------- 1 | describe("Observer", function() { 2 | var Ruler = FontFaceObserver.Ruler; 3 | 4 | describe("#constructor", function() { 5 | it("creates a new instance with the correct signature", function() { 6 | var observer = new FontFaceObserver("my family", {}); 7 | expect(observer, "not to be", null); 8 | expect(observer.load, "to be a function"); 9 | }); 10 | 11 | it("parses descriptors", function() { 12 | var observer = new FontFaceObserver("my family", { 13 | weight: "bold" 14 | }); 15 | 16 | expect(observer.family, "to equal", "my family"); 17 | expect(observer.weight, "to equal", "bold"); 18 | }); 19 | 20 | it("defaults descriptors that are not given", function() { 21 | var observer = new FontFaceObserver("my family", { 22 | weight: "bold" 23 | }); 24 | 25 | expect(observer.style, "to equal", "normal"); 26 | }); 27 | }); 28 | 29 | describe("#getStyle", function() { 30 | it("creates the correct default style", function() { 31 | var observer = new FontFaceObserver("my family", {}); 32 | 33 | if (FontFaceObserver.supportStretch()) { 34 | expect( 35 | observer.getStyle("sans-serif"), 36 | "to equal", 37 | "normal normal normal 100px sans-serif" 38 | ); 39 | } else { 40 | expect( 41 | observer.getStyle("sans-serif"), 42 | "to equal", 43 | "normal normal 100px sans-serif" 44 | ); 45 | } 46 | }); 47 | 48 | it("passes through all descriptors", function() { 49 | var observer = new FontFaceObserver("my family", { 50 | style: "italic", 51 | weight: "bold", 52 | stretch: "condensed" 53 | }); 54 | 55 | if (FontFaceObserver.supportStretch()) { 56 | expect( 57 | observer.getStyle("sans-serif"), 58 | "to equal", 59 | "italic bold condensed 100px sans-serif" 60 | ); 61 | } else { 62 | expect( 63 | observer.getStyle("sans-serif"), 64 | "to equal", 65 | "italic bold 100px sans-serif" 66 | ); 67 | } 68 | }); 69 | }); 70 | 71 | describe("#load", function() { 72 | this.timeout(5000); 73 | 74 | it("finds a font and resolve the promise", function(done) { 75 | var observer = new FontFaceObserver("observer-test1", {}); 76 | var ruler = new Ruler("hello"); 77 | 78 | document.body.appendChild(ruler.getElement()); 79 | 80 | ruler.setFont("monospace", ""); 81 | var beforeWidth = ruler.getWidth(); 82 | 83 | ruler.setFont("100px observer-test1, monospace"); 84 | observer.load(null, 5000).then( 85 | function() { 86 | var activeWidth = ruler.getWidth(); 87 | 88 | expect(activeWidth, "not to equal", beforeWidth); 89 | 90 | setTimeout(function() { 91 | var afterWidth = ruler.getWidth(); 92 | 93 | expect(afterWidth, "to equal", activeWidth); 94 | expect(afterWidth, "not to equal", beforeWidth); 95 | document.body.removeChild(ruler.getElement()); 96 | done(); 97 | }, 0); 98 | }, 99 | function() { 100 | done(new Error("Timeout")); 101 | } 102 | ); 103 | }); 104 | 105 | it("finds a font and resolves the promise even though the @font-face rule is not in the CSSOM yet", function(done) { 106 | var observer = new FontFaceObserver("observer-test9", {}), 107 | ruler = new Ruler("hello"); 108 | 109 | document.body.appendChild(ruler.getElement()); 110 | 111 | ruler.setFont("monospace", ""); 112 | var beforeWidth = ruler.getWidth(); 113 | 114 | ruler.setFont("100px observer-test9, monospace"); 115 | 116 | observer.load(null, 10000).then( 117 | function() { 118 | var activeWidth = ruler.getWidth(); 119 | 120 | expect(activeWidth, "not to equal", beforeWidth); 121 | 122 | setTimeout(function() { 123 | var afterWidth = ruler.getWidth(); 124 | 125 | expect(afterWidth, "to equal", activeWidth); 126 | expect(afterWidth, "not to equal", beforeWidth); 127 | document.body.removeChild(ruler.getElement()); 128 | done(); 129 | }, 0); 130 | }, 131 | function() { 132 | done(new Error("Timeout")); 133 | } 134 | ); 135 | 136 | // We don't use a style element here because IE9/10 have issues with 137 | // dynamically inserted @font-face rules. 138 | var link = document.createElement("link"); 139 | 140 | link.rel = "stylesheet"; 141 | link.href = "assets/late.css"; 142 | 143 | document.head.appendChild(link); 144 | }); 145 | 146 | it("finds a font and resolve the promise even when the page is RTL", function(done) { 147 | var observer = new FontFaceObserver("observer-test8", {}), 148 | ruler = new Ruler("hello"); 149 | 150 | document.body.dir = "rtl"; 151 | document.body.appendChild(ruler.getElement()); 152 | 153 | ruler.setFont("monospace", ""); 154 | var beforeWidth = ruler.getWidth(); 155 | 156 | ruler.setFont("100px observer-test1, monospace"); 157 | observer.load(null, 5000).then( 158 | function() { 159 | var activeWidth = ruler.getWidth(); 160 | 161 | expect(activeWidth, "not to equal", beforeWidth); 162 | 163 | setTimeout(function() { 164 | var afterWidth = ruler.getWidth(); 165 | 166 | expect(afterWidth, "to equal", activeWidth); 167 | expect(afterWidth, "not to equal", beforeWidth); 168 | document.body.removeChild(ruler.getElement()); 169 | document.body.dir = "ltr"; 170 | done(); 171 | }, 0); 172 | }, 173 | function() { 174 | done(new Error("Timeout")); 175 | } 176 | ); 177 | }); 178 | 179 | it("finds a font with spaces in the name and resolve the promise", function(done) { 180 | var observer = new FontFaceObserver("Trebuchet W01 Regular", {}), 181 | ruler = new Ruler("hello"); 182 | 183 | document.body.appendChild(ruler.getElement()); 184 | 185 | ruler.setFont("100px monospace"); 186 | var beforeWidth = ruler.getWidth(); 187 | 188 | ruler.setFont('100px "Trebuchet W01 Regular", monospace'); 189 | observer.load(null, 5000).then( 190 | function() { 191 | var activeWidth = ruler.getWidth(); 192 | 193 | expect(activeWidth, "not to equal", beforeWidth); 194 | 195 | setTimeout(function() { 196 | var afterWidth = ruler.getWidth(); 197 | 198 | expect(afterWidth, "to equal", activeWidth); 199 | expect(afterWidth, "not to equal", beforeWidth); 200 | document.body.removeChild(ruler.getElement()); 201 | done(); 202 | }, 0); 203 | }, 204 | function() { 205 | done(new Error("Timeout")); 206 | } 207 | ); 208 | }); 209 | 210 | it("loads a font with spaces and numbers in the name and resolve the promise", function(done) { 211 | var observer = new FontFaceObserver("Neue Frutiger 1450 W04", {}), 212 | ruler = new Ruler("hello"); 213 | 214 | document.body.appendChild(ruler.getElement()); 215 | 216 | ruler.setFont("100px monospace"); 217 | var beforeWidth = ruler.getWidth(); 218 | 219 | ruler.setFont('100px "Neue Frutiger 1450 W04", monospace'); 220 | observer.load(null, 5000).then( 221 | function() { 222 | var activeWidth = ruler.getWidth(); 223 | 224 | expect(activeWidth, "not to equal", beforeWidth); 225 | 226 | setTimeout(function() { 227 | var afterWidth = ruler.getWidth(); 228 | 229 | expect(afterWidth, "to equal", activeWidth); 230 | expect(afterWidth, "not to equal", beforeWidth); 231 | document.body.removeChild(ruler.getElement()); 232 | done(); 233 | }, 0); 234 | }, 235 | function() { 236 | done(new Error("Timeout")); 237 | } 238 | ); 239 | }); 240 | 241 | it("fails to find a font and reject the promise", function(done) { 242 | var observer = new FontFaceObserver("observer-test2", {}); 243 | 244 | observer.load(null, 50).then( 245 | function() { 246 | done(new Error("Should not resolve")); 247 | }, 248 | function(err) { 249 | try { 250 | expect(err.message, "to equal", "50ms timeout exceeded"); 251 | expect(err.constructor.name, "to equal", "Error"); 252 | done(); 253 | } catch (testFailure) { 254 | done(testFailure); 255 | } 256 | } 257 | ); 258 | }); 259 | 260 | it("finds the font even if it is already loaded", function(done) { 261 | var observer = new FontFaceObserver("observer-test3", {}); 262 | 263 | observer.load(null, 5000).then(function() { 264 | done(); 265 | }); 266 | }); 267 | 268 | it("finds the font even if it is already loaded", function(done) { 269 | var observer = new FontFaceObserver("observer-test3", {}); 270 | 271 | observer.load(null, 5000).then( 272 | function() { 273 | observer.load(null, 5000).then( 274 | function() { 275 | done(); 276 | }, 277 | function() { 278 | done(new Error("Second call failed")); 279 | } 280 | ); 281 | }, 282 | function() { 283 | done(new Error("Timeout")); 284 | } 285 | ); 286 | }); 287 | 288 | it("finds a font with a custom unicode range within ASCII", function(done) { 289 | var observer = new FontFaceObserver("observer-test4", {}), 290 | ruler = new Ruler("\u0021"); 291 | 292 | ruler.setFont("monospace", ""); 293 | document.body.appendChild(ruler.getElement()); 294 | 295 | var beforeWidth = ruler.getWidth(); 296 | 297 | ruler.setFont("100px observer-test4,monospace"); 298 | 299 | observer.load("\u0021", 5000).then( 300 | function() { 301 | var activeWidth = ruler.getWidth(); 302 | 303 | expect(activeWidth, "not to equal", beforeWidth); 304 | 305 | setTimeout(function() { 306 | var afterWidth = ruler.getWidth(); 307 | 308 | expect(afterWidth, "to equal", activeWidth); 309 | expect(afterWidth, "not to equal", beforeWidth); 310 | 311 | document.body.removeChild(ruler.getElement()); 312 | done(); 313 | }, 0); 314 | }, 315 | function() { 316 | done(new Error("Timeout")); 317 | } 318 | ); 319 | }); 320 | 321 | it("finds a font with a custom unicode range outside ASCII (but within BMP)", function(done) { 322 | var observer = new FontFaceObserver("observer-test5", {}), 323 | ruler = new Ruler("\u4e2d\u56fd"); 324 | 325 | ruler.setFont("100px monospace"); 326 | document.body.appendChild(ruler.getElement()); 327 | 328 | var beforeWidth = ruler.getWidth(); 329 | 330 | ruler.setFont("100px observer-test5,monospace"); 331 | 332 | observer.load("\u4e2d\u56fd", 5000).then( 333 | function() { 334 | var activeWidth = ruler.getWidth(); 335 | 336 | expect(activeWidth, "not to equal", beforeWidth); 337 | 338 | setTimeout(function() { 339 | var afterWidth = ruler.getWidth(); 340 | 341 | expect(afterWidth, "to equal", activeWidth); 342 | expect(afterWidth, "not to equal", beforeWidth); 343 | 344 | document.body.removeChild(ruler.getElement()); 345 | 346 | done(); 347 | }, 0); 348 | }, 349 | function() { 350 | done(new Error("Timeout")); 351 | } 352 | ); 353 | }); 354 | 355 | it("finds a font with a custom unicode range outside the BMP", function(done) { 356 | var observer = new FontFaceObserver("observer-test6", {}), 357 | ruler = new Ruler("\udbff\udfff"); 358 | 359 | ruler.setFont("100px monospace"); 360 | document.body.appendChild(ruler.getElement()); 361 | 362 | var beforeWidth = ruler.getWidth(); 363 | 364 | ruler.setFont("100px observer-test6,monospace"); 365 | 366 | observer.load("\udbff\udfff", 5000).then( 367 | function() { 368 | var activeWidth = ruler.getWidth(); 369 | 370 | expect(activeWidth, "not to equal", beforeWidth); 371 | 372 | setTimeout(function() { 373 | var afterWidth = ruler.getWidth(); 374 | 375 | expect(afterWidth, "to equal", activeWidth); 376 | expect(afterWidth, "not to equal", beforeWidth); 377 | 378 | document.body.removeChild(ruler.getElement()); 379 | 380 | done(); 381 | }, 0); 382 | }, 383 | function() { 384 | done(new Error("Timeout")); 385 | } 386 | ); 387 | }); 388 | 389 | it("fails to find the font if it is available but does not contain the test string", function(done) { 390 | var observer = new FontFaceObserver("observer-test7", {}); 391 | 392 | observer.load(null, 50).then( 393 | function() { 394 | done(new Error("Should not be called")); 395 | }, 396 | function() { 397 | done(); 398 | } 399 | ); 400 | }); 401 | 402 | // it("finds a locally installed font", function(done) { 403 | // var observer = new FontFaceObserver("sans-serif", {}); 404 | 405 | // observer.load(null, 50).then( 406 | // function() { 407 | // done(); 408 | // }, 409 | // function() { 410 | // done(new Error("Did not detect local font")); 411 | // } 412 | // ); 413 | // }); 414 | 415 | // it("finds a locally installed font with the same metrics as the a fallback font (on OS X)", function(done) { 416 | // var observer = new FontFaceObserver("serif", {}); 417 | 418 | // observer.load(null, 50).then( 419 | // function() { 420 | // done(); 421 | // }, 422 | // function() { 423 | // done(new Error("Did not detect local font")); 424 | // } 425 | // ); 426 | // }); 427 | }); 428 | 429 | describe("hasSafari10Bug", function() { 430 | var getUserAgent = null; 431 | var getNavigatorVendor = null; 432 | var supportsNativeFontLoading = null; 433 | 434 | beforeEach(function() { 435 | FontFaceObserver.HAS_SAFARI_10_BUG = null; 436 | 437 | getUserAgent = sinon.stub(FontFaceObserver, "getUserAgent"); 438 | getNavigatorVendor = sinon.stub(FontFaceObserver, "getNavigatorVendor"); 439 | supportsNativeFontLoading = sinon.stub( 440 | FontFaceObserver, 441 | "supportsNativeFontLoading" 442 | ); 443 | }); 444 | 445 | afterEach(function() { 446 | getUserAgent.restore(); 447 | getNavigatorVendor.restore(); 448 | supportsNativeFontLoading.restore(); 449 | }); 450 | 451 | it("returns false when the user agent is not WebKit", function() { 452 | getUserAgent.returns( 453 | "Mozilla/5.0 (Android; Mobile; rv:13.0) Gecko/15.0 Firefox/14.0" 454 | ); 455 | getNavigatorVendor.returns("Google"); 456 | supportsNativeFontLoading.returns(true); 457 | 458 | expect(FontFaceObserver.hasSafari10Bug(), "to be false"); 459 | }); 460 | 461 | it("returns true if the browser is an affected version of Safari 10", function() { 462 | getUserAgent.returns( 463 | "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0.1 Safari/602.2.14" 464 | ); 465 | getNavigatorVendor.returns("Apple"); 466 | supportsNativeFontLoading.returns(true); 467 | 468 | expect(FontFaceObserver.hasSafari10Bug(), "to be true"); 469 | }); 470 | 471 | it("returns true if the browser is an WebView with an affected version of Safari 10", function() { 472 | getUserAgent.returns( 473 | "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/602.2.14 (KHTML, like Gecko) FxiOS/6.1 Safari/602.2.14" 474 | ); 475 | getNavigatorVendor.returns("Apple"); 476 | supportsNativeFontLoading.returns(true); 477 | 478 | expect(FontFaceObserver.hasSafari10Bug(), "to be true"); 479 | }); 480 | 481 | it("returns false in older versions of Safari", function() { 482 | getUserAgent.returns( 483 | "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/9.3.2 Safari/537.75.14" 484 | ); 485 | getNavigatorVendor.returns("Apple"); 486 | supportsNativeFontLoading.returns(false); 487 | 488 | expect(FontFaceObserver.hasSafari10Bug(), "to be false"); 489 | }); 490 | 491 | it("returns false in newer versions of Safari", function() { 492 | getUserAgent.returns( 493 | "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/603.1.20 (KHTML, like Gecko) Version/10.1 Safari/603.1.20" 494 | ); 495 | getNavigatorVendor.returns("Apple"); 496 | supportsNativeFontLoading.returns(true); 497 | 498 | expect(FontFaceObserver.hasSafari10Bug(), "to be false"); 499 | }); 500 | }); 501 | 502 | describe("hasWebKitFallbackBug", function() { 503 | var getUserAgent = null; 504 | 505 | beforeEach(function() { 506 | FontFaceObserver.HAS_WEBKIT_FALLBACK_BUG = null; 507 | 508 | getUserAgent = sinon.stub(FontFaceObserver, "getUserAgent"); 509 | }); 510 | 511 | afterEach(function() { 512 | getUserAgent.restore(); 513 | }); 514 | 515 | it("returns false when the user agent is not WebKit", function() { 516 | getUserAgent.returns( 517 | "Mozilla/5.0 (Android; Mobile; rv:13.0) Gecko/15.0 Firefox/14.0" 518 | ); 519 | 520 | expect(FontFaceObserver.hasWebKitFallbackBug(), "to be false"); 521 | }); 522 | 523 | it("returns false when the user agent is WebKit but the bug is not present", function() { 524 | getUserAgent.returns( 525 | "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.12 (KHTML, like Gecko) Chrome/20.0.814.2 Safari/536.12" 526 | ); 527 | 528 | expect(FontFaceObserver.hasWebKitFallbackBug(), "to be false"); 529 | }); 530 | 531 | it("returns true when the user agent is WebKit and the bug is present", function() { 532 | getUserAgent.returns( 533 | "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.814.2 Safari/536.11" 534 | ); 535 | 536 | expect(FontFaceObserver.hasWebKitFallbackBug(), "to be true"); 537 | }); 538 | 539 | it("returns true when the user agent is WebKit and the bug is present in an old version", function() { 540 | getUserAgent.returns( 541 | "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/20.0.814.2 Safari/535.19" 542 | ); 543 | 544 | expect(FontFaceObserver.hasWebKitFallbackBug(), "to be true"); 545 | }); 546 | 547 | it("caches the results", function() { 548 | getUserAgent.returns( 549 | "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.814.2 Safari/536.11" 550 | ); 551 | 552 | expect(FontFaceObserver.hasWebKitFallbackBug(), "to be true"); 553 | 554 | getUserAgent.returns( 555 | "Mozilla/5.0 (Android; Mobile; rv:13.0) Gecko/15.0 Firefox/14.0" 556 | ); 557 | 558 | expect(FontFaceObserver.hasWebKitFallbackBug(), "to be true"); 559 | }); 560 | }); 561 | }); 562 | -------------------------------------------------------------------------------- /test/ruler-test.js: -------------------------------------------------------------------------------- 1 | describe("Ruler", function() { 2 | var Ruler = FontFaceObserver.Ruler; 3 | var ruler = null; 4 | 5 | beforeEach(function() { 6 | ruler = new Ruler("hello"); 7 | ruler.setFont("", ""); 8 | ruler.setWidth(100); 9 | document.body.appendChild(ruler.getElement()); 10 | }); 11 | 12 | afterEach(function() { 13 | document.body.removeChild(ruler.getElement()); 14 | ruler = null; 15 | }); 16 | 17 | describe("#constructor", function() { 18 | it("creates a new instance with the correct signature", function() { 19 | expect(ruler, "not to be", null); 20 | expect(ruler.onResize, "to be a function"); 21 | expect(ruler.setFont, "to be a function"); 22 | }); 23 | }); 24 | 25 | describe("#onResize", function() { 26 | it("detects expansion", function(done) { 27 | ruler.onResize(function(width) { 28 | expect(width, "to equal", 200); 29 | done(); 30 | }); 31 | 32 | ruler.setWidth(200); 33 | }); 34 | 35 | it("detects multiple expansions", function(done) { 36 | var first = true; 37 | 38 | ruler.onResize(function(width) { 39 | if (first) { 40 | expect(width, "to equal", 200); 41 | ruler.setWidth(300); 42 | first = false; 43 | } else { 44 | expect(width, "to equal", 300); 45 | done(); 46 | } 47 | }); 48 | 49 | ruler.setWidth(200); 50 | }); 51 | 52 | it("detects collapse", function(done) { 53 | ruler.onResize(function(width) { 54 | expect(width, "to equal", 50); 55 | done(); 56 | }); 57 | 58 | ruler.setWidth(50); 59 | }); 60 | 61 | it("detects multiple collapses", function(done) { 62 | var first = true; 63 | 64 | ruler.onResize(function(width) { 65 | if (first) { 66 | expect(width, "to equal", 70); 67 | ruler.setWidth(50); 68 | first = false; 69 | } else { 70 | expect(width, "to equal", 50); 71 | done(); 72 | } 73 | }); 74 | 75 | ruler.setWidth(70); 76 | }); 77 | 78 | it("detects a collapse and an expansion", function(done) { 79 | var first = true; 80 | 81 | ruler.onResize(function(width) { 82 | if (first) { 83 | expect(width, "to equal", 70); 84 | ruler.setWidth(100); 85 | first = false; 86 | } else { 87 | expect(width, "to equal", 100); 88 | done(); 89 | } 90 | }); 91 | 92 | ruler.setWidth(70); 93 | }); 94 | 95 | it("detects an expansion and a collapse", function(done) { 96 | var first = true; 97 | 98 | ruler.onResize(function(width) { 99 | if (first) { 100 | expect(width, "to equal", 200); 101 | ruler.setWidth(100); 102 | first = false; 103 | } else { 104 | expect(width, "to equal", 100); 105 | done(); 106 | } 107 | }); 108 | 109 | ruler.setWidth(200); 110 | }); 111 | }); 112 | }); 113 | --------------------------------------------------------------------------------