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 | 14x 14x 14x 14x 19291x 10905x 225x 7308x 3019x 56x 45x 209x 139x 5486x 14x 1072x 1072x 1072x 14x 25x 25x 68x 25x 7x 25x 280x 11x 280x 280x 280x 280x 280x 640x 280x 456x 453x 248x 453x 456x 691x 691x 45x 646x 22x 624x 26x 51x 26x 598x 9x 9x 24x 9x 589x 589x 7308x 2613x 4695x 4414x 281x 589x 2468x 5001x 2606x 2606x 2606x 2606x 2606x 2606x 2606x 265x 17x 265x 265x 265x 265x 2606x 2343x 2606x 2606x 2625x 2606x 69x 68x 68x 2715x 69x 73x 3x 70x 70x 70x 70x 4x 3x 3x 69x 69x 2346x 69x 69x 69x 69x 69x 69x 69x 45x 579x 45x 24x 69x 69x 69x 148x 69x 69x 3x 66x 66x 66x 19x 19x 19x 19x 19x 7x 7x 7x 19x 13x 13x 13x 13x 13x 13x 13x 6x 19x 19x 19x 19x 66x 7x 7x 7x 66x 66x 66x 66x 66x 66x 13x 13x 13x 13x 13x 13x 66x 66x 66x 66x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 7x 2x 5x 3x 2x 2x 1x 1x 306x 14x 256x 260x 260x 260x 2x 2x 2x 2x 618x 468x 212x 256x 256x 260x 260x 260x 463x 1421x 415x 260x 82x 260x 260x 260x 15x 4x 11x 15x 15x 15x 245x 9x 9x 9x 236x 236x 236x 11x 225x 163x 62x 251x 3159x 3159x 14x 74x 51x 23x 4x 4x 4x 19x 19x 19x 2x 17x 17x 14x 8x 3x 19x 19x 19x 9x 9x 7x 2x 10x 3004x 7537x 7537x 129x 3621x 3621x 7928x 7928x 6921x 2880x 2880x 32x 4041x 1007x 1007x 258x 7928x 222x 222x 1370x 16x 206x 2556x 2556x 9x 2547x 2547x 5467x 5467x 2441x 2441x 3026x 2547x 5660x 5660x 5660x 5438x 2434x 163x 3004x 3004x 2324x 5438x 222x 2547x 29x 29x 1x 1x 1x 14x 7x 7x 14x 123x 58x 65x 65x 65x 65x 14x 59x 59x 8x 51x 51x 51x 4x 25x 4x 18x 18x 14x 18x 14x 14x 74x 74x 94x 74x 118x 74x 36x 38x 38x 38x 718x 38x 38x 14x 74x 74x 74x 74x 73x 7x 7x 7x 7x 74x 73x 72x 72x 3x 69x 70x 70x 70x 75x 75x 74x 70x 303x 73x 70x 70x 34x 34x 34x 34x 34x 422x 1x 1x 1x 421x 196x 225x 213x 70x 184x 184x 128x 184x 70x 70x 70x 70x 123x 70x 70x 70x 70x 70x 70x 202x 202x 248x 248x 13x 235x 235x 202x 70x 256x 256x 132x 132x 132x 70x 233x 233x 233x 232x 232x 232x 233x 232x 232x 232x 233x 39x 39x 17x 17x 233x 560x 77x 77x 77x 3x 77x 87x 233x 233x 233x 233x 11x 4x 7x 7x 7x 7x 233x 233x 233x 233x 11x 11x 11x 2x 2x 2x 1x 1x 1x 1x 1x 9x 231x 77x 37x 25x 12x 233x 70x 70x 23x 23x 23x 12x 11x 11x 23x 31x 25x 6x 6x 70x 70x 70x 70x 20x 50x 50x 50x 50x 99x 130x 50x 123x 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) )
, 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);
while( p.firstChild )
px.append(p.firstChild);
return px;
};
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;
}
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' )
{
if( templateNode.tagName === S || templateNode.documentElement?.tagName === S )
return tagUid(templateNode)
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']">
<dce-text>
<xsl:copy>
<xsl:apply-templates mode="sanitize" select="*|@*|text()"/>
</xsl:copy>
</dce-text>
</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: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)
}
const params = [];
[...fr.querySelectorAll('dce-root>attribute')].forEach( a=>
{
const p = cloneAs(a,'xsl:param')
, name = attr(a,'name');
payload.append(p);
let select = attr(p,'select')?.split('??')
if( !select)
{ select = ['//'+name, `'${p.textContent}'`];
emptyNode(p);
p.setAttribute('name',name);
}
let val;
if( select?.length>1 ){
p.removeAttribute('select');
const c = $( xslDom, 'template[match="ignore"]>choose').cloneNode(true);
emptyNode(c.firstElementChild).append( createText(c,'{'+select[0]+'}'));
emptyNode(c.lastElementChild ).append( createText(c,'{'+select[1]+'}'));
c.firstElementChild.setAttribute('test',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');
params.push(p)
});
[...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)
ret.params = params;
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 ) );
if( sel.hasAttribute('slice-value') )
{ if( el.value === undefined)
s.removeAttribute('value')
else
s.setAttribute('value', el.value );
const v = 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 = 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]
return [dce]
}
return [dom]
}catch (error){ return [dce]}
}
export function mergeAttr( from, to )
{ for( let a of from.attributes)
{ a.namespaceURI? to.setAttributeNS( a.namespaceURI, a.name, a.value ) : to.setAttribute( a.name, a.value )
if( a.name === 'value')
to.value = a.value
}
}
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()
{
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()
, declaredAttributes = templateDocs.reduce( (ret,t) => { if( t.params ) ret.push( ...t.params ); return ret; }, [] );
class DceElement extends HTMLElement
{
static get observedAttributes(){ return declaredAttributes.map( a=>attr(a,'name')); }
#inTransform = 0;
connectedCallback()
{ let payload = 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 = t.content.childNodes;
for( const n of [...t.content.childNodes] )
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 ) );
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 )
})
DceElement.observedAttributes.map( a =>
{ let v = attr(this.firstElementChild,a);
if( v !== attr(this,a) )
{ this.setAttribute( a, v );
this.#applyAttribute( a, v );
}
})
forEach$( this,'[slice],[slice-event]', el =>
{ if( !el.dceInitialized )
{ el.dceInitialized = 1;
let evs = attr(el,'slice-event');
if( el.hasAttribute('custom-validity') )
evs += ' change submit';
[...new Set((evs || 'change') .split(' '))]
.forEach( t=> (el.localName==='slice'? el.parentElement : el)
.addEventListener( t, ev=>
{ ev.sliceElement = el;
ev.sliceEventSource = ev.currentTarget || ev.target;
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(el,'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( el.hasAttribute('slice-value') || el.hasAttribute('value') || el.value )
this.onSlice({type:'init', target: el, sliceElement:el, sliceEventSource:el })
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
{ 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;
|