font_face_observer 2.0.9

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 50

Overview

Font load events, simple, small and efficient. It wil use the FontFace api if available, otherwise it falls back to a Dart port of https://github.com/bramstein/fontfaceobserver

Usage Example

import 'package:font_face_observer/font_face_observer.dart';
import 'package:font_face_observer/data_uri.dart';

FontFaceObserver ffo = new FontFaceObserver('Arial', weight: 'bold');
FontLoadResult result = await ffo.load('/url/to/arial.ttf');
if (result.isLoaded) {
    // at this point we're absolutely sure that the font has loaded
}
if (result.didTimeout) {
    // We've timed out and are not sure if the font has loaded.
    // You can reissue a ffo.check() call to check again if you want
}

// Build a base64 encoded data URI
DataUri di = new DataUri();
  ..data = DataUri.base64EncodeString('test');
  ..mimeType = 'text/plain';
  ..encoding = 'utf-8';
di.toString(); # data:text/plain;charset=utf-8;base64,dGVzdA==

Run the demo

To run the demo, just install dependencies and run pub serve test. Then open http://localhost:8080

pub get
pub serve test

Public API

// Constructing a new FontFaceObserver (with default values)
FontFaceObserver(
    String family,
    {
        String style: 'normal',
        String weight: 'normal',
        String stretch: 'normal',
        String testString: 'BESbswy',
        int timeout: 3000,
        bool useSimulatedLoadEvents: false
    }
);

// Check if the font face is loaded successfully
Future<FontLoadResult> check() async

// Load a font from the given URL by adding a font-face rule
// returns the same Future<FontLoadResult> from check()
Future<FontLoadResult> load(String url) async

// Unload a group of fonts (static call)
Future<int> FontFaceObserver.unloadGroup(String group);

// Unload a specific font by key and group
Future<bool> FontFaceObserver.unload(String key, String group);

Notes

Font Face Observer will use the FontFace API https://developer.mozilla.org/en-US/docs/Web/API/FontFace if available to detect when a font has loaded. If the browser does not support that API it will fallback to the method used in https://github.com/bramstein/fontfaceobserver which relies on scroll events when the font loads and is quite efficient. If you want to force the use of the fallback mode, you can set useSimulatedLoadEvents: true when constructing your FontFaceObserver.

2.0.7

  • [x] Added more analysis option lint rules
  • [x] default to DDC for running tests

2.0.6

  • [x] #29 Add CHANGELOG.md

2.0.5

This patch release includes the following changes:

Miscellaneous

  • [x] #27 Remove semver audit dependency, publish publicly

2.0.4

This patch release includes the following changes:

Miscellaneous

  • [x] #23 HY-5546 Add license to more files
    • HY-5546 Add license to more files
  • [x] #25 Adds license info from the original JS font face observer & W3C

example/main.dart

/*
Copyright 2017 Workiva Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

This software or document includes material copied from or derived 
from fontfaceobserver (https://github.com/bramstein/fontfaceobserver), 
Copyright (c) 2014 - Bram Stein, which is licensed under the following terms:

Redistribution and use in source and binary forms, with or without 
modification, are permitted provided that the following conditions 
are met:
 
 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer. 
 2. Redistributions in binary form must reproduce the above copyright 
    notice, this list of conditions and the following disclaimer in the 
    documentation and/or other materials provided with the distribution. 

THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED 
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO 
EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

This software or document includes material copied from or derived from 
CSS Font Loading Module Level 3 (https://drafts.csswg.org/css-font-loading/)
Copyright © 2017 W3C® (MIT, ERCIM, Keio, Beihang) which is licensed 
under the following terms:

By obtaining and/or copying this work, you (the licensee) agree that you 
have read, understood, and will comply with the following terms and conditions.
Permission to copy, modify, and distribute this work, with or without 
modification, for any purpose and without fee or royalty is hereby granted, 
provided that you include the following on ALL copies of the work or portions 
thereof, including modifications:
The full text of this NOTICE in a location viewable to users of the 
redistributed or derivative work. Any pre-existing intellectual property 
disclaimers, notices, or terms and conditions. If none exist, the W3C 
Software and Document Short Notice should be included.
Notice of any changes or modifications, through a copyright statement 
on the new code or document such as "This software or document 
includes material copied from or derived from 
[title and URI of the W3C document]. 
Copyright © [YEAR] W3C® (MIT, ERCIM, Keio, Beihang)."

https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document
*/
import 'dart:async';
import 'dart:html';
import 'package:font_face_observer/font_face_observer.dart';
import 'package:font_face_observer/support.dart';
import 'package:font_face_observer/src/adobe_blank.dart';

