@ultraq/icu-message-formatter 0.13.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +2 -4
  3. package/dist/icu-message-formatter.browser.es.min.js +2 -0
  4. package/dist/icu-message-formatter.browser.es.min.js.map +1 -0
  5. package/dist/icu-message-formatter.browser.min.js +2 -0
  6. package/dist/icu-message-formatter.browser.min.js.map +1 -0
  7. package/{lib/icu-message-formatter.cjs.js → dist/icu-message-formatter.cjs} +65 -52
  8. package/dist/icu-message-formatter.cjs.map +1 -0
  9. package/dist/icu-message-formatter.d.cts +153 -0
  10. package/dist/icu-message-formatter.d.ts +153 -0
  11. package/{lib/icu-message-formatter.es.js → dist/icu-message-formatter.js} +65 -52
  12. package/dist/icu-message-formatter.js.map +1 -0
  13. package/package.json +25 -16
  14. package/dist/icu-message-formatter.es.min.js +0 -2
  15. package/dist/icu-message-formatter.es.min.js.map +0 -1
  16. package/dist/icu-message-formatter.min.js +0 -2
  17. package/dist/icu-message-formatter.min.js.map +0 -1
  18. package/index.d.ts +0 -5
  19. package/lib/icu-message-formatter.cjs.js.map +0 -1
  20. package/lib/icu-message-formatter.es.js.map +0 -1
  21. package/rollup.config.dist.js +0 -36
  22. package/rollup.config.js +0 -35
  23. package/source/IcuMessageFormatter.js +0 -20
  24. package/source/MessageFormatter.js +0 -138
  25. package/source/MessageFormatter.test.js +0 -153
  26. package/source/pluralTypeHandler.js +0 -122
  27. package/source/pluralTypeHandler.test.js +0 -188
  28. package/source/selectTypeHandler.js +0 -46
  29. package/source/selectTypeHandler.test.js +0 -59
  30. package/source/utilities.js +0 -174
  31. package/source/utilities.test.js +0 -123
  32. package/types/IcuMessageFormatter.d.ts +0 -4
  33. package/types/MessageFormatter.d.ts +0 -71
  34. package/types/pluralTypeHandler.d.ts +0 -15
  35. package/types/selectTypeHandler.d.ts +0 -15
  36. package/types/typedefs.d.ts +0 -3
  37. package/types/utilities.d.ts +0 -52
