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

feat: support FormattedMessage intl components for namespaces #17

Merged
merged 3 commits into from
Oct 19, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this previously wasn't returning

}

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