Skip to content

Commit

Permalink
Initial release.
Browse files Browse the repository at this point in the history
  • Loading branch information
blueimp committed Mar 28, 2014
0 parents commit 10d45fe
Show file tree
Hide file tree
Showing 11 changed files with 782 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.DS_Store
node_modules
bower_components
coverage
81 changes: 81 additions & 0 deletions .jshintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
{
"bitwise" : true, // true: Prohibit bitwise operators (&, |, ^, etc.)
"camelcase" : true, // true: Identifiers must be in camelCase
"curly" : true, // true: Require {} for every new block or scope
"eqeqeq" : true, // true: Require triple equals (===) for comparison
"forin" : true, // true: Require filtering for..in loops with obj.hasOwnProperty()
"immed" : true, // true: Require immediate invocations to be wrapped in parens
// e.g. `(function () { } ());`
"indent" : 4, // {int} Number of spaces to use for indentation
"latedef" : true, // true: Require variables/functions to be defined before being used
"newcap" : true, // true: Require capitalization of all constructor functions e.g. `new F()`
"noarg" : true, // true: Prohibit use of `arguments.caller` and `arguments.callee`
"noempty" : true, // true: Prohibit use of empty blocks
"nonew" : true, // true: Prohibit use of constructors for side-effects (without assignment)
"plusplus" : false, // true: Prohibit use of `++` & `--`
"quotmark" : "single", // Quotation mark consistency:
// false : do nothing (default)
// true : ensure whatever is used is consistent
// "single" : require single quotes
// "double" : require double quotes
"undef" : true, // true: Require all non-global variables to be declared (prevents global leaks)
"unused" : true, // true: Require all defined variables be used
"strict" : true, // true: Requires all functions run in ES5 Strict Mode
"trailing" : true, // true: Prohibit trailing whitespaces
"maxparams" : false, // {int} Max number of formal params allowed per function
"maxdepth" : false, // {int} Max depth of nested blocks (within functions)
"maxstatements" : false, // {int} Max number statements per function
"maxcomplexity" : false, // {int} Max cyclomatic complexity per function
"maxlen" : false, // {int} Max number of characters per line

// Relaxing
"asi" : false, // true: Tolerate Automatic Semicolon Insertion (no semicolons)
"boss" : false, // true: Tolerate assignments where comparisons would be expected
"debug" : false, // true: Allow debugger statements e.g. browser breakpoints.
"eqnull" : false, // true: Tolerate use of `== null`
"es5" : false, // true: Allow ES5 syntax (ex: getters and setters)
"esnext" : false, // true: Allow ES.next (ES6) syntax (ex: `const`)
"moz" : false, // true: Allow Mozilla specific syntax (extends and overrides esnext features)
// (ex: `for each`, multiple try/catch, function expression…)
"evil" : false, // true: Tolerate use of `eval` and `new Function()`
"expr" : false, // true: Tolerate `ExpressionStatement` as Programs
"funcscope" : false, // true: Tolerate defining variables inside control statements"
"globalstrict" : false, // true: Allow global "use strict" (also enables 'strict')
"iterator" : false, // true: Tolerate using the `__iterator__` property
"lastsemic" : false, // true: Tolerate omitting a semicolon for the last statement of a 1-line block
"laxbreak" : false, // true: Tolerate possibly unsafe line breakings
"laxcomma" : false, // true: Tolerate comma-first style coding
"loopfunc" : false, // true: Tolerate functions being defined in loops
"multistr" : false, // true: Tolerate multi-line strings
"proto" : false, // true: Tolerate using the `__proto__` property
"scripturl" : false, // true: Tolerate script-targeted URLs
"smarttabs" : false, // true: Tolerate mixed tabs/spaces when used for alignment
"shadow" : false, // true: Allows re-define variables later in code e.g. `var x=1; x=2;`
"sub" : false, // true: Tolerate using `[]` notation when it can still be expressed in dot notation
"supernew" : false, // true: Tolerate `new function () { ... };` and `new Object;`
"validthis" : false, // true: Tolerate using this in a non-constructor function

// Environments
"browser" : false, // Web Browser (window, document, etc)
"couch" : false, // CouchDB
"devel" : false, // Development/debugging (alert, confirm, etc)
"dojo" : false, // Dojo Toolkit
"jquery" : false, // jQuery
"mootools" : false, // MooTools
"node" : false, // Node.js
"nonstandard" : false, // Widely adopted globals (escape, unescape, etc)
"prototypejs" : false, // Prototype and Scriptaculous
"rhino" : false, // Rhino
"worker" : false, // Web Workers
"wsh" : false, // Windows Scripting Host
"yui" : false, // Yahoo User Interface

// Legacy
"nomen" : true, // true: Prohibit dangling `_` in variables
"onevar" : true, // true: Allow only one `var` statement per function
"passfail" : false, // true: Stop on first error
"white" : true, // true: Check against strict whitespace and indentation rules

// Custom Globals
"globals" : {} // additional predefined global variables
}
54 changes: 54 additions & 0 deletions Gruntfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/* global module */

