prefer-dom-node-dataset.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. const isValidVariableName = require('./utils/is-valid-variable-name.js');
  3. const quoteString = require('./utils/quote-string.js');
  4. const {methodCallSelector} = require('./selectors/index.js');
  5. const MESSAGE_ID = 'prefer-dom-node-dataset';
  6. const messages = {
  7. [MESSAGE_ID]: 'Prefer `.dataset` over `setAttribute(…)`.',
  8. };
  9. const selector = [
  10. methodCallSelector({
  11. method: 'setAttribute',
  12. argumentsLength: 2,
  13. }),
  14. '[arguments.0.type="Literal"]',
  15. ].join('');
  16. const parseNodeText = (context, argument) => context.getSourceCode().getText(argument);
  17. const dashToCamelCase = string => string.replace(/-[a-z]/g, s => s[1].toUpperCase());
  18. const fix = (context, node, fixer) => {
  19. const [nameNode, valueNode] = node.arguments;
  20. const calleeObject = parseNodeText(context, node.callee.object);
  21. const name = dashToCamelCase(nameNode.value.slice(5));
  22. const value = parseNodeText(context, valueNode);
  23. const replacement = `${calleeObject}.dataset${
  24. isValidVariableName(name)
  25. ? `.${name}`
  26. : `[${quoteString(name, nameNode.raw.charAt(0))}]`
  27. } = ${value}`;
  28. return fixer.replaceText(node, replacement);
  29. };
  30. /** @param {import('eslint').Rule.RuleContext} context */
  31. const create = context => ({
  32. [selector](node) {
  33. const name = node.arguments[0].value;
  34. if (typeof name !== 'string' || !name.startsWith('data-') || name === 'data-') {
  35. return;
  36. }
  37. return {
  38. node,
  39. messageId: MESSAGE_ID,
  40. fix: fixer => fix(context, node, fixer),
  41. };
  42. },
  43. });
  44. /** @type {import('eslint').Rule.RuleModule} */
  45. module.exports = {
  46. create,
  47. meta: {
  48. type: 'suggestion',
  49. docs: {
  50. description: 'Prefer using `.dataset` on DOM elements over `.setAttribute(…)`.',
  51. },
  52. fixable: 'code',
  53. messages,
  54. },
  55. };