forked from 99ff00/react-native-dynamic-fonts
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
82 lines (68 loc) · 1.97 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
/**
* Copyright (c) 2017-present, Wyatt Greenway. All rights reserved.
*
* This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
const { NativeModules } = require('react-native');
const { DynamicFonts } = NativeModules;
const loadedFonts = {};
function loadFont(name, data, type, forceLoad) {
/* Check if this font was already loaded */
if (!forceLoad && loadedFonts[name])
return Promise.resolve(loadedFonts[name]);
if (!name)
throw new Error('Name is a required argument');
if (!data)
throw new Error('Data is a required argument');
/* Load font via native binary code */
return new Promise(function(resolve, reject) {
DynamicFonts.loadFont({
name: name,
data: data,
type: type
}, function(err, givenName) {
if (err) {
reject(err);
return;
}
/* Loaded successfully... resolve promise with "real" font name */
loadedFonts[name] = givenName;
resolve(givenName);
});
});
}
function loadFontFromFile(name, filePath) {
if (!name)
throw new Error('name is a required argument');
if (!filePath)
throw new Error('filePath is a required argument');
return new Promise(function(resolve, reject) {
DynamicFonts.loadFontFromFile({
name,
filePath
}, function(err, givenName) {
if (err) {
reject(err);
return;
}
resolve(givenName);
});
});
}
function unsupportedFeature () {
return Promise.reject("The feature is unsupported on this platform")
}
function loadFonts(_fontList, forceLoad) {
var fontList = _fontList;
if (!fontList)
return Promise.resolve([]);
if (!(fontList instanceof Array))
fontList = [fontList];
return Promise.all(fontList.filter((font) => font).map((font) => loadFont(font.name, font.data, font.type, forceLoad)));
}
module.exports = {
loadFont: loadFont,
loadFonts: loadFonts,
loadFontFromFile: loadFontFromFile
}