const String _successMessage = 'Pack my box with five dozen liquor jugs';

class _FontConfig {
  String url;
  String family;
  String testString;
  bool useSimulatedLoadEvents;
  bool expectLoad;
  _FontConfig(
      {this.family,
      this.url,
      this.testString: _successMessage,
      this.expectLoad: true,
      this.useSimulatedLoadEvents: false});
}

final List<_FontConfig> _fonts = <_FontConfig>[]
  ..add(new _FontConfig(family: 'AdobeBlank', url: adobeBlankFontBase64Url))
  ..add(new _FontConfig(
      family: 'AdobeBlank',
      url: adobeBlankFontBase64Url,
      useSimulatedLoadEvents: true))
  ..add(new _FontConfig(family: 'Roboto', url: '/fonts/Roboto.ttf'))
  ..add(new _FontConfig(
      family: 'Roboto', url: '/fonts/Roboto.ttf', useSimulatedLoadEvents: true))
  ..add(new _FontConfig(
      family: 'Wdesk_Icons',
      url: '/fonts/Wdesk_Icons.ttf',
      testString: '\uE600 \uE601'))
  ..add(new _FontConfig(
      family: 'Wdesk_Icons',
      url: '/fonts/Wdesk_Icons.ttf',
      testString: '\uE600 \uE601',
      useSimulatedLoadEvents: true))
  ..add(new _FontConfig(
      family: 'Wdesk_Doctype-Icons',
      url: '/fonts/Wdesk_Doctype-Icons.ttf',
      testString: '\uE6D9 \uE026'))
  ..add(new _FontConfig(
      family: 'Wdesk_Doctype-Icons',
      url: '/fonts/Wdesk_Doctype-Icons.ttf',
      testString: '\uE6D9 \uE026',
      useSimulatedLoadEvents: true))
  ..add(new _FontConfig(
      family: 'Subset',
      url: '/fonts/subset.ttf',
      testString: '\u25FC \u4E2D \u56FD'))
  ..add(new _FontConfig(
      family: 'Subset',
      url: '/fonts/subset.ttf',
      testString: '\u25FC \u4E2D \u56FD',
      useSimulatedLoadEvents: true))
  ..add(new _FontConfig(
      family: 'empty',
      url: '/fonts/empty.otf',
      expectLoad: true,
      testString: '',
      useSimulatedLoadEvents: true))
  ..add(new _FontConfig(family: 'W', url: '/fonts/W.ttf', testString: '\uE0FF'))
  ..add(new _FontConfig(
      family: 'W',
      url: '/fonts/W.ttf',
      testString: '\uE0FF',
      useSimulatedLoadEvents: true));

void _drawTextToCanvas(String text, String fontName, CanvasElement canvas) {
  // ignore: avoid_as
  canvas.getContext('2d') as CanvasRenderingContext2D
    ..setFillColorRgb(255, 255, 255)
    ..fillRect(0, 0, canvas.width, canvas.height)
    ..setFillColorRgb(0, 0, 0)
    ..font = '18px $fontName'
    ..fillText(text, 5, 28);
}

