domAttrConfig.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import { makeMap } from './makeMap'
  2. /**
  3. * On the client we only need to offer special cases for boolean attributes that
  4. * have different names from their corresponding dom properties:
  5. * - itemscope -> N/A
  6. * - allowfullscreen -> allowFullscreen
  7. * - formnovalidate -> formNoValidate
  8. * - ismap -> isMap
  9. * - nomodule -> noModule
  10. * - novalidate -> noValidate
  11. * - readonly -> readOnly
  12. */
  13. const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`
  14. export const isSpecialBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs)
  15. /**
  16. * The full list is needed during SSR to produce the correct initial markup.
  17. */
  18. export const isBooleanAttr = /*#__PURE__*/ makeMap(
  19. specialBooleanAttrs +
  20. `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,` +
  21. `inert,loop,open,required,reversed,scoped,seamless,` +
  22. `checked,muted,multiple,selected`,
  23. )
  24. /**
  25. * Boolean attributes should be included if the value is truthy or ''.
  26. * e.g. `<select multiple>` compiles to `{ multiple: '' }`
  27. */
  28. export function includeBooleanAttr(value: unknown): boolean {
  29. return !!value || value === ''
  30. }
  31. const unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/
  32. const attrValidationCache: Record<string, boolean> = {}
  33. export function isSSRSafeAttrName(name: string): boolean {
  34. if (attrValidationCache.hasOwnProperty(name)) {
  35. return attrValidationCache[name]
  36. }
  37. const isUnsafe = unsafeAttrCharRE.test(name)
  38. if (isUnsafe) {
  39. console.error(`unsafe attribute name: ${name}`)
  40. }
  41. return (attrValidationCache[name] = !isUnsafe)
  42. }
  43. export const propsToAttrMap: Record<string, string | undefined> = {
  44. acceptCharset: 'accept-charset',
  45. className: 'class',
  46. htmlFor: 'for',
  47. httpEquiv: 'http-equiv',
  48. }
  49. /**
  50. * Known attributes, this is used for stringification of runtime static nodes
  51. * so that we don't stringify bindings that cannot be set from HTML.
  52. * Don't also forget to allow `data-*` and `aria-*`!
  53. * Generated from https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
  54. */
  55. export const isKnownHtmlAttr = /*#__PURE__*/ makeMap(
  56. `accept,accept-charset,accesskey,action,align,allow,alt,async,` +
  57. `autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,` +
  58. `border,buffered,capture,challenge,charset,checked,cite,class,code,` +
  59. `codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,` +
  60. `coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,` +
  61. `disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,` +
  62. `formaction,formenctype,formmethod,formnovalidate,formtarget,headers,` +
  63. `height,hidden,high,href,hreflang,http-equiv,icon,id,importance,inert,integrity,` +
  64. `ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,` +
  65. `manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,` +
  66. `open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,` +
  67. `referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,` +
  68. `selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,` +
  69. `start,step,style,summary,tabindex,target,title,translate,type,usemap,` +
  70. `value,width,wrap`,
  71. )
  72. /**
  73. * Generated from https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute
  74. */
  75. export const isKnownSvgAttr = /*#__PURE__*/ makeMap(
  76. `xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,` +
  77. `arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,` +
  78. `baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,` +
  79. `clip,clipPathUnits,clip-path,clip-rule,color,color-interpolation,` +
  80. `color-interpolation-filters,color-profile,color-rendering,` +
  81. `contentScriptType,contentStyleType,crossorigin,cursor,cx,cy,d,decelerate,` +
  82. `descent,diffuseConstant,direction,display,divisor,dominant-baseline,dur,dx,` +
  83. `dy,edgeMode,elevation,enable-background,end,exponent,fill,fill-opacity,` +
  84. `fill-rule,filter,filterRes,filterUnits,flood-color,flood-opacity,` +
  85. `font-family,font-size,font-size-adjust,font-stretch,font-style,` +
  86. `font-variant,font-weight,format,from,fr,fx,fy,g1,g2,glyph-name,` +
  87. `glyph-orientation-horizontal,glyph-orientation-vertical,glyphRef,` +
  88. `gradientTransform,gradientUnits,hanging,height,href,hreflang,horiz-adv-x,` +
  89. `horiz-origin-x,id,ideographic,image-rendering,in,in2,intercept,k,k1,k2,k3,` +
  90. `k4,kernelMatrix,kernelUnitLength,kerning,keyPoints,keySplines,keyTimes,` +
  91. `lang,lengthAdjust,letter-spacing,lighting-color,limitingConeAngle,local,` +
  92. `marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,` +
  93. `mask,maskContentUnits,maskUnits,mathematical,max,media,method,min,mode,` +
  94. `name,numOctaves,offset,opacity,operator,order,orient,orientation,origin,` +
  95. `overflow,overline-position,overline-thickness,panose-1,paint-order,path,` +
  96. `pathLength,patternContentUnits,patternTransform,patternUnits,ping,` +
  97. `pointer-events,points,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,` +
  98. `preserveAspectRatio,primitiveUnits,r,radius,referrerPolicy,refX,refY,rel,` +
  99. `rendering-intent,repeatCount,repeatDur,requiredExtensions,requiredFeatures,` +
  100. `restart,result,rotate,rx,ry,scale,seed,shape-rendering,slope,spacing,` +
  101. `specularConstant,specularExponent,speed,spreadMethod,startOffset,` +
  102. `stdDeviation,stemh,stemv,stitchTiles,stop-color,stop-opacity,` +
  103. `strikethrough-position,strikethrough-thickness,string,stroke,` +
  104. `stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,` +
  105. `stroke-miterlimit,stroke-opacity,stroke-width,style,surfaceScale,` +
  106. `systemLanguage,tabindex,tableValues,target,targetX,targetY,text-anchor,` +
  107. `text-decoration,text-rendering,textLength,to,transform,transform-origin,` +
  108. `type,u1,u2,underline-position,underline-thickness,unicode,unicode-bidi,` +
  109. `unicode-range,units-per-em,v-alphabetic,v-hanging,v-ideographic,` +
  110. `v-mathematical,values,vector-effect,version,vert-adv-y,vert-origin-x,` +
  111. `vert-origin-y,viewBox,viewTarget,visibility,width,widths,word-spacing,` +
  112. `writing-mode,x,x-height,x1,x2,xChannelSelector,xlink:actuate,xlink:arcrole,` +
  113. `xlink:href,xlink:role,xlink:show,xlink:title,xlink:type,xmlns:xlink,xml:base,xml:lang,` +
  114. `xml:space,y,y1,y2,yChannelSelector,z,zoomAndPan`,
  115. )
  116. /**
  117. * Shared between server-renderer and runtime-core hydration logic
  118. */
  119. export function isRenderableAttrValue(value: unknown): boolean {
  120. if (value == null) {
  121. return false
  122. }
  123. const type = typeof value
  124. return type === 'string' || type === 'number' || type === 'boolean'
  125. }