html-react-parser
Advanced tools
Comparing version 0.11.1 to 0.12.0
@@ -5,2 +5,13 @@ # Change Log | ||
<a name="0.12.0"></a> | ||
# [0.12.0](https://github.com/remarkablemark/html-react-parser/compare/v0.11.1...v0.12.0) (2020-06-04) | ||
### Features | ||
* **index:** add htmlparser2 type to HTMLReactParserOptions ([81f74fb](https://github.com/remarkablemark/html-react-parser/commit/81f74fb)) | ||
* **index:** add options.htmlparser2 ([c4ecf64](https://github.com/remarkablemark/html-react-parser/commit/c4ecf64)) | ||
<a name="0.11.1"></a> | ||
@@ -7,0 +18,0 @@ ## [0.11.1](https://github.com/remarkablemark/html-react-parser/compare/v0.11.0...v0.11.1) (2020-06-03) |
@@ -1639,9 +1639,14 @@ (function (global, factory) { | ||
// decode HTML entities by default for `htmlparser2` | ||
var domParserOptions = { decodeEntities: true, lowerCaseAttributeNames: false }; | ||
/** | ||
* Converts HTML string to React elements. | ||
* | ||
* @param {String} html - The HTML string to parse to React. | ||
* @param {Object} [options] - The parser options. | ||
* @param {Function} [options.replace] - The replace method. | ||
* @return {JSX.Element|JSX.Element[]|String} - Returns React element(s), string, or empty array. | ||
* @param {String} html - HTML string. | ||
* @param {Object} [options] - Parser options. | ||
* @param {Object} [options.htmlparser2] - htmlparser2 options. | ||
* @param {Object} [options.library] - Library for React, Preact, etc. | ||
* @param {Function} [options.replace] - Replace method. | ||
* @return {JSX.Element|JSX.Element[]|String} - React element(s), empty array, or string. | ||
*/ | ||
@@ -1655,3 +1660,7 @@ function HTMLReactParser(html, options) { | ||
} | ||
return domToReact_1(htmlToDomClient(html), options); | ||
options = options || {}; | ||
return domToReact_1( | ||
htmlToDomClient(html, options.htmlparser2 || domParserOptions), | ||
options | ||
); | ||
} | ||
@@ -1658,0 +1667,0 @@ |
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):(e=e||self).HTMLReactParser=t(e.React)}(this,function(g){"use strict";g=g&&Object.prototype.hasOwnProperty.call(g,"default")?g.default:g;var e={Properties:{autoFocus:4,accept:0,acceptCharset:0,accessKey:0,action:0,allowFullScreen:4,allowTransparency:0,alt:0,as:0,async:4,autoComplete:0,autoPlay:4,capture:4,cellPadding:0,cellSpacing:0,charSet:0,challenge:0,checked:5,cite:0,classID:0,className:0,cols:24,colSpan:0,content:0,contentEditable:0,contextMenu:0,controls:4,controlsList:0,coords:0,crossOrigin:0,data:0,dateTime:0,default:4,defer:4,dir:0,disabled:4,download:32,draggable:0,encType:0,form:0,formAction:0,formEncType:0,formMethod:0,formNoValidate:4,formTarget:0,frameBorder:0,headers:0,height:0,hidden:4,high:0,href:0,hrefLang:0,htmlFor:0,httpEquiv:0,icon:0,id:0,inputMode:0,integrity:0,is:0,keyParams:0,keyType:0,kind:0,label:0,lang:0,list:0,loop:4,low:0,manifest:0,marginHeight:0,marginWidth:0,max:0,maxLength:0,media:0,mediaGroup:0,method:0,min:0,minLength:0,multiple:5,muted:5,name:0,nonce:0,noValidate:4,open:4,optimum:0,pattern:0,placeholder:0,playsInline:4,poster:0,preload:0,profile:0,radioGroup:0,readOnly:4,referrerPolicy:0,rel:0,required:4,reversed:4,role:0,rows:24,rowSpan:8,sandbox:0,scope:0,scoped:4,scrolling:0,seamless:4,selected:5,shape:0,size:24,sizes:0,span:24,spellCheck:0,src:0,srcDoc:0,srcLang:0,srcSet:0,start:8,step:0,style:0,summary:0,tabIndex:0,target:0,title:0,type:0,useMap:0,value:0,width:0,wmode:0,wrap:0,about:0,datatype:0,inlist:0,prefix:0,property:0,resource:0,typeof:0,vocab:0,autoCapitalize:0,autoCorrect:0,autoSave:0,color:0,itemProp:0,itemScope:4,itemType:0,itemID:0,itemRef:0,results:0,security:0,unselectable:0},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"}},t={Properties:{accentHeight:0,accumulate:0,additive:0,alignmentBaseline:0,allowReorder:0,alphabetic:0,amplitude:0,arabicForm:0,ascent:0,attributeName:0,attributeType:0,autoReverse:0,azimuth:0,baseFrequency:0,baseProfile:0,baselineShift:0,bbox:0,begin:0,bias:0,by:0,calcMode:0,capHeight:0,clip:0,clipPath:0,clipRule:0,clipPathUnits:0,colorInterpolation:0,colorInterpolationFilters:0,colorProfile:0,colorRendering:0,contentScriptType:0,contentStyleType:0,cursor:0,cx:0,cy:0,d:0,decelerate:0,descent:0,diffuseConstant:0,direction:0,display:0,divisor:0,dominantBaseline:0,dur:0,dx:0,dy:0,edgeMode:0,elevation:0,enableBackground:0,end:0,exponent:0,externalResourcesRequired:0,fill:0,fillOpacity:0,fillRule:0,filter:0,filterRes:0,filterUnits:0,floodColor:0,floodOpacity:0,focusable:0,fontFamily:0,fontSize:0,fontSizeAdjust:0,fontStretch:0,fontStyle:0,fontVariant:0,fontWeight:0,format:0,from:0,fx:0,fy:0,g1:0,g2:0,glyphName:0,glyphOrientationHorizontal:0,glyphOrientationVertical:0,glyphRef:0,gradientTransform:0,gradientUnits:0,hanging:0,horizAdvX:0,horizOriginX:0,ideographic:0,imageRendering:0,in:0,in2:0,intercept:0,k:0,k1:0,k2:0,k3:0,k4:0,kernelMatrix:0,kernelUnitLength:0,kerning:0,keyPoints:0,keySplines:0,keyTimes:0,lengthAdjust:0,letterSpacing:0,lightingColor:0,limitingConeAngle:0,local:0,markerEnd:0,markerMid:0,markerStart:0,markerHeight:0,markerUnits:0,markerWidth:0,mask:0,maskContentUnits:0,maskUnits:0,mathematical:0,mode:0,numOctaves:0,offset:0,opacity:0,operator:0,order:0,orient:0,orientation:0,origin:0,overflow:0,overlinePosition:0,overlineThickness:0,paintOrder:0,panose1:0,pathLength:0,patternContentUnits:0,patternTransform:0,patternUnits:0,pointerEvents:0,points:0,pointsAtX:0,pointsAtY:0,pointsAtZ:0,preserveAlpha:0,preserveAspectRatio:0,primitiveUnits:0,r:0,radius:0,refX:0,refY:0,renderingIntent:0,repeatCount:0,repeatDur:0,requiredExtensions:0,requiredFeatures:0,restart:0,result:0,rotate:0,rx:0,ry:0,scale:0,seed:0,shapeRendering:0,slope:0,spacing:0,specularConstant:0,specularExponent:0,speed:0,spreadMethod:0,startOffset:0,stdDeviation:0,stemh:0,stemv:0,stitchTiles:0,stopColor:0,stopOpacity:0,strikethroughPosition:0,strikethroughThickness:0,string:0,stroke:0,strokeDasharray:0,strokeDashoffset:0,strokeLinecap:0,strokeLinejoin:0,strokeMiterlimit:0,strokeOpacity:0,strokeWidth:0,surfaceScale:0,systemLanguage:0,tableValues:0,targetX:0,targetY:0,textAnchor:0,textDecoration:0,textRendering:0,textLength:0,to:0,transform:0,u1:0,u2:0,underlinePosition:0,underlineThickness:0,unicode:0,unicodeBidi:0,unicodeRange:0,unitsPerEm:0,vAlphabetic:0,vHanging:0,vIdeographic:0,vMathematical:0,values:0,vectorEffect:0,version:0,vertAdvY:0,vertOriginX:0,vertOriginY:0,viewBox:0,viewTarget:0,visibility:0,widths:0,wordSpacing:0,writingMode:0,x:0,xHeight:0,x1:0,x2:0,xChannelSelector:0,xlinkActuate:0,xlinkArcrole:0,xlinkHref:0,xlinkRole:0,xlinkShow:0,xlinkTitle:0,xlinkType:0,xmlBase:0,xmlns:0,xmlnsXlink:0,xmlLang:0,xmlSpace:0,y:0,y1:0,y2:0,yChannelSelector:0,z:0,zoomAndPan:0},DOMAttributeNames:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDasharray:"stroke-dasharray",strokeDashoffset:"stroke-dashoffset",strokeLinecap:"stroke-linecap",strokeLinejoin:"stroke-linejoin",strokeMiterlimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",xlinkActuate:"xlink:actuate",xlinkArcrole:"xlink:arcrole",xlinkHref:"xlink:href",xlinkRole:"xlink:role",xlinkShow:"xlink:show",xlinkTitle:"xlink:title",xlinkType:"xlink:type",xmlBase:"xml:base",xmlnsXlink:"xmlns:xlink",xmlLang:"xml:lang",xmlSpace:"xml:space"}},s=1,c=4,u=8,p=24,f=32;function d(e,t){return(e&t)===t}function r(e,t,r){var n,i,o,a=e.Properties,l=e.DOMAttributeNames;for(i in a)n=l[i]||(r?i:i.toLowerCase()),o=a[i],t[n]={attributeName:n,propertyName:i,mustUseProperty:d(o,s),hasBooleanValue:d(o,c),hasNumericValue:d(o,u),hasPositiveNumericValue:d(o,p),hasOverloadedBooleanValue:d(o,f)}}var n={};r(e,n);var i={};r(t,i,!0);var o={};r(e,o),r(t,o,!0);function m(n,r){if("string"!=typeof n)throw new TypeError("First argument must be a string");if(!n)return[];r=r||{};var i=1,o=1;function a(e){var t=e.match(y);t&&(i+=t.length);var r=e.lastIndexOf("\n");o=~r?e.length-r:o+e.length}function l(){var t={line:i,column:o};return function(e){return e.position=new s(t),p(),e}}function s(e){this.start=e,this.end={line:i,column:o},this.source=r.source}function c(e){var t=new Error(r.source+":"+i+":"+o+": "+e);if(t.reason=e,t.filename=r.source,t.line=i,t.column=o,t.source=n,!r.silent)throw t}function u(e){var t=e.exec(n);if(t){var r=t[0];return a(r),n=n.slice(r.length),t}}function p(){u(v)}function f(e){var t;for(e=e||[];t=d();)!1!==t&&e.push(t);return e}function d(){var e=l();if("/"==n.charAt(0)&&"*"==n.charAt(1)){for(var t=2;T!=n.charAt(t)&&("*"!=n.charAt(t)||"/"!=n.charAt(t+1));)++t;if(t+=2,T===n.charAt(t-1))return c("End of comment missing");var r=n.slice(2,t-2);return o+=2,a(r),n=n.slice(t),o+=2,e({type:"comment",comment:r})}}function m(){var e=l(),t=u(k);if(t){if(d(),!u(x))return c("property missing ':'");var r=u(b),n=e({type:"declaration",property:E(t[0].replace(h,T)),value:r?E(r[0].replace(h,T)):T});return u(w),n}}return s.prototype.content=n,p(),function(){var e,t=[];for(f(t);e=m();)!1!==e&&(t.push(e),f(t));return t}()}var a={html:n,svg:i,properties:o,isCustomAttribute:RegExp.prototype.test.bind(new RegExp("^(data|aria)-[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"))},h=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,y=/\n/g,v=/^\s*/,k=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,x=/^:\s*/,b=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,w=/^[;\s]*/,l=/^\s+|\s+$/g,T="";function E(e){return e?e.replace(l,T):T}var S=function(e,t){var r,n=null;if(!e||"string"!=typeof e)return n;for(var i,o,a=m(e),l="function"==typeof t,s=0,c=a.length;s<c;s++)i=(r=a[s]).property,o=r.value,l?t(i,o,r):o&&((n=n||{})[i]=o);return n},C=/-([a-z])/g,O=/^--[a-zA-Z0-9-]+$|^[^-]+$/;var F={PRESERVE_CUSTOM_ATTRIBUTES:16<=g.version.split(".")[0],camelCase:function(e){if("string"!=typeof e)throw new TypeError("First argument must be a string");return O.test(e)?e:e.toLowerCase().replace(C,function(e,t){return t.toUpperCase()})},invertObject:function(e,t){if(!e||"object"!=typeof e)throw new TypeError("First argument must be an object");var r,n,i="function"==typeof t,o={},a={};for(r in e)n=e[r],i&&(o=t(r,n))&&2===o.length?a[o[0]]=o[1]:"string"==typeof n&&(a[n]=r);return a},isCustomComponent:function(e,t){if(-1===e.indexOf("-"))return t&&"string"==typeof t.is;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}},A=F.camelCase,M=a.html,R=a.svg,P=a.isCustomAttribute,D=Object.prototype.hasOwnProperty;var L=function(e){var t,r,n,i;e=e||{};var o={};for(t in e)n=e[t],P(t)?o[t]=n:(r=t.toLowerCase(),D.call(M,r)?o[(i=M[r]).propertyName]=!!(i.hasBooleanValue||i.hasOverloadedBooleanValue&&!n)||n:D.call(R,t)?o[(i=R[t]).propertyName]=n:F.PRESERVE_CUSTOM_ATTRIBUTES&&(o[t]=n));return null!=e.style&&(o.style=function(e){var r={};e&&S(e,function(e,t){e&&t&&(r[A(e)]=t)});return r}(e.style)),o};for(var N,B=function e(t,r){for(var n,i,o,a,l,s=(r=r||{}).library||g,c=s.cloneElement,u=s.createElement,p=s.isValidElement,f=[],d="function"==typeof r.replace,m=0,h=t.length;m<h;m++)if(n=t[m],d&&p(i=r.replace(n)))1<h&&(i=c(i,{key:i.key||m})),f.push(i);else if("text"!==n.type){if(o=n.attribs,l=n,F.PRESERVE_CUSTOM_ATTRIBUTES&&"tag"===l.type&&F.isCustomComponent(l.name,l.attribs)||(o=L(n.attribs)),a=null,"script"===n.type||"style"===n.type)n.children[0]&&(o.dangerouslySetInnerHTML={__html:n.children[0].data});else{if("tag"!==n.type)continue;"textarea"===n.name&&n.children[0]?o.defaultValue=n.children[0].data:n.children&&n.children.length&&(a=e(n.children,r))}1<h&&(o.key=m),f.push(u(n.name,o,a))}else f.push(n.data);return 1===f.length?f[0]:f},z=["animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussainBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","linearGradient","radialGradient","textPath"],I={},H=0,V=z.length;H<V;H++)I[(N=z[H]).toLowerCase()]=N;function U(e){for(var t,r={},n=0,i=e.length;n<i;n++)r[(t=e[n]).name]=t.value;return r}function j(e){e=e.toLowerCase();var t=I[e];return t||e}var X={formatAttributes:U,formatDOM:function e(t,r,n){r=r||null;for(var i,o,a,l=[],s=0,c=t.length;s<c;s++){switch(i=t[s],a={next:null,prev:l[s-1]||null,parent:r},(o=l[s-1])&&(o.next=a),"#"!==i.nodeName[0]&&(a.name=j(i.nodeName),a.attribs={},i.attributes&&i.attributes.length&&(a.attribs=U(i.attributes))),i.nodeType){case 1:"script"===a.name||"style"===a.name?a.type=a.name:a.type="tag",a.children=e(i.childNodes,a);break;case 3:a.type="text",a.data=i.nodeValue;break;case 8:a.type="comment",a.data=i.nodeValue}l.push(a)}return n&&(l.unshift({name:n.substring(0,n.indexOf(" ")).toLowerCase(),data:n,type:"directive",next:l[0]?l[0]:null,prev:null,parent:r}),l[1]&&(l[1].prev=l[0])),l},isIE:function(e){return e?document.documentMode===e:/(MSIE |Trident\/|Edge\/)/.test(navigator.userAgent)}},_="body",q=/<([a-zA-Z]+[0-9]?)/,Y=/<head.*>/i,$=/<body.*>/i,G=/<(area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr)(.*?)\/?>/gi,W=X.isIE(9),Z=W||X.isIE(),K=function(){throw new Error("This browser does not support `document.implementation.createHTMLDocument`")},J=function(){throw new Error("This browser does not support `DOMParser.prototype.parseFromString`")};if("function"==typeof window.DOMParser){var Q=new window.DOMParser,ee=W?"text/xml":"text/html";K=J=function(e,t){return t&&(e="<"+t+">"+e+"</"+t+">"),W&&(e=e.replace(G,"<$1$2$3/>")),Q.parseFromString(e,ee)}}if(document.implementation){var te=document.implementation.createHTMLDocument(Z?"html-dom-parser":void 0);K=function(t,e){if(e)return te.documentElement.getElementsByTagName(e)[0].innerHTML=t,te;try{return te.documentElement.innerHTML=t,te}catch(e){if(J)return J(t)}}}var re,ne=document.createElement("template");ne.content&&(re=function(e){return ne.innerHTML=e,ne.content.childNodes});var ie=function(e){var t,r,n,i,o=e.match(q);switch(o&&o[1]&&(t=o[1].toLowerCase()),t){case"html":return r=J(e),Y.test(e)||(n=r.getElementsByTagName("head")[0])&&n.parentNode.removeChild(n),$.test(e)||(n=r.getElementsByTagName(_)[0])&&n.parentNode.removeChild(n),r.getElementsByTagName("html");case"head":case _:return i=K(e).getElementsByTagName(t),$.test(e)&&Y.test(e)?i[0].parentNode.childNodes:i;default:return re?re(e):K(e,_).getElementsByTagName(_)[0].childNodes}},oe=X.formatDOM,ae=X.isIE(9),le=/<(![a-zA-Z\s]+)>/;var se=function(e){if("string"!=typeof e)throw new TypeError("First argument must be a string");if(!e)return[];var t,r=e.match(le);return r&&r[1]&&(t=r[1],ae&&(e=e.replace(r[0],""))),oe(ie(e),null,t)};function ce(e,t){if("string"!=typeof e)throw new TypeError("First argument must be a string");return""===e?[]:B(se(e),t)}ce.domToReact=B,ce.htmlToDOM=se;var ue=ce,pe=ce;return ue.default=pe,ue}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):(e=e||self).HTMLReactParser=t(e.React)}(this,function(g){"use strict";g=g&&Object.prototype.hasOwnProperty.call(g,"default")?g.default:g;var e={Properties:{autoFocus:4,accept:0,acceptCharset:0,accessKey:0,action:0,allowFullScreen:4,allowTransparency:0,alt:0,as:0,async:4,autoComplete:0,autoPlay:4,capture:4,cellPadding:0,cellSpacing:0,charSet:0,challenge:0,checked:5,cite:0,classID:0,className:0,cols:24,colSpan:0,content:0,contentEditable:0,contextMenu:0,controls:4,controlsList:0,coords:0,crossOrigin:0,data:0,dateTime:0,default:4,defer:4,dir:0,disabled:4,download:32,draggable:0,encType:0,form:0,formAction:0,formEncType:0,formMethod:0,formNoValidate:4,formTarget:0,frameBorder:0,headers:0,height:0,hidden:4,high:0,href:0,hrefLang:0,htmlFor:0,httpEquiv:0,icon:0,id:0,inputMode:0,integrity:0,is:0,keyParams:0,keyType:0,kind:0,label:0,lang:0,list:0,loop:4,low:0,manifest:0,marginHeight:0,marginWidth:0,max:0,maxLength:0,media:0,mediaGroup:0,method:0,min:0,minLength:0,multiple:5,muted:5,name:0,nonce:0,noValidate:4,open:4,optimum:0,pattern:0,placeholder:0,playsInline:4,poster:0,preload:0,profile:0,radioGroup:0,readOnly:4,referrerPolicy:0,rel:0,required:4,reversed:4,role:0,rows:24,rowSpan:8,sandbox:0,scope:0,scoped:4,scrolling:0,seamless:4,selected:5,shape:0,size:24,sizes:0,span:24,spellCheck:0,src:0,srcDoc:0,srcLang:0,srcSet:0,start:8,step:0,style:0,summary:0,tabIndex:0,target:0,title:0,type:0,useMap:0,value:0,width:0,wmode:0,wrap:0,about:0,datatype:0,inlist:0,prefix:0,property:0,resource:0,typeof:0,vocab:0,autoCapitalize:0,autoCorrect:0,autoSave:0,color:0,itemProp:0,itemScope:4,itemType:0,itemID:0,itemRef:0,results:0,security:0,unselectable:0},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"}},t={Properties:{accentHeight:0,accumulate:0,additive:0,alignmentBaseline:0,allowReorder:0,alphabetic:0,amplitude:0,arabicForm:0,ascent:0,attributeName:0,attributeType:0,autoReverse:0,azimuth:0,baseFrequency:0,baseProfile:0,baselineShift:0,bbox:0,begin:0,bias:0,by:0,calcMode:0,capHeight:0,clip:0,clipPath:0,clipRule:0,clipPathUnits:0,colorInterpolation:0,colorInterpolationFilters:0,colorProfile:0,colorRendering:0,contentScriptType:0,contentStyleType:0,cursor:0,cx:0,cy:0,d:0,decelerate:0,descent:0,diffuseConstant:0,direction:0,display:0,divisor:0,dominantBaseline:0,dur:0,dx:0,dy:0,edgeMode:0,elevation:0,enableBackground:0,end:0,exponent:0,externalResourcesRequired:0,fill:0,fillOpacity:0,fillRule:0,filter:0,filterRes:0,filterUnits:0,floodColor:0,floodOpacity:0,focusable:0,fontFamily:0,fontSize:0,fontSizeAdjust:0,fontStretch:0,fontStyle:0,fontVariant:0,fontWeight:0,format:0,from:0,fx:0,fy:0,g1:0,g2:0,glyphName:0,glyphOrientationHorizontal:0,glyphOrientationVertical:0,glyphRef:0,gradientTransform:0,gradientUnits:0,hanging:0,horizAdvX:0,horizOriginX:0,ideographic:0,imageRendering:0,in:0,in2:0,intercept:0,k:0,k1:0,k2:0,k3:0,k4:0,kernelMatrix:0,kernelUnitLength:0,kerning:0,keyPoints:0,keySplines:0,keyTimes:0,lengthAdjust:0,letterSpacing:0,lightingColor:0,limitingConeAngle:0,local:0,markerEnd:0,markerMid:0,markerStart:0,markerHeight:0,markerUnits:0,markerWidth:0,mask:0,maskContentUnits:0,maskUnits:0,mathematical:0,mode:0,numOctaves:0,offset:0,opacity:0,operator:0,order:0,orient:0,orientation:0,origin:0,overflow:0,overlinePosition:0,overlineThickness:0,paintOrder:0,panose1:0,pathLength:0,patternContentUnits:0,patternTransform:0,patternUnits:0,pointerEvents:0,points:0,pointsAtX:0,pointsAtY:0,pointsAtZ:0,preserveAlpha:0,preserveAspectRatio:0,primitiveUnits:0,r:0,radius:0,refX:0,refY:0,renderingIntent:0,repeatCount:0,repeatDur:0,requiredExtensions:0,requiredFeatures:0,restart:0,result:0,rotate:0,rx:0,ry:0,scale:0,seed:0,shapeRendering:0,slope:0,spacing:0,specularConstant:0,specularExponent:0,speed:0,spreadMethod:0,startOffset:0,stdDeviation:0,stemh:0,stemv:0,stitchTiles:0,stopColor:0,stopOpacity:0,strikethroughPosition:0,strikethroughThickness:0,string:0,stroke:0,strokeDasharray:0,strokeDashoffset:0,strokeLinecap:0,strokeLinejoin:0,strokeMiterlimit:0,strokeOpacity:0,strokeWidth:0,surfaceScale:0,systemLanguage:0,tableValues:0,targetX:0,targetY:0,textAnchor:0,textDecoration:0,textRendering:0,textLength:0,to:0,transform:0,u1:0,u2:0,underlinePosition:0,underlineThickness:0,unicode:0,unicodeBidi:0,unicodeRange:0,unitsPerEm:0,vAlphabetic:0,vHanging:0,vIdeographic:0,vMathematical:0,values:0,vectorEffect:0,version:0,vertAdvY:0,vertOriginX:0,vertOriginY:0,viewBox:0,viewTarget:0,visibility:0,widths:0,wordSpacing:0,writingMode:0,x:0,xHeight:0,x1:0,x2:0,xChannelSelector:0,xlinkActuate:0,xlinkArcrole:0,xlinkHref:0,xlinkRole:0,xlinkShow:0,xlinkTitle:0,xlinkType:0,xmlBase:0,xmlns:0,xmlnsXlink:0,xmlLang:0,xmlSpace:0,y:0,y1:0,y2:0,yChannelSelector:0,z:0,zoomAndPan:0},DOMAttributeNames:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDasharray:"stroke-dasharray",strokeDashoffset:"stroke-dashoffset",strokeLinecap:"stroke-linecap",strokeLinejoin:"stroke-linejoin",strokeMiterlimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",xlinkActuate:"xlink:actuate",xlinkArcrole:"xlink:arcrole",xlinkHref:"xlink:href",xlinkRole:"xlink:role",xlinkShow:"xlink:show",xlinkTitle:"xlink:title",xlinkType:"xlink:type",xmlBase:"xml:base",xmlnsXlink:"xmlns:xlink",xmlLang:"xml:lang",xmlSpace:"xml:space"}},s=1,c=4,u=8,p=24,f=32;function d(e,t){return(e&t)===t}function r(e,t,r){var n,i,o,a=e.Properties,l=e.DOMAttributeNames;for(i in a)n=l[i]||(r?i:i.toLowerCase()),o=a[i],t[n]={attributeName:n,propertyName:i,mustUseProperty:d(o,s),hasBooleanValue:d(o,c),hasNumericValue:d(o,u),hasPositiveNumericValue:d(o,p),hasOverloadedBooleanValue:d(o,f)}}var n={};r(e,n);var i={};r(t,i,!0);var o={};r(e,o),r(t,o,!0);function m(n,r){if("string"!=typeof n)throw new TypeError("First argument must be a string");if(!n)return[];r=r||{};var i=1,o=1;function a(e){var t=e.match(y);t&&(i+=t.length);var r=e.lastIndexOf("\n");o=~r?e.length-r:o+e.length}function l(){var t={line:i,column:o};return function(e){return e.position=new s(t),p(),e}}function s(e){this.start=e,this.end={line:i,column:o},this.source=r.source}function c(e){var t=new Error(r.source+":"+i+":"+o+": "+e);if(t.reason=e,t.filename=r.source,t.line=i,t.column=o,t.source=n,!r.silent)throw t}function u(e){var t=e.exec(n);if(t){var r=t[0];return a(r),n=n.slice(r.length),t}}function p(){u(v)}function f(e){var t;for(e=e||[];t=d();)!1!==t&&e.push(t);return e}function d(){var e=l();if("/"==n.charAt(0)&&"*"==n.charAt(1)){for(var t=2;T!=n.charAt(t)&&("*"!=n.charAt(t)||"/"!=n.charAt(t+1));)++t;if(t+=2,T===n.charAt(t-1))return c("End of comment missing");var r=n.slice(2,t-2);return o+=2,a(r),n=n.slice(t),o+=2,e({type:"comment",comment:r})}}function m(){var e=l(),t=u(k);if(t){if(d(),!u(x))return c("property missing ':'");var r=u(b),n=e({type:"declaration",property:E(t[0].replace(h,T)),value:r?E(r[0].replace(h,T)):T});return u(w),n}}return s.prototype.content=n,p(),function(){var e,t=[];for(f(t);e=m();)!1!==e&&(t.push(e),f(t));return t}()}var a={html:n,svg:i,properties:o,isCustomAttribute:RegExp.prototype.test.bind(new RegExp("^(data|aria)-[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"))},h=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,y=/\n/g,v=/^\s*/,k=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,x=/^:\s*/,b=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,w=/^[;\s]*/,l=/^\s+|\s+$/g,T="";function E(e){return e?e.replace(l,T):T}var C=function(e,t){var r,n=null;if(!e||"string"!=typeof e)return n;for(var i,o,a=m(e),l="function"==typeof t,s=0,c=a.length;s<c;s++)i=(r=a[s]).property,o=r.value,l?t(i,o,r):o&&((n=n||{})[i]=o);return n},S=/-([a-z])/g,O=/^--[a-zA-Z0-9-]+$|^[^-]+$/;var F={PRESERVE_CUSTOM_ATTRIBUTES:16<=g.version.split(".")[0],camelCase:function(e){if("string"!=typeof e)throw new TypeError("First argument must be a string");return O.test(e)?e:e.toLowerCase().replace(S,function(e,t){return t.toUpperCase()})},invertObject:function(e,t){if(!e||"object"!=typeof e)throw new TypeError("First argument must be an object");var r,n,i="function"==typeof t,o={},a={};for(r in e)n=e[r],i&&(o=t(r,n))&&2===o.length?a[o[0]]=o[1]:"string"==typeof n&&(a[n]=r);return a},isCustomComponent:function(e,t){if(-1===e.indexOf("-"))return t&&"string"==typeof t.is;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}},A=F.camelCase,M=a.html,R=a.svg,P=a.isCustomAttribute,D=Object.prototype.hasOwnProperty;var L=function(e){var t,r,n,i;e=e||{};var o={};for(t in e)n=e[t],P(t)?o[t]=n:(r=t.toLowerCase(),D.call(M,r)?o[(i=M[r]).propertyName]=!!(i.hasBooleanValue||i.hasOverloadedBooleanValue&&!n)||n:D.call(R,t)?o[(i=R[t]).propertyName]=n:F.PRESERVE_CUSTOM_ATTRIBUTES&&(o[t]=n));return null!=e.style&&(o.style=function(e){var r={};e&&C(e,function(e,t){e&&t&&(r[A(e)]=t)});return r}(e.style)),o};for(var N,B=function e(t,r){for(var n,i,o,a,l,s=(r=r||{}).library||g,c=s.cloneElement,u=s.createElement,p=s.isValidElement,f=[],d="function"==typeof r.replace,m=0,h=t.length;m<h;m++)if(n=t[m],d&&p(i=r.replace(n)))1<h&&(i=c(i,{key:i.key||m})),f.push(i);else if("text"!==n.type){if(o=n.attribs,l=n,F.PRESERVE_CUSTOM_ATTRIBUTES&&"tag"===l.type&&F.isCustomComponent(l.name,l.attribs)||(o=L(n.attribs)),a=null,"script"===n.type||"style"===n.type)n.children[0]&&(o.dangerouslySetInnerHTML={__html:n.children[0].data});else{if("tag"!==n.type)continue;"textarea"===n.name&&n.children[0]?o.defaultValue=n.children[0].data:n.children&&n.children.length&&(a=e(n.children,r))}1<h&&(o.key=m),f.push(u(n.name,o,a))}else f.push(n.data);return 1===f.length?f[0]:f},z=["animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussainBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","linearGradient","radialGradient","textPath"],I={},H=0,V=z.length;H<V;H++)I[(N=z[H]).toLowerCase()]=N;function U(e){for(var t,r={},n=0,i=e.length;n<i;n++)r[(t=e[n]).name]=t.value;return r}function j(e){e=e.toLowerCase();var t=I[e];return t||e}var X={formatAttributes:U,formatDOM:function e(t,r,n){r=r||null;for(var i,o,a,l=[],s=0,c=t.length;s<c;s++){switch(i=t[s],a={next:null,prev:l[s-1]||null,parent:r},(o=l[s-1])&&(o.next=a),"#"!==i.nodeName[0]&&(a.name=j(i.nodeName),a.attribs={},i.attributes&&i.attributes.length&&(a.attribs=U(i.attributes))),i.nodeType){case 1:"script"===a.name||"style"===a.name?a.type=a.name:a.type="tag",a.children=e(i.childNodes,a);break;case 3:a.type="text",a.data=i.nodeValue;break;case 8:a.type="comment",a.data=i.nodeValue}l.push(a)}return n&&(l.unshift({name:n.substring(0,n.indexOf(" ")).toLowerCase(),data:n,type:"directive",next:l[0]?l[0]:null,prev:null,parent:r}),l[1]&&(l[1].prev=l[0])),l},isIE:function(e){return e?document.documentMode===e:/(MSIE |Trident\/|Edge\/)/.test(navigator.userAgent)}},_="body",q=/<([a-zA-Z]+[0-9]?)/,Y=/<head.*>/i,$=/<body.*>/i,G=/<(area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr)(.*?)\/?>/gi,W=X.isIE(9),Z=W||X.isIE(),K=function(){throw new Error("This browser does not support `document.implementation.createHTMLDocument`")},J=function(){throw new Error("This browser does not support `DOMParser.prototype.parseFromString`")};if("function"==typeof window.DOMParser){var Q=new window.DOMParser,ee=W?"text/xml":"text/html";K=J=function(e,t){return t&&(e="<"+t+">"+e+"</"+t+">"),W&&(e=e.replace(G,"<$1$2$3/>")),Q.parseFromString(e,ee)}}if(document.implementation){var te=document.implementation.createHTMLDocument(Z?"html-dom-parser":void 0);K=function(t,e){if(e)return te.documentElement.getElementsByTagName(e)[0].innerHTML=t,te;try{return te.documentElement.innerHTML=t,te}catch(e){if(J)return J(t)}}}var re,ne=document.createElement("template");ne.content&&(re=function(e){return ne.innerHTML=e,ne.content.childNodes});var ie=function(e){var t,r,n,i,o=e.match(q);switch(o&&o[1]&&(t=o[1].toLowerCase()),t){case"html":return r=J(e),Y.test(e)||(n=r.getElementsByTagName("head")[0])&&n.parentNode.removeChild(n),$.test(e)||(n=r.getElementsByTagName(_)[0])&&n.parentNode.removeChild(n),r.getElementsByTagName("html");case"head":case _:return i=K(e).getElementsByTagName(t),$.test(e)&&Y.test(e)?i[0].parentNode.childNodes:i;default:return re?re(e):K(e,_).getElementsByTagName(_)[0].childNodes}},oe=X.formatDOM,ae=X.isIE(9),le=/<(![a-zA-Z\s]+)>/;var se=function(e){if("string"!=typeof e)throw new TypeError("First argument must be a string");if(!e)return[];var t,r=e.match(le);return r&&r[1]&&(t=r[1],ae&&(e=e.replace(r[0],""))),oe(ie(e),null,t)},ce={decodeEntities:!0,lowerCaseAttributeNames:!1};function ue(e,t){if("string"!=typeof e)throw new TypeError("First argument must be a string");return""===e?[]:B(se(e,(t=t||{}).htmlparser2||ce),t)}ue.domToReact=B,ue.htmlToDOM=se;var pe=ue,fe=ue;return pe.default=fe,pe}); | ||
//# sourceMappingURL=html-react-parser.min.js.map |
// TypeScript Version: 3.3 | ||
import { DomElement } from 'domhandler'; | ||
import { DomElement, ParserOptions } from 'htmlparser2'; | ||
import domToReact from './lib/dom-to-react'; | ||
@@ -8,5 +8,4 @@ import htmlToDOM from 'html-dom-parser'; | ||
export interface HTMLReactParserOptions { | ||
replace?: ( | ||
domNode: DomElement | ||
) => JSX.Element | object | void | undefined | null | false; | ||
htmlparser2?: ParserOptions; | ||
library?: { | ||
@@ -22,2 +21,6 @@ cloneElement: ( | ||
}; | ||
replace?: ( | ||
domNode: DomElement | ||
) => JSX.Element | object | void | undefined | null | false; | ||
} | ||
@@ -28,5 +31,5 @@ | ||
* | ||
* @param html - HTML string to parse to JSX element(s). | ||
* @param html - HTML string. | ||
* @param options - Parser options. | ||
* @return - JSX element(s). | ||
* @return - JSX element(s), empty array, or string. | ||
*/ | ||
@@ -38,4 +41,4 @@ declare function HTMLReactParser( | ||
export { DomElement, domToReact, htmlToDOM }; | ||
export { DomElement, ParserOptions, domToReact, htmlToDOM }; | ||
export default HTMLReactParser; |
16
index.js
@@ -10,6 +10,8 @@ var domToReact = require('./lib/dom-to-react'); | ||
* | ||
* @param {String} html - The HTML string to parse to React. | ||
* @param {Object} [options] - The parser options. | ||
* @param {Function} [options.replace] - The replace method. | ||
* @return {JSX.Element|JSX.Element[]|String} - Returns React element(s), string, or empty array. | ||
* @param {String} html - HTML string. | ||
* @param {Object} [options] - Parser options. | ||
* @param {Object} [options.htmlparser2] - htmlparser2 options. | ||
* @param {Object} [options.library] - Library for React, Preact, etc. | ||
* @param {Function} [options.replace] - Replace method. | ||
* @return {JSX.Element|JSX.Element[]|String} - React element(s), empty array, or string. | ||
*/ | ||
@@ -23,3 +25,7 @@ function HTMLReactParser(html, options) { | ||
} | ||
return domToReact(htmlToDOM(html, domParserOptions), options); | ||
options = options || {}; | ||
return domToReact( | ||
htmlToDOM(html, options.htmlparser2 || domParserOptions), | ||
options | ||
); | ||
} | ||
@@ -26,0 +32,0 @@ |
{ | ||
"name": "html-react-parser", | ||
"version": "0.11.1", | ||
"version": "0.12.0", | ||
"description": "HTML to React parser.", | ||
@@ -35,3 +35,3 @@ "author": "Mark <mark@remarkablemark.org>", | ||
"dependencies": { | ||
"@types/domhandler": "2.4.1", | ||
"@types/htmlparser2": "3.10.1", | ||
"html-dom-parser": "0.3.0", | ||
@@ -38,0 +38,0 @@ "react-property": "1.0.1", |
@@ -109,3 +109,3 @@ # html-react-parser | ||
The first argument is an object with the same output as [htmlparser2](https://github.com/fb55/htmlparser2)'s [domhandler](https://github.com/fb55/domhandler#example): | ||
The first argument is an object with the same output as [htmlparser2](https://github.com/fb55/htmlparser2/tree/v3.10.1)'s [domhandler](https://github.com/fb55/domhandler#example): | ||
@@ -228,2 +228,30 @@ ```js | ||
### htmlparser2 | ||
This library passes the following options to [htmlparser2](https://github.com/fb55/htmlparser2/tree/v3.10.1) on the server-side: | ||
```js | ||
{ | ||
decodeEntities: true, | ||
lowerCaseAttributeNames: false | ||
} | ||
``` | ||
By passing your own options, the default library options will be **replaced** (not merged). | ||
As a result, to enable `decodeEntities` and `xmlMode`, you need to do the following: | ||
```js | ||
parse('<p /><p />', { | ||
htmlparser2: { | ||
decodeEntities: true, | ||
xmlMode: true | ||
} | ||
}); | ||
``` | ||
See [htmlparser2 options](https://github.com/fb55/htmlparser2/wiki/Parser-options). | ||
> **Warning**: By overriding htmlparser2 options, there's a chance of breaking universal rendering. Do this at your own risk. | ||
## FAQ | ||
@@ -230,0 +258,0 @@ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
248418
1917
349
+ Added@types/htmlparser2@3.10.1
+ Added@types/domhandler@2.4.53.1.0(transitive)
+ Added@types/domutils@1.7.8(transitive)
+ Added@types/htmlparser2@3.10.1(transitive)
+ Added@types/node@22.13.8(transitive)
+ Addeddomhandler@5.0.3(transitive)
+ Addedundici-types@6.20.0(transitive)
- Removed@types/domhandler@2.4.1