index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. 'use strict';
  2. const declarationValueIndex = require('../../utils/declarationValueIndex');
  3. const findNotContiguousOrRectangular = require('./utils/findNotContiguousOrRectangular');
  4. const isRectangular = require('./utils/isRectangular');
  5. const report = require('../../utils/report');
  6. const ruleMessages = require('../../utils/ruleMessages');
  7. const validateOptions = require('../../utils/validateOptions');
  8. const valueParser = require('postcss-value-parser');
  9. const ruleName = 'named-grid-areas-no-invalid';
  10. const messages = ruleMessages(ruleName, {
  11. expectedToken: () => 'Expected cell token within string',
  12. expectedSameNumber: () => 'Expected same number of cell tokens in each string',
  13. expectedRectangle: (name) => `Expected single filled-in rectangle for "${name}"`,
  14. });
  15. const meta = {
  16. url: 'https://stylelint.io/user-guide/rules/list/named-grid-areas-no-invalid',
  17. };
  18. /** @type {import('stylelint').Rule} */
  19. const rule = (primary) => {
  20. return (root, result) => {
  21. const validOptions = validateOptions(result, ruleName, { actual: primary });
  22. if (!validOptions) {
  23. return;
  24. }
  25. root.walkDecls(/^(?:grid|grid-template|grid-template-areas)$/i, (decl) => {
  26. const { value } = decl;
  27. if (value.toLowerCase().trim() === 'none') return;
  28. /** @type {string[][]} */
  29. const areas = [];
  30. let reportSent = false;
  31. valueParser(value).walk(({ sourceIndex, type, value: tokenValue }) => {
  32. if (type !== 'string') return;
  33. if (tokenValue === '') {
  34. complain(messages.expectedToken(), sourceIndex);
  35. reportSent = true;
  36. return;
  37. }
  38. areas.push(
  39. tokenValue
  40. .trim()
  41. .split(' ')
  42. .filter((s) => s.length > 0),
  43. );
  44. });
  45. if (reportSent) return;
  46. if (!isRectangular(areas)) {
  47. complain(messages.expectedSameNumber());
  48. return;
  49. }
  50. const notContiguousOrRectangular = findNotContiguousOrRectangular(areas);
  51. for (const name of notContiguousOrRectangular.sort()) {
  52. complain(messages.expectedRectangle(name));
  53. }
  54. /**
  55. * @param {string} message
  56. * @param {number} [sourceIndex=0]
  57. */
  58. function complain(message, sourceIndex = 0) {
  59. report({
  60. message,
  61. node: decl,
  62. index: declarationValueIndex(decl) + sourceIndex,
  63. result,
  64. ruleName,
  65. });
  66. }
  67. });
  68. };
  69. };
  70. rule.ruleName = ruleName;
  71. rule.messages = messages;
  72. rule.meta = meta;
  73. module.exports = rule;