eslint-plugin-primer-react 6.0.0-rc.ad9e155 → 6.0.1-rc.684a5eb

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,15 +1,27 @@
1
1
  # eslint-plugin-primer-react
2
2
 
3
+ ## 6.0.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [#216](https://github.com/primer/eslint-plugin-primer-react/pull/216) [`55c5256`](https://github.com/primer/eslint-plugin-primer-react/commit/55c52562bc66fd661a5f0ef8218b90bf900411a4) Thanks [@iansan5653](https://github.com/iansan5653)! - Fix invalid rule names
8
+
3
9
  ## 6.0.0
4
10
 
5
11
  ### Major Changes
6
12
 
7
13
  - [#207](https://github.com/primer/eslint-plugin-primer-react/pull/207) [`baff792`](https://github.com/primer/eslint-plugin-primer-react/commit/baff792c0aa01a29374e44e8aa770dbe2cb889a1) Thanks [@iansan5653](https://github.com/iansan5653)! - [Breaking] Adds `no-unnecessary-components` lint rule and enables it by default. This may raise new (typically autofixable) lint errors in existing codebases.
8
14
 
15
+ - [#211](https://github.com/primer/eslint-plugin-primer-react/pull/211) [`3f92cd4`](https://github.com/primer/eslint-plugin-primer-react/commit/3f92cd4b689e437bb9efe6a9fe873501ddf76bf2) Thanks [@camchenry](https://github.com/camchenry)! - [Breaking] Adds `prefer-action-list-item-onselect` lint rule and enables it by default. This may raise new auto-fixable lint errors or type-checking errors in existing codebases.
16
+
9
17
  ### Minor Changes
10
18
 
11
19
  - [#204](https://github.com/primer/eslint-plugin-primer-react/pull/204) [`e2cab87`](https://github.com/primer/eslint-plugin-primer-react/commit/e2cab872c265f4211750436fad32fe5fd8927c5c) Thanks [@joshblack](https://github.com/joshblack)! - Add use-deprecated-from-deprecated rule
12
20
 
21
+ ### Patch Changes
22
+
23
+ - [#212](https://github.com/primer/eslint-plugin-primer-react/pull/212) [`78d4600`](https://github.com/primer/eslint-plugin-primer-react/commit/78d460024ae4c10b6a754b615c6d594e4dfb646e) Thanks [@langermank](https://github.com/langermank)! - no-system-props: Add `padding` and `gap` as exceptions for `Stack`
24
+
13
25
  ## 5.4.0
14
26
 
15
27
  ### Minor Changes
@@ -0,0 +1,37 @@
1
+ # Prefer using `onSelect` instead of `onClick` for `ActionList.Item` components (`prefer-action-list-item-onselect`)
2
+
3
+ 🔧 The `--fix` option on the [ESLint CLI](https://eslint.org/docs/user-guide/command-line-interface#fixing-problems) can automatically fix some of the problems reported by this rule.
4
+
5
+ ## Rule details
6
+
7
+ When using the `onClick` attribute on `ActionList.Item` components, this callback only fires when a user clicks on the element with a mouse. If the user navigates to the element with a keyboard and presses the `Enter` key, the callback will not fire. This produces an inaccessible experience for keyboard users.
8
+
9
+ Using `onSelect` will lead to a more accessible experience for keyboard users compared to using `onClick`.
10
+
11
+ This rule is generally auto-fixable, though you may encounter type checking errors that result from not properly handling keyboard events which are not part of the `onSelect` callback signature.
12
+
13
+ 👎 Examples of **incorrect** code for this rule:
14
+
15
+ ```jsx
16
+ <ActionList.Item onClick={handleClick} />
17
+ <ActionList.Item
18
+ aria-label="Edit item 1"
19
+ onClick={(event) => {
20
+ event.preventDefault()
21
+ handleClick()
22
+ }}
23
+ />
24
+ ```
25
+
26
+ 👍 Examples of **correct** code for this rule:
27
+
28
+ ```jsx
29
+ <ActionList.Item onSelect={handleClick} />
30
+ <ActionList.Item
31
+ aria-label="Edit item 1"
32
+ onSelect={(event) => {
33
+ event.preventDefault()
34
+ handleClick()
35
+ }}
36
+ />
37
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-primer-react",
3
- "version": "6.0.0-rc.ad9e155",
3
+ "version": "6.0.1-rc.684a5eb",
4
4
  "description": "ESLint rules for Primer React",
5
5
  "main": "src/index.js",
6
6
  "scripts": {
@@ -19,6 +19,7 @@ module.exports = {
19
19
  'primer-react/a11y-remove-disable-tooltip': 'error',
20
20
  'primer-react/a11y-use-next-tooltip': 'error',
21
21
  'primer-react/no-unnecessary-components': 'error',
22
+ 'primer-react/prefer-action-list-item-onselect': 'error',
22
23
  },
23
24
  settings: {
24
25
  github: {
package/src/index.js CHANGED
@@ -11,7 +11,8 @@ module.exports = {
11
11
  'a11y-remove-disable-tooltip': require('./rules/a11y-remove-disable-tooltip'),
12
12
  'a11y-use-next-tooltip': require('./rules/a11y-use-next-tooltip'),
13
13
  'use-deprecated-from-deprecated': require('./rules/use-deprecated-from-deprecated'),
14
- 'primer-react/no-unnecessary-components': require('./rules/no-unnecessary-components'),
14
+ 'no-unnecessary-components': require('./rules/no-unnecessary-components'),
15
+ 'prefer-action-list-item-onselect': require('./rules/prefer-action-list-item-onselect'),
15
16
  },
16
17
  configs: {
17
18
  recommended: require('./configs/recommended'),
@@ -65,6 +65,16 @@ ruleTester.run('unnecessary-components', rule, {
65
65
  filename,
66
66
  },
67
67
  ]),
68
+ {
69
+ name: `Text with weight prop`,
70
+ code: `${prcImport}${jsx(`<Text weight='medium'>Hello World</Text>`)}`,
71
+ filename,
72
+ },
73
+ {
74
+ name: `Text with size prop`,
75
+ code: `${prcImport}${jsx(`<Text size='small'>Hello World</Text>`)}`,
76
+ filename,
77
+ },
68
78
  ],
69
79
  invalid: Object.entries(components).flatMap(([component, {messageId, replacement}]) => [
70
80
  {
@@ -0,0 +1,67 @@
1
+ const {RuleTester} = require('@typescript-eslint/rule-tester')
2
+ const rule = require('../prefer-action-list-item-onselect')
3
+
4
+ const ruleTester = new RuleTester({
5
+ parser: require.resolve('@typescript-eslint/parser'),
6
+ parserOptions: {
7
+ ecmaVersion: 2018,
8
+ sourceType: 'module',
9
+ ecmaFeatures: {
10
+ jsx: true,
11
+ },
12
+ },
13
+ })
14
+
15
+ ruleTester.run('prefer-action-list-item-onselect', rule, {
16
+ valid: [
17
+ {code: `<ActionList.Item onSelect={() => console.log(1)} />`},
18
+ {code: `<ActionList.Item onSelect={() => console.log(1)} onClick={() => console.log(1)} />`},
19
+ {code: `<Other onClick={() => console.log(1)} />`},
20
+ {code: `<Button onClick={onSelect} />`},
21
+ {code: `<Button onSelect={onClick} />`},
22
+ {code: `<ActionList.Item onClick={() => console.log(1)} onKeyDown={() => console.log(1)} />`},
23
+ {code: `<ActionList.Item onClick={() => console.log(1)} onKeyUp={() => console.log(1)} />`},
24
+ // For now, we are not handling spread attributes as this is much less common
25
+ {code: `<ActionList.Item {...onClick} />`},
26
+ ],
27
+ invalid: [
28
+ {
29
+ code: `<ActionList.Item onClick={() => console.log(1)} />`,
30
+ errors: [{messageId: 'prefer-action-list-item-onselect'}],
31
+ output: `<ActionList.Item onSelect={() => console.log(1)} />`,
32
+ },
33
+ {
34
+ code: `<ActionList.Item aria-label="Edit item 1" onClick={() => console.log(1)} />`,
35
+ errors: [{messageId: 'prefer-action-list-item-onselect'}],
36
+ output: `<ActionList.Item aria-label="Edit item 1" onSelect={() => console.log(1)} />`,
37
+ },
38
+ {
39
+ code: `<ActionList.Item aria-label="Edit item 1" onClick={onClick} />`,
40
+ errors: [{messageId: 'prefer-action-list-item-onselect'}],
41
+ output: `<ActionList.Item aria-label="Edit item 1" onSelect={onClick} />`,
42
+ },
43
+ {
44
+ code: `<ActionList.Item
45
+ aria-label="Edit item 1"
46
+ onClick={(event) => {
47
+ event.preventDefault()
48
+ handleClick()
49
+ }}
50
+ />`,
51
+ errors: [{messageId: 'prefer-action-list-item-onselect'}],
52
+ output: `<ActionList.Item
53
+ aria-label="Edit item 1"
54
+ onSelect={(event) => {
55
+ event.preventDefault()
56
+ handleClick()
57
+ }}
58
+ />`,
59
+ },
60
+ // This is invalid, but we can fix it anyway
61
+ {
62
+ code: `<ActionList.Item aria-label="Edit item 1" onClick />`,
63
+ errors: [{messageId: 'prefer-action-list-item-onselect'}],
64
+ output: `<ActionList.Item aria-label="Edit item 1" onSelect />`,
65
+ },
66
+ ],
67
+ })
@@ -46,6 +46,7 @@ const excludedComponentProps = new Map([
46
46
  ['ProgressBar', new Set(['bg'])],
47
47
  ['PointerBox', new Set(['bg'])],
48
48
  ['Truncate', new Set(['maxWidth'])],
49
+ ['Stack', new Set(['padding', 'gap'])],
49
50
  ])
50
51
 
51
52
  const alwaysExcludedProps = new Set(['variant', 'size'])
@@ -12,11 +12,13 @@ const components = {
12
12
  replacement: 'div',
13
13
  messageId: 'unecessaryBox',
14
14
  message: 'Prefer plain HTML elements over `Box` when not using `sx` for styling.',
15
+ allowedProps: new Set(['sx']), // + styled-system props
15
16
  },
16
17
  Text: {
17
18
  replacement: 'span',
18
19
  messageId: 'unecessarySpan',
19
20
  message: 'Prefer plain HTML elements over `Text` when not using `sx` for styling.',
21
+ allowedProps: new Set(['sx', 'size', 'weight']), // + styled-system props
20
22
  },
21
23
  }
22
24
 
@@ -68,33 +70,36 @@ const rule = ESLintUtils.RuleCreator.withoutDocs({
68
70
  const isPrimer = skipImportCheck || isPrimerComponent(name, context.sourceCode.getScope(openingElement))
69
71
  if (!isPrimer) return
70
72
 
71
- // Validate the attributes and ensure an `sx` prop is present or spreaded in
73
+ /** @param {string} name */
74
+ const isAllowedProp = name => componentConfig.allowedProps.has(name) || isStyledSystemProp(name)
75
+
76
+ // Validate the attributes and ensure an allowed prop is present or spreaded in
72
77
  /** @type {typeof attributes[number] | undefined | null} */
73
78
  let asProp = undefined
74
79
  for (const attribute of attributes) {
75
- // If there is a spread type, check if the type of the spreaded value has an `sx` property
80
+ // If there is a spread type, check if the type of the spreaded value has an allowed property
76
81
  if (attribute.type === 'JSXSpreadAttribute') {
77
82
  const services = ESLintUtils.getParserServices(context)
78
83
  const typeChecker = services.program.getTypeChecker()
79
84
 
80
85
  const spreadType = services.getTypeAtLocation(attribute.argument)
81
- if (typeChecker.getPropertyOfType(spreadType, 'sx') !== undefined) return
82
86
 
83
- // Check if the spread type has a string index signature - this could hide an `sx` property
87
+ // Check if the spread type has a string index signature - this could hide an allowed property
84
88
  if (typeChecker.getIndexTypeOfType(spreadType, IndexKind.String) !== undefined) return
85
89
 
90
+ const spreadPropNames = typeChecker.getPropertiesOfType(spreadType).map(prop => prop.getName())
91
+
92
+ // If an allowed prop gets spread in, this is a valid use of the component
93
+ if (spreadPropNames.some(isAllowedProp)) return
94
+
86
95
  // If there is an `as` inside the spread object, we can't autofix reliably
87
- if (typeChecker.getPropertyOfType(spreadType, 'as') !== undefined) asProp = null
96
+ if (spreadPropNames.includes('as')) asProp = null
88
97
 
89
98
  continue
90
99
  }
91
100
 
92
- // Has sx prop, so should keep using this component
93
- if (
94
- attribute.name.type === 'JSXIdentifier' &&
95
- (attribute.name.name === 'sx' || isStyledSystemProp(attribute.name.name))
96
- )
97
- return
101
+ // Has an allowed prop, so should keep using this component
102
+ if (attribute.name.type === 'JSXIdentifier' && isAllowedProp(attribute.name.name)) return
98
103
 
99
104
  // If there is an `as` prop we will need to account for that when autofixing
100
105
  if (attribute.name.type === 'JSXIdentifier' && attribute.name.name === 'as') asProp = attribute
@@ -0,0 +1,67 @@
1
+ // @ts-check
2
+
3
+ const messages = {
4
+ 'prefer-action-list-item-onselect': `Use the 'onSelect' event handler instead of 'onClick' for ActionList.Item components, so that it is accessible by keyboard and mouse.`,
5
+ }
6
+
7
+ /** @type {import('@typescript-eslint/utils/ts-eslint').RuleModule<keyof typeof messages>} */
8
+ module.exports = {
9
+ meta: {
10
+ docs: {
11
+ description:
12
+ 'To do something when an `ActionList.Item` is selected, you should use the `onSelect` event handler instead of `onClick`, because it handles both keyboard and mouse events. Otherwise, it will only be accessible by mouse.',
13
+ recommended: true,
14
+ },
15
+ messages,
16
+ type: 'problem',
17
+ schema: [],
18
+ fixable: 'code',
19
+ },
20
+ defaultOptions: [],
21
+ create(context) {
22
+ return {
23
+ JSXElement(node) {
24
+ // Only check components that have the name `ActionList.Item`. We don't check if this comes from Primer
25
+ // because the chance of conflict here is very low
26
+ const isActionListItem =
27
+ node.openingElement.name.type === 'JSXMemberExpression' &&
28
+ node.openingElement.name.object.type === 'JSXIdentifier' &&
29
+ node.openingElement.name.object.name === 'ActionList' &&
30
+ node.openingElement.name.property.name === 'Item'
31
+ if (!isActionListItem) return
32
+
33
+ const attributes = node.openingElement.attributes
34
+ const onClickAttribute = attributes.find(attr => attr.type === 'JSXAttribute' && attr.name.name === 'onClick')
35
+ const onSelectAttribute = attributes.find(attr => attr.type === 'JSXAttribute' && attr.name.name === 'onSelect')
36
+
37
+ const keyboardHandlers = ['onKeyDown', 'onKeyUp']
38
+ const keyboardAttributes = attributes.filter(
39
+ attr =>
40
+ attr.type === 'JSXAttribute' &&
41
+ (typeof attr.name.name === 'string'
42
+ ? keyboardHandlers.includes(attr.name.name)
43
+ : keyboardHandlers.includes(attr.name.name.name)),
44
+ )
45
+
46
+ // If the component has `onSelect`, then it's already using the correct event
47
+ if (onSelectAttribute) return
48
+ // If there is no `onClick` attribute, then we should also be fine
49
+ if (!onClickAttribute) return
50
+ // If there is an onClick attribute as well as keyboard handlers, we will assume it is handled correctly
51
+ if (onClickAttribute && keyboardAttributes.length > 0) return
52
+
53
+ context.report({
54
+ node: onClickAttribute,
55
+ messageId: 'prefer-action-list-item-onselect',
56
+ fix: fixer => {
57
+ // Replace `onClick` with `onSelect`
58
+ if (onClickAttribute.type === 'JSXAttribute') {
59
+ return fixer.replaceText(onClickAttribute.name, 'onSelect')
60
+ }
61
+ return null
62
+ },
63
+ })
64
+ },
65
+ }
66
+ },
67
+ }