no-unknown-property.js 26 KB

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