├── .editorconfig ├── .eslintrc.js ├── .gitignore ├── .npmignore ├── .travis.yml ├── LICENSE ├── README.md ├── gulpfile.js ├── lib ├── locale.directive.d.ts └── locale.directive.js ├── package.json ├── src └── locale.directive.ts ├── tsconfig.json └── tslint.json /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | parserOptions: { 4 | sourceType: 'module' 5 | }, 6 | // https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style 7 | extends: 'standard', 8 | // required to lint *.vue files 9 | plugins: [ 10 | 'html' 11 | ], 12 | // add your custom rules here 13 | 'rules': { 14 | // allow paren-less arrow functions 15 | 'arrow-parens': 0, 16 | // allow debugger during development 17 | 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0 18 | }, 19 | globals: { 20 | localStorage: true, 21 | location: true, 22 | FormData: true 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | npm-debug.log 4 | test/ 5 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .babelrc 2 | .editorconfig 3 | .eslintrc.js 4 | .gitignore 5 | .travis.yml 6 | 7 | gulpfile.babel.js 8 | node_modules/ 9 | npm-debug.log 10 | 11 | test/ 12 | src/ 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "4" 4 | - "5" 5 | - "6" 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | VueJS Logo 2 | 3 | # VueJS TS Locale
[![Sponsored by][sponsor-img]][sponsor] [![Version][npm-version-img]][npm] [![Downloads][npm-downloads-img]][npm] [![Build Status][ci-img]][ci] [![Dependencies][deps-img]][deps] 4 | 5 | [VueJS] Plugin for advanced localization of web applications using typescript 6 | 7 | [sponsor-img]: https://img.shields.io/badge/Sponsored%20by-TWCAPPS-692446.svg 8 | [sponsor]: https://www.twcapps.com 9 | [VueJS]: https://github.com/vuejs/vue 10 | [ci-img]: https://travis-ci.org/bartsidee/vue-ts-locale.svg 11 | [ci]: https://travis-ci.org/bartsidee/vue-ts-locale 12 | [deps]: https://david-dm.org/bartsidee/vue-ts-locale 13 | [deps-img]: https://david-dm.org/bartsidee/vue-ts-locale.svg 14 | [npm]: https://www.npmjs.com/package/vue-ts-locale 15 | [npm-downloads-img]: https://img.shields.io/npm/dm/vue-ts-locale.svg 16 | [npm-version-img]: https://img.shields.io/npm/v/vue-ts-locale.svg 17 | 18 | 19 | ## Links 20 | 21 | - [GitHub](https://github.com/bartsidee/vue-ts-locale) 22 | - [NPM](https://www.npmjs.com/package/vue-ts-locale) 23 | 24 | 25 | ## Installation 26 | 27 | Should be installed locally in your project source code: 28 | 29 | ```bash 30 | npm install vue-ts-locale --save 31 | ``` 32 | 33 | ## Integration 34 | 35 | Inside your VueJS application you have to register the `VueLocale` plugin: 36 | 37 | ```js 38 | import VueLocale from "vue-ts-locale"; 39 | 40 | Vue.use(VueLocale, 41 | { 42 | language: SELECTED_LANGUAGE, 43 | currency: SELECTED_CURRENCY, 44 | messages: MESSAGE_TEXTS 45 | }) 46 | ``` 47 | 48 | While these are typical examples of values: 49 | 50 | - `SELECTED_LANGUAGE`: `"de"`, `"en"`, `"fr"`, ... (any valid language identifier) 51 | - `SELECTED_CURRENCY`: `"EUR"`, `"USD"`, ... (any valid currency from [CLDR data](http://www.currency-iso.org/dam/downloads/lists/list_one.xml)) 52 | - `MESSAGE_TEXTS`: `{ key : value, ...}` 53 | 54 | 55 | ## Loading required locale data 56 | 57 | Depending on whether your clients support the `Intl` API + all relevant locales (prominent exceptions right now are NodeJS, Safari on Mac and Safari on iOS) the amount of data and polyfills to load differs. 58 | 59 | ### Loading Intl-Polyfill + Data for 4 Locales 60 | 61 | ```ts 62 | 63 | import "intl"; 64 | import "intl/locale-data/jsonp/en.js"; 65 | import "intl/locale-data/jsonp/de.js"; 66 | import "intl/locale-data/jsonp/fr.js"; 67 | import "intl/locale-data/jsonp/es.js"; 68 | 69 | ``` 70 | 71 | The data loaded here contains information on how to format dates (+ calendar data) and numbers (+ currencies). 72 | 73 | ## Usage 74 | 75 | ### Adding Messages 76 | 77 | You should pass the matching locale data structure with relevant messages e.g. Dutch. 78 | 79 | ```js 80 | let messages = 81 | { 82 | "my-message-identifier": "Hallo wereld!", 83 | "my-html-identifier": "Hallo wereld!", 84 | "my-personal-identifier": "Hallo {name}!", 85 | ... 86 | } 87 | ``` 88 | 89 | ### Translating messages using VueJS filter 90 | 91 | - Plain Text: ```{{ "my-message-identifier" | format-message }}``` 92 | - HTML Output: ```{{{ "my-html-identifier" | format-message }}}``` 93 | - Personal: Not possible because we can't pass the required additional data structure to the filter 94 | 95 | 96 | ### Translating using function calls 97 | 98 | - Plain Text: ```{{ $formatMessage("my-message-identifier") }}``` 99 | - HTML Output: ```{{{ $formatMessage("my-html-identifier") }}}``` 100 | - Personal: `{{{ $formatMessage("my-personal-identifier", { name : screenName }) }}}` 101 | 102 | 103 | ### Formatting Numbers 104 | 105 | - Number Formatting #1: ```{{ 3.14159 | format-number }}``` => `"3,14159"` 106 | - Number Formatting #2: ```{{ 3.14159 | format-number 2 }}``` => `"3,14"` 107 | - Number Formatting #3: ```{{ 3.14159 | format-number 0 }}``` => `"3"` 108 | - Percent Formatting #1: ```{{ 0.641322 | format-percent }}``` => `"64%"` 109 | - Percent Formatting #2: ```{{ 0.641322 | format-percent 2 }}``` => `"64,13%"` 110 | - Currency Formatting #1: ```{{ 21.37 | format-currency }}``` => `"21 €"` 111 | - Currency Formatting #2: ```{{ 21.37 | format-currency-precise }}``` => `"21,37 €"` 112 | 113 | 114 | ### Formatting Dates/Times 115 | 116 | - Date Formatting: ```{{ new Date | format-date }}``` => `12.2.2016` 117 | - Time Formatting: ```{{ new Date | format-time }}``` => `14:23 Uhr` 118 | 119 | 120 | ### Formatting Relative Dates 121 | 122 | - Relative Formatting: ```{{ new Date - (1000 * 60 * 10) | format-relative }}``` => `vor 10 Minuten` 123 | 124 | 125 | ### Use format methods outside of Vue component 126 | 127 | It is possible to use the format methods directly in TS code, but only after the plugin is initialised 128 | 129 | ``` 130 | import { formatMessage } from "vue-ts-locale"; 131 | formatMessage("my-message-identifier"); 132 | ``` 133 | 134 | 135 | ## Copyright 136 | This plugin is based on the work of Sebastian Werner 137 | https://github.com/sebastian-software/vue-locale -------------------------------------------------------------------------------- /gulpfile.js: -------------------------------------------------------------------------------- 1 | var gulp = require('gulp'); 2 | var ts = require('gulp-typescript'); 3 | var merge = require('merge2'); 4 | 5 | var tsProject = ts.createProject('tsconfig.json'); 6 | gulp.task('build', function () { 7 | var tsResult = tsProject.src() 8 | .pipe(tsProject()); 9 | 10 | return merge([ 11 | tsResult.dts.pipe(gulp.dest('lib')), 12 | tsResult.js.pipe(gulp.dest('lib')) 13 | ]); 14 | }); -------------------------------------------------------------------------------- /lib/locale.directive.d.ts: -------------------------------------------------------------------------------- 1 | export declare let getLanguage: any; 2 | export declare let setLanguage: any; 3 | export declare let formatDate: any; 4 | export declare let formatTime: any; 5 | export declare let formatNumber: any; 6 | export declare let formatRelative: any; 7 | export declare let formatMessage: any; 8 | declare const _default: { 9 | install: (Vue: any, options: any) => void; 10 | }; 11 | export default _default; 12 | -------------------------------------------------------------------------------- /lib/locale.directive.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | var underscore_1 = require("underscore"); 4 | var MessageFormat = require("intl-messageformat"); 5 | var RelativeFormat = require("intl-relativeformat"); 6 | var memoizeFormatConstructor = require("intl-format-cache"); 7 | var isNode = Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]"; 8 | if (isNode) { 9 | Intl.NumberFormat = IntlPolyfill.NumberFormat; 10 | Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat; 11 | } 12 | var clamp = function (number, min, max) { 13 | return Math.min(Math.max(number, min), max); 14 | }; 15 | var kebabCase = function (string) { 16 | var result = string; 17 | result = result.replace(/([a-z][A-Z])/g, function (match) { 18 | return match.substr(0, 1) + '-' + match.substr(1, 1).toLowerCase(); 19 | }); 20 | result = result.toLowerCase(); 21 | result = result.replace(/[^-a-z0-9]+/g, '-'); 22 | result = result.replace(/^-+/, '').replace(/-$/, ''); 23 | return result; 24 | }; 25 | var formats = MessageFormat.formats; 26 | var getCachedNumberFormat = memoizeFormatConstructor(Intl.NumberFormat); 27 | var getCachedDateTimeFormat = memoizeFormatConstructor(Intl.DateTimeFormat); 28 | var getCachedMessageFormat = memoizeFormatConstructor(MessageFormat); 29 | var getCachedRelativeFormat = memoizeFormatConstructor(RelativeFormat); 30 | var maximumFractionDigits = 18; 31 | function install(Vue, options) { 32 | var language = options.language, currency = options.currency, messages = options.messages; 33 | var locale = language; 34 | exports.getLanguage = function () { 35 | return { language: language, currency: currency, messages: messages }; 36 | }; 37 | exports.setLanguage = function (options, reloadLocation) { 38 | language = options.language; 39 | currency = options.currency; 40 | messages = options.messages; 41 | locale = language; 42 | if (reloadLocation) 43 | window.location.reload(true); 44 | }; 45 | exports.formatDate = function (date, format) { 46 | var parsedDate = new Date(date); 47 | if (!underscore_1.isDate(parsedDate)) 48 | throw new TypeError("A date or timestamp must be provided to {{formatDate}}"); 49 | if (underscore_1.isString(format) && format in formats.date) 50 | format = formats.date[format]; 51 | return getCachedDateTimeFormat(locale, format).format(parsedDate); 52 | }; 53 | exports.formatTime = function (date, format) { 54 | var parsedDate = new Date(date); 55 | if (!underscore_1.isDate(date)) 56 | throw new TypeError("A date or timestamp must be provided to {{formatTime}}"); 57 | if (underscore_1.isString(format) && format in formats.time) 58 | format = formats.time[format]; 59 | return getCachedDateTimeFormat(locale, format).format(parsedDate); 60 | }; 61 | exports.formatNumber = function (num, format) { 62 | if (!underscore_1.isNumber(num)) 63 | throw new TypeError("A number must be provided to {{formatNumber}}"); 64 | if (underscore_1.isString(format)) { 65 | if (format === "currency") 66 | format = { style: "currency", currency: currency }; 67 | else if (format in formats.number) 68 | format = formats.number[format]; 69 | } 70 | return getCachedNumberFormat(locale, format).format(num); 71 | }; 72 | exports.formatRelative = function (date, format, now) { 73 | var parsedDate = new Date(date); 74 | if (!underscore_1.isDate(parsedDate)) 75 | throw new TypeError("A date or timestamp must be provided to {{formatRelative}}"); 76 | return getCachedRelativeFormat(locale, format).format(parsedDate, { 77 | now: now || new Date() 78 | }); 79 | }; 80 | exports.formatMessage = function (message) { 81 | var formatOptions = []; 82 | for (var _i = 1; _i < arguments.length; _i++) { 83 | formatOptions[_i - 1] = arguments[_i]; 84 | } 85 | if (message in messages) 86 | message = messages[message]; 87 | if (typeof message === "string") 88 | message = getCachedMessageFormat(message, locale, {}); 89 | if (formatOptions.length === 1 && underscore_1.isObject(formatOptions[0])) 90 | formatOptions = formatOptions[0]; 91 | return message.format(formatOptions); 92 | }; 93 | var decimalTestNumber = 3.1; 94 | var decimalSeparator = exports.formatNumber(decimalTestNumber).charAt(1); 95 | function extractNumberParts(value) { 96 | var parsed = parseInt(value.replace(/[^0-9]/g, ""), 0); 97 | return isNaN(parsed) ? 0 : parsed; 98 | } 99 | function parseToNumber(value) { 100 | if (value == undefined || value === "") 101 | return 0; 102 | var splits = value.split(decimalSeparator).map(extractNumberParts); 103 | if (splits[1] > 0) 104 | return parseFloat(splits[0] + "." + splits[1]); 105 | return splits[0]; 106 | } 107 | var helpers = { 108 | formatDate: exports.formatDate, 109 | formatTime: exports.formatTime, 110 | formatRelative: exports.formatRelative, 111 | formatNumber: exports.formatNumber, 112 | formatMessage: exports.formatMessage 113 | }; 114 | underscore_1.each(helpers, function (helper, name) { 115 | Vue.filter(kebabCase(name), helper); 116 | Vue.prototype["$" + name] = helper; 117 | }); 118 | Vue.filter("format-currency", { 119 | read: function (val) { 120 | var numberOptions = { 121 | style: "currency", 122 | currency: currency, 123 | minimumFractionDigits: 0, 124 | maximumFractionDigits: 0 125 | }; 126 | return exports.formatNumber(val == undefined || val === "" || isNaN(val) ? 0 : val, numberOptions); 127 | }, 128 | write: function (val) { 129 | return parseToNumber(val); 130 | } 131 | }); 132 | Vue.filter("format-currency-precise", { 133 | read: function (val) { 134 | return exports.formatNumber(val == undefined || val === "" || isNaN(val) ? 0 : val, "currency"); 135 | }, 136 | write: function (val) { 137 | return parseToNumber(val); 138 | } 139 | }); 140 | Vue.filter("format-percent", { 141 | read: function (val, fractionDigits) { 142 | return exports.formatNumber(val == undefined || val === "" ? 0 : clamp(val / 100, 0, 1), { 143 | style: "percent", 144 | minimumFractionDigits: fractionDigits == undefined ? 0 : fractionDigits, 145 | maximumFractionDigits: fractionDigits == undefined ? maximumFractionDigits : fractionDigits 146 | }); 147 | }, 148 | write: function (val) { 149 | return parseToNumber(val); 150 | } 151 | }); 152 | Vue.filter("format-number", { 153 | read: function (val, fractionDigits) { 154 | return val == undefined || val === "" ? 0 : exports.formatNumber(val, { 155 | minimumFractionDigits: fractionDigits == undefined ? 0 : fractionDigits, 156 | maximumFractionDigits: fractionDigits == undefined ? maximumFractionDigits : fractionDigits 157 | }); 158 | }, 159 | write: function (val) { 160 | return parseToNumber(val); 161 | } 162 | }); 163 | } 164 | exports.default = { 165 | install: install 166 | }; 167 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vue-ts-locale", 3 | "version": "1.0.2", 4 | "description": "Advanced typescript localization support for VueJS", 5 | "keywords": [ 6 | "vuejs", 7 | "locale", 8 | "translation", 9 | "formatting", 10 | "date", 11 | "number", 12 | "formatjs" 13 | ], 14 | "main": "./lib/locale.directive.js", 15 | "types": "./lib/locale.directive.d.ts", 16 | "author": { 17 | "name": "Bart van den Ende", 18 | "email": "info@bartvandenende.nl", 19 | "url": "http://www.twcapps.com" 20 | }, 21 | "contributor": [ 22 | { 23 | "name": "Sebastian Werner", 24 | "email": "s.werner@sebastian-software.de" 25 | } 26 | ], 27 | "license": "Apache-2.0", 28 | "repository": "https://github.com/twcapps/vue-ts-locale", 29 | "bugs": { 30 | "url": "https://github.com/twcapps/vue-ts-locale/issues" 31 | }, 32 | "homepage": "https://github.com/twcapps/vue-ts-locale", 33 | "dependencies": { 34 | "intl": "^1.2.5", 35 | "intl-format-cache": "^2.0.5", 36 | "intl-messageformat": "^1.3.0", 37 | "intl-relativeformat": "^1.3.0", 38 | "underscore": "^1.8.3", 39 | "vue": "^2.2.6" 40 | }, 41 | "scripts": { 42 | "build": "gulp build", 43 | "pretest": "npm run build", 44 | "test": "ava ./test/**/*.js", 45 | "test:watch": "ava ./test/**/*.js --watch", 46 | "prepublish": "npm run build", 47 | "release": "release-it --github.release --npm.publish --non-interactive", 48 | "release-minor": "release-it --github.release --npm.publish --non-interactive --increment minor", 49 | "release-major": "release-it --github.release --npm.publish --non-interactive --increment major", 50 | "depupdate": "updtr" 51 | }, 52 | "devDependencies": { 53 | "@types/node": "^7.0.12", 54 | "ava": "^0.19.1", 55 | "babel-register": "^6.24.1", 56 | "gulp": "^3.9.1", 57 | "gulp-typescript": "^3.1.6", 58 | "merge2": "^1.0.3", 59 | "tslint": "^5.1.0", 60 | "typescript": "^2.2.2", 61 | "updtr": "^1.0.0" 62 | }, 63 | "ava": { 64 | "files": [ 65 | "./test/**/*.js" 66 | ], 67 | "require": [ 68 | "babel-register" 69 | ] 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/locale.directive.ts: -------------------------------------------------------------------------------- 1 | import * as Vue from "vue"; 2 | 3 | import {isObject, isString, isNumber, isDate, each } from "underscore"; 4 | 5 | const MessageFormat = require("intl-messageformat"); 6 | const RelativeFormat = require("intl-relativeformat"); 7 | const memoizeFormatConstructor = require("intl-format-cache"); 8 | 9 | // NodeJS by default to not offer full ICU support and therefor break the unit tests 10 | declare var IntlPolyfill: any; 11 | const isNode = Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]"; 12 | if (isNode) { 13 | Intl.NumberFormat = IntlPolyfill.NumberFormat; 14 | Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat; 15 | } 16 | 17 | const clamp = function(number, min, max) { 18 | return Math.min(Math.max(number, min), max); 19 | } 20 | 21 | const kebabCase = function(string){ 22 | let result = string; 23 | result = result.replace(/([a-z][A-Z])/g, function(match) { 24 | return match.substr(0, 1) + '-' + match.substr(1, 1).toLowerCase(); 25 | }); 26 | result = result.toLowerCase(); 27 | result = result.replace(/[^-a-z0-9]+/g, '-'); 28 | result = result.replace(/^-+/, '').replace(/-$/, ''); 29 | return result; 30 | } 31 | 32 | const formats = MessageFormat.formats; 33 | 34 | const getCachedNumberFormat = memoizeFormatConstructor(Intl.NumberFormat); 35 | const getCachedDateTimeFormat = memoizeFormatConstructor(Intl.DateTimeFormat); 36 | const getCachedMessageFormat = memoizeFormatConstructor(MessageFormat); 37 | const getCachedRelativeFormat = memoizeFormatConstructor(RelativeFormat); 38 | 39 | // A constant defined by the standard Intl.NumberFormat 40 | // const maximumFractionDigits = 20; 41 | // Unfortunately through formatting issues of percent values in IE 42 | // we have to use a small value here, because IE (as of v11) seems to 43 | // account the percent symbol + optional space to the fraction digits. 44 | // See also: https://github.com/sebastian-software/vue-locale/issues/1#issuecomment-215396481 45 | const maximumFractionDigits = 18; 46 | 47 | export let getLanguage: any; 48 | export let setLanguage: any; 49 | export let formatDate: any; 50 | export let formatTime: any; 51 | export let formatNumber: any; 52 | export let formatRelative: any; 53 | export let formatMessage: any; 54 | 55 | function install(Vue: any, options: any) { 56 | let { language, currency, messages } = options; 57 | let locale = language; 58 | 59 | // ============================================= 60 | // SET & GET LANGUAGE 61 | // ============================================= 62 | getLanguage = function() { 63 | return {language, currency, messages }; 64 | }; 65 | 66 | setLanguage = function(options, reloadLocation) { 67 | language = options.language; 68 | currency = options.currency; 69 | messages = options.messages; 70 | locale = language; 71 | 72 | if (reloadLocation) window.location.reload(true); 73 | }; 74 | 75 | // ============================================= 76 | // FORMATTER FUNCTIONS 77 | // ============================================= 78 | 79 | formatDate = function(date: any, format: any) { 80 | let parsedDate = new Date(date); 81 | if (!isDate(parsedDate)) 82 | throw new TypeError("A date or timestamp must be provided to {{formatDate}}"); 83 | 84 | if (isString(format) && format in formats.date) 85 | format = formats.date[format]; 86 | 87 | return getCachedDateTimeFormat(locale, format).format(parsedDate); 88 | }; 89 | 90 | formatTime = function(date: any, format: any) { 91 | let parsedDate = new Date(date); 92 | if (!isDate(date)) 93 | throw new TypeError("A date or timestamp must be provided to {{formatTime}}"); 94 | 95 | if (isString(format) && format in formats.time) 96 | format = formats.time[format]; 97 | 98 | return getCachedDateTimeFormat(locale, format).format(parsedDate); 99 | }; 100 | 101 | formatNumber = function(num: any, format?: any) { 102 | if (!isNumber(num)) 103 | throw new TypeError("A number must be provided to {{formatNumber}}"); 104 | 105 | if (isString(format)) { 106 | if (format === "currency") 107 | format = { style: "currency", currency: currency }; 108 | else if (format in formats.number) 109 | format = formats.number[format]; 110 | } 111 | 112 | return getCachedNumberFormat(locale, format).format(num); 113 | }; 114 | 115 | formatRelative = function(date: any, format: any, now: any) { 116 | let parsedDate = new Date(date); 117 | if (!isDate(parsedDate)) 118 | throw new TypeError("A date or timestamp must be provided to {{formatRelative}}"); 119 | 120 | return getCachedRelativeFormat(locale, format).format(parsedDate, { 121 | now: now || new Date() 122 | }); 123 | }; 124 | 125 | formatMessage = function(message: any, ...formatOptions: any[]) { 126 | // Read real message from DB 127 | if (message in messages) 128 | message = messages[message]; 129 | 130 | if (typeof message === "string") 131 | message = getCachedMessageFormat(message, locale, {}); 132 | 133 | // If there is a single map parameter, use that instead of the formatOptions array 134 | if (formatOptions.length === 1 && isObject(formatOptions[0])) 135 | formatOptions = formatOptions[0]; 136 | 137 | return message.format(formatOptions); 138 | }; 139 | 140 | 141 | 142 | // ============================================= 143 | // PARSERS 144 | // ============================================= 145 | 146 | // Figuring out whether the separator is either "," or "." (Are there any other possibilities at all?) 147 | let decimalTestNumber = 3.1; 148 | let decimalSeparator = formatNumber(decimalTestNumber).charAt(1); 149 | 150 | function extractNumberParts(value: any) { 151 | let parsed = parseInt(value.replace(/[^0-9]/g, ""), 0); 152 | return isNaN(parsed) ? 0 : parsed; 153 | } 154 | 155 | function parseToNumber(value: any) { 156 | if (value == undefined || value === "") 157 | return 0; 158 | 159 | let splits = value.split(decimalSeparator).map(extractNumberParts); 160 | 161 | // Build up float number to let parseFloat convert it back into a number 162 | if (splits[1] > 0) 163 | return parseFloat(splits[0] + "." + splits[1]); 164 | 165 | // Return plain integer 166 | return splits[0]; 167 | } 168 | 169 | 170 | // ============================================= 171 | // REGISTER FILTERS 172 | // ============================================= 173 | 174 | let helpers = { 175 | formatDate, 176 | formatTime, 177 | formatRelative, 178 | formatNumber, 179 | formatMessage 180 | }; 181 | 182 | each(helpers, function(helper, name) { 183 | // Adding features as a VueJS filter for easily pass a string over (only numberic parameters though) 184 | Vue.filter(kebabCase(name), helper); 185 | 186 | // Support alternative full blown calling of methods with real options object 187 | Vue.prototype["$" + name] = helper; 188 | }); 189 | 190 | // ============================================= 191 | // ADDITIONAL FILTERS 192 | // ============================================= 193 | 194 | Vue.filter("format-currency", { 195 | // model -> view: formats the value when updating the input element. 196 | read: function(val: any) { 197 | let numberOptions = { 198 | style: "currency", 199 | currency: currency, 200 | minimumFractionDigits: 0, 201 | maximumFractionDigits: 0 202 | }; 203 | 204 | return formatNumber(val == undefined || val === "" || isNaN(val) ? 0 : val, numberOptions); 205 | }, 206 | 207 | // view -> model: formats the value when writing to the data. 208 | write: function(val: any) { 209 | return parseToNumber(val); 210 | } 211 | }); 212 | 213 | Vue.filter("format-currency-precise", { 214 | // model -> view: formats the value when updating the input element. 215 | read: function(val: any) { 216 | return formatNumber(val == undefined || val === "" || isNaN(val) ? 0 : val, "currency"); 217 | }, 218 | 219 | // view -> model: formats the value when writing to the data. 220 | write: function(val: any) { 221 | return parseToNumber(val); 222 | } 223 | }); 224 | 225 | Vue.filter("format-percent", { 226 | // model -> view: formats the value when updating the input element. 227 | read: function(val: any, fractionDigits: any) 228 | { 229 | return formatNumber(val == undefined || val === "" ? 0 : clamp(val / 100, 0, 1), 230 | { 231 | style: "percent", 232 | minimumFractionDigits: fractionDigits == undefined ? 0 : fractionDigits, 233 | maximumFractionDigits: fractionDigits == undefined ? maximumFractionDigits : fractionDigits 234 | }); 235 | }, 236 | 237 | // view -> model: formats the value when writing to the data. 238 | write: function(val: any) { 239 | return parseToNumber(val); 240 | } 241 | }); 242 | 243 | Vue.filter("format-number", { 244 | // model -> view: formats the value when updating the input element. 245 | read: function(val: any, fractionDigits: any) 246 | { 247 | return val == undefined || val === "" ? 0 : formatNumber(val, 248 | { 249 | minimumFractionDigits: fractionDigits == undefined ? 0 : fractionDigits, 250 | maximumFractionDigits: fractionDigits == undefined ? maximumFractionDigits : fractionDigits 251 | }); 252 | }, 253 | 254 | // view -> model: formats the value when writing to the data. 255 | write: function(val: any) { 256 | return parseToNumber(val); 257 | } 258 | }); 259 | } 260 | 261 | // Vue plugin 262 | export default { 263 | install: install 264 | }; -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": [ 5 | "dom", 6 | "es2015" 7 | ], 8 | "module": "commonjs", 9 | "moduleResolution": "node", 10 | "isolatedModules": false, 11 | "experimentalDecorators": true, 12 | "noImplicitAny": false, 13 | "noImplicitThis": true, 14 | "strictNullChecks": true, 15 | "removeComments": true, 16 | "suppressImplicitAnyIndexErrors": true, 17 | "declaration": true 18 | }, 19 | "include": [ 20 | "./src/**/*.ts" 21 | ], 22 | "compileOnSave": false 23 | } 24 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rules": { 3 | "class-name": true, 4 | "comment-format": [true, 5 | "check-space" 6 | ], 7 | "indent": [true, 8 | "spaces" 9 | ], 10 | "linebreak-style": [true, "LF"], 11 | "one-line": [true, 12 | "check-open-brace", 13 | "check-whitespace" 14 | ], 15 | "no-var-keyword": true, 16 | "quotemark": [true, 17 | "double", 18 | "avoid-escape" 19 | ], 20 | "semicolon": [true, "always"], 21 | "whitespace": [true, 22 | "check-branch", 23 | "check-decl", 24 | "check-operator", 25 | "check-module", 26 | "check-separator", 27 | "check-type" 28 | ], 29 | "typedef-whitespace": [true, { 30 | "call-signature": "nospace", 31 | "index-signature": "nospace", 32 | "parameter": "nospace", 33 | "property-declaration": "nospace", 34 | "variable-declaration": "nospace" 35 | }], 36 | "no-internal-module": true, 37 | "no-trailing-whitespace": true, 38 | "no-inferrable-types": true, 39 | "no-null-keyword": true 40 | } 41 | } --------------------------------------------------------------------------------