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 47a773d
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 7 deletions.
4 changes: 2 additions & 2 deletions fluent-react/src/localization.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,11 @@ 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) {
return id;
return fallback || id;
}

const msg = mcx.getMessage(id);
Expand Down
6 changes: 3 additions & 3 deletions fluent-react/src/with_localization.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ 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) {
return id;
return fallback || 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 47a773d

Please sign in to comment.