@@ -1 +0,0 @@
1
- {"version":3,"file":"icu-message-formatter.min.js","sources":["../source/utilities.js","../node_modules/@ultraq/array-utils/array-utils.es.js","../source/pluralTypeHandler.js","../source/selectTypeHandler.js","../source/MessageFormatter.js","../node_modules/@ultraq/function-utils/function-utils.es.js"],"sourcesContent":["/* \n * Copyright 2019, Emanuel Rabina (http://www.ultraq.net.nz/)\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @typedef ParseCasesResult\n * @property {string[]} args\n * A list of prepended arguments.\n * @property {Record<string,string>} cases\n * A map of all cases.\n */\n\n/**\n * Most branch-based type handlers are based around \"cases\". For example,\n * `select` and `plural` compare compare a value to \"case keys\" to choose a\n * subtranslation.\n * \n * This util splits \"matches\" portions provided to the aforementioned handlers\n * into case strings, and extracts any prepended arguments (for example,\n * `plural` supports an `offset:n` argument used for populating the magic `#`\n * variable).\n * \n * @param {string} string\n * @return {ParseCasesResult}\n */\nexport function parseCases(string) {\n\tconst isWhitespace = ch => /\\s/.test(ch);\n\n\tconst args = [];\n\tconst cases = {};\n\n\tlet currTermStart = 0;\n\tlet latestTerm = null;\n\tlet inTerm = false;\n\n\tlet i = 0;\n\twhile (i < string.length) {\n\t\t// Term ended\n\t\tif (inTerm && (isWhitespace(string[i]) || string[i] === '{')) {\n\t\t\tinTerm = false;\n\t\t\tlatestTerm = string.slice(currTermStart, i);\n\n\t\t\t// We want to process the opening char again so the case will be properly registered.\n\t\t\tif (string[i] === '{') {\n\t\t\t\ti--;\n\t\t\t}\n\t\t}\n\n\t\t// New term\n\t\telse if (!inTerm && !isWhitespace(string[i])) {\n\t\t\tconst caseBody = string[i] === '{';\n\n\t\t\t// If there's a previous term, we can either handle a whole\n\t\t\t// case, or add that as an argument.\n\t\t\tif (latestTerm && caseBody) {\n\t\t\t\tconst branchEndIndex = findClosingBracket(string, i);\n\n\t\t\t\tif (branchEndIndex === -1) {\n\t\t\t\t\tthrow new Error(`Unbalanced curly braces in string: \"${string}\"`);\n\t\t\t\t}\n\n\t\t\t\tcases[latestTerm] = string.slice(i + 1, branchEndIndex); // Don't include the braces\n\n\t\t\t\ti = branchEndIndex; // Will be moved up where needed at end of loop.\n\t\t\t\tlatestTerm = null;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (latestTerm) {\n\t\t\t\t\targs.push(latestTerm);\n\t\t\t\t\tlatestTerm = null;\n\t\t\t\t}\n\n\t\t\t\tinTerm = true;\n\t\t\t\tcurrTermStart = i;\n\t\t\t}\n\t\t}\n\t\ti++;\n\t}\n\n\tif (inTerm) {\n\t\tlatestTerm = string.slice(currTermStart);\n\t}\n\n\tif (latestTerm) {\n\t\targs.push(latestTerm);\n\t}\n\n\treturn {\n\t\targs,\n\t\tcases\n\t};\n}\n\n/**\n * Finds the index of the matching closing curly bracket, including through\n * strings that could have nested brackets.\n * \n * @param {string} string\n * @param {number} fromIndex\n * @return {number}\n * The index of the matching closing bracket, or -1 if no closing bracket\n * could be found.\n */\nexport function findClosingBracket(string, fromIndex) {\n\tlet depth = 0;\n\tfor (let i = fromIndex + 1; i < string.length; i++) {\n\t\tlet char = string.charAt(i);\n\t\tif (char === '}') {\n\t\t\tif (depth === 0) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t\tdepth--;\n\t\t}\n\t\telse if (char === '{') {\n\t\t\tdepth++;\n\t\t}\n\t}\n\treturn -1;\n}\n\n/**\n * Split a `{key, type, format}` block into those 3 parts, taking into account\n * nested message syntax that can exist in the `format` part.\n * \n * @param {string} block\n * @return {string[]}\n * An array with `key`, `type`, and `format` items in that order, if present\n * in the formatted argument block.\n */\nexport function splitFormattedArgument(block) {\n\treturn split(block.slice(1, -1), ',', 3);\n}\n\n/**\n * Like `String.prototype.split()` but where the limit parameter causes the\n * remainder of the string to be grouped together in a final entry.\n * \n * @private\n * @param {string} string\n * @param {string} separator\n * @param {number} limit\n * @param {string[]} accumulator\n * @return {string[]}\n */\nfunction split(string, separator, limit, accumulator = []) {\n\tif (!string) {\n\t\treturn accumulator;\n\t}\n\tif (limit === 1) {\n\t\taccumulator.push(string);\n\t\treturn accumulator;\n\t}\n\tlet indexOfDelimiter = string.indexOf(separator);\n\tif (indexOfDelimiter === -1) {\n\t\taccumulator.push(string);\n\t\treturn accumulator;\n\t}\n\tlet head = string.substring(0, indexOfDelimiter).trim();\n\tlet tail = string.substring(indexOfDelimiter + separator.length + 1).trim();\n\taccumulator.push(head);\n\treturn split(tail, separator, limit - 1, accumulator);\n}\n","/* \n * Copyright 2017, Emanuel Rabina (http://www.ultraq.net.nz/)\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Flattens an array of arrays of infinite depth into a single-dimension array.\n *\n * > This is now natively in JavaScript as the `flat` method on an Array\n * > instance. [Check MDN for which browsers have access to this feature](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat).\n * > If you can't use `flat`, then this method will do the job 🙂\n *\n * @param {Array<any>} array\n * @return {Array<any>} Flattened array.\n */\nexport function flatten(array) {\n return array.reduce((acc, value) => {\n return acc.concat(Array.isArray(value) ? flatten(value) : value);\n }, []);\n}\n\n/**\n * Creates an array of numbers from the starting value (inclusive) to the end\n * (exclusive), with an optional step (the gap between values).\n *\n * @param {Number} start\n * The value to start at, the first item in the returned array.\n * @param {Number} end\n * The value to end with, the last item in the returned array.\n * @param {Number} [step=1]\n * The increment/gap between values, defaults to 1.\n * @return {number[]} An array encompassing the given range.\n */\nexport function range(start, end) {\n let step = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n return Array.apply(0, Array(Math.ceil((end - start) / step))).map((empty, index) => index * step + start);\n}\n\n/**\n * A function to execute on each item in an array, returning truthy\n * if the item passes whatever test is required for the use of this\n * predicate.\n *\n * @template T\n * @callback Predicate<T>\n * @param {T} item\n * @return {boolean}\n */\n\n/**\n * Remove and return the first item from `array` that matches the predicate\n * function.\n *\n * @template T\n * @param {T[]} array\n * @param {Predicate<T>} predicate\n * Function to test each item of the array with. If it returns a truthy value\n * for the item, then that item is removed and returned.\n * @return {T | undefined} The matching item, or `undefined` if no match was found.\n */\nexport function remove(array, predicate) {\n return array.find((item, index) => {\n if (predicate(item)) {\n array.splice(index, 1);\n return item;\n }\n return false;\n });\n}\n\n//# sourceMappingURL=array-utils.es.js.map","/* \n * Copyright 2019, Emanuel Rabina (http://www.ultraq.net.nz/)\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {parseCases} from './utilities.js';\n\nlet pluralFormatter;\n\nlet keyCounter = 0;\n\n// All the special keywords that can be used in `plural` blocks for the various branches\nconst ONE = 'one';\nconst OTHER = 'other';\n\n/**\n * @private\n * @param {string} caseBody\n * @param {number} value\n * @return {{caseBody: string, numberValues: object}}\n */\nfunction replaceNumberSign(caseBody, value) {\n\tlet i = 0;\n\tlet output = '';\n\tlet numBraces = 0;\n\tconst numberValues = {};\n\n\twhile (i < caseBody.length) {\n\t\tif (caseBody[i] === '#' && !numBraces) {\n\t\t\tlet keyParam = `__hashToken${keyCounter++}`;\n\t\t\toutput += `{${keyParam}, number}`;\n\t\t\tnumberValues[keyParam] = value;\n\t\t}\n\t\telse {\n\t\t\toutput += caseBody[i];\n\t\t}\n\n\t\tif (caseBody[i] === '{') {\n\t\t\tnumBraces++;\n\t\t}\n\t\telse if (caseBody[i] === '}') {\n\t\t\tnumBraces--;\n\t\t}\n\n\t\ti++;\n\t}\n\n\treturn {\n\t\tcaseBody: output,\n\t\tnumberValues\n\t};\n}\n\n/**\n * Handler for `plural` statements within ICU message syntax strings. Returns\n * a formatted string for the branch that closely matches the current value.\n * \n * See https://formatjs.io/docs/core-concepts/icu-syntax#plural-format for more\n * details on how the `plural` statement works.\n *\n * @param {string} value\n * @param {string} matches\n * @param {string} locale\n * @param {Record<string,any>} values\n * @param {(message: string, values?: Record<string,any>) => any[]} process\n * @return {any | any[]}\n */\nexport default function pluralTypeHandler(value, matches = '', locale, values, process) {\n\tconst {args, cases} = parseCases(matches);\n\n\tlet intValue = parseInt(value);\n\n\targs.forEach((arg) => {\n\t\tif (arg.startsWith('offset:')) {\n\t\t\tintValue -= parseInt(arg.slice('offset:'.length));\n\t\t}\n\t});\n\n\tconst keywordPossibilities = [];\n\n\tif ('PluralRules' in Intl) {\n\t\t// Effectively memoize because instantiation of `Int.*` objects is expensive.\n\t\tif (pluralFormatter === undefined || pluralFormatter.resolvedOptions().locale !== locale) {\n\t\t\tpluralFormatter = new Intl.PluralRules(locale);\n\t\t}\n\n\t\tconst pluralKeyword = pluralFormatter.select(intValue);\n\n\t\t// Other is always added last with least priority, so we don't want to add it here.\n\t\tif (pluralKeyword !== OTHER) {\n\t\t\tkeywordPossibilities.push(pluralKeyword);\n\t\t}\n\t}\n\tif (intValue === 1) {\n\t\tkeywordPossibilities.push(ONE);\n\t}\n\tkeywordPossibilities.push(`=${intValue}`, OTHER);\n\n\tfor (let i = 0; i < keywordPossibilities.length; i++) {\n\t\tconst keyword = keywordPossibilities[i];\n\t\tif (keyword in cases) {\n\t\t\tconst {caseBody, numberValues} = replaceNumberSign(cases[keyword], intValue);\n\t\t\treturn process(caseBody, {\n\t\t\t\t...values,\n\t\t\t\t...numberValues\n\t\t\t});\n\t\t}\n\t}\n\n\treturn value;\n}\n","/* \n * Copyright 2019, Emanuel Rabina (http://www.ultraq.net.nz/)\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {parseCases} from './utilities.js';\n\nconst OTHER = 'other';\n\n/**\n * Handler for `select` statements within ICU message syntax strings. Returns\n * a formatted string for the branch that closely matches the current value.\n * \n * See https://formatjs.io/docs/core-concepts/icu-syntax#select-format for more\n * details on how the `select` statement works.\n * \n * @param {string} value\n * @param {string} matches\n * @param {string} locale\n * @param {Record<string,any>} values\n * @param {(message: string, values?: Record<string,any>) => any[]} process\n * @return {any | any[]}\n */\nexport default function selectTypeHandler(value, matches = '', locale, values, process) {\n\tconst {cases} = parseCases(matches);\n\n\tif (value in cases) {\n\t\treturn process(cases[value], values);\n\t}\n\telse if (OTHER in cases) {\n\t\treturn process(cases[OTHER], values);\n\t}\n\n\treturn value;\n}\n","/* \n * Copyright 2019, Emanuel Rabina (http://www.ultraq.net.nz/)\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {findClosingBracket, splitFormattedArgument} from './utilities.js';\n\nimport {flatten} from '@ultraq/array-utils';\nimport {memoize} from '@ultraq/function-utils';\n\n/**\n * @typedef {Record<string,any>} FormatValues\n */\n\n/**\n * @callback ProcessFunction\n * @param {string} message\n * @param {FormatValues} [values={}]\n * @return {any[]}\n */\n\n/**\n * @callback TypeHandler\n * @param {any} value\n * The object which matched the key of the block being processed.\n * @param {string} matches\n * Any format options associated with the block being processed.\n * @param {string} locale\n * The locale to use for formatting.\n * @param {FormatValues} values\n * The object of placeholder data given to the original `format`/`process`\n * call.\n * @param {ProcessFunction} process\n * The `process` function itself so that sub-messages can be processed by type\n * handlers.\n * @return {any | any[]}\n */\n\n/**\n * The main class for formatting messages.\n * \n * @author Emanuel Rabina\n */\nexport default class MessageFormatter {\n\n\t/**\n\t * Creates a new formatter that can work using any of the custom type handlers\n\t * you register.\n\t * \n\t * @param {string} locale\n\t * @param {Record<string,TypeHandler>} [typeHandlers]\n\t * Optional object where the keys are the names of the types to register,\n\t * their values being the functions that will return a nicely formatted\n\t * string for the data and locale they are given.\n\t */\n\tconstructor(locale, typeHandlers = {}) {\n\n\t\tthis.locale = locale;\n\t\tthis.typeHandlers = typeHandlers;\n\t}\n\n\t/**\n\t * Formats an ICU message syntax string using `values` for placeholder data\n\t * and any currently-registered type handlers.\n\t * \n\t * @type {(message: string, values?: FormatValues) => string}\n\t */\n\tformat = memoize((message, values = {}) => {\n\n\t\treturn flatten(this.process(message, values)).join('');\n\t});\n\n\t/**\n\t * Process an ICU message syntax string using `values` for placeholder data\n\t * and any currently-registered type handlers. The result of this method is\n\t * an array of the component parts after they have been processed in turn by\n\t * their own type handlers. This raw output is useful for other renderers,\n\t * eg: React where components can be used instead of being forced to return\n\t * raw strings.\n\t * \n\t * This method is used by {@link MessageFormatter#format} where it acts as a\n\t * string renderer.\n\t * \n\t * @param {string} message\n\t * @param {FormatValues} [values]\n\t * @return {any[]}\n\t */\n\tprocess(message, values = {}) {\n\n\t\tif (!message) {\n\t\t\treturn [];\n\t\t}\n\n\t\tlet blockStartIndex = message.indexOf('{');\n\t\tif (blockStartIndex !== -1) {\n\t\t\tlet blockEndIndex = findClosingBracket(message, blockStartIndex);\n\t\t\tif (blockEndIndex !== -1) {\n\t\t\t\tlet block = message.substring(blockStartIndex, blockEndIndex + 1);\n\t\t\t\tif (block) {\n\t\t\t\t\tlet result = [];\n\t\t\t\t\tlet head = message.substring(0, blockStartIndex);\n\t\t\t\t\tif (head) {\n\t\t\t\t\t\tresult.push(head);\n\t\t\t\t\t}\n\t\t\t\t\tlet [key, type, format] = splitFormattedArgument(block);\n\t\t\t\t\tlet body = values[key];\n\t\t\t\t\tif (body === null || body === undefined) {\n\t\t\t\t\t\tbody = '';\n\t\t\t\t\t}\n\t\t\t\t\tlet typeHandler = type && this.typeHandlers[type];\n\t\t\t\t\tresult.push(typeHandler ?\n\t\t\t\t\t\ttypeHandler(body, format, this.locale, values, this.process.bind(this)) :\n\t\t\t\t\t\tbody);\n\t\t\t\t\tlet tail = message.substring(blockEndIndex + 1);\n\t\t\t\t\tif (tail) {\n\t\t\t\t\t\tresult.push(this.process(tail, values));\n\t\t\t\t\t}\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new Error(`Unbalanced curly braces in string: \"${message}\"`);\n\t\t\t}\n\t\t}\n\t\treturn [message];\n\t}\n}\n","/**\n * A higher-order function to apply [memoization](https://en.wikipedia.org/wiki/Memoization).\n * \n * If memoizing a recursive function, then memoize and define the function at\n * the same time so you can make a call to the memoized function, eg:\n * \n * ```javascript\n * const myFunction = memoize(() => myFunction());\n * ```\n * \n * @param {Function} func\n * @return {Function} \n */\nexport function memoize(func) {\n var cache = {};\n return function () {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n var key = args.length ? args.map(function (arg) {\n return arg === null ? 'null' : arg === undefined ? 'undefined' : typeof arg === 'function' ? arg.toString() : arg instanceof Date ? arg.toISOString() : JSON.stringify(arg);\n }).join('|') : '_(no-args)_';\n if (Object.prototype.hasOwnProperty.call(cache, key)) {\n return cache[key];\n }\n var result = func.apply(void 0, args);\n cache[key] = result;\n return result;\n };\n}\n\n//# sourceMappingURL=function-utils.es.js.map"],"names":["parseCases","string","isWhitespace","ch","test","args","cases","currTermStart","latestTerm","inTerm","i","length","slice","caseBody","branchEndIndex","findClosingBracket","Error","push","fromIndex","depth","char","charAt","splitFormattedArgument","block","split","separator","limit","accumulator","arguments","undefined","indexOfDelimiter","indexOf","head","substring","trim","tail","flatten","array","reduce","acc","value","concat","Array","isArray","pluralFormatter","keyCounter","OTHER","replaceNumberSign","output","numBraces","numberValues","keyParam","constructor","locale","_this","this","typeHandlers","func","cache","_defineProperty","memoize","message","values","process","join","_len","_key","key","map","arg","toString","Date","toISOString","JSON","stringify","Object","prototype","hasOwnProperty","call","result","apply","blockStartIndex","blockEndIndex","type","format","body","typeHandler","bind","matches","intValue","parseInt","forEach","startsWith","keywordPossibilities","Intl","resolvedOptions","PluralRules","pluralKeyword","select","keyword"],"mappings":"yfAqCO,SAASA,EAAWC,GAC1B,MAAMC,EAAeC,GAAM,KAAKC,KAAKD,GAE/BE,EAAO,GACPC,EAAQ,CAAA,EAEd,IAAIC,EAAgB,EAChBC,EAAa,KACbC,GAAS,EAETC,EAAI,EACR,KAAOA,EAAIT,EAAOU,QAAQ,CAEzB,GAAIF,IAAWP,EAAaD,EAAOS,KAAqB,MAAdT,EAAOS,IAChDD,GAAS,EACTD,EAAaP,EAAOW,MAAML,EAAeG,GAGvB,MAAdT,EAAOS,IACVA,SAKG,IAAKD,IAAWP,EAAaD,EAAOS,IAAK,CAC7C,MAAMG,EAAyB,MAAdZ,EAAOS,GAIxB,GAAIF,GAAcK,EAAU,CAC3B,MAAMC,EAAiBC,EAAmBd,EAAQS,GAElD,IAAwB,IAApBI,EAC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2
- export * from './types/MessageFormatter';
3
- export * from './types/pluralTypeHandler';
4
- export * from './types/selectTypeHandler';
5
- export * from './types/utilities';
@@ -1 +0,0 @@
1
- {"version":3,"file":"icu-message-formatter.cjs.js","sources":["../source/utilities.js","../source/MessageFormatter.js","../source/pluralTypeHandler.js","../source/selectTypeHandler.js"],"sourcesContent":["/* \n * Copyright 2019, Emanuel Rabina (http://www.ultraq.net.nz/)\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @typedef ParseCasesResult\n * @property {string[]} args\n * A list of prepended arguments.\n * @property {Record<string,string>} cases\n * A map of all cases.\n */\n\n/**\n * Most branch-based type handlers are based around \"cases\". For example,\n * `select` and `plural` compare compare a value to \"case keys\" to choose a\n * subtranslation.\n * \n * This util splits \"matches\" portions provided to the aforementioned handlers\n * into case strings, and extracts any prepended arguments (for example,\n * `plural` supports an `offset:n` argument used for populating the magic `#`\n * variable).\n * \n * @param {string} string\n * @return {ParseCasesResult}\n */\nexport function parseCases(string) {\n\tconst isWhitespace = ch => /\\s/.test(ch);\n\n\tconst args = [];\n\tconst cases = {};\n\n\tlet currTermStart = 0;\n\tlet latestTerm = null;\n\tlet inTerm = false;\n\n\tlet i = 0;\n\twhile (i < string.length) {\n\t\t// Term ended\n\t\tif (inTerm && (isWhitespace(string[i]) || string[i] === '{')) {\n\t\t\tinTerm = false;\n\t\t\tlatestTerm = string.slice(currTermStart, i);\n\n\t\t\t// We want to process the opening char again so the case will be properly registered.\n\t\t\tif (string[i] === '{') {\n\t\t\t\ti--;\n\t\t\t}\n\t\t}\n\n\t\t// New term\n\t\telse if (!inTerm && !isWhitespace(string[i])) {\n\t\t\tconst caseBody = string[i] === '{';\n\n\t\t\t// If there's a previous term, we can either handle a whole\n\t\t\t// case, or add that as an argument.\n\t\t\tif (latestTerm && caseBody) {\n\t\t\t\tconst branchEndIndex = findClosingBracket(string, i);\n\n\t\t\t\tif (branchEndIndex === -1) {\n\t\t\t\t\tthrow new Error(`Unbalanced curly braces in string: \"${string}\"`);\n\t\t\t\t}\n\n\t\t\t\tcases[latestTerm] = string.slice(i + 1, branchEndIndex); // Don't include the braces\n\n\t\t\t\ti = branchEndIndex; // Will be moved up where needed at end of loop.\n\t\t\t\tlatestTerm = null;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (latestTerm) {\n\t\t\t\t\targs.push(latestTerm);\n\t\t\t\t\tlatestTerm = null;\n\t\t\t\t}\n\n\t\t\t\tinTerm = true;\n\t\t\t\tcurrTermStart = i;\n\t\t\t}\n\t\t}\n\t\ti++;\n\t}\n\n\tif (inTerm) {\n\t\tlatestTerm = string.slice(currTermStart);\n\t}\n\n\tif (latestTerm) {\n\t\targs.push(latestTerm);\n\t}\n\n\treturn {\n\t\targs,\n\t\tcases\n\t};\n}\n\n/**\n * Finds the index of the matching closing curly bracket, including through\n * strings that could have nested brackets.\n * \n * @param {string} string\n * @param {number} fromIndex\n * @return {number}\n * The index of the matching closing bracket, or -1 if no closing bracket\n * could be found.\n */\nexport function findClosingBracket(string, fromIndex) {\n\tlet depth = 0;\n\tfor (let i = fromIndex + 1; i < string.length; i++) {\n\t\tlet char = string.charAt(i);\n\t\tif (char === '}') {\n\t\t\tif (depth === 0) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t\tdepth--;\n\t\t}\n\t\telse if (char === '{') {\n\t\t\tdepth++;\n\t\t}\n\t}\n\treturn -1;\n}\n\n/**\n * Split a `{key, type, format}` block into those 3 parts, taking into account\n * nested message syntax that can exist in the `format` part.\n * \n * @param {string} block\n * @return {string[]}\n * An array with `key`, `type`, and `format` items in that order, if present\n * in the formatted argument block.\n */\nexport function splitFormattedArgument(block) {\n\treturn split(block.slice(1, -1), ',', 3);\n}\n\n/**\n * Like `String.prototype.split()` but where the limit parameter causes the\n * remainder of the string to be grouped together in a final entry.\n * \n * @private\n * @param {string} string\n * @param {string} separator\n * @param {number} limit\n * @param {string[]} accumulator\n * @return {string[]}\n */\nfunction split(string, separator, limit, accumulator = []) {\n\tif (!string) {\n\t\treturn accumulator;\n\t}\n\tif (limit === 1) {\n\t\taccumulator.push(string);\n\t\treturn accumulator;\n\t}\n\tlet indexOfDelimiter = string.indexOf(separator);\n\tif (indexOfDelimiter === -1) {\n\t\taccumulator.push(string);\n\t\treturn accumulator;\n\t}\n\tlet head = string.substring(0, indexOfDelimiter).trim();\n\tlet tail = string.substring(indexOfDelimiter + separator.length + 1).trim();\n\taccumulator.push(head);\n\treturn split(tail, separator, limit - 1, accumulator);\n}\n","/* \n * Copyright 2019, Emanuel Rabina (http://www.ultraq.net.nz/)\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {findClosingBracket, splitFormattedArgument} from './utilities.js';\n\nimport {flatten} from '@ultraq/array-utils';\nimport {memoize} from '@ultraq/function-utils';\n\n/**\n * @typedef {Record<string,any>} FormatValues\n */\n\n/**\n * @callback ProcessFunction\n * @param {string} message\n * @param {FormatValues} [values={}]\n * @return {any[]}\n */\n\n/**\n * @callback TypeHandler\n * @param {any} value\n * The object which matched the key of the block being processed.\n * @param {string} matches\n * Any format options associated with the block being processed.\n * @param {string} locale\n * The locale to use for formatting.\n * @param {FormatValues} values\n * The object of placeholder data given to the original `format`/`process`\n * call.\n * @param {ProcessFunction} process\n * The `process` function itself so that sub-messages can be processed by type\n * handlers.\n * @return {any | any[]}\n */\n\n/**\n * The main class for formatting messages.\n * \n * @author Emanuel Rabina\n */\nexport default class MessageFormatter {\n\n\t/**\n\t * Creates a new formatter that can work using any of the custom type handlers\n\t * you register.\n\t * \n\t * @param {string} locale\n\t * @param {Record<string,TypeHandler>} [typeHandlers]\n\t * Optional object where the keys are the names of the types to register,\n\t * their values being the functions that will return a nicely formatted\n\t * string for the data and locale they are given.\n\t */\n\tconstructor(locale, typeHandlers = {}) {\n\n\t\tthis.locale = locale;\n\t\tthis.typeHandlers = typeHandlers;\n\t}\n\n\t/**\n\t * Formats an ICU message syntax string using `values` for placeholder data\n\t * and any currently-registered type handlers.\n\t * \n\t * @type {(message: string, values?: FormatValues) => string}\n\t */\n\tformat = memoize((message, values = {}) => {\n\n\t\treturn flatten(this.process(message, values)).join('');\n\t});\n\n\t/**\n\t * Process an ICU message syntax string using `values` for placeholder data\n\t * and any currently-registered type handlers. The result of this method is\n\t * an array of the component parts after they have been processed in turn by\n\t * their own type handlers. This raw output is useful for other renderers,\n\t * eg: React where components can be used instead of being forced to return\n\t * raw strings.\n\t * \n\t * This method is used by {@link MessageFormatter#format} where it acts as a\n\t * string renderer.\n\t * \n\t * @param {string} message\n\t * @param {FormatValues} [values]\n\t * @return {any[]}\n\t */\n\tprocess(message, values = {}) {\n\n\t\tif (!message) {\n\t\t\treturn [];\n\t\t}\n\n\t\tlet blockStartIndex = message.indexOf('{');\n\t\tif (blockStartIndex !== -1) {\n\t\t\tlet blockEndIndex = findClosingBracket(message, blockStartIndex);\n\t\t\tif (blockEndIndex !== -1) {\n\t\t\t\tlet block = message.substring(blockStartIndex, blockEndIndex + 1);\n\t\t\t\tif (block) {\n\t\t\t\t\tlet result = [];\n\t\t\t\t\tlet head = message.substring(0, blockStartIndex);\n\t\t\t\t\tif (head) {\n\t\t\t\t\t\tresult.push(head);\n\t\t\t\t\t}\n\t\t\t\t\tlet [key, type, format] = splitFormattedArgument(block);\n\t\t\t\t\tlet body = values[key];\n\t\t\t\t\tif (body === null || body === undefined) {\n\t\t\t\t\t\tbody = '';\n\t\t\t\t\t}\n\t\t\t\t\tlet typeHandler = type && this.typeHandlers[type];\n\t\t\t\t\tresult.push(typeHandler ?\n\t\t\t\t\t\ttypeHandler(body, format, this.locale, values, this.process.bind(this)) :\n\t\t\t\t\t\tbody);\n\t\t\t\t\tlet tail = message.substring(blockEndIndex + 1);\n\t\t\t\t\tif (tail) {\n\t\t\t\t\t\tresult.push(this.process(tail, values));\n\t\t\t\t\t}\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new Error(`Unbalanced curly braces in string: \"${message}\"`);\n\t\t\t}\n\t\t}\n\t\treturn [message];\n\t}\n}\n","/* \n * Copyright 2019, Emanuel Rabina (http://www.ultraq.net.nz/)\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {parseCases} from './utilities.js';\n\nlet pluralFormatter;\n\nlet keyCounter = 0;\n\n// All the special keywords that can be used in `plural` blocks for the various branches\nconst ONE = 'one';\nconst OTHER = 'other';\n\n/**\n * @private\n * @param {string} caseBody\n * @param {number} value\n * @return {{caseBody: string, numberValues: object}}\n */\nfunction replaceNumberSign(caseBody, value) {\n\tlet i = 0;\n\tlet output = '';\n\tlet numBraces = 0;\n\tconst numberValues = {};\n\n\twhile (i < caseBody.length) {\n\t\tif (caseBody[i] === '#' && !numBraces) {\n\t\t\tlet keyParam = `__hashToken${keyCounter++}`;\n\t\t\toutput += `{${keyParam}, number}`;\n\t\t\tnumberValues[keyParam] = value;\n\t\t}\n\t\telse {\n\t\t\toutput += caseBody[i];\n\t\t}\n\n\t\tif (caseBody[i] === '{') {\n\t\t\tnumBraces++;\n\t\t}\n\t\telse if (caseBody[i] === '}') {\n\t\t\tnumBraces--;\n\t\t}\n\n\t\ti++;\n\t}\n\n\treturn {\n\t\tcaseBody: output,\n\t\tnumberValues\n\t};\n}\n\n/**\n * Handler for `plural` statements within ICU message syntax strings. Returns\n * a formatted string for the branch that closely matches the current value.\n * \n * See https://formatjs.io/docs/core-concepts/icu-syntax#plural-format for more\n * details on how the `plural` statement works.\n *\n * @param {string} value\n * @param {string} matches\n * @param {string} locale\n * @param {Record<string,any>} values\n * @param {(message: string, values?: Record<string,any>) => any[]} process\n * @return {any | any[]}\n */\nexport default function pluralTypeHandler(value, matches = '', locale, values, process) {\n\tconst {args, cases} = parseCases(matches);\n\n\tlet intValue = parseInt(value);\n\n\targs.forEach((arg) => {\n\t\tif (arg.startsWith('offset:')) {\n\t\t\tintValue -= parseInt(arg.slice('offset:'.length));\n\t\t}\n\t});\n\n\tconst keywordPossibilities = [];\n\n\tif ('PluralRules' in Intl) {\n\t\t// Effectively memoize because instantiation of `Int.*` objects is expensive.\n\t\tif (pluralFormatter === undefined || pluralFormatter.resolvedOptions().locale !== locale) {\n\t\t\tpluralFormatter = new Intl.PluralRules(locale);\n\t\t}\n\n\t\tconst pluralKeyword = pluralFormatter.select(intValue);\n\n\t\t// Other is always added last with least priority, so we don't want to add it here.\n\t\tif (pluralKeyword !== OTHER) {\n\t\t\tkeywordPossibilities.push(pluralKeyword);\n\t\t}\n\t}\n\tif (intValue === 1) {\n\t\tkeywordPossibilities.push(ONE);\n\t}\n\tkeywordPossibilities.push(`=${intValue}`, OTHER);\n\n\tfor (let i = 0; i < keywordPossibilities.length; i++) {\n\t\tconst keyword = keywordPossibilities[i];\n\t\tif (keyword in cases) {\n\t\t\tconst {caseBody, numberValues} = replaceNumberSign(cases[keyword], intValue);\n\t\t\treturn process(caseBody, {\n\t\t\t\t...values,\n\t\t\t\t...numberValues\n\t\t\t});\n\t\t}\n\t}\n\n\treturn value;\n}\n","/* \n * Copyright 2019, Emanuel Rabina (http://www.ultraq.net.nz/)\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {parseCases} from './utilities.js';\n\nconst OTHER = 'other';\n\n/**\n * Handler for `select` statements within ICU message syntax strings. Returns\n * a formatted string for the branch that closely matches the current value.\n * \n * See https://formatjs.io/docs/core-concepts/icu-syntax#select-format for more\n * details on how the `select` statement works.\n * \n * @param {string} value\n * @param {string} matches\n * @param {string} locale\n * @param {Record<string,any>} values\n * @param {(message: string, values?: Record<string,any>) => any[]} process\n * @return {any | any[]}\n */\nexport default function selectTypeHandler(value, matches = '', locale, values, process) {\n\tconst {cases} = parseCases(matches);\n\n\tif (value in cases) {\n\t\treturn process(cases[value], values);\n\t}\n\telse if (OTHER in cases) {\n\t\treturn process(cases[OTHER], values);\n\t}\n\n\treturn value;\n}\n"],"names":["parseCases","string","isWhitespace","ch","test","args","cases","currTermStart","latestTerm","inTerm","i","length","slice","caseBody","branchEndIndex","findClosingBracket","Error","push","fromIndex","depth","char","charAt","splitFormattedArgument","block","split","separator","limit","accumulator","arguments","undefined","indexOfDelimiter","indexOf","head","substring","trim","tail","MessageFormatter","constructor","locale","_this","typeHandlers","_defineProperty","memoize","message","values","flatten","process","join","blockStartIndex","blockEndIndex","result","key","type","format","body","typeHandler","bind","pluralFormatter","keyCounter","ONE","OTHER","replaceNumberSign","value","output","numBraces","numberValues","keyParam","pluralTypeHandler","matches","intValue","parseInt","forEach","arg","startsWith","keywordPossibilities","Intl","resolvedOptions","PluralRules","pluralKeyword","select","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AAlB,SAAA,CAAAjB,MAAA,GAAAiB,CAAAA,GAAAA,SAAA,MAAAC,SAAA,CAAA;EACrF,MAAM;AAACvB,IAAAA,KAAAA;AAAK,GAAC,GAAGN,UAAU,CAACoE,OAAO,CAAC,CAAA;EAEnC,IAAIN,KAAK,IAAIxD,KAAK,EAAE;IACnB,OAAOwC,OAAO,CAACxC,KAAK,CAACwD,KAAK,CAAC,EAAElB,MAAM,CAAC,CAAA;AACrC,GAAC,MACI,IAAIgB,KAAK,IAAItD,KAAK,EAAE;IACxB,OAAOwC,OAAO,CAACxC,KAAK,CAACsD,KAAK,CAAC,EAAEhB,MAAM,CAAC,CAAA;AACrC,GAAA;AAEA,EAAA,OAAOkB,KAAK,CAAA;AACb;;;;;;;;;"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"icu-message-formatter.es.js","sources":["../source/utilities.js","../source/MessageFormatter.js","../source/pluralTypeHandler.js","../source/selectTypeHandler.js"],"sourcesContent":["/* \n * Copyright 2019, Emanuel Rabina (http://www.ultraq.net.nz/)\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @typedef ParseCasesResult\n * @property {string[]} args\n * A list of prepended arguments.\n * @property {Record<string,string>} cases\n * A map of all cases.\n */\n\n/**\n * Most branch-based type handlers are based around \"cases\". For example,\n * `select` and `plural` compare compare a value to \"case keys\" to choose a\n * subtranslation.\n * \n * This util splits \"matches\" portions provided to the aforementioned handlers\n * into case strings, and extracts any prepended arguments (for example,\n * `plural` supports an `offset:n` argument used for populating the magic `#`\n * variable).\n * \n * @param {string} string\n * @return {ParseCasesResult}\n */\nexport function parseCases(string) {\n\tconst isWhitespace = ch => /\\s/.test(ch);\n\n\tconst args = [];\n\tconst cases = {};\n\n\tlet currTermStart = 0;\n\tlet latestTerm = null;\n\tlet inTerm = false;\n\n\tlet i = 0;\n\twhile (i < string.length) {\n\t\t// Term ended\n\t\tif (inTerm && (isWhitespace(string[i]) || string[i] === '{')) {\n\t\t\tinTerm = false;\n\t\t\tlatestTerm = string.slice(currTermStart, i);\n\n\t\t\t// We want to process the opening char again so the case will be properly registered.\n\t\t\tif (string[i] === '{') {\n\t\t\t\ti--;\n\t\t\t}\n\t\t}\n\n\t\t// New term\n\t\telse if (!inTerm && !isWhitespace(string[i])) {\n\t\t\tconst caseBody = string[i] === '{';\n\n\t\t\t// If there's a previous term, we can either handle a whole\n\t\t\t// case, or add that as an argument.\n\t\t\tif (latestTerm && caseBody) {\n\t\t\t\tconst branchEndIndex = findClosingBracket(string, i);\n\n\t\t\t\tif (branchEndIndex === -1) {\n\t\t\t\t\tthrow new Error(`Unbalanced curly braces in string: \"${string}\"`);\n\t\t\t\t}\n\n\t\t\t\tcases[latestTerm] = string.slice(i + 1, branchEndIndex); // Don't include the braces\n\n\t\t\t\ti = branchEndIndex; // Will be moved up where needed at end of loop.\n\t\t\t\tlatestTerm = null;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (latestTerm) {\n\t\t\t\t\targs.push(latestTerm);\n\t\t\t\t\tlatestTerm = null;\n\t\t\t\t}\n\n\t\t\t\tinTerm = true;\n\t\t\t\tcurrTermStart = i;\n\t\t\t}\n\t\t}\n\t\ti++;\n\t}\n\n\tif (inTerm) {\n\t\tlatestTerm = string.slice(currTermStart);\n\t}\n\n\tif (latestTerm) {\n\t\targs.push(latestTerm);\n\t}\n\n\treturn {\n\t\targs,\n\t\tcases\n\t};\n}\n\n/**\n * Finds the index of the matching closing curly bracket, including through\n * strings that could have nested brackets.\n * \n * @param {string} string\n * @param {number} fromIndex\n * @return {number}\n * The index of the matching closing bracket, or -1 if no closing bracket\n * could be found.\n */\nexport function findClosingBracket(string, fromIndex) {\n\tlet depth = 0;\n\tfor (let i = fromIndex + 1; i < string.length; i++) {\n\t\tlet char = string.charAt(i);\n\t\tif (char === '}') {\n\t\t\tif (depth === 0) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t\tdepth--;\n\t\t}\n\t\telse if (char === '{') {\n\t\t\tdepth++;\n\t\t}\n\t}\n\treturn -1;\n}\n\n/**\n * Split a `{key, type, format}` block into those 3 parts, taking into account\n * nested message syntax that can exist in the `format` part.\n * \n * @param {string} block\n * @return {string[]}\n * An array with `key`, `type`, and `format` items in that order, if present\n * in the formatted argument block.\n */\nexport function splitFormattedArgument(block) {\n\treturn split(block.slice(1, -1), ',', 3);\n}\n\n/**\n * Like `String.prototype.split()` but where the limit parameter causes the\n * remainder of the string to be grouped together in a final entry.\n * \n * @private\n * @param {string} string\n * @param {string} separator\n * @param {number} limit\n * @param {string[]} accumulator\n * @return {string[]}\n */\nfunction split(string, separator, limit, accumulator = []) {\n\tif (!string) {\n\t\treturn accumulator;\n\t}\n\tif (limit === 1) {\n\t\taccumulator.push(string);\n\t\treturn accumulator;\n\t}\n\tlet indexOfDelimiter = string.indexOf(separator);\n\tif (indexOfDelimiter === -1) {\n\t\taccumulator.push(string);\n\t\treturn accumulator;\n\t}\n\tlet head = string.substring(0, indexOfDelimiter).trim();\n\tlet tail = string.substring(indexOfDelimiter + separator.length + 1).trim();\n\taccumulator.push(head);\n\treturn split(tail, separator, limit - 1, accumulator);\n}\n","/* \n * Copyright 2019, Emanuel Rabina (http://www.ultraq.net.nz/)\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {findClosingBracket, splitFormattedArgument} from './utilities.js';\n\nimport {flatten} from '@ultraq/array-utils';\nimport {memoize} from '@ultraq/function-utils';\n\n/**\n * @typedef {Record<string,any>} FormatValues\n */\n\n/**\n * @callback ProcessFunction\n * @param {string} message\n * @param {FormatValues} [values={}]\n * @return {any[]}\n */\n\n/**\n * @callback TypeHandler\n * @param {any} value\n * The object which matched the key of the block being processed.\n * @param {string} matches\n * Any format options associated with the block being processed.\n * @param {string} locale\n * The locale to use for formatting.\n * @param {FormatValues} values\n * The object of placeholder data given to the original `format`/`process`\n * call.\n * @param {ProcessFunction} process\n * The `process` function itself so that sub-messages can be processed by type\n * handlers.\n * @return {any | any[]}\n */\n\n/**\n * The main class for formatting messages.\n * \n * @author Emanuel Rabina\n */\nexport default class MessageFormatter {\n\n\t/**\n\t * Creates a new formatter that can work using any of the custom type handlers\n\t * you register.\n\t * \n\t * @param {string} locale\n\t * @param {Record<string,TypeHandler>} [typeHandlers]\n\t * Optional object where the keys are the names of the types to register,\n\t * their values being the functions that will return a nicely formatted\n\t * string for the data and locale they are given.\n\t */\n\tconstructor(locale, typeHandlers = {}) {\n\n\t\tthis.locale = locale;\n\t\tthis.typeHandlers = typeHandlers;\n\t}\n\n\t/**\n\t * Formats an ICU message syntax string using `values` for placeholder data\n\t * and any currently-registered type handlers.\n\t * \n\t * @type {(message: string, values?: FormatValues) => string}\n\t */\n\tformat = memoize((message, values = {}) => {\n\n\t\treturn flatten(this.process(message, values)).join('');\n\t});\n\n\t/**\n\t * Process an ICU message syntax string using `values` for placeholder data\n\t * and any currently-registered type handlers. The result of this method is\n\t * an array of the component parts after they have been processed in turn by\n\t * their own type handlers. This raw output is useful for other renderers,\n\t * eg: React where components can be used instead of being forced to return\n\t * raw strings.\n\t * \n\t * This method is used by {@link MessageFormatter#format} where it acts as a\n\t * string renderer.\n\t * \n\t * @param {string} message\n\t * @param {FormatValues} [values]\n\t * @return {any[]}\n\t */\n\tprocess(message, values = {}) {\n\n\t\tif (!message) {\n\t\t\treturn [];\n\t\t}\n\n\t\tlet blockStartIndex = message.indexOf('{');\n\t\tif (blockStartIndex !== -1) {\n\t\t\tlet blockEndIndex = findClosingBracket(message, blockStartIndex);\n\t\t\tif (blockEndIndex !== -1) {\n\t\t\t\tlet block = message.substring(blockStartIndex, blockEndIndex + 1);\n\t\t\t\tif (block) {\n\t\t\t\t\tlet result = [];\n\t\t\t\t\tlet head = message.substring(0, blockStartIndex);\n\t\t\t\t\tif (head) {\n\t\t\t\t\t\tresult.push(head);\n\t\t\t\t\t}\n\t\t\t\t\tlet [key, type, format] = splitFormattedArgument(block);\n\t\t\t\t\tlet body = values[key];\n\t\t\t\t\tif (body === null || body === undefined) {\n\t\t\t\t\t\tbody = '';\n\t\t\t\t\t}\n\t\t\t\t\tlet typeHandler = type && this.typeHandlers[type];\n\t\t\t\t\tresult.push(typeHandler ?\n\t\t\t\t\t\ttypeHandler(body, format, this.locale, values, this.process.bind(this)) :\n\t\t\t\t\t\tbody);\n\t\t\t\t\tlet tail = message.substring(blockEndIndex + 1);\n\t\t\t\t\tif (tail) {\n\t\t\t\t\t\tresult.push(this.process(tail, values));\n\t\t\t\t\t}\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new Error(`Unbalanced curly braces in string: \"${message}\"`);\n\t\t\t}\n\t\t}\n\t\treturn [message];\n\t}\n}\n","/* \n * Copyright 2019, Emanuel Rabina (http://www.ultraq.net.nz/)\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {parseCases} from './utilities.js';\n\nlet pluralFormatter;\n\nlet keyCounter = 0;\n\n// All the special keywords that can be used in `plural` blocks for the various branches\nconst ONE = 'one';\nconst OTHER = 'other';\n\n/**\n * @private\n * @param {string} caseBody\n * @param {number} value\n * @return {{caseBody: string, numberValues: object}}\n */\nfunction replaceNumberSign(caseBody, value) {\n\tlet i = 0;\n\tlet output = '';\n\tlet numBraces = 0;\n\tconst numberValues = {};\n\n\twhile (i < caseBody.length) {\n\t\tif (caseBody[i] === '#' && !numBraces) {\n\t\t\tlet keyParam = `__hashToken${keyCounter++}`;\n\t\t\toutput += `{${keyParam}, number}`;\n\t\t\tnumberValues[keyParam] = value;\n\t\t}\n\t\telse {\n\t\t\toutput += caseBody[i];\n\t\t}\n\n\t\tif (caseBody[i] === '{') {\n\t\t\tnumBraces++;\n\t\t}\n\t\telse if (caseBody[i] === '}') {\n\t\t\tnumBraces--;\n\t\t}\n\n\t\ti++;\n\t}\n\n\treturn {\n\t\tcaseBody: output,\n\t\tnumberValues\n\t};\n}\n\n/**\n * Handler for `plural` statements within ICU message syntax strings. Returns\n * a formatted string for the branch that closely matches the current value.\n * \n * See https://formatjs.io/docs/core-concepts/icu-syntax#plural-format for more\n * details on how the `plural` statement works.\n *\n * @param {string} value\n * @param {string} matches\n * @param {string} locale\n * @param {Record<string,any>} values\n * @param {(message: string, values?: Record<string,any>) => any[]} process\n * @return {any | any[]}\n */\nexport default function pluralTypeHandler(value, matches = '', locale, values, process) {\n\tconst {args, cases} = parseCases(matches);\n\n\tlet intValue = parseInt(value);\n\n\targs.forEach((arg) => {\n\t\tif (arg.startsWith('offset:')) {\n\t\t\tintValue -= parseInt(arg.slice('offset:'.length));\n\t\t}\n\t});\n\n\tconst keywordPossibilities = [];\n\n\tif ('PluralRules' in Intl) {\n\t\t// Effectively memoize because instantiation of `Int.*` objects is expensive.\n\t\tif (pluralFormatter === undefined || pluralFormatter.resolvedOptions().locale !== locale) {\n\t\t\tpluralFormatter = new Intl.PluralRules(locale);\n\t\t}\n\n\t\tconst pluralKeyword = pluralFormatter.select(intValue);\n\n\t\t// Other is always added last with least priority, so we don't want to add it here.\n\t\tif (pluralKeyword !== OTHER) {\n\t\t\tkeywordPossibilities.push(pluralKeyword);\n\t\t}\n\t}\n\tif (intValue === 1) {\n\t\tkeywordPossibilities.push(ONE);\n\t}\n\tkeywordPossibilities.push(`=${intValue}`, OTHER);\n\n\tfor (let i = 0; i < keywordPossibilities.length; i++) {\n\t\tconst keyword = keywordPossibilities[i];\n\t\tif (keyword in cases) {\n\t\t\tconst {caseBody, numberValues} = replaceNumberSign(cases[keyword], intValue);\n\t\t\treturn process(caseBody, {\n\t\t\t\t...values,\n\t\t\t\t...numberValues\n\t\t\t});\n\t\t}\n\t}\n\n\treturn value;\n}\n","/* \n * Copyright 2019, Emanuel Rabina (http://www.ultraq.net.nz/)\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {parseCases} from './utilities.js';\n\nconst OTHER = 'other';\n\n/**\n * Handler for `select` statements within ICU message syntax strings. Returns\n * a formatted string for the branch that closely matches the current value.\n * \n * See https://formatjs.io/docs/core-concepts/icu-syntax#select-format for more\n * details on how the `select` statement works.\n * \n * @param {string} value\n * @param {string} matches\n * @param {string} locale\n * @param {Record<string,any>} values\n * @param {(message: string, values?: Record<string,any>) => any[]} process\n * @return {any | any[]}\n */\nexport default function selectTypeHandler(value, matches = '', locale, values, process) {\n\tconst {cases} = parseCases(matches);\n\n\tif (value in cases) {\n\t\treturn process(cases[value], values);\n\t}\n\telse if (OTHER in cases) {\n\t\treturn process(cases[OTHER], values);\n\t}\n\n\treturn value;\n}\n"],"names":["parseCases","string","isWhitespace","ch","test","args","cases","currTermStart","latestTerm","inTerm","i","length","slice","caseBody","branchEndIndex","findClosingBracket","Error","push","fromIndex","depth","char","charAt","splitFormattedArgument","block","split","separator","limit","accumulator","arguments","undefined","indexOfDelimiter","indexOf","head","substring","trim","tail","MessageFormatter","constructor","locale","_this","typeHandlers","_defineProperty","memoize","message","values","flatten","process","join","blockStartIndex","blockEndIndex","result","key","type","format","body","typeHandler","bind","pluralFormatter","keyCounter","ONE","OTHER","replaceNumberSign","value","output","numBraces","numberValues","keyParam","pluralTypeHandler","matches","intValue","parseInt","forEach","arg","startsWith","keywordPossibilities","Intl","resolvedOptions","PluralRules","pluralKeyword","select","keyword","selectTypeHandler"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASA,UAAUA,CAACC,MAAM,EAAE;EAClC,MAAMC,YAAY,GAAGC,EAAE,IAAI,IAAI,CAACC,IAAI,CAACD,EAAE,CAAC,CAAA;EAExC,MAAME,IAAI,GAAG,EAAE,CAAA;EACf,MAAMC,KAAK,GAAG,EAAE,CAAA;EAEhB,IAAIC,aAAa,GAAG,CAAC,CAAA;EACrB,IAAIC,UAAU,GAAG,IAAI,CAAA;EACrB,IAAIC,MAAM,GAAG,KAAK,CAAA;EAElB,IAAIC,CAAC,GAAG,CAAC,CAAA;AACT,EAAA,OAAOA,CAAC,GAAGT,MAAM,CAACU,MAAM,EAAE;AACzB;AACA,IAAA,IAAIF,MAAM,KAAKP,YAAY,CAACD,MAAM,CAACS,CAAC,CAAC,CAAC,IAAIT,MAAM,CAACS,CAAC,CAAC,KAAK,GAAG,CAAC,EAAE;AAC7DD,MAAAA,MAAM,GAAG,KAAK,CAAA;MACdD,UAAU,GAAGP,MAAM,CAACW,KAAK,CAACL,aAAa,EAAEG,CAAC,CAAC,CAAA;;AA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ACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAASqB,iBAAiBA,CAACnB,KAAK,EAAyC;AAAA,EAAA,IAAvCM,OAAO,GAAAxC,SAAA,CAAAjB,MAAA,GAAA,CAAA,IAAAiB,SAAA,CAAA,CAAA,CAAA,KAAAC,SAAA,GAAAD,SAAA,CAAA,CAAA,CAAA,GAAG,EAAE,CAAA;EAAQ,IAAEgB,MAAM,GAAAhB,SAAA,CAAAjB,MAAA,GAAAiB,CAAAA,GAAAA,SAAA,MAAAC,SAAA,CAAA;EAAA,IAAEiB,OAAO,GAAAlB,SAAA,CAAAjB,MAAA,GAAAiB,CAAAA,GAAAA,SAAA,MAAAC,SAAA,CAAA;EACrF,MAAM;AAACvB,IAAAA,KAAAA;AAAK,GAAC,GAAGN,UAAU,CAACoE,OAAO,CAAC,CAAA;EAEnC,IAAIN,KAAK,IAAIxD,KAAK,EAAE;IACnB,OAAOwC,OAAO,CAACxC,KAAK,CAACwD,KAAK,CAAC,EAAElB,MAAM,CAAC,CAAA;AACrC,GAAC,MACI,IAAIgB,KAAK,IAAItD,KAAK,EAAE;IACxB,OAAOwC,OAAO,CAACxC,KAAK,CAACsD,KAAK,CAAC,EAAEhB,MAAM,CAAC,CAAA;AACrC,GAAA;AAEA,EAAA,OAAOkB,KAAK,CAAA;AACb;;;;"}
@@ -1,36 +0,0 @@
1
- import babel from '@rollup/plugin-babel';
2
- import commonjs from '@rollup/plugin-commonjs';
3
- import nodeResolve from '@rollup/plugin-node-resolve';
4
- import terser from '@rollup/plugin-terser';
5
-
6
- export default {
7
- input: 'source/IcuMessageFormatter.js',
8
- output: [
9
- {
10
- file: 'dist/icu-message-formatter.min.js',
11
- format: 'iife',
12
- name: 'IcuMessageFormatter',
13
- sourcemap: true
14
- },
15
- {
16
- file: 'dist/icu-message-formatter.es.min.js',
17
- format: 'es',
18
- name: 'IcuMessageFormatter',
19
- sourcemap: true
20
- }
21
- ],
22
- plugins: [
23
- commonjs(),
24
- babel({
25
- babelHelpers: 'bundled',
26
- skipPreflightCheck: true // See: https://github.com/rollup/plugins/issues/381#issuecomment-627215009
27
- }),
28
- nodeResolve({
29
- browser: true
30
- }),
31
- terser()
32
- ],
33
- treeshake: {
34
- moduleSideEffects: false
35
- }
36
- };
package/rollup.config.js DELETED
@@ -1,35 +0,0 @@
1
-
2
- import babel from '@rollup/plugin-babel';
3
- import commonjs from '@rollup/plugin-commonjs';
4
- import nodeResolve from '@rollup/plugin-node-resolve';
5
-
6
- export default {
7
- input: 'source/IcuMessageFormatter.js',
8
- output: [
9
- {
10
- file: `lib/icu-message-formatter.cjs.js`,
11
- format: 'cjs',
12
- sourcemap: true
13
- },
14
- {
15
- file: `lib/icu-message-formatter.es.js`,
16
- format: 'es',
17
- sourcemap: true
18
- }
19
- ],
20
- plugins: [
21
- commonjs(),
22
- babel({
23
- babelHelpers: 'runtime'
24
- }),
25
- nodeResolve()
26
- ],
27
- external: [
28
- /@babel\/runtime/,
29
- '@ultraq/array-utils',
30
- '@ultraq/function-utils'
31
- ],
32
- treeshake: {
33
- moduleSideEffects: false
34
- }
35
- };
@@ -1,20 +0,0 @@
1
- /*
2
- * Copyright 2019, Emanuel Rabina (http://www.ultraq.net.nz/)
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
-
17
- export {default as MessageFormatter} from './MessageFormatter.js';
18
- export {default as pluralTypeHandler} from './pluralTypeHandler.js';
19
- export {default as selectTypeHandler} from './selectTypeHandler.js';
20
- export {findClosingBracket, parseCases, splitFormattedArgument} from './utilities.js';
@@ -1,138 +0,0 @@
1
- /*
2
- * Copyright 2019, Emanuel Rabina (http://www.ultraq.net.nz/)
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
-
17
- import {findClosingBracket, splitFormattedArgument} from './utilities.js';
18
-
19
- import {flatten} from '@ultraq/array-utils';
20
- import {memoize} from '@ultraq/function-utils';
21
-
22
- /**
23
- * @typedef {Record<string,any>} FormatValues
24
- */
25
-
26
- /**
27
- * @callback ProcessFunction
28
- * @param {string} message
29
- * @param {FormatValues} [values={}]
30
- * @return {any[]}
31
- */
32
-
33
- /**
34
- * @callback TypeHandler
35
- * @param {any} value
36
- * The object which matched the key of the block being processed.
37
- * @param {string} matches
38
- * Any format options associated with the block being processed.
39
- * @param {string} locale
40
- * The locale to use for formatting.
41
- * @param {FormatValues} values
42
- * The object of placeholder data given to the original `format`/`process`
43
- * call.
44
- * @param {ProcessFunction} process
45
- * The `process` function itself so that sub-messages can be processed by type
46
- * handlers.
47
- * @return {any | any[]}
48
- */
49
-
50
- /**
51
- * The main class for formatting messages.
52
- *
53
- * @author Emanuel Rabina
54
- */
55
- export default class MessageFormatter {
56
-
57
- /**
58
- * Creates a new formatter that can work using any of the custom type handlers
59
- * you register.
60
- *
61
- * @param {string} locale
62
- * @param {Record<string,TypeHandler>} [typeHandlers]
63
- * Optional object where the keys are the names of the types to register,
64
- * their values being the functions that will return a nicely formatted
65
- * string for the data and locale they are given.
66
- */
67
- constructor(locale, typeHandlers = {}) {
68
-
69
- this.locale = locale;
70
- this.typeHandlers = typeHandlers;
71
- }
72
-
73
- /**
74
- * Formats an ICU message syntax string using `values` for placeholder data
75
- * and any currently-registered type handlers.
76
- *
77
- * @type {(message: string, values?: FormatValues) => string}
78
- */
79
- format = memoize((message, values = {}) => {
80
-
81
- return flatten(this.process(message, values)).join('');
82
- });
83
-
84
- /**
85
- * Process an ICU message syntax string using `values` for placeholder data
86
- * and any currently-registered type handlers. The result of this method is
87
- * an array of the component parts after they have been processed in turn by
88
- * their own type handlers. This raw output is useful for other renderers,
89
- * eg: React where components can be used instead of being forced to return
90
- * raw strings.
91
- *
92
- * This method is used by {@link MessageFormatter#format} where it acts as a
93
- * string renderer.
94
- *
95
- * @param {string} message
96
- * @param {FormatValues} [values]
97
- * @return {any[]}
98
- */
99
- process(message, values = {}) {
100
-
101
- if (!message) {
102
- return [];
103
- }
104
-
105
- let blockStartIndex = message.indexOf('{');
106
- if (blockStartIndex !== -1) {
107
- let blockEndIndex = findClosingBracket(message, blockStartIndex);
108
- if (blockEndIndex !== -1) {
109
- let block = message.substring(blockStartIndex, blockEndIndex + 1);
110
- if (block) {
111
- let result = [];
112
- let head = message.substring(0, blockStartIndex);
113
- if (head) {
114
- result.push(head);
115
- }
116
- let [key, type, format] = splitFormattedArgument(block);
117
- let body = values[key];
118
- if (body === null || body === undefined) {
119
- body = '';
120
- }
121
- let typeHandler = type && this.typeHandlers[type];
122
- result.push(typeHandler ?
123
- typeHandler(body, format, this.locale, values, this.process.bind(this)) :
124
- body);
125
- let tail = message.substring(blockEndIndex + 1);
126
- if (tail) {
127
- result.push(this.process(tail, values));
128
- }
129
- return result;
130
- }
131
- }
132
- else {
133
- throw new Error(`Unbalanced curly braces in string: "${message}"`);
134
- }
135
- }
136
- return [message];
137
- }
138
- }
@@ -1,153 +0,0 @@
1
- /*
2
- * Copyright 2019, Emanuel Rabina (http://www.ultraq.net.nz/)
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
-
17
- /* eslint-env jest */
18
- import MessageFormatter from './MessageFormatter';
19
- import pluralTypeHandler from './pluralTypeHandler';
20
- import selectTypeHandler from './selectTypeHandler';
21
-
22
- /**
23
- * Tests for the ICU message formatter.
24
- */
25
- describe('MessageFormatter', function() {
26
-
27
- describe('#format', function() {
28
-
29
- test('Basic string replacement', function() {
30
- let formatter = new MessageFormatter('en-NZ');
31
- let message = formatter.format('Hey {name}, that\'s gonna cost you!', {
32
- name: 'Emanuel'
33
- });
34
- expect(message).toBe('Hey Emanuel, that\'s gonna cost you!');
35
- });
36
-
37
- test('Options finding when containing nested types', function() {
38
- let locale = 'en-NZ';
39
- let selectSpy = jest.fn(selectTypeHandler);
40
- let formatter = new MessageFormatter(locale, {
41
- select: selectSpy
42
- });
43
-
44
- let values = {
45
- at: 'asap'
46
- };
47
- let message = formatter.format(
48
- 'Hit me up {at, select, date {at {specificDate, date}} asap {as soon as possible}}',
49
- values
50
- );
51
-
52
- expect(selectSpy).toHaveBeenCalledWith(
53
- values.at,
54
- 'date {at {specificDate, date}} asap {as soon as possible}',
55
- locale,
56
- values,
57
- expect.any(Function)
58
- );
59
- expect(message).toBe('Hit me up as soon as possible');
60
- });
61
-
62
- test('Replaces multiple instances of the same parameter', function() {
63
- let formatter = new MessageFormatter('en-NZ');
64
- let message = formatter.format('Hello {name} {name}!', {
65
- name: 'Emanuel'
66
- });
67
- expect(message).toBe('Hello Emanuel Emanuel!');
68
- });
69
-
70
- test('Returns empty strings for null/undefined message values', function() {
71
- let formatter = new MessageFormatter('en-NZ');
72
- [null, undefined].forEach(value => {
73
- let message = formatter.format(value);
74
- expect(message).toBe('');
75
- });
76
- });
77
-
78
- test('Lets falsey values in parameters through', function() {
79
- let formatter = new MessageFormatter('en-NZ');
80
- [0, false].forEach(value => {
81
- let message = formatter.format(`{param}`, {
82
- param: value
83
- });
84
- expect(message).toBe(value.toString());
85
- });
86
- });
87
-
88
- test('Plural inside select', function() {
89
- let formatter = new MessageFormatter('en-NZ', {
90
- plural: pluralTypeHandler,
91
- select: selectTypeHandler
92
- });
93
- let message = `{gender_of_host, select,
94
- female {{num_guests, plural,
95
- =0 {{host} does not give a party.}
96
- =1 {{host} invites {guest} to her party.}
97
- =2 {{host} invites {guest} and one other person to her party.}
98
- other {{host} invites {guest} and # other people to her party.}
99
- }}
100
- male {{num_guests, plural,
101
- =0 {{host} does not give a party.}
102
- =1 {{host} invites {guest} to his party.}
103
- =2 {{host} invites {guest} and one other person to his party.}
104
- other {{host} invites {guest} and # other people to his party.}
105
- }}
106
- other {{num_guests, plural,
107
- =0 {{host} does not give a party.}
108
- =1 {{host} invites {guest} to their party.}
109
- =2 {{host} invites {guest} and one other person to their party.}
110
- other {{host} invites {guest} and # other people to their party.}
111
- }}
112
- }`;
113
-
114
- expect(formatter.format(message, {'gender_of_host': 'male', host: 'John', 'num_guests': 115, guest: 'you'})).toBe('John invites you and 115 other people to his party.');
115
- expect(formatter.format(message, {'gender_of_host': 'female', host: 'John', 'num_guests': 1, guest: 'you'})).toBe('John invites you to her party.');
116
- expect(formatter.format(message, {'gender_of_host': 'other', host: 'John', 'num_guests': 2, guest: 'you'})).toBe('John invites you and one other person to their party.');
117
- expect(formatter.format(message, {'gender_of_host': 'other', host: 'John', 'num_guests': 12345, guest: 'you'})).toBe('John invites you and 12345 other people to their party.');
118
- });
119
-
120
- test('Select inside plural', function() {
121
- let formatter = new MessageFormatter('en-NZ', {
122
- plural: pluralTypeHandler,
123
- select: selectTypeHandler
124
- });
125
-
126
- let message = `{num_guests, plural,
127
- =0 {{host} does not give a party.}
128
- =1 {{gender_of_host, select,
129
- female {{host} invites {guest} to her party.}
130
- male {{host} invites {guest} to his party.}
131
- other {{host} invites {guest} to their party.}
132
- }}
133
- =2 {{gender_of_host, select,
134
- female {{host} invites {guest} and one other person to her party.}
135
- male {{host} invites {guest} and one other person to his party.}
136
- other {{host} invites {guest} and one other person to their party.}
137
- }}
138
- other {{gender_of_host, select,
139
- female {{host} invites {guest} and # other people to her party.}
140
- male {{host} invites {guest} and # other people to his party.}
141
- other {{host} invites {guest} and # other people to their party.}
142
- }}
143
- }`;
144
-
145
- expect(formatter.format(message, {'gender_of_host': 'female', host: 'John', 'num_guests': 1, guest: 'you'})).toBe('John invites you to her party.');
146
- expect(formatter.format(message, {'gender_of_host': 'other', host: 'John', 'num_guests': 2, guest: 'you'})).toBe('John invites you and one other person to their party.');
147
-
148
- // number sign only works in the immediately corresponding layer! Can't use a nested one.
149
- expect(formatter.format(message, {'gender_of_host': 'male', host: 'John', 'num_guests': 115, guest: 'you'})).toBe('John invites you and # other people to his party.');
150
- expect(formatter.format(message, {'gender_of_host': 'other', host: 'John', 'num_guests': 12345, guest: 'you'})).toBe('John invites you and # other people to their party.');
151
- });
152
- });
153
- });