Permalink
Browse files

Added a very simple inline-l10n module.

  • Loading branch information...
1 parent 15ab560 commit b7b997160cc08d3dd050099ce81e5b6218bbe87a @toolness committed Dec 4, 2012
Showing with 68 additions and 0 deletions.
  1. +26 −0 js/inline-l10n.js
  2. +1 −0 test/all-tests.js
  3. +41 −0 test/test-inline-l10n.js
View
@@ -0,0 +1,26 @@
+define(function() {
+ var L10N_RE = /L10N(?:\:([a-z\-]+))?\[\[\[([\s\S]+?)\]\]\]/g;
+
+ var InlineL10n = function InlineL10n(str, l10n) {
+ return str.replace(L10N_RE, function(match, key, value) {
+ if (!key)
+ key = value;
+ if (key in l10n)
+ return l10n[key];
+ return value;
+ });
+ return str;
+ };
+
+ InlineL10n.parse = function InlineL10n_parse(str) {
+ var defaultValues = {};
+ str.replace(L10N_RE, function(match, key, value) {
+ if (!key)
+ key = value;
+ defaultValues[key] = value;
+ });
+ return defaultValues;
+ };
+
+ return InlineL10n;
+});
View
@@ -1,5 +1,6 @@
defineTests.combine([
"test/test-app",
+ "test/test-inline-l10n",
"test/test-help",
"test/test-templates",
"test/test-indexable-codemirror",
View
@@ -0,0 +1,41 @@
+defineTests(["inline-l10n"], function(InlineL10n) {
+ module("inline-l10n");
+
+ test("named key replaces default value", function() {
+ equal(InlineL10n("L10N:meh[[[hello]]] there", {
+ meh: "bonjour"
+ }), "bonjour there");
+ });
+
+ test("default value used when named key unavailable", function() {
+ equal(InlineL10n("L10N:meh[[[hello]]] there", {}), "hello there");
+ });
+
+ test("key name defaults to default value", function() {
+ equal(InlineL10n("L10N[[[hello]]] there", {
+ hello: 'bonjour'
+ }), "bonjour there");
+ });
+
+ test("L10N accepts newlines inside default value", function() {
+ equal(InlineL10n("L10N:meh[[[hel\nlo]]] there", {
+ meh: "bonjour"
+ }), "bonjour there");
+ });
+
+ test("multiple occurrences of L10N expressions work", function() {
+ equal(InlineL10n("L10N:meh[[[hi]]] there L10N[[[u]]]", {
+ meh: "bonjour",
+ u: "nom"
+ }), "bonjour there nom");
+ });
+
+ test("parse() returns mapping of keys to default values", function() {
+ deepEqual(InlineL10n.parse("L10N[[[hello]]] there"), {
+ hello: 'hello'
+ }, "works w/ unnamed keys");
+ deepEqual(InlineL10n.parse("L10N:meh[[[hello]]] there"), {
+ meh: 'hello'
+ }, "works w/ named keys");
+ });
+});

0 comments on commit b7b9971

Please sign in to comment.