Skip to content
This repository has been archived by the owner on Feb 6, 2019. It is now read-only.

Commit

Permalink
feat: support FormattedMessage intl components for namespaces (#17)
Browse files Browse the repository at this point in the history
* feat: support FormattedMessage intl components for namespaces

* nits + fix

* format
  • Loading branch information
jquense committed Oct 19, 2018
1 parent a2871b7 commit e6fba0e
Showing 1 changed file with 37 additions and 6 deletions.
43 changes: 37 additions & 6 deletions namespace-plugin.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,50 @@
const DEFINE_MESSAGES = 'defineMessages';

const COMPONENT_NAMES = ['FormattedMessage', 'FormattedHTMLMessage'];

function getPrefix(state) {
let { prefix } = state.opts;
if (!prefix.endsWith(':')) prefix = `${prefix}:`;
return prefix;
}

function referencesImport(path) {
if (!(path.isIdentifier() || path.isJSXIdentifier())) return false;
return COMPONENT_NAMES.some(name =>
path.referencesImport('react-intl', name),
);
}

module.exports = function namespacePlugin({ types: t }) {
return {
visitor: {
JSXOpeningElement(path, state) {
const name = path.get('name');
if (!referencesImport(name)) return;

const prefix = getPrefix(state);

const idAttr = path
.get('attributes')
.find(attr => attr.isJSXAttribute() && attr.node.name.name === 'id');

if (idAttr && !idAttr.node.value.value.startsWith(prefix)) {
idAttr
.get('value')
.replaceWith(
t.StringLiteral(`${prefix}{idAttr.node.value.value}`),
);
}
},

CallExpression(path, state) {
let PREFIX = state.opts.prefix;
const callee = path.get('callee').node;

if (!t.isIdentifier(callee) || callee.name !== DEFINE_MESSAGES) {
return;
}

if (!PREFIX.endsWith(':')) {
PREFIX = `${PREFIX}:`;
}
const prefix = getPrefix(state);

function processMessageObject(messageObj) {
if (!messageObj || !messageObj.isObjectExpression()) {
Expand All @@ -25,9 +56,9 @@ module.exports = function namespacePlugin({ types: t }) {
.find(p => p.get('key').node.name === 'id')
.get('value');

if (idProp && !idProp.node.value.startsWith(PREFIX)) {
if (idProp && !idProp.node.value.startsWith(prefix)) {
idProp.replaceWith(
t.StringLiteral(PREFIX + idProp.node.value), // eslint-disable-line new-cap
t.StringLiteral(`${prefix}{idProp.node.value}`), // eslint-disable-line new-cap
);
}
}
Expand Down

0 comments on commit e6fba0e

Please sign in to comment.