index.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. 'use strict';
  2. const findFontFamily = require('../../utils/findFontFamily');
  3. const isStandardSyntaxValue = require('../../utils/isStandardSyntaxValue');
  4. const isVariable = require('../../utils/isVariable');
  5. const { fontFamilyKeywords } = require('../../reference/keywords');
  6. const report = require('../../utils/report');
  7. const ruleMessages = require('../../utils/ruleMessages');
  8. const validateOptions = require('../../utils/validateOptions');
  9. const ruleName = 'font-family-name-quotes';
  10. const messages = ruleMessages(ruleName, {
  11. expected: (family) => `Expected quotes around "${family}"`,
  12. rejected: (family) => `Unexpected quotes around "${family}"`,
  13. });
  14. const meta = {
  15. url: 'https://stylelint.io/user-guide/rules/font-family-name-quotes',
  16. fixable: true,
  17. };
  18. /**
  19. * @param {string} font
  20. * @returns {boolean}
  21. */
  22. function isSystemFontKeyword(font) {
  23. if (font.startsWith('-apple-')) {
  24. return true;
  25. }
  26. if (font === 'BlinkMacSystemFont') {
  27. return true;
  28. }
  29. return false;
  30. }
  31. /**
  32. * "To avoid mistakes in escaping, it is recommended to quote font family names
  33. * that contain white space, digits, or punctuation characters other than hyphens"
  34. * (https://www.w3.org/TR/CSS2/fonts.html#font-family-prop)
  35. *
  36. * @param {string} family
  37. * @returns {boolean}
  38. */
  39. function quotesRecommended(family) {
  40. return !/^[-a-zA-Z]+$/.test(family);
  41. }
  42. /**
  43. * Quotes are required if the family is not a valid CSS identifier
  44. * (regexes from https://mathiasbynens.be/notes/unquoted-font-family)
  45. *
  46. * @param {string} family
  47. * @returns {boolean}
  48. */
  49. function quotesRequired(family) {
  50. return family
  51. .split(/\s+/)
  52. .some((word) => /^(?:-?\d|--)/.test(word) || !/^[-\w\u{00A0}-\u{10FFFF}]+$/u.test(word));
  53. }
  54. /**
  55. * @typedef {{
  56. * name: string,
  57. * rawName: string,
  58. * hasQuotes: boolean,
  59. * sourceIndex: number,
  60. * resetIndexes: (offset: number) => void,
  61. * removeQuotes: () => void,
  62. * addQuotes: () => void,
  63. * }} MutableNode
  64. */
  65. /**
  66. *
  67. * @param {import('postcss-value-parser').Node[]} fontFamilies
  68. * @param {import('postcss').Declaration} decl
  69. * @returns {MutableNode[]}
  70. */
  71. const makeMutableFontFamilies = (fontFamilies, decl) => {
  72. /**
  73. * @type {MutableNode[]}
  74. */
  75. const mutableNodes = [];
  76. fontFamilies.forEach((fontFamily, idx) => {
  77. const quote = 'quote' in fontFamily && fontFamily.quote;
  78. const name = fontFamily.value;
  79. /** @type {MutableNode} */
  80. const newNode = {
  81. name,
  82. rawName: quote ? `${quote}${name}${quote}` : name,
  83. sourceIndex: fontFamily.sourceIndex,
  84. hasQuotes: Boolean(quote),
  85. resetIndexes(offset) {
  86. mutableNodes.slice(idx + 1).forEach((n) => (n.sourceIndex += offset));
  87. },
  88. removeQuotes() {
  89. if (this.hasQuotes === false) return;
  90. const openIndex = this.sourceIndex;
  91. const closeIndex = openIndex + this.name.length + 2;
  92. this.hasQuotes = false;
  93. decl.value = decl.value.slice(0, openIndex) + this.name + decl.value.substring(closeIndex);
  94. this.resetIndexes(-2);
  95. },
  96. addQuotes() {
  97. if (this.hasQuotes === true) return;
  98. const openIndex = this.sourceIndex;
  99. const closeIndex = openIndex + this.name.length;
  100. this.hasQuotes = true;
  101. const fixedName = `"${this.name}"`;
  102. decl.value = decl.value.slice(0, openIndex) + fixedName + decl.value.substring(closeIndex);
  103. this.resetIndexes(2);
  104. },
  105. };
  106. mutableNodes.push(newNode);
  107. });
  108. return mutableNodes;
  109. };
  110. /** @type {import('stylelint').Rule} */
  111. const rule = (primary, _secondary, context) => {
  112. return (root, result) => {
  113. const validOptions = validateOptions(result, ruleName, {
  114. actual: primary,
  115. possible: ['always-where-required', 'always-where-recommended', 'always-unless-keyword'],
  116. });
  117. if (!validOptions) {
  118. return;
  119. }
  120. root.walkDecls(/^font(-family)?$/i, (decl) => {
  121. if (!isStandardSyntaxValue(decl.value)) {
  122. return;
  123. }
  124. let fontFamilyNodes = makeMutableFontFamilies(findFontFamily(decl.value), decl);
  125. if (fontFamilyNodes.length === 0) {
  126. return;
  127. }
  128. for (const fontFamilyNode of fontFamilyNodes) {
  129. checkFamilyName(fontFamilyNode, decl);
  130. }
  131. });
  132. /**
  133. * @param {MutableNode} fontFamilyNode
  134. * @param {import('postcss').Declaration} decl
  135. */
  136. function checkFamilyName(fontFamilyNode, decl) {
  137. const { name: family, rawName: rawFamily, hasQuotes } = fontFamilyNode;
  138. if (isVariable(rawFamily)) {
  139. return;
  140. }
  141. // Disallow quotes around (case-insensitive) keywords
  142. // and system font keywords in all cases
  143. if (fontFamilyKeywords.has(family.toLowerCase()) || isSystemFontKeyword(family)) {
  144. if (hasQuotes) {
  145. if (context.fix) {
  146. fontFamilyNode.removeQuotes();
  147. return;
  148. }
  149. return complain(messages.rejected(family), rawFamily, decl);
  150. }
  151. return;
  152. }
  153. const required = quotesRequired(family);
  154. const recommended = quotesRecommended(family);
  155. switch (primary) {
  156. case 'always-unless-keyword':
  157. if (!hasQuotes) {
  158. if (context.fix) {
  159. fontFamilyNode.addQuotes();
  160. return;
  161. }
  162. return complain(messages.expected(family), rawFamily, decl);
  163. }
  164. return;
  165. case 'always-where-recommended':
  166. if (!recommended && hasQuotes) {
  167. if (context.fix) {
  168. fontFamilyNode.removeQuotes();
  169. return;
  170. }
  171. return complain(messages.rejected(family), rawFamily, decl);
  172. }
  173. if (recommended && !hasQuotes) {
  174. if (context.fix) {
  175. fontFamilyNode.addQuotes();
  176. return;
  177. }
  178. return complain(messages.expected(family), rawFamily, decl);
  179. }
  180. return;
  181. case 'always-where-required':
  182. if (!required && hasQuotes) {
  183. if (context.fix) {
  184. fontFamilyNode.removeQuotes();
  185. return;
  186. }
  187. return complain(messages.rejected(family), rawFamily, decl);
  188. }
  189. if (required && !hasQuotes) {
  190. if (context.fix) {
  191. fontFamilyNode.addQuotes();
  192. return;
  193. }
  194. return complain(messages.expected(family), rawFamily, decl);
  195. }
  196. }
  197. }
  198. /**
  199. * @param {string} message
  200. * @param {string} family
  201. * @param {import('postcss').Declaration} decl
  202. */
  203. function complain(message, family, decl) {
  204. report({
  205. result,
  206. ruleName,
  207. message,
  208. node: decl,
  209. word: family,
  210. });
  211. }
  212. };
  213. };
  214. rule.ruleName = ruleName;
  215. rule.messages = messages;
  216. rule.meta = meta;
  217. module.exports = rule;