react-native-custom-fonts
Version:
Use fonts specified via a network location, instead of managing them in your native builds!
225 lines (178 loc) • 11.5 kB
JavaScript
;
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = exports.useCustomFont = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _typeCheck = require("type-check");
var _reactNative = require("react-native");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
var RNCustomFonts = _reactNative.NativeModules.RNCustomFonts;
var throwOnInvalidUri = function throwOnInvalidUri(uri) {
if (!(0, _typeCheck.typeCheck)("String", uri) || uri.length <= 0) {
throw new Error("Expected String uri, encountered ".concat(uri, "."));
}
return "".concat(uri);
};
var throwOnInvalidFontFamily = function throwOnInvalidFontFamily(fontFamily) {
if (!(0, _typeCheck.typeCheck)("String", fontFamily) || fontFamily.length <= 0) {
throw new Error("Expected String fontFamily, encountered ".concat(fontFamily, "."));
}
return "".concat(fontFamily);
};
var throwOnInvalidFontWeight = function throwOnInvalidFontWeight(fontWeight) {
if ((0, _typeCheck.typeCheck)("String", fontWeight) && fontWeight.length >= 0) {
return "".concat(fontWeight);
} else if (fontWeight === undefined) {
return 'Normal';
}
throw new Error("Expected non-empty String or undefined fontWeight, encountered ".concat(fontWeight, "."));
};
var modulateFontWeight = function modulateFontWeight(fontWeight) {
return _reactNative.Platform.OS === 'ios' ? fontWeight : fontWeight.toLowerCase();
};
var defaultFontFaces = Object.freeze({});
var defaultFallback = Object.freeze({
color: '#000000',
fontFamily: _reactNative.Platform.OS === 'ios' ? 'Avenir' : 'Roboto',
fontWeight: modulateFontWeight('normal')
});
var defaultContext = Object.freeze({
fontFaces: defaultFontFaces,
fallback: defaultFallback
});
var CustomFontsContext = _react["default"].createContext(defaultContext);
var sanitizeFontFaces = function sanitizeFontFaces() {
var fontFaces = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return Object.fromEntries(Object.entries(fontFaces).map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
k = _ref2[0],
_ref2$ = _ref2[1],
uri = _ref2$.uri,
fontFamily = _ref2$.fontFamily,
fontWeight = _ref2$.fontWeight,
extras = _objectWithoutProperties(_ref2$, ["uri", "fontFamily", "fontWeight"]);
return [k, _objectSpread({
uri: throwOnInvalidUri(uri),
fontFamily: throwOnInvalidFontFamily(fontFamily),
fontWeight: modulateFontWeight(throwOnInvalidFontWeight(fontWeight))
}, extras)];
}));
};
var CustomFontsProvider = function CustomFontsProvider(_ref3) {
var children = _ref3.children,
fontFaces = _ref3.fontFaces,
fallback = _ref3.fallback,
onDownloadDidStart = _ref3.onDownloadDidStart,
onDownloadDidEnd = _ref3.onDownloadDidEnd,
onDownloadDidError = _ref3.onDownloadDidError,
extraProps = _objectWithoutProperties(_ref3, ["children", "fontFaces", "fallback", "onDownloadDidStart", "onDownloadDidEnd", "onDownloadDidError"]);
var _useState = (0, _react.useState)(defaultContext),
_useState2 = _slicedToArray(_useState, 2),
state = _useState2[0],
setState = _useState2[1];
(0, _react.useEffect)(function () {
var nextState = Object.freeze({
fontFaces: sanitizeFontFaces(fontFaces),
fallback: Object.freeze(fallback)
});
onDownloadDidStart();
return RNCustomFonts.onFontFacesChanged(Object.values(nextState.fontFaces)).then(function () {
return setState(nextState);
}).then(onDownloadDidEnd)["catch"](function (e) {
if (__DEV__) {
console.warn("Failed to load fonts.");
}
setState(defaultContext);
return onDownloadDidError(e);
}) && undefined;
}, [fontFaces, onDownloadDidStart, onDownloadDidEnd, onDownloadDidError, fallback, setState]);
return /*#__PURE__*/_react["default"].createElement(CustomFontsContext.Provider, {
value: state,
children: children
});
};
var getSafeCustomStyle = function getSafeCustomStyle(_ref4) {
var uri = _ref4.uri,
fontFamily = _ref4.fontFamily,
fontWeight = _ref4.fontWeight,
extras = _objectWithoutProperties(_ref4, ["uri", "fontFamily", "fontWeight"]);
if (_reactNative.Platform.OS === 'ios') {
return _objectSpread({
fontFamily: fontFamily,
fontWeight: fontWeight
}, extras);
} // XXX: This is a hack; Android does not play nicely with conflicting font assignments.
// These override our direct calls to setTypeface().
return extras;
};
var useCustomFont = function useCustomFont(name) {
var ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
var context = (0, _react.useContext)(CustomFontsContext);
var _useState3 = (0, _react.useState)(fallback),
_useState4 = _slicedToArray(_useState3, 2),
style = _useState4[0],
setStyle = _useState4[1]; // XXX: Evaluate fonts.
var fontFaces = context.fontFaces,
fallback = context.fallback;
var fontFace = fontFaces[name];
var hasCustomFontFace = (0, _typeCheck.typeCheck)("Object", fontFace); // XXX: Evaluate refs.
var localRef = (0, _react.useRef)();
var resolvedRef = ref || localRef;
(0, _react.useEffect)(function () {
if (hasCustomFontFace) {
var fontFamily = fontFace.fontFamily,
fontWeight = fontFace.fontWeight;
return RNCustomFonts.onRequestFontFamily((0, _reactNative.findNodeHandle)(resolvedRef.current), fontFamily, fontWeight).then(function () {
return setStyle(getSafeCustomStyle(fontFace));
})["catch"](function (e) {
console.error(e);
setStyle(fallback);
}) && undefined;
}
setStyle(fallback);
return undefined;
}, [resolvedRef, fallback, name, fontFaces, fontFace, hasCustomFontFace, setStyle]);
return {
style: style,
ref: resolvedRef
};
};
exports.useCustomFont = useCustomFont;
CustomFontsProvider.propTypes = {
fontFaces: _propTypes["default"].shape({}),
fallback: _propTypes["default"].shape({}),
onDownloadDidStart: _propTypes["default"].func,
onDownloadDidEnd: _propTypes["default"].func,
onDownloadDidError: _propTypes["default"].func
};
CustomFontsProvider.defaultProps = {
fontFaces: defaultFontFaces,
fallback: defaultFallback,
onDownloadDidStart: function onDownloadDidStart() {
return null;
},
onDownloadDidEnd: function onDownloadDidEnd() {
return null;
},
onDownloadDidError: function onDownloadDidError() {
return null;
}
};
var _default = CustomFontsProvider;
exports["default"] = _default;