Skip to content

Commit

Permalink
add(getString): add third argument to getString for fallback message
Browse files Browse the repository at this point in the history
  • Loading branch information
hkasemir committed Feb 6, 2018
1 parent f676215 commit 402d83c
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 5 deletions.
5 changes: 4 additions & 1 deletion fluent-react/src/localization.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,13 @@ export default class ReactLocalization {
/*
* Find a translation by `id` and format it to a string using `args`.
*/
getString(id, args) {
getString(id, args, fallback) {
const mcx = this.getMessageContext(id);

if (mcx === null) {
if (fallback) {
return fallback;
}
return id;
}

Expand Down
7 changes: 5 additions & 2 deletions fluent-react/src/with_localization.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,17 @@ export default function withLocalization(Inner) {
/*
* Find a translation by `id` and format it to a string using `args`.
*/
getString(id, args) {
getString(id, args, fallback) {
const { l10n } = this.context;

if (!l10n) {
if (fallback) {
return fallback;
}
return id;
}

return l10n.getString(id, args);
return l10n.getString(id, args, fallback);
}

render() {
Expand Down
41 changes: 39 additions & 2 deletions fluent-react/test/with_localization_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,26 @@ foo = FOO

const getString = wrapper.prop('getString');
// Returns the translation.
assert.equal(getString('foo'), 'FOO');
assert.equal(getString('foo', {}), 'FOO');
});

test('getString with access to the l10n context, with fallback value', function() {
const mcx = new MessageContext();
const l10n = new ReactLocalization([mcx]);
const EnhancedComponent = withLocalization(DummyComponent);

mcx.addMessages(`
foo = FOO
`);

const wrapper = shallow(
<EnhancedComponent />,
{ context: { l10n } }
);

const getString = wrapper.prop('getString');
// Returns the translation, even if fallback value provided.
assert.equal(getString('bar', {}, 'fallback'), 'fallback');
});

test('getString without access to the l10n context', function() {
Expand All @@ -63,7 +82,25 @@ foo = FOO
);

const getString = wrapper.prop('getString');
// Returns the id.
// Returns the id if no fallback.
assert.equal(getString('foo', {arg: 1}), 'foo');
});

test('getString without access to the l10n context, with fallback value', function() {
const mcx = new MessageContext();
const l10n = new ReactLocalization([mcx]);
const EnhancedComponent = withLocalization(DummyComponent);

mcx.addMessages(`
foo = FOO
`);

const wrapper = shallow(
<EnhancedComponent />
);

const getString = wrapper.prop('getString');
// Returns the fallback if provided.
assert.equal(getString('foo', {arg: 1}, 'fallback message'), 'fallback message');
});
});

0 comments on commit 402d83c

Please sign in to comment.