index.js 6.2 KB

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