Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 | 14x 14x 14x 14x 20712x 11477x 238x 7708x 3048x 61x 53x 233x 154x 5548x 229x 14x 910x 910x 910x 14x 39x 39x 61x 39x 11x 39x 307x 11x 316x 316x 316x 316x 316x 477x 316x 264x 261x 47x 261x 264x 109x 592x 727x 727x 49x 678x 22x 656x 26x 51x 26x 630x 11x 11x 28x 11x 619x 619x 7708x 2777x 4931x 4638x 293x 619x 2600x 5295x 2774x 2774x 2774x 2774x 2774x 2774x 2774x 269x 23x 269x 269x 269x 269x 2774x 2509x 2774x 2774x 2801x 2774x 75x 74x 74x 2851x 75x 79x 79x 79x 79x 3x 76x 76x 76x 76x 4x 3x 3x 75x 75x 2550x 75x 75x 75x 75x 75x 75x 75x 51x 647x 51x 24x 75x 75x 75x 155x 75x 75x 3x 72x 72x 27x 27x 27x 27x 27x 9x 27x 27x 14x 14x 14x 14x 8x 8x 8x 8x 8x 8x 8x 6x 14x 14x 14x 13x 13x 72x 7x 7x 7x 72x 72x 72x 72x 72x 72x 13x 13x 13x 13x 13x 13x 72x 72x 72x 72x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 7x 2x 5x 3x 2x 2x 1x 1x 330x 14x 274x 278x 278x 278x 2x 2x 2x 2x 636x 496x 222x 274x 274x 278x 278x 278x 492x 1513x 438x 278x 98x 278x 278x 278x 278x 18x 4x 14x 18x 18x 18x 260x 11x 11x 11x 249x 249x 249x 11x 238x 176x 62x 267x 3430x 3430x 14x 80x 57x 23x 4x 4x 4x 19x 19x 19x 2x 17x 17x 14x 8x 3x 19x 19x 19x 9x 9x 7x 2x 2x 10x 3150x 7958x 7958x 7958x 138x 3732x 3732x 8287x 8287x 7243x 3014x 3014x 29x 4229x 1044x 1044x 259x 8287x 232x 232x 1372x 16x 216x 2671x 2671x 8x 2663x 2663x 5753x 5753x 2581x 2581x 3172x 2663x 5956x 5956x 5956x 5724x 2574x 182x 3150x 3150x 2413x 5724x 232x 2663x 29x 29x 1x 1x 1x 14x 7x 7x 14x 125x 59x 66x 66x 66x 66x 14x 60x 60x 8x 52x 52x 52x 4x 26x 4x 18x 18x 14x 18x 14x 14x 82x 82x 104x 82x 120x 82x 36x 46x 46x 46x 902x 46x 46x 14x 80x 13x 80x 80x 80x 80x 79x 7x 7x 7x 7x 80x 79x 78x 78x 3x 75x 76x 76x 76x 82x 82x 81x 76x 75x 82x 79x 79x 38x 38x 38x 38x 38x 242x 1x 1x 1x 241x 205x 36x 24x 79x 236x 236x 155x 236x 79x 79x 79x 79x 137x 79x 79x 79x 79x 79x 79x 79x 79x 79x 227x 227x 265x 265x 14x 251x 251x 227x 79x 273x 273x 148x 148x 148x 79x 258x 258x 258x 258x 258x 258x 258x 258x 258x 258x 258x 27x 7x 7x 258x 36x 36x 24x 24x 584x 584x 584x 258x 584x 584x 584x 584x 88x 88x 3x 88x 98x 245x 245x 245x 245x 245x 11x 4x 7x 7x 7x 7x 245x 245x 245x 245x 11x 11x 11x 2x 2x 2x 1x 1x 1x 1x 1x 9x 243x 88x 42x 30x 12x 258x 79x 79x 37x 37x 37x 37x 37x 57x 51x 6x 6x 75x 75x 75x 75x 22x 53x 53x 53x 53x 99x 142x 53x 135x 3x 1x 14x | const XSL_NS_URL = 'http://www.w3.org/1999/XSL/Transform'
, HTML_NS_URL = 'http://www.w3.org/1999/xhtml'
, EXSL_NS_URL = 'http://exslt.org/common'
, DCE_NS_URL ="urn:schemas-epa-wg:dce";
// const log = x => console.debug( new XMLSerializer().serializeToString( x ) );
const attr = (el, attr)=> el.getAttribute?.(attr)
, isText = e => e.nodeType === 3
, isString = s => typeof s === 'string'
, isNode = e => e && typeof e.nodeType === 'number'
, createText = ( d, t) => (d.ownerDocument || d ).createTextNode( t )
, removeChildren = n => { while(n.firstChild) n.firstChild.remove(); return n; }
, emptyNode = n => { n.getAttributeNames().map( a => n.removeAttribute(a) ); return removeChildren(n); }
, xslNs = x => ( x?.setAttribute('xmlns:xsl', XSL_NS_URL ), x )
, xslHtmlNs = x => ( x?.setAttribute('xmlns:xhtml', HTML_NS_URL ), xslNs(x) )
, isValidTagName = tag=> ( /^[_a-zA-Z][-_:a-zA-Z0-9]*$/ .test(tag) )
, mix = (o,kv) => { Object.keys(kv).map(k=> o[k] = kv[k] ) ; return o}
, create = ( tag, t = '', d=document ) =>
{
const create = tag => ( e => ((t && e.append(createText(d.ownerDocument||d, t))),e) )((d.ownerDocument || d ).createElement( tag ))
Eif( isValidTagName(tag) )
return create(tag)
const e = create('dce-object');
e.setAttribute('dce-object-name',tag)
return e;
}
, cloneAs = (p,tag) =>
{ const px = p.ownerDocument.createElementNS(p.namespaceURI,tag);
for( let a of p.attributes)
px.setAttribute(a.name, a.value);
for( let c of p.childNodes )
px.append(c.cloneNode(true));
return px;
};
export {cloneAs,mix};
function
ASSERT(x)
{
// if(!x)
// debugger
}
export function
xml2dom( xmlString )
{
return new DOMParser().parseFromString( xmlString, "application/xml" )
}
export function
xmlString(doc){ return new XMLSerializer().serializeToString( doc ) }
function x(doc) { return xmlString(doc) }
function
injectData( root, sectionName, arr, cb )
{ const create = ( tag ) => root.ownerDocument.createElement( tag );
const inject = ( tag, parent, s ) =>
{ parent.append( s = create( tag ) );
return s;
};
const l = inject( sectionName, root );
[ ...arr ].forEach( e => l.append( cb( e ) ) );
return l;
}
function
assureSlot( e )
{
if( !e.slot )
{
if( !e.setAttribute )
e = create( 'span', e.textContent.replaceAll( '\n', '' ) );
e.setAttribute( 'slot', '' )
}
return e;
}
function
keepAttributes(e, aNames)
{ e.getAttributeNames().forEach( n=> aNames.includes(n) || e.removeAttribute(n) ); }
export const
sanitizeBlankText = payload=> [...payload].filter(e=>!(e.nodeType===3 && e.data.trim() ==='' ));
export function
obj2node( o, tag, doc )
{ const t = typeof o;
if( t === 'string' )
return create(tag,o,doc);
if( t === 'number' )
return create(tag,''+o,doc);
if( o instanceof Array )
{ const ret = create('array','',doc);
o.map( ae => ret.append( obj2node(ae,tag,doc)) );
return ret
}
if( o instanceof FormData )
{ const ret = create('form-data','',doc);
for( const p of o )
ret.append( obj2node(p[1],p[0],doc) );
return ret
}
const ret = create(tag,'',doc);
for( let k in o )
if( isNode(o[k]) || typeof o[k] ==='function' || o[k] instanceof Window )
continue
else
if( typeof o[k] !== "object" && isValidTagName(k) )
ret.setAttribute(k, o[k] );
else
ret.append(obj2node(o[k], k, doc))
return ret;
}
export function
tagUid( node )
{ // {} to xsl:value-of
forEach$(node,'*',d => [...d.childNodes]
.filter( e => e.nodeType === 3 && e.parentNode.localName !== 'style' && e.data )
.forEach( e=>
{ const s = e.data,
m = s.matchAll( /{([^}]*)}/g );
Eif(m)
{ let l = 0
, txt = t => createText(e,t)
, tt = [];
[...m].forEach(t=>
{ if( t.index > l )
tt.push( txt( t.input.substring( l, t.index ) ))
const v = node.querySelector('value-of').cloneNode();
v.setAttribute('select', t[1] );
tt.push(v);
l = t.index+t[0].length;
})
if( l < s.length)
tt.push( txt( s.substring(l,s.length) ));
Eif( tt.length )
{ for( let t of tt )
d.insertBefore(t,e);
d.removeChild(e);
}
}
}));
if( 'all' in node ) {
let i= 1;
for( let e of node.all )
e.setAttribute && !e.tagName.startsWith('xsl:') && e.setAttribute('data-dce-id', '' + i++)
}
return node
}
export function
createXsltFromDom( templateNode, S = 'xsl:stylesheet' )
{
const declaredAttributes = []
, hardcodedAttributes = {}
, exposedAttributes={};
if( templateNode.tagName === S || templateNode.documentElement?.tagName === S )
return tagUid(mix( templateNode, { declaredAttributes, hardcodedAttributes, exposedAttributes } ));
const sanitizeXsl = xml2dom(`<xsl:stylesheet version="1.0" xmlns:xsl="${ XSL_NS_URL }" xmlns:xhtml="${ HTML_NS_URL }" xmlns:exsl="${EXSL_NS_URL}" exclude-result-prefixes="exsl" >
<xsl:output method="xml"/>
<xsl:template match="/"><dce-root xmlns="${ HTML_NS_URL }"><xsl:apply-templates select="*" /></dce-root></xsl:template>
<xsl:template match="*[name()='template']">
<xsl:apply-templates mode="sanitize" select="*|text()"/>
</xsl:template>
<xsl:template match="*">
<xsl:apply-templates mode="sanitize" select="*|text()"/>
</xsl:template>
<xsl:template match="*[name()='svg']|*[name()='math']">
<xsl:apply-templates mode="sanitize" select="."/>
</xsl:template>
<xsl:template mode="sanitize" match="*[count(text())=1 and count(*)=0]">
<xsl:copy>
<xsl:apply-templates mode="sanitize" select="@*"/>
<xsl:value-of select="text()"></xsl:value-of>
</xsl:copy>
</xsl:template>
<xsl:template mode="sanitize" match="xhtml:*[count(text())=1 and count(*)=0]">
<xsl:element name="{local-name()}">
<xsl:apply-templates mode="sanitize" select="@*"/>
<xsl:value-of select="text()"></xsl:value-of>
</xsl:element>
</xsl:template>
<xsl:template mode="sanitize" match="*|@*">
<xsl:copy>
<xsl:apply-templates mode="sanitize" select="*|@*|text()"/>
</xsl:copy>
</xsl:template>
<xsl:template mode="sanitize" match="text()[normalize-space(.) = '']"/>
<xsl:template mode="sanitize" match="text()">
<dce-text>
<xsl:copy/>
</dce-text>
</xsl:template>
<xsl:template mode="sanitize" match="xsl:value-of|*[name()='slot']">
<xsl:copy>
<xsl:apply-templates mode="sanitize" select="*|@*|text()"/>
</xsl:copy>
</xsl:template>
<xsl:template mode="sanitize" match="xhtml:*">
<xsl:element name="{local-name()}">
<xsl:apply-templates mode="sanitize" select="*|@*|text()"/>
</xsl:element>
</xsl:template>
<xsl:template mode="sanitize" match="xhtml:input">
<xsl:element name="{local-name()}">
<xsl:apply-templates mode="sanitize" select="*[not(name()='slice')]|@*|text()"/>
</xsl:element>
<xsl:for-each select="slice">
<xsl:copy>
<xsl:attribute name="for" >^</xsl:attribute>
<xsl:apply-templates mode="sanitize" select="*|@*|text()"/>
</xsl:copy>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>`)
const sanitizeProcessor = new XSLTProcessor()
, tc = (n =>
{
forEach$(n,'custom-element', ce=>{
Eif( 'template' === ce.firstElementChild.localName )
{
[...ce.firstElementChild.content.childNodes].forEach(n=>ce.append(n));
ce.firstElementChild.remove();
}
})
forEach$(n,'script', s=> s.remove() );
const xslRoot = n.content ?? n.firstElementChild?.content ?? n.body ?? n;
xslTags.forEach( tag => forEach$( xslRoot, tag, el=>toXsl(el,xslRoot) ) );
const e = n.firstElementChild?.content || n.content
, asXmlNode = r => {
const d = xml2dom( '<xhtml/>' )
, n = d.importNode(r, true);
d.replaceChild(n,d.documentElement);
return xslHtmlNs(n);
};
if( e )
{ const t = create('div');
[ ...e.childNodes ].map( c => t.append(c.cloneNode(true)) )
return asXmlNode(t)
}
return asXmlNode(n.documentElement || n.body || n)
})(templateNode)
, xslDom = xml2dom(
`<xsl:stylesheet version="1.0"
xmlns:xsl="${ XSL_NS_URL }"
xmlns:xhtml="${ HTML_NS_URL }"
xmlns:dce="urn:schemas-epa-wg:dce"
xmlns:exsl="http://exslt.org/common"
exclude-result-prefixes="exsl"
>
<xsl:template match="ignore">
<xsl:choose>
<xsl:when test="//attr">{//attr}</xsl:when>
<xsl:otherwise>{def}</xsl:otherwise>
</xsl:choose><xsl:value-of select="."></xsl:value-of></xsl:template>
<xsl:template mode="payload" match="attributes"></xsl:template>
<xsl:template match="/">
<xsl:apply-templates mode="payload" select="/datadom/attributes"/>
</xsl:template>
<xsl:template name="slot" >
<xsl:param name="slotname" />
<xsl:param name="defaultvalue" />
<xsl:choose>
<xsl:when test="//payload/*[@slot=$slotname]">
<xsl:copy-of select="//payload/*[@slot=$slotname]"/>
</xsl:when>
<xsl:otherwise>
<xsl:copy-of select="$defaultvalue"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:variable name="js-injected-body">
<xsl:call-template name="slot" >
<xsl:with-param name="slotname" select="''"/>
<xsl:with-param name="defaultvalue"/>
</xsl:call-template>
</xsl:variable>
</xsl:stylesheet>`
);
sanitizeProcessor.importStylesheet( sanitizeXsl );
const fr = sanitizeProcessor.transformToFragment(tc, document)
, $ = (e,css) => e.querySelector(css)
, payload = $( xslDom, 'template[mode="payload"]');
if( !fr )
return console.error("transformation error",{ xml:tc.outerHTML, xsl: xmlString( sanitizeXsl ) });
Iif( 'dce-root'!==fr.firstElementChild.localName )
{ const r = fr.ownerDocument.createElement('dce-root');
[...fr.childNodes].forEach(n=>r.append(n));
fr.append(r)
}
[...fr.querySelectorAll('dce-root>attribute')].forEach( a=>
{
keepAttributes(a,'namespace,name,select');
const p = cloneAs(a,'xsl:param')
, name = attr(a,'name');
declaredAttributes.push(name);
if( a.childNodes.length)
hardcodedAttributes[name] = a.textContent;
payload.append(p);
if( a.hasAttribute('select') )
{
exposedAttributes[ name ] = attr( a, 'select' );
keepAttributes( p, 'select,name' );
let select = attr(a,'select').split('??');
let val;
if( select?.length>1 )
{ p.removeAttribute('select');
const c = $( xslDom, 'template[match="ignore"]>choose').cloneNode(true);
// todo multiple ?? operators
emptyNode(c.firstElementChild).append( createText(c,'{'+select[0]+'}'));
emptyNode(c.lastElementChild ).append( createText(c,'{'+select[1]+'}'));
c.firstElementChild.setAttribute('test','string-length('+select[0]+')');
p.append(c);
val = c.cloneNode(true);
}else
val = cloneAs(a,'xsl:value-of');
val.removeAttribute('name');
a.append(val);
a.removeAttribute('select');
}else
{ keepAttributes( p, 'name' );
p.setAttribute('select','/datadom/attributes/'+name)
}
});
[...fr.querySelectorAll('[value]')].filter(el=>el.getAttribute('value').match( /\{(.*)\?\?(.*)\}/g )).forEach(el=>
{ const v = attr(el,'value');
Eif(v)
el.setAttribute('value', evalCurly(v));
});
for( const c of fr.childNodes )
payload.append(xslDom.importNode(c,true))
const embeddedTemplates = [...payload.getElementsByTagName('xsl:template')];
embeddedTemplates.forEach(t=>payload.ownerDocument.documentElement.append(t));
const slotCall = $(xslDom,'call-template[name="slot"]')
, slot2xsl = s =>
{ const v = slotCall.cloneNode(true)
, name = attr(s,'name');
name && v.firstElementChild.setAttribute('select',`'${ name }'`)
for( let c of s.childNodes)
v.lastElementChild.append(c)
return v
};
forEach$( payload,'slot', s => s.parentNode.replaceChild( slot2xsl(s), s ) )
const ret = tagUid(xslDom);
mix( ret, { declaredAttributes, hardcodedAttributes, exposedAttributes } );
return ret;
}
export async function
xhrTemplate(src)
{
const dom = await new Promise((resolve,reject)=>
{ const xhr = new XMLHttpRequest();
xhr.open("GET", src);
xhr.responseType = "document";
// xhr.overrideMimeType("text/xml");
xhr.onload = () =>
{ if( xhr.readyState === xhr.DONE && xhr.status === 200 )
resolve( xhr.responseXML?.body || xhr.responseXML || create('div', xhr.responseText ) )
else
Ereject(`${xhr.statusText} - ${src}`)
};
xhr.addEventListener("error", ev=>reject(ev) );
xhr.send();
})
return dom
}
export function
deepEqual(a, b, O=false)
{
if( a === b )
return true;
if( (typeof a !== "object" || a === null) || (typeof b !== "object" || b === null)
|| Object.keys(a).length !== Object.keys(b).length )
return O;
for( let k in a )
if( !(k in b) || !deepEqual( a[k], b[k] ) )
return O
return true;
}
const splitSliceNames = v => v.split('|').map( s=>s.trim() ).filter(s=>s);
export const
assureSlices = ( root, names) =>
splitSliceNames(names).map( xp =>
{ let d = root.ownerDocument
, append = n=> (root.append(n),n);
if(xp.includes('/'))
{ const ret = [], r = d.evaluate( xp, root );
for( let n; n = r.iterateNext(); )
ret.push( n )
return ret
}
return [...root.childNodes].find(n=>n.localName === xp) || append( create(xp,'',d) );
}).flat();
/**
*
* @param x slice node
* @param sliceNames slice name, xPath in /datadom/slice/
* @param ev Event obj
* @param dce
*/
export function
event2slice( x, sliceNames, ev, dce )
{
if( ev.sliceProcessed )
return
ev.sliceProcessed = 1;
// evaluate slices[]
// inject @attributes
// inject event
// evaluate slice-value
// slice[i] = slice-value
return assureSlices( x, sliceNames ?? '' ).map( s =>
{
const d = x.ownerDocument
, el = ev.sliceEventSource
, sel = ev.sliceElement
, cleanSliceValue = ()=>[...s.childNodes].filter(n=>n.nodeType===3 || n.localName==='value' || n.localName==='form-data').map(n=>n.remove());
el.getAttributeNames().map( a => s.setAttribute( a, attr(el,a) ) );
[...s.childNodes].filter(n=>n.localName==='event').map(n=>n.remove());
if( 'validationMessage' in el )
s.setAttribute('validation-message', el.validationMessage);
ev.type==='init' && cleanSliceValue();
s.append( obj2node( ev, 'event', d ) );
const notChecked = ( 'checkbox' === el.type || 'radio' === el.type ) && !el.checked ;
if( sel.hasAttribute('slice-value') )
{ if( el.value === undefined)
s.removeAttribute('value')
else
s.setAttribute('value', el.value );
const v = notChecked? '' : xPath( attr( sel, 'slice-value'),s );
cleanSliceValue();
s.append( createText( d, v ) );
}else
{ if( 'elements' in el )
{ cleanSliceValue();
s.append( obj2node(new FormData(el),'value', s.ownerDocument) )
return s
}
const v = notChecked? '' : el.value ?? attr( el, 'value' );
cleanSliceValue();
if( v === null || v === undefined )
[...s.childNodes].filter(n=>n.localName!=='event').map(n=>n.remove());
else
if( isString(v) )
s.append( createText( d, v) );
else
s.append( obj2node(v,'value',s.ownerDocument) )
}
return s
})
}
function forEach$( el, css, cb){
Eif( el.querySelectorAll )
[...el.querySelectorAll(css)].forEach(cb)
}
const loadTemplateRoots = async ( src, dce )=>
{
if( !src || !src.trim() )
return [dce]
if( src.startsWith('#') )
return ( n =>
{ const a = n.querySelectorAll(src)
return [...( a.length ? a : n.getRootNode().querySelectorAll(src) )]
})(dce.parentElement)
try
{ const [path, hash] = src.split('#');
if( '.' === src.charAt(0))
src = new URL(path, dce.closest('[base]')?.getAttribute('base') || location ).href;
else
try
{ src = import.meta.resolve( path );
if(hash)
src +='#'+hash;
}
catch( e )
{ console.error(e.message) }
// todo cache
const dom = await xhrTemplate(src);
dce.setAttributeNS('xml', 'base', src );
if( hash )
{ const ret = dom.querySelectorAll('#'+hash);
if( ret.length )
return [...ret];
console.error('template not found',src+'#'+hash);
return [dce]
}
return [dom]
}catch (error){ return [dce]}
}
export function mergeAttr( from, to )
{ for( let a of from.attributes)
try
{ a.namespaceURI? to.setAttributeNS( a.namespaceURI, a.name, a.value ) : to.setAttribute( a.name, a.value )
if( a.name === 'value')
to.value = a.value
}catch(e)
{ console.warn('attribute assignment error',e?.message || e); }
}
export function assureUnique(n, id=0)
{
const m = {}
for( const e of n.childNodes )
{
const a = attr(e,'data-dce-id') || e.dceId || 0;
if( !m[a] )
{ if( !a )
{ m[a] = e.dceId = ++id;
if( e.setAttribute )
e.setAttribute('data-dce-id', e.dceId )
}else
m[a] = 1;
}else
{ const v = e.dceId = a + '-' + m[a]++;
if( e.setAttribute )
e.setAttribute('data-dce-id', v )
}
e.childNodes.length && assureUnique(e)
}
}
export function appendByDceId(parent,e,k)
{
k = 1*k;
for( let n of parent.childNodes )
if( (n.dceId ?? n.getAttribute('data-dce-id')*1) > k )
return parent.insertBefore(e,n);
parent.append(e)
}
export function merge( parent, fromArr )
{
Iif( 'dce-root' === parent.firstElementChild?.localName && 'dce-root' !== fromArr[0]?.localName)
return;
if( !fromArr.length )
return 'dce-root' !== parent.firstElementChild?.localName && removeChildren(parent);
const id2old = {};
for( let c of parent.childNodes)
{ ASSERT( !id2old[c.dceId] );
if( isText(c) )
{ ASSERT( c.data.trim() );
id2old[c.dceId || 0] = c;
} else
id2old[attr(c, 'data-dce-id') || 0] = c;
}
for( let e of [...fromArr] )
{ const k = attr(e, 'data-dce-id') || e.dceId;
const o = id2old[ k ];
if( o )
{ if( isText(e) )
{ if( o.nodeValue !== e.nodeValue )
o.nodeValue = e.nodeValue;
}else
{ mergeAttr(e,o)
if( o.childNodes.length || e.childNodes.length )
merge(o, e.childNodes)
}
delete id2old[ k ]
}else
appendByDceId(parent,e,k)
}
for( let v of Object.values(id2old) )
Eif( v.localName !== 'dce-root')
v.remove();
}
export function assureUID(n,attr)
{ Eif( !n.hasAttribute(attr) )
n.setAttribute(attr, crypto.randomUUID());
return n.getAttribute(attr)
}
export const evalCurly = s =>
{ const exp = [...s?.matchAll( /([^{}]*)(\{)([^}]+)}([^{}]*)/g ) ].map(l=>`${l[1]}{${ xPathDefaults(l[3] )}}${l[4]}`);
return exp.join('');
}
export const xPathDefaults = x=>
{ if(!x.trim())
return x;
const xx = x.split('??')
, a = xx.shift()
, b = xPathDefaults(xx.join('??'));
return xx.length ? `concat( ${a} , substring( ${b} , (1+string-length( ${b} )) * string-length( ${a} ) ) )`: x
// return xx.length ? `${a}|(${xPathDefaults(xx.join('??'))})[not(${a})]`: a
}
export const xPath = (x,root)=>
{
const xx = x.split('??');
if( xx.length > 1 )
return xPath(xx[0], root) || xPath(xx[1], root);
x = xPathDefaults(x);
const it = root.ownerDocument.evaluate(x, root);
switch( it.resultType )
{ case XPathResult.NUMBER_TYPE: return it.numberValue;
case XPathResult.STRING_TYPE: return it.stringValue;
case XPathResult.BOOLEAN_TYPE: return it.booleanValue;
}
let ret = '';
for( let n ;n=it.iterateNext(); )
ret += n.textContent;
return ret
}
export const xslTags = 'stylesheet,transform,import,include,strip-space,preserve-space,output,key,decimal-format,namespace-alias,value-of,copy-of,number,apply-templates,apply-imports,for-each,sort,if,choose,when,otherwise,attribute-set,call-template,with-param,variable,param,text,processing-instruction,element,attribute,comment,copy,message,fallback'.split(',');
export const toXsl = (el, defParent) => {
const x = create('xsl:'+el.localName);
for( let a of el.attributes )
x.setAttribute( a.name, a.value );
while(el.firstChild)
x.append(el.firstChild);
if( el.parentElement )
el.parentElement.replaceChild( x, el );
else
{ const p = (el.parentElement || defParent)
, arr = [...p.childNodes];
arr.forEach((n, i) => {
if (n === el)
arr[i] = x;
});
p.replaceChildren(...arr);
}
};
export class
CustomElement extends HTMLElement
{
static observedAttributes = ['src','tag','hidden'];
async connectedCallback()
{
if(this.firstElementChild && this.firstElementChild.localName !== 'template')
console.warn('custom-element used without template wrapping content\n', this.outerHTML);
const templateRoots = await loadTemplateRoots( attr( this, 'src' ), this )
, tag = attr( this, 'tag' )
, tagName = tag ? tag : 'dce-'+crypto.randomUUID();
for( const t of templateRoots )
forEach$(t.templateNode||t.content||t, 'style',s=>{
const slot = s.closest('slot');
const sName = slot ? `slot[name="${slot.name}"]`:'';
s.innerHTML = `${tagName} ${sName}{${s.innerHTML}}`;
this.append(s);
})
const templateDocs = templateRoots.map( n => createXsltFromDom( n ) )
, xp = templateDocs.map( (td, p) =>
{ p = new XSLTProcessor();
try{ p.importStylesheet( td ) }
catch( e )
{ console.error(e, xmlString(td)) }
return p
})
Object.defineProperty( this, "xsltString", { get: ()=>templateDocs.map( td => xmlString(td) ).join('\n') });
const dce = this
, sliceNodes = [...this.templateNode.querySelectorAll('[slice]')]
, sliceNames = sliceNodes.map(e=>attr(e,'slice'))
.filter(n=>!n.includes('/'))
.filter((v, i, a)=>a.indexOf(v) === i)
.map(splitSliceNames).flat();
const { declaredAttributes, hardcodedAttributes, exposedAttributes } = templateDocs[0];
class DceElement extends HTMLElement
{
static get observedAttributes(){ return declaredAttributes; }
#inTransform = 0;
connectedCallback()
{ let payload = sanitizeBlankText(this.childNodes);
if( this.firstElementChild?.tagName === 'TEMPLATE' )
{
Iif( this.firstElementChild !== this.lastElementChild )
{ console.error('payload should have TEMPLATE as only child', this.outerHTML ) }
const t = this.firstElementChild;
t.remove();
payload = sanitizeBlankText(t.content.childNodes);
for( const n of payload )
if( n.localName === 'style' ){
const id = assureUID(this,'data-dce-style')
n.innerHTML= `${tagName}[data-dce-style="${id}"]{${n.innerHTML}}`;
t.insertAdjacentElement('beforebegin',n);
}else
if(n.nodeType===1)
t.insertAdjacentElement('beforebegin',n);
else if(n.nodeType===3)
t.insertAdjacentText('beforebegin',n.data);
}
const x = xml2dom( '<datadom/>' ).documentElement;
const createXmlNode = ( tag, t = '' ) => ( e =>
{ if( t )
e.append( createText( x, t ))
return e;
})(x.ownerDocument.createElement( tag ))
const payloadNode = injectData( x, 'payload' , payload , assureSlot );
xslNs(payloadNode);
xslHtmlNs(payloadNode);
this.innerHTML='';
const attrsRoot = injectData( x, 'attributes' , this.attributes, e => createXmlNode( e.nodeName, e.value ) )
, inAttrs = a=> this.hasAttribute(a) || [...attrsRoot.children].find(e=>e.localName === a);
Object.keys(hardcodedAttributes).map(a=> inAttrs(a) || attrsRoot.append(createXmlNode(a,hardcodedAttributes[a])) );
declaredAttributes.map(a=> inAttrs(a) || attrsRoot.append(createXmlNode(a)) );
injectData( x, 'dataset', Object.keys( this.dataset ), k => createXmlNode( k, this.dataset[ k ] ) );
const sliceRoot = injectData( x, 'slice', sliceNames, k => createXmlNode( k, '' ) )
, sliceXPath = x => xPath(x, sliceRoot);
this.xml = x;
const sliceEvents=[];
const applySlices = ()=>
{ const processed = {}
for(let ev; ev = sliceEvents.pop(); )
{ const s = attr( ev.sliceElement, 'slice');
if( processed[s] )
continue;
event2slice( sliceRoot, s, ev, this );
processed[s] = ev;
}
Object.keys(processed).length !== 0 && transform();
}
let timeoutID;
this.onSlice = ev=>
{ sliceEvents.push(ev);
if( !timeoutID )
timeoutID = setTimeout(()=>
{ applySlices();
timeoutID =0;
},1);
};
const transform = this.transform = ()=>
{ Iif(this.#inTransform){ debugger }
this.#inTransform = 1;
const ff = xp.map( (p,i) =>
{ const f = p.transformToFragment(x.ownerDocument, document)
Iif( !f )
console.error( "XSLT transformation error. xsl:\n", xmlString(templateDocs[i]), '\nxml:\n', xmlString(x) );
return f
});
ff.map( f =>
{ Iif( !f )
return;
assureUnique(f);
merge( this, f.childNodes )
})
Object.entries(hardcodedAttributes).map(( [a,v] )=>
{ if( !this.hasAttribute(a) && v !== attr(this,a) )
{ this.setAttribute( a, v );
this.#applyAttribute( a, v );
}
});
Object.keys(exposedAttributes).map( a =>
{ let v = attr(this.firstElementChild,a);
if( v !== attr(this,a) )
{ this.setAttribute( a, v );
this.#applyAttribute( a, v );
}
});
function getSliceTarget(el)
{ let r = el;
Iif( el.localName === 'slice')
{ const ref= attr(el,'for');
if( !ref )
r = el.parentElement;
if( '^' === ref )
{ do r = r.previousElementSibling;
while( r.localName === 'slice' )
} else
r = this.querySelector(ref)
if( !r )
return console.warn(`can not find selector in "slice for=${ref}" `, el.outerHTML);
attr(el,'slice') || el.setAttribute('slice', attr(el,'name'))
}
return r;
}
forEach$( this,'[slice],[slice-event]', el =>
{ let evs = attr(el,'slice-event');
const sVal = el.hasAttribute('slice-value') || el.hasAttribute('value') || el.value;
const tgt = getSliceTarget(el);
if( !el.dceInitialized )
{ el.dceInitialized = 1;
if( tgt.hasAttribute('custom-validity') )
evs += ' change submit';
[...new Set((evs || 'change') .split(' '))]
.forEach( t=>
tgt.addEventListener( t, ev=>
{ ev.sliceElement = el;
ev.sliceEventSource = ev.currentTarget || ev.target;
ev.sliceProcessed = 0;
const slices = event2slice( sliceRoot, attr( ev.sliceElement, 'slice'), ev, this );
forEach$(this,'[custom-validity]',el =>
{ if( !el.setCustomValidity )
return;
const x = attr( el, 'custom-validity' );
try
{ const v = x && xPath( x, attrsRoot );
el.setCustomValidity( v === true? '': v === false ? 'invalid' : v );
}catch(err)
{ console.error(err, 'xPath', x) }
})
const x = attr(tgt,'custom-validity')
, v = x && xPath( x, attrsRoot )
, msg = v === true? '' : v;
if( x )
{ el.setCustomValidity ? el.setCustomValidity( msg ) : ( el.validationMessage = msg );
slices.map( s => s.setAttribute('validation-message', msg ) );
if( ev.type === 'submit' )
{ Iif( v === true )
return;
setTimeout(transform,1)
if( !!v === v )
{ v || ev.preventDefault();
return v;
}
Eif( v )
{ ev.preventDefault();
return !1
}
return ;
}else
setTimeout(transform,1)
}
this.onSlice(ev);
} ));
if( !evs || evs.includes('init') )
{ if( sVal )
this.onSlice({type:'init', target: tgt, sliceElement:el, sliceEventSource:tgt })
else
el.value = sliceXPath( attr(el,'slice') )
}
}
});
this.#inTransform = 0;
};
transform();
applySlices();
}
#applyAttribute(name, newValue)
{ Iif( 'value' === name )
this.value = newValue;
let a = this.xml.querySelector(`attributes>${name}`);
if( a )
emptyNode(a).append( createText(a,newValue) );
else
E{ a = create( name, newValue, this.xml );
this.xml.querySelector('attributes').append( a );
}
this.dispatchEvent(new CustomEvent('change', { bubbles: true,detail: { [name]: newValue }}))
}
attributeChangedCallback(name, oldValue, newValue)
{ if( !this.xml || this.#inTransform )
return;
this.#applyAttribute(name, newValue);
this.transform(); // needs throttling
}
get dce(){ return dce }
}
const registerTag = tag =>
{
Eif( window.customElements.get(tag) !== DceElement )
window.customElements.define( tag, DceElement);
};
if(tag)
registerTag(tag);
else
{ const t = tagName;
this.setAttribute('tag', t );
registerTag(t);
const el = document.createElement(t);
this.getAttributeNames().forEach(a=>el.setAttribute(a,this.getAttribute(a)));
el.append(...[...this.childNodes].filter( e => e.localName!=='style') );
this.append(el);
}
}
get templateNode(){ return this.firstElementChild?.tagName === 'TEMPLATE'? this.firstElementChild.content : this }
get dce(){ return this }
get xslt(){ return xml2dom( this.xsltString ) }
}
window.customElements.define( 'custom-element', CustomElement );
export default CustomElement;
|