Created
August 28, 2019 16:48
-
-
Save SebastianHGonzalez/683b96c19d21a3ce19aad4ac15fac594 to your computer and use it in GitHub Desktop.
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
import { string, shape } from "prop-types"; | |
import es from "./messages_es"; | |
function I18n({ id, fallback, fillers }) { | |
const message = es[id] || fallback || id; | |
const filledMessage = fillMessage(message, fillers); | |
if(fillTagRegex.test(filledMessage)) { | |
console.warn("Message missing fillers:", id); | |
} | |
return filledMessage; | |
} | |
const fillTagRegex = /\${(.*?)}/g; // it matches all tags in a string ex. '${foo}' | |
const fillTagCleanupRegex = /[a-zA-Z0-9]+/g; // it cleans up tag sintax ex. '${foo}' => 'foo' | |
/** | |
* Replaces string tags with values in provided as fillers | |
* ex. "a ${foo} is a ${baz}", { foo: "dog", baz: "canine"} => "a dog is a canine" | |
* | |
* @param {string} message | |
* @param {{[key: string]: string}} fillers | |
* @returns {string} filled message | |
*/ | |
function fillMessage(message, fillers = {}) { | |
return (message.match(fillTagRegex) || []) | |
.map(fillTag => ({ | |
fillTag, | |
fillerKey: fillTag.match(fillTagCleanupRegex)[0] | |
})) | |
.reduce( | |
(partiallyFilledMessage, { fillTag, fillerKey }) => | |
partiallyFilledMessage.replace(fillTag, fillers[fillerKey] || fillTag), | |
message | |
); | |
} | |
I18n.propTypes = { | |
id: string.isRequired, | |
fallback: string, | |
fillers: shape({}) | |
}; | |
I18n.defaultProps = { | |
fallback: "", | |
fillers: {} | |
}; | |
export default I18n; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment