@xysfe/memento-snapshot
Version:
rrweb's component to take a snapshot of DOM, aka DOM serializer
3 lines (2 loc) • 13.8 kB
JavaScript
var snapshot=function(e){"use strict";var t;(t=e.NodeType||(e.NodeType={}))[t.Document=0]="Document",t[t.DocumentType=1]="DocumentType",t[t.Element=2]="Element",t[t.Text=3]="Text",t[t.CDATA=4]="CDATA",t[t.Comment=5]="Comment";var r=1,n=RegExp("[^a-z1-6-]");function i(e){try{var t=e.rules||e.cssRules;return t?Array.from(t).reduce(function(e,t){return e+(function(e){return"styleSheet"in e}(r=t)?i(r.styleSheet)||"":r.cssText);var r},""):null}catch(e){return null}}var a=/url\((?:'([^']*)'|"([^"]*)"|([^)]*))\)/gm,o=/^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/\/).*/,s=/^(data:)([\w\/\+\-]+);(charset=[\w-]+|base64).*,(.*)/i;function c(e,t){return(e||"").replace(a,function(e,r,n,i){var a,c=r||n||i;if(!c)return e;if(!o.test(c))return"url('"+c+"')";if(s.test(c))return"url("+c+")";if("/"===c[0])return"url('"+(((a=t).indexOf("//")>-1?a.split("/").slice(0,3).join("/"):a.split("/")[0]).split("?")[0]+c)+"')";var u=t.split("/"),l=c.split("/");u.pop();for(var f=0,m=l;f<m.length;f++){var p=m[f];"."!==p&&(".."===p?u.pop():u.push(p))}return"url('"+u.join("/")+"')"})}function u(e,t){if(!t||""===t.trim())return t;var r=e.createElement("a");return r.href=t,r.href}function l(e,t,r){return"src"===t||"href"===t&&r?u(e,r):"srcset"===t&&r?function(e,t){return""===t.trim()?t:t.split(",").map(function(t){var r=t.trimLeft().trimRight().split(" ");return 2===r.length?u(e,r[0])+" "+r[1]:1===r.length?""+u(e,r[0]):""}).join(", ")}(e,r):"style"===t&&r?c(r,location.href):r}function f(t,r,a,o,s,u,f){switch(void 0===s&&(s={}),void 0===u&&(u=[]),void 0===f&&(f=!1),t.nodeType){case t.DOCUMENT_NODE:return{type:e.NodeType.Document,childNodes:[]};case t.DOCUMENT_TYPE_NODE:return{type:e.NodeType.DocumentType,name:t.name,publicId:t.publicId,systemId:t.systemId};case t.ELEMENT_NODE:var m=!1,p="";"string"==typeof a?m=t.classList.contains(a):t.classList&&t.classList.forEach&&t.classList.forEach(function(e){a.test(e)&&(m=!0)});var d=function(e){var t=e.toLowerCase().trim();return n.test(t)?"div":t}(t.tagName);if(!m)for(var h=0,v=u;h<v.length;h++){var g=v[h];if(d===g.tagName){m=!0,g.placeholder&&(p=g.placeholder);break}}for(var y={},T=0,N=Array.from(t.attributes);T<N.length;T++){var _=N[T],b=_.name,E=_.value;y[b]=l(r,b,E);var w="img"===d&&"src"===b||"link"===d&&"href"===b,x=t.rel;!w||("dns-prefetch"===x||"preload"===x)||/^data:image/i.test(y[b])||(y["_memimage_"+b]=y[b])}var C=t.rel;if("link"===d&&!("dns-prefetch"===C||"preload"===C||"prefetch"===C)&&o){var D,A=Array.from(r.styleSheets).find(function(e){return e.href===t.href});(D=i(A))&&(delete y.rel,delete y.href,"_memimage_href"in y&&delete y._memimage_href,y._cssText=c(D,A.href))}if("style"===d&&t.sheet&&!(t.innerText||t.textContent||"").trim().length)(D=i(t.sheet))&&(y._cssText=c(D,location.href));if("input"===d||"textarea"===d||"select"===d){E=t.value;"radio"!==y.type&&"checkbox"!==y.type&&"submit"!==y.type&&"button"!==y.type&&E?y.value=s[y.type]||s[d]?"*".repeat(E.length):E:t.checked&&(y.checked=t.checked)}if("option"===d){var k=t.parentElement;y.value===k.value&&(y.selected=t.selected)}if("canvas"===d&&f&&(y.mem_dataURL=t.toDataURL()),t.scrollLeft&&(y.mem_scrollLeft=t.scrollLeft),t.scrollTop&&(y.mem_scrollTop=t.scrollTop),m){var L=t.getBoundingClientRect(),O=L.width,S=L.height;y.mem_width=O+"px",y.mem_height=S+"px",p&&(y.mem_placeholder=p)}return{type:e.NodeType.Element,tagName:d,attributes:y,childNodes:[],isSVG:(G=t,"svg"===G.tagName||G instanceof SVGElement||void 0),needBlock:m};case t.TEXT_NODE:var I=t.parentNode&&t.parentNode.tagName,R=t.textContent,M="STYLE"===I||void 0;return M&&R&&(R=c(R,location.href)),"SCRIPT"===I&&(R="SCRIPT_PLACEHOLDER"),{type:e.NodeType.Text,textContent:R||"",isStyle:M};case t.CDATA_SECTION_NODE:return{type:e.NodeType.CDATA,textContent:""};case t.COMMENT_NODE:return{type:e.NodeType.Comment,textContent:t.textContent||""};default:return!1}var G}function m(t,n,i,a,o,s,c,u,l){void 0===o&&(o=!1),void 0===s&&(s=!0),void 0===u&&(u=[]),void 0===l&&(l=!1);var p,d=f(t,n,a,s,c,u,l);if(!d)return console.warn(t,"not serialized"),null;p="__sn"in t?t.__sn.id:r++;var h=Object.assign(d,{id:p});t.__sn=h,i[p]=t;var v=!o;if(h.type===e.NodeType.Element&&(v=v&&!h.needBlock,delete h.needBlock),(h.type===e.NodeType.Document||h.type===e.NodeType.Element)&&v)for(var g=0,y=Array.from(t.childNodes);g<y.length;g++){var T=m(y[g],n,i,a,o,s,c,u,l);T&&h.childNodes.push(T)}return h}var p=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g;function d(e,t){void 0===t&&(t={});var r=1,n=1;function i(e){var t=e.match(/\n/g);t&&(r+=t.length);var i=e.lastIndexOf("\n");n=-1===i?n+e.length:e.length-i}function a(){var e={line:r,column:n};return function(t){return t.position=new o(e),d(),t}}var o=function(){return function(e){this.start=e,this.end={line:r,column:n},this.source=t.source}}();o.prototype.content=e;var s=[];function c(i){var a=new Error(t.source+":"+r+":"+n+": "+i);if(a.reason=i,a.filename=t.source,a.line=r,a.column=n,a.source=e,!t.silent)throw a;s.push(a)}function u(){return m(/^{\s*/)}function l(){return m(/^}/)}function f(){var t,r=[];for(d(),v(r);e.length&&"}"!==e.charAt(0)&&(t=D()||A());)!1!==t&&(r.push(t),v(r));return r}function m(t){var r=t.exec(e);if(r){var n=r[0];return i(n),e=e.slice(n.length),r}}function d(){m(/^\s*/)}function v(e){var t;for(void 0===e&&(e=[]);t=g();)!1!==t&&e.push(t),t=g();return e}function g(){var t=a();if("/"===e.charAt(0)&&"*"===e.charAt(1)){for(var r=2;""!==e.charAt(r)&&("*"!==e.charAt(r)||"/"!==e.charAt(r+1));)++r;if(r+=2,""===e.charAt(r-1))return c("End of comment missing");var o=e.slice(2,r-2);return n+=2,i(o),e=e.slice(r),n+=2,t({type:"comment",comment:o})}}function y(){var e=m(/^([^{]+)/);if(e)return h(e[0]).replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g,"").replace(/"(?:\\"|[^"])*"|'(?:\\'|[^'])*'/g,function(e){return e.replace(/,/g,"")}).split(/\s*(?![^(]*\)),\s*/).map(function(e){return e.replace(/\u200C/g,",")})}function T(){var e=a(),t=m(/^(\*?[-#\/\*\\\w]+(\[[0-9a-z_-]+\])?)\s*/);if(t){var r=h(t[0]);if(!m(/^:\s*/))return c("property missing ':'");var n=m(/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^\)]*?\)|[^};])+)/),i=e({type:"declaration",property:r.replace(p,""),value:n?h(n[0]).replace(p,""):""});return m(/^[;\s]*/),i}}function N(){var e,t=[];if(!u())return c("missing '{'");for(v(t);e=T();)!1!==e&&(t.push(e),v(t)),e=T();return l()?t:c("missing '}'")}function _(){for(var e,t=[],r=a();e=m(/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/);)t.push(e[1]),m(/^,\s*/);if(t.length)return r({type:"keyframe",values:t,declarations:N()})}var b,E=C("import"),w=C("charset"),x=C("namespace");function C(e){var t=new RegExp("^@"+e+"\\s*([^;]+);");return function(){var r=a(),n=m(t);if(n){var i={type:e};return i[e]=n[1].trim(),r(i)}}}function D(){if("@"===e[0])return function(){var e=a(),t=m(/^@([-\w]+)?keyframes\s*/);if(t){var r=t[1];if(!(t=m(/^([-\w]+)\s*/)))return c("@keyframes missing name");var n,i=t[1];if(!u())return c("@keyframes missing '{'");for(var o=v();n=_();)o.push(n),o=o.concat(v());return l()?e({type:"keyframes",name:i,vendor:r,keyframes:o}):c("@keyframes missing '}'")}}()||function(){var e=a(),t=m(/^@media *([^{]+)/);if(t){var r=h(t[1]);if(!u())return c("@media missing '{'");var n=v().concat(f());return l()?e({type:"media",media:r,rules:n}):c("@media missing '}'")}}()||function(){var e=a(),t=m(/^@custom-media\s+(--[^\s]+)\s*([^{;]+);/);if(t)return e({type:"custom-media",name:h(t[1]),media:h(t[2])})}()||function(){var e=a(),t=m(/^@supports *([^{]+)/);if(t){var r=h(t[1]);if(!u())return c("@supports missing '{'");var n=v().concat(f());return l()?e({type:"supports",supports:r,rules:n}):c("@supports missing '}'")}}()||E()||w()||x()||function(){var e=a(),t=m(/^@([-\w]+)?document *([^{]+)/);if(t){var r=h(t[1]),n=h(t[2]);if(!u())return c("@document missing '{'");var i=v().concat(f());return l()?e({type:"document",document:n,vendor:r,rules:i}):c("@document missing '}'")}}()||function(){var e=a();if(m(/^@page */)){var t=y()||[];if(!u())return c("@page missing '{'");for(var r,n=v();r=T();)n.push(r),n=n.concat(v());return l()?e({type:"page",selectors:t,declarations:n}):c("@page missing '}'")}}()||function(){var e=a();if(m(/^@host\s*/)){if(!u())return c("@host missing '{'");var t=v().concat(f());return l()?e({type:"host",rules:t}):c("@host missing '}'")}}()||function(){var e=a();if(m(/^@font-face\s*/)){if(!u())return c("@font-face missing '{'");for(var t,r=v();t=T();)r.push(t),r=r.concat(v());return l()?e({type:"font-face",declarations:r}):c("@font-face missing '}'")}}()}function A(){var e=a(),t=y();return t?(v(),e({type:"rule",selectors:t,declarations:N()})):c("selector missing")}return function e(t,r){var n=t&&"string"==typeof t.type;var i=n?t:r;for(var a=0,o=Object.keys(t);a<o.length;a++){var s=o[a],c=t[s];Array.isArray(c)?c.forEach(function(t){e(t,i)}):c&&"object"==typeof c&&e(c,i)}n&&Object.defineProperty(t,"parent",{configurable:!0,writable:!0,enumerable:!1,value:r||null});return t}((b=f(),{type:"stylesheet",stylesheet:{source:t.source,rules:b,parsingErrors:s}}))}function h(e){return e?e.replace(/^\s+|\s+$/g,""):""}var v={script:"noscript",altglyph:"altGlyph",altglyphdef:"altGlyphDef",altglyphitem:"altGlyphItem",animatecolor:"animateColor",animatemotion:"animateMotion",animatetransform:"animateTransform",clippath:"clipPath",feblend:"feBlend",fecolormatrix:"feColorMatrix",fecomponenttransfer:"feComponentTransfer",fecomposite:"feComposite",feconvolvematrix:"feConvolveMatrix",fediffuselighting:"feDiffuseLighting",fedisplacementmap:"feDisplacementMap",fedistantlight:"feDistantLight",fedropshadow:"feDropShadow",feflood:"feFlood",fefunca:"feFuncA",fefuncb:"feFuncB",fefuncg:"feFuncG",fefuncr:"feFuncR",fegaussianblur:"feGaussianBlur",feimage:"feImage",femerge:"feMerge",femergenode:"feMergeNode",femorphology:"feMorphology",feoffset:"feOffset",fepointlight:"fePointLight",fespecularlighting:"feSpecularLighting",fespotlight:"feSpotLight",fetile:"feTile",feturbulence:"feTurbulence",foreignobject:"foreignObject",glyphref:"glyphRef",lineargradient:"linearGradient",radialgradient:"radialGradient"};var g=/([^\\]):hover/g,y=/(\s|;|\{)inset\s*:([^;}]+)/gi;function T(e){var t=d(e,{silent:!0});return t.stylesheet&&t.stylesheet.rules?(t.stylesheet.rules.forEach(function(t){"selectors"in t&&(t.selectors||[]).forEach(function(t){if(g.test(t)){var r=t.replace(g,"$1.\\:hover");e=e.replace(t,t+", "+r)}})}),e.replace(y,"$1top: $2; right: $2; bottom: $2; left: $2;")):e}var N=/url\((data:image\/svg\+xml;charset=[\w-].*?)\)\s*(;|\}|$)/gi;function _(e){return e?e.replace(N,function(e,t,r){return'url("'+t+'")'+r}):e}function b(t,r,n,i){switch(void 0===i&&(i=!0),t.type){case e.NodeType.Document:return r.implementation.createDocument(null,"",null);case e.NodeType.DocumentType:return r.implementation.createDocumentType(t.name,t.publicId,t.systemId);case e.NodeType.Element:var a,o=function(e){var t=v[e.tagName]?v[e.tagName]:e.tagName;return"link"===t&&e.attributes._cssText&&(t="style"),t}(t);a=t.isSVG?r.createElementNS("http://www.w3.org/2000/svg",o):r.createElement(o);var s=function(e){if(!t.attributes.hasOwnProperty(e))return"continue";if(t.attributes.hasOwnProperty("_memimage_"+e))return"continue";var s=t.attributes[e];s="boolean"==typeof s||"number"==typeof s?"":s;var c=e;if((e=e.replace("_memimage_","")).startsWith("mem_")){if("canvas"===o&&"mem_dataURL"===e){var u=document.createElement("img");u.src=s,u.onload=function(){var e=a.getContext("2d");e&&e.drawImage(u,0,0,u.width,u.height)}}"mem_imgwidth"===e?a.style.width=s:"mem_width"===e?a.style.width=s:"mem_imgheight"===e?a.style.height=s:"mem_height"===e?a.style.height=s:"video"===o&&"mem_placeholder"===c&&(a.style.background="center / cover no-repeat url("+s+") !important")}else{var l="textarea"===o&&"value"===e,f="style"===o&&"_cssText"===e;if(f&&n&&(s=_(s=T(s))),l||f){for(var m=r.createTextNode(s),p=0,d=Array.from(a.childNodes);p<d.length;p++){var h=d[p];h.nodeType===a.TEXT_NODE&&a.removeChild(h)}return a.appendChild(m),"continue"}if("iframe"===o&&"src"===e)return"continue";try{t.isSVG&&"xlink:href"===e?a.setAttributeNS("http://www.w3.org/1999/xlink",e,s):"onload"===e||"onclick"===e||"onmouse"===e.substring(0,7)?a.setAttribute("_"+e,s):(i&&"link"===o&&"_memimage_href"===c&&s&&s.match(/memento\.oss/)&&(s=s.replace(/^http\:\/\//,"https://")),a.setAttribute(e,s))}catch(e){}}};for(var c in t.attributes)s(c);return a;case e.NodeType.Text:var u=t.isStyle?_(t.textContent):t.textContent;return r.createTextNode(t.isStyle&&n?T(u):u);case e.NodeType.CDATA:return r.createCDATASection(t.textContent);case e.NodeType.Comment:return r.createComment(t.textContent);default:return null}}function E(t,r,n,i,a,o){void 0===i&&(i=!1),void 0===a&&(a=!0),void 0===o&&(o=!0);var s=b(t,r,a,o);if(!s)return null;if(t.type===e.NodeType.Document&&(r.close(),r.open(),s=r),s.__sn=t,n[t.id]=s,(t.type===e.NodeType.Document||t.type===e.NodeType.Element)&&!i)for(var c=0,u=t.childNodes;c<u.length;c++){var l=u[c],f=E(l,r,n,!1,a,o);f?s.appendChild(f):console.warn("Failed to rebuild",l)}return s}return e.snapshot=function(e,t,r,n,i,a){void 0===t&&(t="mem-block"),void 0===r&&(r=!0),void 0===i&&(i=[]),void 0===a&&(a=!1);var o={};return[m(e,e,o,t,!1,r,!0===n?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0}:!1===n?{}:n,i,a),o]},e.serializeNodeWithId=m,e.rebuild=function(t,r,n,i){void 0===n&&(n=!0),void 0===i&&(i=!0);var a={},o=E(t,r,a,!1,n,i);return function(t){for(var r in t){var n=t[r],i=n.__sn;if(i.type===e.NodeType.Element){var a=n;for(var o in i.attributes)if(i.attributes.hasOwnProperty(o)&&o.startsWith("mem_")){var s=i.attributes[o];"mem_scrollLeft"===o&&(a.scrollLeft=s),"mem_scrollTop"===o&&(a.scrollTop=s)}}}}(a),[o,a]},e.buildNodeWithSN=E,e.addHoverClass=T,e.transformAttribute=l,e}({});
//# sourceMappingURL=memento-snapshot.min.js.map