Skip to content

Commit 11af0d8

Browse files
committed
remove plateform-specific code
- add example in README
1 parent e6f556a commit 11af0d8

File tree

7 files changed

+17
-190
lines changed

7 files changed

+17
-190
lines changed

README.md

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,16 @@ const font = new opentype.Font({
126126
ascender: 800,
127127
descender: -200,
128128
glyphs: glyphs});
129-
font.download();
129+
130+
// case 1: node fs
131+
require('fs').appendFileSync('font.otf', Buffer.from(font.toArrayBuffer()));
132+
133+
// case 2: browser download
134+
const blob = new Blob([font.toArrayBuffer()], {type: 'font/opentype'});
135+
document.body.appendChild(Object.assign(document.createElement('a'), {
136+
download: 'myFont.otf', href: URL.createObjectURL(blob)
137+
})).click();
138+
130139
```
131140

132141
If you want to inspect the font, use `font.toTables()`

externs/opentype.js

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -632,18 +632,6 @@ opentype.LookupList = function(lookupListTable, subtableMakers) {};
632632
*/
633633
opentype.BoundingBox = function() {};
634634

635-
/**
636-
* @param {string} url - The URL of the font to load.
637-
* @param {Function} callback - The callback.
638-
*/
639-
opentype.load = function(url, callback) {};
640-
641-
/**
642-
* @param {string} url - The URL of the font to load.
643-
* @return {opentype.Font}
644-
*/
645-
opentype.loadSync = function(url) {};
646-
647635
/**
648636
* @param {ArrayBuffer}
649637
* @return {opentype.Font}

package.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,9 @@
3030
"test": "npm run build && npm run dist && mocha --recursive && npm run lint",
3131
"lint": "eslint src",
3232
"lint-fix": "eslint src --fix",
33-
"start": "esbuild --bundle src/opentype.js --outdir=dist --target=es2018 --format=iife --out-extension:.js=.js --global-name=opentype --footer:js=\"(function (root, factory) { if (typeof define === 'function' && define.amd)define(factory); else if (typeof module === 'object' && module.exports)module.exports = factory(); else root.opentype = factory(); }(typeof self !== 'undefined' ? self : this, () => ({...opentype,'default':opentype})));\" --watch --servedir=. --footer:js=\"new EventSource('/esbuild').addEventListener('change', () => location.reload())\"",
34-
"b:umd": "esbuild --bundle src/opentype.js --outdir=dist --target=es2018 --format=iife --out-extension:.js=.js --global-name=opentype --footer:js=\"(function (root, factory) { if (typeof define === 'function' && define.amd)define(factory); else if (typeof module === 'object' && module.exports)module.exports = factory(); else root.opentype = factory(); }(typeof self !== 'undefined' ? self : this, () => ({...opentype,'default':opentype})));\"",
35-
"d:umd": "esbuild --bundle src/opentype.js --outdir=dist --target=es2018 --format=iife --out-extension:.js=.min.js --global-name=opentype --footer:js=\"(function (root, factory) { if (typeof define === 'function' && define.amd)define(factory); else if (typeof module === 'object' && module.exports)module.exports = factory(); else root.opentype = factory(); }(typeof self !== 'undefined' ? self : this, () => ({...opentype,'default':opentype})));\" --minify --sourcemap",
33+
"start": "esbuild --bundle src/opentype.js --outdir=dist --target=es2018 --format=iife --out-extension:.js=.js --global-name=opentype --footer:js=\"(function (root, factory) { if (typeof define === 'function' && define.amd)define(factory); else if (typeof module === 'object' && module.exports)module.exports = factory(); else root.opentype = factory(); }(typeof self !== 'undefined' ? self : this, () => ({...opentype,'default':opentype})));\" --watch --servedir=. --footer:js=\"new EventSource('/esbuild').addEventListener('change', () => location.reload())\"",
34+
"b:umd": "esbuild --bundle src/opentype.js --outdir=dist --target=es2018 --format=iife --out-extension:.js=.js --global-name=opentype --footer:js=\"(function (root, factory) { if (typeof define === 'function' && define.amd)define(factory); else if (typeof module === 'object' && module.exports)module.exports = factory(); else root.opentype = factory(); }(typeof self !== 'undefined' ? self : this, () => ({...opentype,'default':opentype})));\"",
35+
"d:umd": "esbuild --bundle src/opentype.js --outdir=dist --target=es2018 --format=iife --out-extension:.js=.min.js --global-name=opentype --footer:js=\"(function (root, factory) { if (typeof define === 'function' && define.amd)define(factory); else if (typeof module === 'object' && module.exports)module.exports = factory(); else root.opentype = factory(); }(typeof self !== 'undefined' ? self : this, () => ({...opentype,'default':opentype})));\" --minify --sourcemap",
3636
"b:esm": "esbuild --bundle src/opentype.js --outdir=dist --target=es2018 --format=esm --out-extension:.js=.module.js",
3737
"d:esm": "esbuild --bundle src/opentype.js --outdir=dist --target=es2018 --format=esm --out-extension:.js=.module.min.js --minify --sourcemap"
3838
},

src/font.js

Lines changed: 1 addition & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { DefaultEncoding } from './encoding.js';
66
import glyphset from './glyphset.js';
77
import Position from './position.js';
88
import Substitution from './substitution.js';
9-
import { isBrowser, checkArgument } from './util.js';
9+
import { checkArgument } from './util.js';
1010
import HintingTrueType from './hintingtt.js';
1111
import Bidi from './bidi.js';
1212

@@ -525,42 +525,6 @@ Font.prototype.toArrayBuffer = function() {
525525
return buffer;
526526
};
527527

528-
/**
529-
* Initiate a download of the OpenType font.
530-
*/
531-
Font.prototype.download = function(fileName) {
532-
const familyName = this.getEnglishName('fontFamily');
533-
const styleName = this.getEnglishName('fontSubfamily');
534-
fileName = fileName || familyName.replace(/\s/g, '') + '-' + styleName + '.otf';
535-
const arrayBuffer = this.toArrayBuffer();
536-
537-
if (isBrowser()) {
538-
window.URL = window.URL || window.webkitURL;
539-
540-
if (window.URL) {
541-
const dataView = new DataView(arrayBuffer);
542-
const blob = new Blob([dataView], {type: 'font/opentype'});
543-
544-
let link = document.createElement('a');
545-
link.href = window.URL.createObjectURL(blob);
546-
link.download = fileName;
547-
548-
let event = document.createEvent('MouseEvents');
549-
event.initEvent('click', true, false);
550-
link.dispatchEvent(event);
551-
} else {
552-
console.warn('Font file could not be downloaded. Try using a different browser.');
553-
}
554-
} else {
555-
const fs = require('fs');
556-
const buffer = Buffer.alloc(arrayBuffer.byteLength);
557-
const view = new Uint8Array(arrayBuffer);
558-
for (let i = 0; i < buffer.length; ++i) {
559-
buffer[i] = view[i];
560-
}
561-
fs.writeFileSync(fileName, buffer);
562-
}
563-
};
564528
/**
565529
* @private
566530
*/

src/opentype.js

Lines changed: 1 addition & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -33,53 +33,12 @@ import _name from './tables/name.js';
3333
import os2 from './tables/os2.js';
3434
import post from './tables/post.js';
3535
import meta from './tables/meta.js';
36-
import { readFile, readFileSync} from 'fs';
36+
3737
/**
3838
* The opentype library.
3939
* @namespace opentype
4040
*/
4141

42-
// File loaders /////////////////////////////////////////////////////////
43-
/**
44-
* Loads a font from a file. The callback throws an error message as the first parameter if it fails
45-
* and the font as an ArrayBuffer in the second parameter if it succeeds.
46-
* @param {string} path - The path of the file
47-
* @param {Function} callback - The function to call when the font load completes
48-
*/
49-
function loadFromFile(path, callback) {
50-
readFile(path, function(err, buffer) {
51-
if (err) {
52-
return callback(err.message);
53-
}
54-
55-
callback(null, buffer);
56-
});
57-
}
58-
59-
/**
60-
* Loads a font from a URL. The callback throws an error message as the first parameter if it fails
61-
* and the font as an ArrayBuffer in the second parameter if it succeeds.
62-
* @param {string} url - The URL of the font file.
63-
* @param {Function} callback - The function to call when the font load completes
64-
*/
65-
function loadFromUrl(url, callback) {
66-
const request = new XMLHttpRequest();
67-
request.open('get', url, true);
68-
request.responseType = 'arraybuffer';
69-
request.onload = function() {
70-
if (request.response) {
71-
return callback(null, request.response);
72-
} else {
73-
return callback('Font could not be loaded: ' + request.statusText);
74-
}
75-
};
76-
77-
request.onerror = function () {
78-
callback('Font could not be loaded');
79-
};
80-
81-
request.send();
82-
}
8342

8443
// Table Directory Entries //////////////////////////////////////////////
8544
/**
@@ -420,66 +379,11 @@ function parseBuffer(buffer, opt={}) {
420379
return font;
421380
}
422381

423-
/**
424-
* Asynchronously load the font from a URL or a filesystem. When done, call the callback
425-
* with two arguments `(err, font)`. The `err` will be null on success,
426-
* the `font` is a Font object.
427-
* We use the node.js callback convention so that
428-
* opentype.js can integrate with frameworks like async.js.
429-
* @alias opentype.load
430-
* @param {string} url - The URL of the font to load.
431-
* @param {Function} callback - The callback.
432-
*/
433-
function load(url, callback, opt = {}) {
434-
const isNode = typeof window === 'undefined';
435-
const loadFn = isNode && !opt.isUrl ? loadFromFile : loadFromUrl;
436-
return new Promise((resolve, reject) => {
437-
loadFn(url, function(err, buffer) {
438-
if (err) {
439-
if (callback) {
440-
return callback(err);
441-
} else {
442-
reject(err);
443-
}
444-
}
445-
let font;
446-
try {
447-
font = parseBuffer(buffer, opt);
448-
} catch (e) {
449-
if (callback) {
450-
return callback(e, null);
451-
} else {
452-
reject(e);
453-
}
454-
}
455-
if (callback) {
456-
return callback(null, font);
457-
} else {
458-
resolve(font);
459-
}
460-
});
461-
});
462-
}
463-
464-
/**
465-
* Synchronously load the font from a URL or file.
466-
* When done, returns the font object or throws an error.
467-
* @alias opentype.loadSync
468-
* @param {string} url - The URL of the font to load.
469-
* @param {Object} opt - opt.lowMemory
470-
* @return {opentype.Font}
471-
*/
472-
function loadSync(url, opt) {
473-
return parseBuffer(readFileSync(url), opt);
474-
}
475-
476382
export {
477383
Font,
478384
Glyph,
479385
Path,
480386
BoundingBox,
481387
parse as _parse,
482388
parseBuffer as parse,
483-
load,
484-
loadSync
485389
};

src/util.js

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,3 @@
1-
function isBrowser() {
2-
return typeof window !== 'undefined';
3-
}
4-
5-
function isNode() {
6-
return typeof window === 'undefined';
7-
}
8-
91
function checkArgument(expression, message) {
102
if (!expression) {
113
throw message;
@@ -32,4 +24,4 @@ function objectsEqual(obj1, obj2) {
3224
return arraysEqual(val1, val2) && arraysEqual(keys1, keys2);
3325
}
3426

35-
export { isBrowser, isNode, checkArgument, arraysEqual, objectsEqual };
27+
export { checkArgument, arraysEqual, objectsEqual };

test/opentypeSpec.js

Lines changed: 1 addition & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import assert from 'assert';
2-
import { Font, Path, Glyph, parse, load} from '../src/opentype.js';
2+
import { Font, Path, Glyph, parse } from '../src/opentype.js';
33
import { readFileSync } from 'fs';
44
const loadSync = (url, opt) => parse(readFileSync(url), opt);
55

@@ -15,19 +15,6 @@ describe('opentype.js', function() {
1515
assert.equal(aGlyph.path.commands.length, 15);
1616
});
1717

18-
it('[deprecated] .load() promise resolve uppon success', function(done) {
19-
load('./test/fonts/Roboto-Black.ttf').then((font) => {
20-
assert.deepEqual(font.names.macintosh.fontFamily, {en: 'Roboto Black'});
21-
assert.deepEqual(font.names.windows.fontFamily, {en: 'Roboto Black'});
22-
assert.equal(font.unitsPerEm, 2048);
23-
assert.equal(font.glyphs.length, 1294);
24-
const aGlyph = font.charToGlyph('A');
25-
assert.equal(aGlyph.unicode, 65);
26-
assert.equal(aGlyph.path.commands.length, 15);
27-
done();
28-
});
29-
});
30-
3118
it('can load a OpenType/CFF font', function() {
3219
const font = loadSync('./test/fonts/FiraSansOT-Medium.otf');
3320
assert.deepEqual(font.names.macintosh.fontFamily, {en: 'Fira Sans OT Medium'});
@@ -68,23 +55,6 @@ describe('opentype.js', function() {
6855
assert.equal(aGlyph.path.commands.length, 14);
6956
});
7057

71-
it('[deprecated] .load() handles a parseBuffer error', function(done) {
72-
load('./test/fonts/badfont.ttf', function(err) {
73-
if (err) {
74-
done();
75-
}
76-
});
77-
});
78-
79-
it('[deprecated] .load() handles a parseBuffer error as a rejected promise', function(done) {
80-
load('./test/fonts/badfont.ttf')
81-
.catch((err) => {
82-
if (err) {
83-
done();
84-
}
85-
});
86-
});
87-
8858
it('throws an error when advanceWidth is not set', function() {
8959
const notdefGlyph = new Glyph({
9060
name: '.notdef',

0 commit comments

Comments
 (0)