no-unknown-property.js 26 KB

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