no-unknown-property.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. /**
  2. * @fileoverview Prevent usage of unknown DOM property
  3. * @author Yannick Croissant
  4. */
  5. 'use strict';
  6. const has = require('hasown');
  7. const docsUrl = require('../util/docsUrl');
  8. const getText = require('../util/eslint').getText;
  9. const testReactVersion = require('../util/version').testReactVersion;
  10. const report = require('../util/report');
  11. // ------------------------------------------------------------------------------
  12. // Constants
  13. // ------------------------------------------------------------------------------
  14. const DEFAULTS = {
  15. ignore: [],
  16. requireDataLowercase: false,
  17. };
  18. const DOM_ATTRIBUTE_NAMES = {
  19. 'accept-charset': 'acceptCharset',
  20. class: 'className',
  21. 'http-equiv': 'httpEquiv',
  22. crossorigin: 'crossOrigin',
  23. for: 'htmlFor',
  24. nomodule: 'noModule',
  25. };
  26. const ATTRIBUTE_TAGS_MAP = {
  27. abbr: ['th', 'td'],
  28. charset: ['meta'],
  29. checked: ['input'],
  30. // image is required for SVG support, all other tags are HTML.
  31. crossOrigin: ['script', 'img', 'video', 'audio', 'link', 'image'],
  32. displaystyle: ['math'],
  33. // https://html.spec.whatwg.org/multipage/links.html#downloading-resources
  34. download: ['a', 'area'],
  35. fill: [ // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill
  36. // Fill color
  37. 'altGlyph',
  38. 'circle',
  39. 'ellipse',
  40. 'g',
  41. 'line',
  42. 'marker',
  43. 'mask',
  44. 'path',
  45. 'polygon',
  46. 'polyline',
  47. 'rect',
  48. 'svg',
  49. 'symbol',
  50. 'text',
  51. 'textPath',
  52. 'tref',
  53. 'tspan',
  54. 'use',
  55. // Animation final state
  56. 'animate',
  57. 'animateColor',
  58. 'animateMotion',
  59. 'animateTransform',
  60. 'set',
  61. ],
  62. focusable: ['svg'],
  63. imageSizes: ['link'],
  64. imageSrcSet: ['link'],
  65. property: ['meta'],
  66. viewBox: ['marker', 'pattern', 'svg', 'symbol', 'view'],
  67. as: ['link'],
  68. align: ['applet', 'caption', 'col', 'colgroup', 'hr', 'iframe', 'img', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr'], // deprecated, but known
  69. valign: ['tr', 'td', 'th', 'thead', 'tbody', 'tfoot', 'colgroup', 'col'], // deprecated, but known
  70. noModule: ['script'],
  71. // Media events allowed only on audio and video tags, see https://github.com/facebook/react/blob/256aefbea1449869620fb26f6ec695536ab453f5/CHANGELOG.md#notable-enhancements
  72. onAbort: ['audio', 'video'],
  73. onCancel: ['dialog'],
  74. onCanPlay: ['audio', 'video'],
  75. onCanPlayThrough: ['audio', 'video'],
  76. onClose: ['dialog'],
  77. onDurationChange: ['audio', 'video'],
  78. onEmptied: ['audio', 'video'],
  79. onEncrypted: ['audio', 'video'],
  80. onEnded: ['audio', 'video'],
  81. onError: ['audio', 'video', 'img', 'link', 'source', 'script', 'picture', 'iframe'],
  82. onLoad: ['script', 'img', 'link', 'picture', 'iframe', 'object', 'source'],
  83. onLoadedData: ['audio', 'video'],
  84. onLoadedMetadata: ['audio', 'video'],
  85. onLoadStart: ['audio', 'video'],
  86. onPause: ['audio', 'video'],
  87. onPlay: ['audio', 'video'],
  88. onPlaying: ['audio', 'video'],
  89. onProgress: ['audio', 'video'],
  90. onRateChange: ['audio', 'video'],
  91. onResize: ['audio', 'video'],
  92. onSeeked: ['audio', 'video'],
  93. onSeeking: ['audio', 'video'],
  94. onStalled: ['audio', 'video'],
  95. onSuspend: ['audio', 'video'],
  96. onTimeUpdate: ['audio', 'video'],
  97. onVolumeChange: ['audio', 'video'],
  98. onWaiting: ['audio', 'video'],
  99. autoPictureInPicture: ['video'],
  100. controls: ['audio', 'video'],
  101. controlsList: ['audio', 'video'],
  102. disablePictureInPicture: ['video'],
  103. disableRemotePlayback: ['audio', 'video'],
  104. loop: ['audio', 'video'],
  105. muted: ['audio', 'video'],
  106. playsInline: ['video'],
  107. allowFullScreen: ['iframe', 'video'],
  108. webkitAllowFullScreen: ['iframe', 'video'],
  109. mozAllowFullScreen: ['iframe', 'video'],
  110. poster: ['video'],
  111. preload: ['audio', 'video'],
  112. scrolling: ['iframe'],
  113. returnValue: ['dialog'],
  114. webkitDirectory: ['input'],
  115. shadowrootmode: ['template'],
  116. shadowrootclonable: ['template'],
  117. shadowrootdelegatesfocus: ['template'],
  118. shadowrootserializable: ['template'],
  119. 'transform-origin': ['rect'],
  120. };
  121. const SVGDOM_ATTRIBUTE_NAMES = {
  122. 'accent-height': 'accentHeight',
  123. 'alignment-baseline': 'alignmentBaseline',
  124. 'arabic-form': 'arabicForm',
  125. 'baseline-shift': 'baselineShift',
  126. 'cap-height': 'capHeight',
  127. 'clip-path': 'clipPath',
  128. 'clip-rule': 'clipRule',
  129. 'color-interpolation': 'colorInterpolation',
  130. 'color-interpolation-filters': 'colorInterpolationFilters',
  131. 'color-profile': 'colorProfile',
  132. 'color-rendering': 'colorRendering',
  133. 'dominant-baseline': 'dominantBaseline',
  134. 'enable-background': 'enableBackground',
  135. 'fill-opacity': 'fillOpacity',
  136. 'fill-rule': 'fillRule',
  137. 'flood-color': 'floodColor',
  138. 'flood-opacity': 'floodOpacity',
  139. 'font-family': 'fontFamily',
  140. 'font-size': 'fontSize',
  141. 'font-size-adjust': 'fontSizeAdjust',
  142. 'font-stretch': 'fontStretch',
  143. 'font-style': 'fontStyle',
  144. 'font-variant': 'fontVariant',
  145. 'font-weight': 'fontWeight',
  146. 'glyph-name': 'glyphName',
  147. 'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
  148. 'glyph-orientation-vertical': 'glyphOrientationVertical',
  149. 'horiz-adv-x': 'horizAdvX',
  150. 'horiz-origin-x': 'horizOriginX',
  151. 'image-rendering': 'imageRendering',
  152. 'letter-spacing': 'letterSpacing',
  153. 'lighting-color': 'lightingColor',
  154. 'marker-end': 'markerEnd',
  155. 'marker-mid': 'markerMid',
  156. 'marker-start': 'markerStart',
  157. 'overline-position': 'overlinePosition',
  158. 'overline-thickness': 'overlineThickness',
  159. 'paint-order': 'paintOrder',
  160. 'panose-1': 'panose1',
  161. 'pointer-events': 'pointerEvents',
  162. 'rendering-intent': 'renderingIntent',
  163. 'shape-rendering': 'shapeRendering',
  164. 'stop-color': 'stopColor',
  165. 'stop-opacity': 'stopOpacity',
  166. 'strikethrough-position': 'strikethroughPosition',
  167. 'strikethrough-thickness': 'strikethroughThickness',
  168. 'stroke-dasharray': 'strokeDasharray',
  169. 'stroke-dashoffset': 'strokeDashoffset',
  170. 'stroke-linecap': 'strokeLinecap',
  171. 'stroke-linejoin': 'strokeLinejoin',
  172. 'stroke-miterlimit': 'strokeMiterlimit',
  173. 'stroke-opacity': 'strokeOpacity',
  174. 'stroke-width': 'strokeWidth',
  175. 'text-anchor': 'textAnchor',
  176. 'text-decoration': 'textDecoration',
  177. 'text-rendering': 'textRendering',
  178. 'underline-position': 'underlinePosition',
  179. 'underline-thickness': 'underlineThickness',
  180. 'unicode-bidi': 'unicodeBidi',
  181. 'unicode-range': 'unicodeRange',
  182. 'units-per-em': 'unitsPerEm',
  183. 'v-alphabetic': 'vAlphabetic',
  184. 'v-hanging': 'vHanging',
  185. 'v-ideographic': 'vIdeographic',
  186. 'v-mathematical': 'vMathematical',
  187. 'vector-effect': 'vectorEffect',
  188. 'vert-adv-y': 'vertAdvY',
  189. 'vert-origin-x': 'vertOriginX',
  190. 'vert-origin-y': 'vertOriginY',
  191. 'word-spacing': 'wordSpacing',
  192. 'writing-mode': 'writingMode',
  193. 'x-height': 'xHeight',
  194. 'xlink:actuate': 'xlinkActuate',
  195. 'xlink:arcrole': 'xlinkArcrole',
  196. 'xlink:href': 'xlinkHref',
  197. 'xlink:role': 'xlinkRole',
  198. 'xlink:show': 'xlinkShow',
  199. 'xlink:title': 'xlinkTitle',
  200. 'xlink:type': 'xlinkType',
  201. 'xml:base': 'xmlBase',
  202. 'xml:lang': 'xmlLang',
  203. 'xml:space': 'xmlSpace',
  204. };
  205. const DOM_PROPERTY_NAMES_ONE_WORD = [
  206. // Global attributes - can be used on any HTML/DOM element
  207. // See https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes
  208. 'dir', 'draggable', 'hidden', 'id', 'lang', 'nonce', 'part', 'slot', 'style', 'title', 'translate', 'inert',
  209. // Element specific attributes
  210. // See https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes (includes global attributes too)
  211. // To be considered if these should be added also to ATTRIBUTE_TAGS_MAP
  212. 'accept', 'action', 'allow', 'alt', 'as', 'async', 'buffered', 'capture', 'challenge', 'cite', 'code', 'cols',
  213. 'content', 'coords', 'csp', 'data', 'decoding', 'default', 'defer', 'disabled', 'form',
  214. 'headers', 'height', 'high', 'href', 'icon', 'importance', 'integrity', 'kind', 'label',
  215. 'language', 'loading', 'list', 'loop', 'low', 'manifest', 'max', 'media', 'method', 'min', 'multiple', 'muted',
  216. 'name', 'open', 'optimum', 'pattern', 'ping', 'placeholder', 'poster', 'preload', 'profile',
  217. 'rel', 'required', 'reversed', 'role', 'rows', 'sandbox', 'scope', 'seamless', 'selected', 'shape', 'size', 'sizes',
  218. 'span', 'src', 'start', 'step', 'summary', 'target', 'type', 'value', 'width', 'wmode', 'wrap',
  219. // SVG attributes
  220. // See https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute
  221. 'accumulate', 'additive', 'alphabetic', 'amplitude', 'ascent', 'azimuth', 'bbox', 'begin',
  222. 'bias', 'by', 'clip', 'color', 'cursor', 'cx', 'cy', 'd', 'decelerate', 'descent', 'direction',
  223. 'display', 'divisor', 'dur', 'dx', 'dy', 'elevation', 'end', 'exponent', 'fill', 'filter',
  224. 'format', 'from', 'fr', 'fx', 'fy', 'g1', 'g2', 'hanging', 'height', 'hreflang', 'ideographic',
  225. 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'local', 'mask', 'mode',
  226. 'offset', 'opacity', 'operator', 'order', 'orient', 'orientation', 'origin', 'overflow', 'path',
  227. 'ping', 'points', 'r', 'radius', 'rel', 'restart', 'result', 'rotate', 'rx', 'ry', 'scale',
  228. 'seed', 'slope', 'spacing', 'speed', 'stemh', 'stemv', 'string', 'stroke', 'to', 'transform',
  229. 'u1', 'u2', 'unicode', 'values', 'version', 'visibility', 'widths', 'x', 'x1', 'x2', 'xmlns',
  230. 'y', 'y1', 'y2', 'z',
  231. // OpenGraph meta tag attributes
  232. 'property',
  233. // React specific attributes
  234. 'ref', 'key', 'children',
  235. // Non-standard
  236. 'results', 'security',
  237. // Video specific
  238. 'controls',
  239. // popovers
  240. 'popover', 'popovertarget', 'popovertargetaction',
  241. ];
  242. const DOM_PROPERTY_NAMES_TWO_WORDS = [
  243. // Global attributes - can be used on any HTML/DOM element
  244. // See https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes
  245. 'accessKey', 'autoCapitalize', 'autoFocus', 'contentEditable', 'enterKeyHint', 'exportParts',
  246. 'inputMode', 'itemID', 'itemRef', 'itemProp', 'itemScope', 'itemType', 'spellCheck', 'tabIndex',
  247. // Element specific attributes
  248. // See https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes (includes global attributes too)
  249. // To be considered if these should be added also to ATTRIBUTE_TAGS_MAP
  250. 'acceptCharset', 'autoComplete', 'autoPlay', 'border', 'cellPadding', 'cellSpacing', 'classID', 'codeBase',
  251. 'colSpan', 'contextMenu', 'dateTime', 'encType', 'formAction', 'formEncType', 'formMethod', 'formNoValidate', 'formTarget',
  252. 'frameBorder', 'hrefLang', 'httpEquiv', 'imageSizes', 'imageSrcSet', 'isMap', 'keyParams', 'keyType', 'marginHeight', 'marginWidth',
  253. 'maxLength', 'mediaGroup', 'minLength', 'noValidate', 'onAnimationEnd', 'onAnimationIteration', 'onAnimationStart',
  254. 'onBlur', 'onChange', 'onClick', 'onContextMenu', 'onCopy', 'onCompositionEnd', 'onCompositionStart',
  255. 'onCompositionUpdate', 'onCut', 'onDoubleClick', 'onDrag', 'onDragEnd', 'onDragEnter', 'onDragExit', 'onDragLeave',
  256. 'onError', 'onFocus', 'onInput', 'onKeyDown', 'onKeyPress', 'onKeyUp', 'onLoad', 'onWheel', 'onDragOver',
  257. 'onDragStart', 'onDrop', 'onMouseDown', 'onMouseEnter', 'onMouseLeave', 'onMouseMove', 'onMouseOut', 'onMouseOver',
  258. 'onMouseUp', 'onPaste', 'onScroll', 'onSelect', 'onSubmit', 'onBeforeToggle', 'onToggle', 'onTransitionEnd', 'radioGroup',
  259. 'readOnly', 'referrerPolicy', 'rowSpan', 'srcDoc', 'srcLang', 'srcSet', 'useMap', 'fetchPriority',
  260. // SVG attributes
  261. // See https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute
  262. 'crossOrigin', 'accentHeight', 'alignmentBaseline', 'arabicForm', 'attributeName',
  263. 'attributeType', 'baseFrequency', 'baselineShift', 'baseProfile', 'calcMode', 'capHeight',
  264. 'clipPathUnits', 'clipPath', 'clipRule', 'colorInterpolation', 'colorInterpolationFilters',
  265. 'colorProfile', 'colorRendering', 'contentScriptType', 'contentStyleType', 'diffuseConstant',
  266. 'dominantBaseline', 'edgeMode', 'enableBackground', 'fillOpacity', 'fillRule', 'filterRes',
  267. 'filterUnits', 'floodColor', 'floodOpacity', 'fontFamily', 'fontSize', 'fontSizeAdjust',
  268. 'fontStretch', 'fontStyle', 'fontVariant', 'fontWeight', 'glyphName',
  269. 'glyphOrientationHorizontal', 'glyphOrientationVertical', 'glyphRef', 'gradientTransform',
  270. 'gradientUnits', 'horizAdvX', 'horizOriginX', 'imageRendering', 'kernelMatrix',
  271. 'kernelUnitLength', 'keyPoints', 'keySplines', 'keyTimes', 'lengthAdjust', 'letterSpacing',
  272. 'lightingColor', 'limitingConeAngle', 'markerEnd', 'markerMid', 'markerStart', 'markerHeight',
  273. 'markerUnits', 'markerWidth', 'maskContentUnits', 'maskUnits', 'mathematical', 'numOctaves',
  274. 'overlinePosition', 'overlineThickness', 'panose1', 'paintOrder', 'pathLength',
  275. 'patternContentUnits', 'patternTransform', 'patternUnits', 'pointerEvents', 'pointsAtX',
  276. 'pointsAtY', 'pointsAtZ', 'preserveAlpha', 'preserveAspectRatio', 'primitiveUnits',
  277. 'referrerPolicy', 'refX', 'refY', 'rendering-intent', 'repeatCount', 'repeatDur',
  278. 'requiredExtensions', 'requiredFeatures', 'shapeRendering', 'specularConstant',
  279. 'specularExponent', 'spreadMethod', 'startOffset', 'stdDeviation', 'stitchTiles', 'stopColor',
  280. 'stopOpacity', 'strikethroughPosition', 'strikethroughThickness', 'strokeDasharray',
  281. 'strokeDashoffset', 'strokeLinecap', 'strokeLinejoin', 'strokeMiterlimit', 'strokeOpacity',
  282. 'strokeWidth', 'surfaceScale', 'systemLanguage', 'tableValues', 'targetX', 'targetY',
  283. 'textAnchor', 'textDecoration', 'textRendering', 'textLength', 'transformOrigin',
  284. 'underlinePosition', 'underlineThickness', 'unicodeBidi', 'unicodeRange', 'unitsPerEm',
  285. 'vAlphabetic', 'vHanging', 'vIdeographic', 'vMathematical', 'vectorEffect', 'vertAdvY',
  286. 'vertOriginX', 'vertOriginY', 'viewBox', 'viewTarget', 'wordSpacing', 'writingMode', 'xHeight',
  287. 'xChannelSelector', 'xlinkActuate', 'xlinkArcrole', 'xlinkHref', 'xlinkRole', 'xlinkShow',
  288. 'xlinkTitle', 'xlinkType', 'xmlBase', 'xmlLang', 'xmlnsXlink', 'xmlSpace', 'yChannelSelector',
  289. 'zoomAndPan',
  290. // Safari/Apple specific, no listing available
  291. 'autoCorrect', // https://stackoverflow.com/questions/47985384/html-autocorrect-for-text-input-is-not-working
  292. 'autoSave', // https://stackoverflow.com/questions/25456396/what-is-autosave-attribute-supposed-to-do-how-do-i-use-it
  293. // React specific attributes https://reactjs.org/docs/dom-elements.html#differences-in-attributes
  294. 'className', 'dangerouslySetInnerHTML', 'defaultValue', 'defaultChecked', 'htmlFor',
  295. // Events' capture events
  296. 'onBeforeInput', 'onChange',
  297. 'onInvalid', 'onReset', 'onTouchCancel', 'onTouchEnd', 'onTouchMove', 'onTouchStart', 'suppressContentEditableWarning', 'suppressHydrationWarning',
  298. 'onAbort', 'onCanPlay', 'onCanPlayThrough', 'onDurationChange', 'onEmptied', 'onEncrypted', 'onEnded',
  299. 'onLoadedData', 'onLoadedMetadata', 'onLoadStart', 'onPause', 'onPlay', 'onPlaying', 'onProgress', 'onRateChange', 'onResize',
  300. 'onSeeked', 'onSeeking', 'onStalled', 'onSuspend', 'onTimeUpdate', 'onVolumeChange', 'onWaiting',
  301. 'onCopyCapture', 'onCutCapture', 'onPasteCapture', 'onCompositionEndCapture', 'onCompositionStartCapture', 'onCompositionUpdateCapture',
  302. 'onFocusCapture', 'onBlurCapture', 'onChangeCapture', 'onBeforeInputCapture', 'onInputCapture', 'onResetCapture', 'onSubmitCapture',
  303. 'onInvalidCapture', 'onLoadCapture', 'onErrorCapture', 'onKeyDownCapture', 'onKeyPressCapture', 'onKeyUpCapture',
  304. 'onAbortCapture', 'onCanPlayCapture', 'onCanPlayThroughCapture', 'onDurationChangeCapture', 'onEmptiedCapture', 'onEncryptedCapture',
  305. 'onEndedCapture', 'onLoadedDataCapture', 'onLoadedMetadataCapture', 'onLoadStartCapture', 'onPauseCapture', 'onPlayCapture',
  306. 'onPlayingCapture', 'onProgressCapture', 'onRateChangeCapture', 'onSeekedCapture', 'onSeekingCapture', 'onStalledCapture', 'onSuspendCapture',
  307. 'onTimeUpdateCapture', 'onVolumeChangeCapture', 'onWaitingCapture', 'onSelectCapture', 'onTouchCancelCapture', 'onTouchEndCapture',
  308. 'onTouchMoveCapture', 'onTouchStartCapture', 'onScrollCapture', 'onWheelCapture', 'onAnimationEndCapture', 'onAnimationIteration',
  309. 'onAnimationStartCapture', 'onTransitionEndCapture',
  310. 'onAuxClick', 'onAuxClickCapture', 'onClickCapture', 'onContextMenuCapture', 'onDoubleClickCapture',
  311. 'onDragCapture', 'onDragEndCapture', 'onDragEnterCapture', 'onDragExitCapture', 'onDragLeaveCapture',
  312. 'onDragOverCapture', 'onDragStartCapture', 'onDropCapture', 'onMouseDown', 'onMouseDownCapture',
  313. 'onMouseMoveCapture', 'onMouseOutCapture', 'onMouseOverCapture', 'onMouseUpCapture',
  314. // Video specific
  315. 'autoPictureInPicture', 'controlsList', 'disablePictureInPicture', 'disableRemotePlayback',
  316. // popovers
  317. 'popoverTarget', 'popoverTargetAction',
  318. ];
  319. const DOM_PROPERTIES_IGNORE_CASE = ['charset', 'allowFullScreen', 'webkitAllowFullScreen', 'mozAllowFullScreen', 'webkitDirectory', 'popoverTarget', 'popoverTargetAction'];
  320. const ARIA_PROPERTIES = [
  321. // See https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes
  322. // Global attributes
  323. 'aria-atomic', 'aria-braillelabel', 'aria-brailleroledescription', 'aria-busy', 'aria-controls', 'aria-current',
  324. 'aria-describedby', 'aria-description', 'aria-details',
  325. 'aria-disabled', 'aria-dropeffect', 'aria-errormessage', 'aria-flowto', 'aria-grabbed', 'aria-haspopup',
  326. 'aria-hidden', 'aria-invalid', 'aria-keyshortcuts', 'aria-label', 'aria-labelledby', 'aria-live',
  327. 'aria-owns', 'aria-relevant', 'aria-roledescription',
  328. // Widget attributes
  329. 'aria-autocomplete', 'aria-checked', 'aria-expanded', 'aria-level', 'aria-modal', 'aria-multiline', 'aria-multiselectable',
  330. 'aria-orientation', 'aria-placeholder', 'aria-pressed', 'aria-readonly', 'aria-required', 'aria-selected',
  331. 'aria-sort', 'aria-valuemax', 'aria-valuemin', 'aria-valuenow', 'aria-valuetext',
  332. // Relationship attributes
  333. 'aria-activedescendant', 'aria-colcount', 'aria-colindex', 'aria-colindextext', 'aria-colspan',
  334. 'aria-posinset', 'aria-rowcount', 'aria-rowindex', 'aria-rowindextext', 'aria-rowspan', 'aria-setsize',
  335. ];
  336. const REACT_ON_PROPS = [
  337. 'onGotPointerCapture',
  338. 'onGotPointerCaptureCapture',
  339. 'onLostPointerCapture',
  340. 'onLostPointerCapture',
  341. 'onLostPointerCaptureCapture',
  342. 'onPointerCancel',
  343. 'onPointerCancelCapture',
  344. 'onPointerDown',
  345. 'onPointerDownCapture',
  346. 'onPointerEnter',
  347. 'onPointerEnterCapture',
  348. 'onPointerLeave',
  349. 'onPointerLeaveCapture',
  350. 'onPointerMove',
  351. 'onPointerMoveCapture',
  352. 'onPointerOut',
  353. 'onPointerOutCapture',
  354. 'onPointerOver',
  355. 'onPointerOverCapture',
  356. 'onPointerUp',
  357. 'onPointerUpCapture',
  358. ];
  359. function getDOMPropertyNames(context) {
  360. return [].concat(
  361. DOM_PROPERTY_NAMES_TWO_WORDS,
  362. DOM_PROPERTY_NAMES_ONE_WORD,
  363. testReactVersion(context, '>= 16.1.0') ? [].concat(
  364. testReactVersion(context, '>= 16.4.0') ? [].concat(
  365. // these were added in React v16.4.0, see https://reactjs.org/blog/2018/05/23/react-v-16-4.html and https://github.com/facebook/react/pull/12507
  366. REACT_ON_PROPS,
  367. testReactVersion(context, '>= 19') ? [
  368. // precedence was added in React v19, see https://react.dev/blog/2024/04/25/react-19#support-for-stylesheets
  369. 'precedence',
  370. ] : []
  371. ) : []
  372. ) : [
  373. // this was removed in React v16.1+, see https://github.com/facebook/react/pull/10823
  374. 'allowTransparency',
  375. ]
  376. );
  377. }
  378. // ------------------------------------------------------------------------------
  379. // Helpers
  380. // ------------------------------------------------------------------------------
  381. /**
  382. * Checks if a node's parent is a JSX tag that is written with lowercase letters,
  383. * and is not a custom web component. Custom web components have a hyphen in tag name,
  384. * or have an `is="some-elem"` attribute.
  385. *
  386. * Note: does not check if a tag's parent against a list of standard HTML/DOM tags. For example,
  387. * a `<fake>`'s child would return `true` because "fake" is written only with lowercase letters
  388. * without a hyphen and does not have a `is="some-elem"` attribute.
  389. *
  390. * @param {Object} childNode - JSX element being tested.
  391. * @returns {boolean} Whether or not the node name match the JSX tag convention.
  392. */
  393. function isValidHTMLTagInJSX(childNode) {
  394. const tagConvention = /^[a-z][^-]*$/;
  395. if (tagConvention.test(childNode.parent.name.name)) {
  396. return !childNode.parent.attributes.some((attrNode) => (
  397. attrNode.type === 'JSXAttribute'
  398. && attrNode.name.type === 'JSXIdentifier'
  399. && attrNode.name.name === 'is'
  400. // To learn more about custom web components and `is` attribute,
  401. // see https://html.spec.whatwg.org/multipage/custom-elements.html#custom-elements-customized-builtin-example
  402. ));
  403. }
  404. return false;
  405. }
  406. /**
  407. * Checks if the attribute name is included in the attributes that are excluded
  408. * from the camel casing.
  409. *
  410. * // returns 'charSet'
  411. * @example normalizeAttributeCase('charset')
  412. *
  413. * Note - these exclusions are not made by React core team, but `eslint-plugin-react` community.
  414. *
  415. * @param {string} name - Attribute name to be normalized
  416. * @returns {string} Result
  417. */
  418. function normalizeAttributeCase(name) {
  419. return DOM_PROPERTIES_IGNORE_CASE.find((element) => element.toLowerCase() === name.toLowerCase()) || name;
  420. }
  421. /**
  422. * Checks if an attribute name is a valid `data-*` attribute:
  423. * if the name starts with "data-" and has alphanumeric words (browsers require lowercase, but React and TS lowercase them),
  424. * not start with any casing of "xml", and separated by hyphens (-) (which is also called "kebab case" or "dash case"),
  425. * then the attribute is a valid data attribute.
  426. *
  427. * @param {string} name - Attribute name to be tested
  428. * @returns {boolean} Result
  429. */
  430. function isValidDataAttribute(name) {
  431. return !/^data-xml/i.test(name) && /^data-[^:]*$/.test(name);
  432. }
  433. /**
  434. * Checks if an attribute name has at least one uppercase characters
  435. *
  436. * @param {string} name
  437. * @returns {boolean} Result
  438. */
  439. function hasUpperCaseCharacter(name) {
  440. return name.toLowerCase() !== name;
  441. }
  442. /**
  443. * Checks if an attribute name is a standard aria attribute by compering it to a list
  444. * of standard aria property names
  445. *
  446. * @param {string} name - Attribute name to be tested
  447. * @returns {boolean} Result
  448. */
  449. function isValidAriaAttribute(name) {
  450. return ARIA_PROPERTIES.some((element) => element === name);
  451. }
  452. /**
  453. * Extracts the tag name for the JSXAttribute
  454. * @param {JSXAttribute} node - JSXAttribute being tested.
  455. * @returns {string | null} tag name
  456. */
  457. function getTagName(node) {
  458. if (
  459. node
  460. && node.parent
  461. && node.parent.name
  462. ) {
  463. return node.parent.name.name;
  464. }
  465. return null;
  466. }
  467. /**
  468. * Test wether the tag name for the JSXAttribute is
  469. * something like <Foo.bar />
  470. * @param {JSXAttribute} node - JSXAttribute being tested.
  471. * @returns {boolean} result
  472. */
  473. function tagNameHasDot(node) {
  474. return !!(
  475. node.parent
  476. && node.parent.name
  477. && node.parent.name.type === 'JSXMemberExpression'
  478. );
  479. }
  480. /**
  481. * Get the standard name of the attribute.
  482. * @param {string} name - Name of the attribute.
  483. * @param {object} context - eslint context
  484. * @returns {string | undefined} The standard name of the attribute, or undefined if no standard name was found.
  485. */
  486. function getStandardName(name, context) {
  487. if (has(DOM_ATTRIBUTE_NAMES, name)) {
  488. return DOM_ATTRIBUTE_NAMES[/** @type {keyof DOM_ATTRIBUTE_NAMES} */ (name)];
  489. }
  490. if (has(SVGDOM_ATTRIBUTE_NAMES, name)) {
  491. return SVGDOM_ATTRIBUTE_NAMES[/** @type {keyof SVGDOM_ATTRIBUTE_NAMES} */ (name)];
  492. }
  493. const names = getDOMPropertyNames(context);
  494. // Let's find a possible attribute match with a case-insensitive search.
  495. return names.find((element) => element.toLowerCase() === name.toLowerCase());
  496. }
  497. // ------------------------------------------------------------------------------
  498. // Rule Definition
  499. // ------------------------------------------------------------------------------
  500. const messages = {
  501. invalidPropOnTag: 'Invalid property \'{{name}}\' found on tag \'{{tagName}}\', but it is only allowed on: {{allowedTags}}',
  502. unknownPropWithStandardName: 'Unknown property \'{{name}}\' found, use \'{{standardName}}\' instead',
  503. unknownProp: 'Unknown property \'{{name}}\' found',
  504. dataLowercaseRequired: 'React does not recognize data-* props with uppercase characters on a DOM element. Found \'{{name}}\', use \'{{lowerCaseName}}\' instead',
  505. };
  506. /** @type {import('eslint').Rule.RuleModule} */
  507. module.exports = {
  508. meta: {
  509. docs: {
  510. description: 'Disallow usage of unknown DOM property',
  511. category: 'Possible Errors',
  512. recommended: true,
  513. url: docsUrl('no-unknown-property'),
  514. },
  515. fixable: 'code',
  516. messages,
  517. schema: [{
  518. type: 'object',
  519. properties: {
  520. ignore: {
  521. type: 'array',
  522. items: {
  523. type: 'string',
  524. },
  525. },
  526. requireDataLowercase: {
  527. type: 'boolean',
  528. default: false,
  529. },
  530. },
  531. additionalProperties: false,
  532. }],
  533. },
  534. create(context) {
  535. function getIgnoreConfig() {
  536. return (context.options[0] && context.options[0].ignore) || DEFAULTS.ignore;
  537. }
  538. function getRequireDataLowercase() {
  539. return (context.options[0] && typeof context.options[0].requireDataLowercase !== 'undefined')
  540. ? !!context.options[0].requireDataLowercase
  541. : DEFAULTS.requireDataLowercase;
  542. }
  543. return {
  544. JSXAttribute(node) {
  545. const ignoreNames = getIgnoreConfig();
  546. const actualName = getText(context, node.name);
  547. if (ignoreNames.indexOf(actualName) >= 0) {
  548. return;
  549. }
  550. const name = normalizeAttributeCase(actualName);
  551. // Ignore tags like <Foo.bar />
  552. if (tagNameHasDot(node)) {
  553. return;
  554. }
  555. if (isValidDataAttribute(name)) {
  556. if (getRequireDataLowercase() && hasUpperCaseCharacter(name)) {
  557. report(context, messages.dataLowercaseRequired, 'dataLowercaseRequired', {
  558. node,
  559. data: {
  560. name: actualName,
  561. lowerCaseName: actualName.toLowerCase(),
  562. },
  563. });
  564. }
  565. return;
  566. }
  567. if (isValidAriaAttribute(name)) { return; }
  568. const tagName = getTagName(node);
  569. if (tagName === 'fbt' || tagName === 'fbs') { return; } // fbt/fbs nodes are bonkers, let's not go there
  570. if (!isValidHTMLTagInJSX(node)) { return; }
  571. // Let's dive deeper into tags that are HTML/DOM elements (`<button>`), and not React components (`<Button />`)
  572. // Some attributes are allowed on some tags only
  573. const allowedTags = has(ATTRIBUTE_TAGS_MAP, name)
  574. ? ATTRIBUTE_TAGS_MAP[/** @type {keyof ATTRIBUTE_TAGS_MAP} */ (name)]
  575. : null;
  576. if (tagName && allowedTags) {
  577. // Scenario 1A: Allowed attribute found where not supposed to, report it
  578. if (allowedTags.indexOf(tagName) === -1) {
  579. report(context, messages.invalidPropOnTag, 'invalidPropOnTag', {
  580. node,
  581. data: {
  582. name: actualName,
  583. tagName,
  584. allowedTags: allowedTags.join(', '),
  585. },
  586. });
  587. }
  588. // Scenario 1B: There are allowed attributes on allowed tags, no need to report it
  589. return;
  590. }
  591. // Let's see if the attribute is a close version to some standard property name
  592. const standardName = getStandardName(name, context);
  593. const hasStandardNameButIsNotUsed = standardName && standardName !== name;
  594. const usesStandardName = standardName && standardName === name;
  595. if (usesStandardName) {
  596. // Scenario 2A: The attribute name is the standard name, no need to report it
  597. return;
  598. }
  599. if (hasStandardNameButIsNotUsed) {
  600. // Scenario 2B: The name of the attribute is close to a standard one, report it with the standard name
  601. report(context, messages.unknownPropWithStandardName, 'unknownPropWithStandardName', {
  602. node,
  603. data: {
  604. name: actualName,
  605. standardName,
  606. },
  607. fix(fixer) {
  608. return fixer.replaceText(node.name, standardName);
  609. },
  610. });
  611. return;
  612. }
  613. // Scenario 3: We have an attribute that is unknown, report it
  614. report(context, messages.unknownProp, 'unknownProp', {
  615. node,
  616. data: {
  617. name: actualName,
  618. },
  619. });
  620. },
  621. };
  622. },
  623. };