Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Docusaurus ESLint plugin to enforce best Docusaurus practices #7206

Merged
merged 21 commits into from Apr 29, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
10 changes: 10 additions & 0 deletions packages/eslint-plugin/.eslintrc.js
@@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

module.exports = {
extends: ['../../.eslintrc.js', 'plugin:eslint-plugin/recommended'],
};
Josh-Cena marked this conversation as resolved.
Show resolved Hide resolved
56 changes: 56 additions & 0 deletions packages/eslint-plugin/README.md
@@ -0,0 +1,56 @@
# `@docusaurus/eslint-plugin`

Docusaurus specific linting rules for eslint

## Installation

You'll first need to install [ESLint](https://eslint.org/):

```sh
npm i -D eslint
```

Next, install `@docusaurus/eslint-plugin`:

```sh
npm i -D @docusaurus/eslint-plugin
```

## Usage

Add `@docusaurus` to the plugins section of your `.eslintrc` configuration file:

```json
{
"plugins": ["@docusaurus"]
}
```

Then, you can extend one of the configs (e.g. the `recommended` config):

```json
{
"extends": ["plugin:@docusaurus/recommended"]
}
```

For more fine-grained control, you can also configure the rules you want to use:

```json
{
"rules": {
"@docusaurus/no-dynamic-i18n-messages": "error",
"@docusaurus/no-untranslated-text": "warn"
}
}
```

## Supported Configs

- recommended
- all

## Supported Rules

- no-dynamic-i18n-messages
- no-untranslated-text
42 changes: 42 additions & 0 deletions packages/eslint-plugin/docs/rules/no-dynamic-i18n-messages.md
@@ -0,0 +1,42 @@
# enforce translate calls to be plain text labels (no-dynamic-i18n-messages)
Josh-Cena marked this conversation as resolved.
Show resolved Hide resolved

Ensures that `<Translate>` children and the message attribute of `translate` function calls are hardcoded strings.

This is to ensure that static extraction of the text will work so it can be translatable. In-string dynamic placeholders are also possible using the values object.

## Rule Details

Examples of **incorrect** code for this rule:

```js
const text = 'Some text to be translated'

// Invalid <Translate> child
<Translate>{text}</Translate>

// Invalid message attribute
translate({message: text})
```

Examples of **correct** code for this rule:

```js
// Valid <Translate> child
<Translate>Some text to be translated</Translate>

// Valid message attribute
translate({message: 'Some text to be translated'})

// Valid <Translate> child using values object as prop
<Translate values={{firstName: 'Sébastien'}}>
{'Welcome, {firstName}! How are you?'}
</Translate>

// Valid message attribute using values object as second argument
translate({message: 'The logo of site {siteName}'}, {siteName: 'Docusaurus'})
```

## Further Reading

- https://docusaurus.io/docs/docusaurus-core#translate
- https://docusaurus.io/docs/docusaurus-core#translate-1
32 changes: 32 additions & 0 deletions packages/eslint-plugin/docs/rules/no-untranslated-text.md
@@ -0,0 +1,32 @@
# enforce text labels in JSX to be wrapped by translate calls (no-untranslated-text)

Ensures that all text labels in JSX are wrapped by `<Translate>` components.