module.exports = function (grunt) {
'use strict';
grunt.initConfig({
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'Gruntfile.js',
'angular-localize.js',
'angular-localize-spec.js'
]
},
karma: {
unit: {
options: {
files: [
'bower_components/angular/angular.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'angular-localize.js',
'bower_components/angular-mocks/angular-mocks.js',
'angular-localize-spec.js'
],
browsers: ['PhantomJS']
},
frameworks: ['jasmine'],
reporters: ['progress', 'coverage'],
preprocessors: {
'angular-localize.js': ['coverage']
},
singleRun: true
}
},
uglify: {
dist: {
options: {
sourceMap: true,
sourceMapName: 'angular-localize.min.js.map'
},
files: {
'angular-localize.min.js': ['angular-localize.js']
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-bump-build-git');
grunt.loadNpmTasks('grunt-karma');
grunt.registerTask('test', ['jshint', 'karma']);
grunt.registerTask('default', ['test', 'uglify']);
};
22 changes: 22 additions & 0 deletions LICENSE-MIT
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
Copyright (c) 2014 Sebastian Tschan

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
166 changes: 166 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
# angular-localize

> A localization module for [AngularJS](http://angularjs.org/).
## Table of contents

- [Getting started](#getting-started)
- [Module setup](#module-setup)
- [Translation functions](#translation-functions)
- [How to automatically create the translation functions](#how-to-automatically-create-the-translation-functions)
- [Usage Examples](#usage-examples)
- [localize directive](#localize-directive)
- [Localize using the element content](#localize-using-the-element-content)
- [Localize using the localize attribute](#localize-using-the-localize-attribute)
- [Localize with dynamic user data](#localize-with-dynamic-user-data)
- [localize service](#localize-service)
- [License](#license)

## Getting started

### Module setup
The easiest way to install the `localize` module is via [Bower](http://bower.io/):

```shell
bower install angular-localize --save
```

You can then include `angular-localize` after including its dependencies, [angular](https://github.com/angular/bower-angular) and [angular-sanitize](https://github.com/angular/bower-angular-sanitize):

```html
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
<script src="bower_components/angular-localize/angular-localize.js"></script>
```

### Translation functions
The `localize` module requires a map with translation functions.
By convention, this is a global object variable called `i18n`, which must be available before the Angular application is initialized:

```js
window.i18n = {
'Hello {name}!': function (data) {
return 'Hallo ' + data.name + '!';
}
};
```

The `localize` module uses this map to lookup the translation results.
If no matching translation function is found, the key is used as the translation result.

Instead of storing the translation functions in a global object, it's also possible to decorate the `i18n` service:

```js
angular.module('localize').config(['$provide', function ($provide) {
$provide.decorator('i18n', function () {
return {
'Hello {name}!': function (data) {
return 'Hallo ' + data.name + '!';
}
};
});
}]);
```

The translation functions are expected to return strings with the translation result.
An optional object with dynamic user data is passed as only argument to the translation functions.

#### How to automatically create the translation functions
[grunt-locales](https://github.com/blueimp/grunt-locales), a plugin for the [Grunt](http://gruntjs.com/) task runner, provides command-line scripts to automate the creation of the translation functions.

[grunt-locales](https://github.com/blueimp/grunt-locales) parses `localize` attributes in HTML files and collects the parsed locale strings in JSON files for translation.
The translated JSON locale files are then compiled into JavaScript files containing the map of translation functions.

To support translation features like pluralization and gender selection, [grunt-locales](https://github.com/blueimp/grunt-locales) relies on Alex Sexton's [MessageFormat](https://github.com/SlexAxton/messageformat.js) library to parse the locale strings and compile the translation functions.

## Usage Examples

### localize directive

#### Localize using the element content
Any HTML element which can contain text nodes can be localized simply by adding the `localize` attribute:

```html
<p localize>Save the Orangutans!</p>
```

If a translation function for the key `"Save the Orangutans!"` exists, the `localize` directive will replace the element content with the result of executing the function.

Localized element content can also contain HTML:

```html
<p localize>Save the <strong>Orangutans</strong>!</p>
```

In this case, the key for the translation function is `"Save the <strong>Orangutans</strong>!"`.

The result of the translation function of localizations defined via element content will always be assigned as HTML, but sanitized via [angular-sanitize](https://github.com/angular/bower-angular-sanitize).

#### Localize using the localize attribute
Instead of the element content, the localization key can also be defined as value of the `localize` attribute:

```html
<p localize="Save the Orangutans!"></p>
```

If no translation function for the key `"Save the Orangutans!"` exists, the attribute value will be used as element content.

Localizations defined via `localize` attribute cannot contain HTML tags, as the translation result will be assigned as text, not as HTML. This limitation enables a slightly faster localization, as no sanitization is required.

#### Localize with dynamic user data
It's also possible to provide dynamic user data to the translation functions.

The `localize` directive observes all non-directive `data-*` attributes and passes them as normalized map of key/value pairs to the translation function:

```html
<p data-name="{{user.name}}" localize="Hello {name}!"></p>
```

Whenever `user.name` is updated, the translation function for `"Hello {name}!"` gets called with an object, e.g. `{name: 'Bob'}` as argument and the element content is updated accordingly.

This also works with the localization key as element content, which allows the use of HTML for the translation result:

```html
<p data-name="{{user.name}}" localize>Hello <strong>{name}</strong>!</p>
```

In this case, all dynamic user data is escaped (HTML special characters are replaced with their respective HTML entity) before it is passed to the translation function.

### localize service
The `localize` service is an equivalent to the `localize` directive and can be used to generate localized results in situations where the directive cannot be used:

```js
angular.module('example')
.controller([
'$scope', 'localize',
function ($scope, localize) {
$scope.text = localize(
'Hello {name}!',
{name: $scope.user.name}
);
}
]);
```

The `localize` service expects the localization key as first argument and an optional object with user data as second argument.

If the third argument is set to `true`, the user data will be escaped (HTML special characters are replaced with their respective HTML entity), which allows to output the translation result as HTML, although it still needs to be properly sanitized depending on the security context:

```js
angular.module('example')
.controller([
'$scope', 'localize',
function ($scope, localize) {
$scope.text = localize(
'Hello <strong>{name}</strong>!',
{name: $scope.user.name},
true
);
}
]);
```

Generally, it is preferable to use the `localize` directive instead of the service, as the directive can determine its security context and because the directive strings can be automatically parsed from the HTML templates with the [grunt-locales](https://github.com/blueimp/grunt-locales) task.

## License
Released under the [MIT license](http://www.opensource.org/licenses/MIT).
Loading

0 comments on commit 10d45fe

Please sign in to comment.