UNPKG

react-native-runescape-text

Version:

Convert text to a text GIF image with RuneScape chat effects for React Native.

62 lines (51 loc) 1.76 kB
const wrap = require("word-wrap"); const ValueError = require("./ValueError"); const { colors, motions, effectsMap } = require("../utils/effectUtil"); class Parser { constructor(config, wordWrapConfig) { this.config = config; this.wordWrapConfig = wordWrapConfig; this.setEffectsRegExp(); } setEffectsRegExp() { const escapedSuffix = this.config.suffix.replace(/(.{1})/g, "\\$1"); const colorString = `(${colors.join("|")})${escapedSuffix}`; const motionString = `(${motions.join("|")})${escapedSuffix}`; this.effectsRegExp = RegExp( `^${colorString}(${motionString})?|^${motionString}(${colorString})?`, "i" ); } sanitizeMessage(string, effectsString) { let sanitizedMessage = string .replace(effectsString, ""); if (!this.config.supportNonAscii) { sanitizedMessage = sanitizedMessage .replace(/([^ -~\t\n]|`)+/g, this.config.replacement); } if (this.config.trimStart) { sanitizedMessage = sanitizedMessage.trimStart(); } sanitizedMessage = sanitizedMessage.slice(0, this.config.maxMessageLength); if (sanitizedMessage === "") { throw new ValueError("message cannot be empty"); } return wrap(sanitizedMessage, this.wordWrapConfig); } parse(string) { const effectsString = (string.match(this.effectsRegExp) || [""])[0]; const effects = effectsString .toLowerCase() .split(this.config.suffix) .filter(Boolean) .reduce((value, effect) => ({ ...value, [effectsMap[effect]]: effect }), { color: this.config.color, motion: this.config.motion, }); return { ...effects, message: this.sanitizeMessage(string, effectsString), }; } } module.exports = Parser;