void _writeSupport() {
  final String supportString = '''
supportsStretch: $supportsStretch
supportsNativeFontLoading: $supportsNativeFontLoading
hasWebKitFallbackBug: $hasWebkitFallbackBug
  ''';
  document.getElementById('supports').text = supportString;
  print(supportString);
}

Future<Null> _loadFont(_FontConfig cfg, bool useSimulatedLoadEvents) async {
  final String uniqFamily = '${cfg.family}_${useSimulatedLoadEvents}';
  print(
      '  > Start Loading $uniqFamily ${useSimulatedLoadEvents ? "simulated" : "native"}');
  final FontFaceObserver ffo = new FontFaceObserver(uniqFamily,
      useSimulatedLoadEvents: useSimulatedLoadEvents, timeout: 500);
  final FontLoadResult result = await ffo.load(cfg.url);
  final bool pass = cfg.expectLoad ? result.isLoaded : !result.isLoaded;
  print('  * $result');
  final String message = cfg.testString;

  final Element table = document.getElementById('table');

  final CanvasElement canvas = new CanvasElement()
    ..width = 400
    ..height = 35;
  final TableRowElement row = new TableRowElement()
    ..append(new TableCellElement()..text = uniqFamily)
    ..append(new TableCellElement()
      ..text = useSimulatedLoadEvents ? 'Simulated' : 'FontFace')
    ..append(new TableCellElement()..text = result.isLoaded ? 'Yes' : 'No')
    ..append(new TableCellElement()
      ..text = pass ? 'Yes' : 'No'
      ..style.backgroundColor = pass ? 'green' : 'red')
    ..append(new TableCellElement()
      ..append(new DivElement()
        ..text = message
        ..style.fontFamily = uniqFamily
        ..style.fontSize = '18px'))
    ..append(new TableCellElement()..append(canvas));
  table.append(row);

  _drawTextToCanvas(message, uniqFamily, canvas);
  print('  > Done Loading ${uniqFamily}');
}

Future<Null> main() async {
  print('1. writing support');
  _writeSupport();
  int i = 0;
  for (; i < _fonts.length; i++) {
    final _FontConfig cfg = _fonts[i];
    print('${i + 2}. Loading ${cfg.family}');
    await _loadFont(cfg, cfg.useSimulatedLoadEvents);
  }
  print('Done');
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  font_face_observer: ^2.0.9

2. Install it

You can install packages from the command line:

with pub:


$ pub get

Alternatively, your editor might support pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:font_face_observer/font_face_observer.dart';
  
Version Uploaded Documentation Archive
2.0.9 Aug 1, 2018 Go to the documentation of font_face_observer 2.0.9 Download font_face_observer 2.0.9 archive
2.0.8 Feb 28, 2018 Go to the documentation of font_face_observer 2.0.8 Download font_face_observer 2.0.8 archive
2.0.7 Feb 19, 2018 Go to the documentation of font_face_observer 2.0.7 Download font_face_observer 2.0.7 archive
2.0.6 Dec 6, 2017 Go to the documentation of font_face_observer 2.0.6 Download font_face_observer 2.0.6 archive
2.0.5 Dec 6, 2017 Go to the documentation of font_face_observer 2.0.5 Download font_face_observer 2.0.5 archive
2.0.4 Dec 6, 2017 Go to the documentation of font_face_observer 2.0.4 Download font_face_observer 2.0.4 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
0
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
50
Learn more about scoring.

We analyzed this package on Oct 10, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0
  • pana: 0.12.4

Platforms

Detected platforms: web

Primary library: package:font_face_observer/font_face_observer.dart with components: html.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.22.1 <3.0.0
dart2_constant ^1.0.0 1.0.2+dart2
Dev dependencies
build_runner >=0.6.0 <1.0.0
build_test >=0.9.0 <1.0.0
build_web_compilers >=0.2.0 <1.0.0
test >=0.12.30 <2.0.0