When the [i18n feature](https://docusaurus.io/docs/i18n/introduction) is used, this rule is to ensure that all strings appearing on the website are being translated, so no string accidentally slips through untranslated.

## Rule Details

Examples of **incorrect** code for this rule:

```js
// Hello World is not translated
<Component>Hello World</Component>
```

Examples of **correct** code for this rule:

```js
// Hello World is translated
<Component>
<Translate>Hello World</Translate>
</Component>
```

## When Not To Use It

If you're not using the [i18n feature](https://docusaurus.io/docs/i18n/introduction) then you can disable this rule.

## Further Reading

- https://docusaurus.io/docs/docusaurus-core#translate
- https://docusaurus.io/docs/docusaurus-core#translate-1
25 changes: 25 additions & 0 deletions packages/eslint-plugin/lib/index.js
@@ -0,0 +1,25 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

const requireIndex = require('requireindex');

module.exports = {
rules: requireIndex(`${__dirname}/rules`),
configs: {
recommended: {
rules: {
'docusaurus/no-dynamic-i18n-messages': 'error',
},
},
all: {
rules: {
'docusaurus/no-dynamic-i18n-messages': 'error',
'docusaurus/no-untranslated-text': 'warn',
},
},
},
};
@@ -0,0 +1,84 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

const rule = require('../no-dynamic-i18n-messages');
const {RuleTester} = require('eslint');
const {getCommonValidTests} = require('../../util');

const errorsJSX = [{messageId: 'translateChildren', type: 'JSXElement'}];
const errorsFunc = [{messageId: 'translateArg', type: 'Identifier'}];

const ruleTester = new RuleTester({
parserOptions: {
ecmaVersion: 2022,
ecmaFeatures: {jsx: true},
},
});
ruleTester.run('no-dynamic-i18n-messages', rule, {
valid: [
...getCommonValidTests(),
{
code: `<Translate
id="homepage.title"
description="The homepage welcome message">
Welcome to my website
</Translate>`,
},
{
code: `<Translate
values={{firstName: 'Sébastien'}}>
{'Welcome, {firstName}! How are you?'}
</Translate>`,
},
{
code: `<Translate>{'This'} is {\`valid\`}</Translate>`,
},
{
code: "translate({message: 'My page meta title'})",
},
{
code: "translate({message: 'The logo of site {siteName}'}, {siteName: 'Docusaurus'})",
},
{
code: 'translate({otherProp: metaTitle})',
},
{
code: 'translate({otherProp: `My page meta title`})',
},
],

invalid: [
{
code: '<Translate>{text}</Translate>',
errors: errorsJSX,
},
{
code: '<Translate>Hi {text} my friend</Translate>',
errors: errorsJSX,
},
{
code: '<Translate> {text} </Translate>',
errors: errorsJSX,
},
{
code: '<Translate>`{text}`</Translate>',
errors: errorsJSX,
},
{
code: '<Translate>{`${text}`}</Translate>',
errors: errorsJSX,
},
{
code: 'translate({message: metaTitle})',
errors: errorsFunc,
},
{
code: 'translate({message: `My page meta title`})',
errors: errorsFunc,
},
],
});
@@ -0,0 +1,64 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

const rule = require('../no-untranslated-text');
const {RuleTester} = require('eslint');
const {getCommonValidTests} = require('../../util');

const errorsJSX = [{messageId: 'translateChildren', type: 'JSXElement'}];
const errorsJSXFragment = [
{messageId: 'translateChildren', type: 'JSXFragment'},
];

const ruleTester = new RuleTester({
parserOptions: {
ecmaVersion: 2022,
ecmaFeatures: {jsx: true},
},
});
ruleTester.run('no-untranslated-text', rule, {
valid: [...getCommonValidTests()],

invalid: [
{
code: '<Component>text</Component>',
errors: errorsJSX,
},
{
code: '<Component> text </Component>',
errors: errorsJSX,
},
{
code: '<Component>"text"</Component>',
errors: errorsJSX,
},
{
code: "<Component>'text'</Component>",
errors: errorsJSX,
},
{
code: '<Component>`text`</Component>',
errors: errorsJSX,
},
{
code: '<Component>{"text"}</Component>',
errors: errorsJSX,
},
{
code: "<Component>{'text'}</Component>",
errors: errorsJSX,
},
{
code: '<Component>{`text`}</Component>',
errors: errorsJSX,
},
{
code: '<>text</>',
errors: errorsJSXFragment,
},
],
});
61 changes: 61 additions & 0 deletions packages/eslint-plugin/lib/rules/no-dynamic-i18n-messages.js
@@ -0,0 +1,61 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

const {isTextLabelChild, report} = require('../util');

/**
* @type {import('eslint').Rule.RuleModule}
*/
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'enforce translate calls to be plain text labels',
category: 'Possible Problems',
url: 'https://github.com/facebook/docusaurus/tree/main/packages/eslint-plugin/docs/rules/no-dynamic-i18n-messages.md',
},
schema: [],
messages: {
translateChildren:
'<Translate> children must be hardcoded strings. You can have in-string dynamic placeholders using the values prop.',
translateArg:
'translation message must be a hardcoded string. You can have in-string dynamic placeholders using the values argument.',
},
},

create(context) {
const isMessageTypeValid = (type) => type === 'Literal';

const isNodeValid = (node) =>
node.children.every((child) => isTextLabelChild({child}));
Copy link
Collaborator

Choose a reason for hiding this comment

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

It would be useful to add an option ignoreJSXAttributes. We may want to flag <div aria-label="untranslated" /> as well. Doesn't have to be in this PR though

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I didn't understand that, could you provide an example usage of ignoreJSXAttributes ? Also what is the purpose of <div aria-label="untranslated" /> ? Self-closing tags do not have children (excluding the children prop) therefore the current rules do not apply in this case, right ?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Oh, sorry, wrong comment place. I was talking about no-untranslated-text. There should be an option that turns on warning for JSX attributes like aria-label as well, not just string literal children.


return {
"JSXElement[openingElement.name.name='Translate']": (node) => {
Copy link
Collaborator

@Josh-Cena Josh-Cena Apr 19, 2022

Choose a reason for hiding this comment

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

I think this is fine for now, but in the long term, we may need to first check the imported name because it may not be imported as Translate (cf our translationExtractor implementation). I'm not aware if we can let ESLint do a two-round traverse in an efficient way—I think people usually use Program:exit?

if (!isNodeValid(node)) {
report(context, node, 'translateChildren');
}
},
"CallExpression > Identifier[name='translate']": (node) => {
const messageProperty = node.parent.arguments[0].properties.find(
(property) => property.key.name === 'message',
);
if (!messageProperty) {
return;
}

const messageType = messageProperty.value.type;
if (!messageType) {
return;
}

if (!isMessageTypeValid(messageType)) {
report(context, node, 'translateArg');
}
},
};
},
};