-
Notifications
You must be signed in to change notification settings - Fork 734
Add dynamic fonts loading (and downloading) #2736
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 7 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
c6f9a28
Add dynamic fonts loading (and downloading)
M-i-k-e-l 5fbf356
Add mock for react-native-fs
M-i-k-e-l 56f817e
Add DynamicFontsScreen
M-i-k-e-l 48bf106
Make react-native-fs an optional dependency
M-i-k-e-l 5bfbf51
Merge branch 'master' into feat/dynamic-fonts
M-i-k-e-l 2251631
DynamicFonts - Android - fix fonts not loaded properly and remove som…
M-i-k-e-l df60328
Bump native lib's version to 4.1.1
M-i-k-e-l f3fa3f5
Comment out loadFontFromFile for now
M-i-k-e-l 82793f2
Add empty lines
M-i-k-e-l b28b703
Update lib/ios/reactnativeuilib/dynamicfont/DynamicFont.m
M-i-k-e-l b3fc748
Remove checkPermissions from ios
M-i-k-e-l File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
120 changes: 120 additions & 0 deletions
120
demo/src/screens/nativeComponentScreens/DynamicFontsScreen.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,120 @@ | ||
import React, {Component, Fragment} from 'react'; | ||
import {ScrollView} from 'react-native'; | ||
import {View, Text, Button, DynamicFonts} from 'react-native-ui-lib'; | ||
import {renderMultipleSegmentOptions} from '../ExampleScreenPresenter'; | ||
|
||
enum FontLoadingEnum { | ||
SINGLE_FONT = 'singleFont', | ||
FONT_FAMILY = 'fontFamily' | ||
} | ||
|
||
type State = { | ||
fontLoadingType: FontLoadingEnum; | ||
loadedFonts: string[]; | ||
}; | ||
|
||
export default class DynamicFontsScreen extends Component<{}, State> { | ||
private fontDownloader: InstanceType<typeof DynamicFonts> = new DynamicFonts({debug: true}); | ||
|
||
state = { | ||
fontLoadingType: FontLoadingEnum.SINGLE_FONT, | ||
loadedFonts: [] | ||
}; | ||
|
||
renderSingleFont = () => { | ||
const {loadedFonts} = this.state; | ||
return ( | ||
<Fragment> | ||
<Text style={{fontSize: 24, lineHeight: 28, fontFamily: 'System'}}>{` | ||
System: | ||
ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | ||
`}</Text> | ||
{loadedFonts.length > 0 && ( | ||
<Text marginT-20 style={{fontSize: 24, lineHeight: 28, fontFamily: loadedFonts[0]}}>{` | ||
${loadedFonts}: | ||
ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | ||
`}</Text> | ||
)} | ||
<Button | ||
marginV-20 | ||
label="Load a single font" | ||
onPress={async () => { | ||
try { | ||
const loadedFonts = await this.fontDownloader.getFont({ | ||
fontUri: | ||
'https://wixmp-1d257fba8470f1b562a0f5f2.wixmp.com/TypographyKits/fonts/Vollkorn/Vollkorn-Regular.ttf', | ||
fontName: 'Vollkorn-Regular', | ||
fontExtension: 'ttf' | ||
}); | ||
this.setState({loadedFonts: [loadedFonts]}); | ||
} catch (error) { | ||
console.log('Error!', error); | ||
} | ||
}} | ||
/> | ||
</Fragment> | ||
); | ||
}; | ||
|
||
renderFontFamily = () => { | ||
const {loadedFonts} = this.state; | ||
return ( | ||
<Fragment> | ||
<Text style={{fontSize: 16, lineHeight: 18, fontFamily: 'System'}}>{` | ||
System: | ||
ABCDEFGH abcdefgh | ||
`}</Text> | ||
<ScrollView> | ||
{loadedFonts?.map(loadedFont => ( | ||
<Text key={loadedFont} style={{fontSize: 16, lineHeight: 18, fontFamily: loadedFont}}>{` | ||
${loadedFont}: | ||
ABCDEFGH abcdefgh | ||
`}</Text> | ||
))} | ||
</ScrollView> | ||
|
||
<Button | ||
marginV-20 | ||
label="Load a complete font family" | ||
onPress={async () => { | ||
try { | ||
const loadedFonts = await this.fontDownloader.getFontFamily('https://wixmp-1d257fba8470f1b562a0f5f2.wixmp.com/TypographyKits/fonts/Vollkorn/', | ||
[ | ||
'Bold', | ||
'BoldItalic', | ||
'ExtraBold', | ||
'ExtraBoldItalic', | ||
'Italic', | ||
'Medium', | ||
'MediumItalic', | ||
'Regular', | ||
'SemiBold' | ||
], | ||
'ttf', | ||
'Vollkorn-'); | ||
this.setState({loadedFonts}); | ||
} catch (error) { | ||
console.log('Error!', error); | ||
} | ||
}} | ||
/> | ||
</Fragment> | ||
); | ||
}; | ||
|
||
render() { | ||
const {fontLoadingType, loadedFonts} = this.state; | ||
return ( | ||
<View bg-grey80 flex padding-20> | ||
{renderMultipleSegmentOptions.call(this, 'Font loading:', 'fontLoadingType', [ | ||
{label: 'Single', value: FontLoadingEnum.SINGLE_FONT}, | ||
{label: 'Family', value: FontLoadingEnum.FONT_FAMILY} | ||
])} | ||
<View flex center key={`${loadedFonts}`}> | ||
{fontLoadingType === FontLoadingEnum.SINGLE_FONT ? this.renderSingleFont() : this.renderFontFamily()} | ||
{loadedFonts && <Text text80>Loaded fonts: {loadedFonts.map(loadedFont => `${loadedFont} `)}</Text>} | ||
</View> | ||
</View> | ||
); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
137 changes: 137 additions & 0 deletions
137
lib/android/src/main/java/com/wix/reactnativeuilib/dynamicfont/DynamicFontModule.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,137 @@ | ||
package com.wix.reactnativeuilib.dynamicfont; | ||
|
||
import android.app.Activity; | ||
import android.graphics.Typeface; | ||
import android.util.Base64; | ||
|
||
import com.facebook.react.bridge.Callback; | ||
import com.facebook.react.bridge.ReactApplicationContext; | ||
import com.facebook.react.bridge.ReactContextBaseJavaModule; | ||
import com.facebook.react.bridge.ReactMethod; | ||
import com.facebook.react.bridge.ReadableMap; | ||
import com.facebook.react.views.text.ReactFontManager; | ||
|
||
import java.io.File; | ||
import java.io.FileOutputStream; | ||
|
||
public class DynamicFontModule extends ReactContextBaseJavaModule { | ||
int tempNameCounter = 0; | ||
|
||
public DynamicFontModule(ReactApplicationContext reactContext) { | ||
super(reactContext); | ||
} | ||
|
||
@Override | ||
public String getName() { | ||
return "DynamicFont"; | ||
} | ||
|
||
@ReactMethod | ||
public void loadFontFromFile(final ReadableMap options, final Callback callback) { | ||
Activity currentActivity = getCurrentActivity(); | ||
if (currentActivity == null) { | ||
callback.invoke("Invalid activity"); | ||
return; | ||
} | ||
|
||
String filePath = options.hasKey("filePath") ? options.getString("filePath") : null, | ||
name = (options.hasKey("name")) ? options.getString("name") : null; | ||
|
||
if (filePath == null || filePath.length() == 0) { | ||
callback.invoke("filePath property empty"); | ||
return; | ||
} | ||
|
||
File f = new File(filePath); | ||
|
||
if (f.exists() && f.canRead()) { | ||
boolean wasLoaded = false; | ||
try { | ||
Typeface typeface = Typeface.createFromFile(f); | ||
//Cache the font for react | ||
ReactFontManager.getInstance().setTypeface(name, typeface.getStyle(), typeface); | ||
wasLoaded = true; | ||
} catch (Throwable e) { | ||
callback.invoke(e.getMessage()); | ||
} finally { | ||
if (wasLoaded) { | ||
callback.invoke(null, name); | ||
} | ||
} | ||
} else { | ||
callback.invoke("invalid file"); | ||
} | ||
} | ||
|
||
@ReactMethod | ||
public void loadFont(final ReadableMap options, final Callback callback) throws Exception { | ||
Activity currentActivity = getCurrentActivity(); | ||
if (currentActivity == null) { | ||
callback.invoke("Invalid activity"); | ||
return; | ||
} | ||
|
||
String name = (options.hasKey("name")) ? options.getString("name") : null, | ||
data = (options.hasKey("data")) ? options.getString("data") : null, | ||
type = null; | ||
|
||
if (name == null || name.length() == 0) { | ||
callback.invoke("Name property empty"); | ||
return; | ||
} | ||
|
||
if (data == null || data.length() == 0) { | ||
callback.invoke("Data property empty"); | ||
return; | ||
} | ||
|
||
if (("data:").equalsIgnoreCase(data.substring(0, 5))) { | ||
Integer pos = data.indexOf(','); | ||
if (pos > 0) { | ||
String[] encodingParams = data.substring(5, pos).split(";"); | ||
String mimeType = encodingParams[0]; | ||
|
||
data = data.substring(pos + 1); | ||
|
||
if (("application/x-font-ttf").equalsIgnoreCase(mimeType) || | ||
("application/x-font-truetype").equalsIgnoreCase(mimeType) || | ||
("font/ttf").equalsIgnoreCase(mimeType)) { | ||
type = "ttf"; | ||
} else if (("application/x-font-opentype").equalsIgnoreCase(mimeType) || | ||
("font/opentype").equalsIgnoreCase(mimeType)) { | ||
type = "otf"; | ||
} | ||
} | ||
} | ||
|
||
if (options.hasKey("type")) | ||
type = options.getString("type"); | ||
|
||
if (type == null) | ||
type = "ttf"; | ||
|
||
try { | ||
byte[] decodedBytes = Base64.decode(data, Base64.DEFAULT); | ||
File cacheFile = new File(currentActivity.getCacheDir(), "tempFont" + (tempNameCounter++) + type); | ||
|
||
FileOutputStream stream = new FileOutputStream(cacheFile); | ||
try { | ||
stream.write(decodedBytes); | ||
} finally { | ||
stream.close(); | ||
} | ||
|
||
//Load the font from the temporary file we just created | ||
Typeface typeface = Typeface.createFromFile(cacheFile); | ||
|
||
//Cache the font for react | ||
ReactFontManager.getInstance().setTypeface(name, Typeface.NORMAL, typeface); | ||
|
||
cacheFile.delete(); | ||
} catch(Exception e) { | ||
callback.invoke(e.getMessage()); | ||
} finally { | ||
callback.invoke(null, name); | ||
} | ||
} | ||
} |
27 changes: 27 additions & 0 deletions
27
lib/android/src/main/java/com/wix/reactnativeuilib/dynamicfont/DynamicFontPackage.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
package com.wix.reactnativeuilib.dynamicfont; | ||
|
||
import java.util.Arrays; | ||
import java.util.Collections; | ||
import java.util.List; | ||
|
||
import com.facebook.react.ReactPackage; | ||
import com.facebook.react.bridge.NativeModule; | ||
import com.facebook.react.bridge.ReactApplicationContext; | ||
import com.facebook.react.uimanager.ViewManager; | ||
import com.facebook.react.bridge.JavaScriptModule; | ||
public class DynamicFontPackage implements ReactPackage { | ||
@Override | ||
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { | ||
return Arrays.<NativeModule>asList(new DynamicFontModule(reactContext)); | ||
} | ||
|
||
// Deprecated from RN 0.47 | ||
public List<Class<? extends JavaScriptModule>> createJSModules() { | ||
return Collections.emptyList(); | ||
} | ||
|
||
@Override | ||
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { | ||
return Collections.emptyList(); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.