-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBlik_2023_fragment.js
1336 lines (1272 loc) · 55.2 KB
/
Blik_2023_fragment.js
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
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {locate,resolve,modularise,agent,virtual,window,jsdom,fetch,digest} from "./Blik_2023_interface.js";
import {note,wait,observe,provide,collect,slip,infer,either,each,pass,tether,buffer,differ,compose,revert,record,combine,whether,swap,compound,something,string,basic,functor,defined,simple,exit,route,drop,crop,same,major,binary,is,has,not,numeric,array,pdflike,when,expect,generator,clock,heritage} from "./Blik_2023_inference.js";
import {search,merge,prune,extract} from "./Blik_2023_search.js";
import {serialize,proceduralize,mime,data} from "./Blik_2023_meta.js";
import layout,{color} from "./Blik_2023_layout.js";
// var [jss,...plugins]=await resolve(["","nested","extend","global"].map(plugin=>
// ["./Isonen_2014_jss",plugin].filter(Boolean).join("_")+".js")).then(modules=>
// modules.map(module=>module.default||module));
if(!window&&!virtual)
// tests require a browser ready.
await jsdom("http://localhost:80/");
export function document(source,namespace,language)
{if(this?.nodeName)
return (source.nodeName?[source]:(Symbol.iterator in source)?Array.from(source):Object.entries(source)).reduce((node,entry)=>(entry.nodeName
?!node.nodeName
?node[entry.nodeName]=entry.nodeValue
:node.appendChild(entry)
:entry.reduce((qualifier,value)=>value&&Object.keys(value).some(isNaN)
?compose
(infer("concat",node.nodeName?Array.from(node.childNodes).filter(({nodeName})=>RegExp(nodeName,"i").test(qualifier)):node[qualifier])
,infer("map",compose(crop(1),value,tether(document)))
)([])
:!node.nodeName
?node[qualifier]=value
:node[(value??false)&&"setAttribute"+(qualifier.split(":")[1]?"NS":"")||"removeAttribute"](...
[qualifier.split(":").reduce((namespace,name)=>
[namespaces[namespace],qualifier])
].flat(),value)),node)
,this);
if(source.nodeName||["NodeList","XMLDocument"].includes(source.constructor?.name))
return source;
if(string(source))
return window.document.createTextNode(source);
let [fragment,...nodes]=Object.entries(source||{}).reduce(function([fragment,...nodes],[name,value])
{if(!value)return [fragment,...nodes];
if(functor(value))
value=value.call(source);
let {textnode,dataset}={textnode:name=="#text",dataset:name=="dataset"};
if(textnode)
value=simple(value)?value[language]||Object.values(value)[0]:value;
if(dataset)
return [fragment,...nodes,...Object.entries(metamarkup(value))];
let child=textnode||value.nodeName;
if(child)
return [fragment.appendChild(document(value,namespace,language))&&fragment,...nodes];
let attribute=["string","number","boolean"].includes(typeof value);
if(attribute)
return [fragment,...nodes,[name,value]];
let classlist=name==="class"&&array(value);
if(classlist)
return [fragment,...nodes,[name,value.join(" ")]];
let defaults=
{a:{target:"_blank"}
,svg:{viewBox:"0 0 1 1",xmlns:namespaces.svg,"xmlns:xlink":namespaces.xlink}
}[name];
let children=[value].flat().filter(Boolean).map(value=>
merge(value,defaults,0)).map(buffer(function(value)
{let qualifier=value.xmlns?name:[name,namespace].find(qualifier=>namespaces[qualifier]);
let specification=namespaces[qualifier]||value.xmlns;
let suffix=specification?"NS":"";
let node=window.document["createElement"+suffix](...[specification,name].filter(Boolean));
let fragment=document(value,qualifier,language);
document.call(node,fragment);
return node;
},fail=>fail.stack));
fragment.append(...children);
return [fragment,...nodes];
},[new window.DocumentFragment()]);
fragment=fragment.childNodes.length==1?fragment.firstChild:fragment;
return nodes.length?provide([fragment,...nodes]):fragment;
};
export function markup(object,indentation)
{let xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
Object.entries(object).map(function markup([key,value],indentation)
{let fragment="";
indentation=typeof indentation=="string"?indentation:"";
if(Array.isArray(value))
fragment+=value.map(child=>
indentation+markup([key,child],indentation+"\t")+"\n").join("");
else if(typeof(value)=="object")
{fragment+=indentation+"<"+key;
let hasChild;
Object.entries(value).forEach(([key,value])=>
key.charAt(0)=="@"
?fragment+=" "+key.substr(1)+"=\""+value.toString()+"\""
:(hasChild=true));
fragment+=hasChild
?">"+
[Object.entries(value).map(([key,value],index)=>
({"#text":value||" ","#cdata":"<![CDATA["+value+"]]>"}[key]||
(key.charAt(0)!="@"?(index?"":"\n")+markup([key,value],indentation+"\t")+"\n":""))).join("")
,0
].reduce(fragment=>
fragment+(fragment.slice(-1)=="\n"?indentation:""))+
"</"+key+">"
:"/>";
}else fragment+=indentation+"<"+key+">"+value.toString()+"</"+key+">";
return fragment;
}).join("");
return indentation?xml.replace(/\t/g,indentation):xml.replace(/\t|\n/g, "");
};
export function demarkup(node,fields)
{fields=[fields].flat().filter(Boolean);
if(fields.length)
return Object.fromEntries(fields.map(field=>
[field,compose(infer("getAttribute",field),whether(isNaN,crop(1),Number))(node)]));
node.normalize();
if(node.documentElement)
return demarkup(node.documentElement);
let nodetypes={3:"#text",4:"#cdata",9:"#document"};
let type=nodetypes[node.nodeType];
if(type=="#text"&&!node.nodeValue?.match(/[^ \f\n\r\t\v]/))
return node.remove();
if(type)
return (
{[type]:Object.entries(
{"\\\\":/[\\]/g,'\\"':/[\"]/g
,'\\n':/[\n]/g,'\\r':/[\r]/g
}).reduce((text,[escape,expression])=>text.replace(expression,escape)
,type=="#cdata"?node.nodeValue:stringify(node))
});
let attributes=Object.fromEntries(Array.from(node.attributes).map(({nodeName,nodeValue})=>
[nodeName,isNaN(Number(nodeValue))?nodeValue?.toString()||"":Number(nodeValue)]));
let children=Array.from(node.childNodes).map(demarkup);
return [attributes,...children].filter(Boolean).reduce(merge);
};
export function metamarkup(object)
{return object&&Object.fromEntries
(object.nodeName
?Object.entries(object.dataset).map(([key,value])=>[key,isNaN(value)?string(value)?value:JSON.parse(value):Number(value)])
:Object.entries(object).map(([key,value])=>["data-"+key,isNaN(value)?string(value)?value:JSON.stringify(value):String(value)])
);
};
export function list(value)
{return prune.call([value].flat(),([field,value])=>!["ul","li","#text"].includes(field)
?compose(infer("map",([field,value],index)=>(
{"#text":field==index&&string(value)?value:field
,ul:value&&(compound(value)||field!=index)?{li:[value]}:undefined
})),provide)(compound(value)?Object.entries(value):[[field,value]])
:value);
};
export var annotate=(fields,labels)=>labels
?prune.call(fields,([field,value])=>defined(labels[field])?{label:labels[field],value}:value,0,0)
:exit("no labels provided to"+annotate.name+" fields.");
export function form(fields={},override)
{let group=Object.entries(fields).reduce((group,[key,value],index)=>
typeof value=="object"&&!Array.isArray(value)&&!index&&key,false);
if(group)
fields=fields[group];
let label=Object.entries(fields).map(([id,entry])=>
{let [value,label]=has.call(entry,"label")
?["value","label"].map(field=>entry[field])
:[entry,id];
if(!defined(value))
return;
let type=whether([is(Date),is(Set),either(array,compound),either(binary,infer("match",/^(true|false)$/))]
,...["date","radio","select","checkbox","text"].map(type=>swap(type)))(value);
return JSON.parse(JSON.stringify(
{for:id,title:id
,class:[group,type,{checkbox:value?"checked":""}[type]].filter(Boolean).join(" ")||undefined
,span:
[{"#text":label}
,defined(value)
?{role:"textbox",tabindex:"0",contenteditable:true,id,name:id
,type:["select","date"].includes(type)?"text":type
,checked:{checkbox:value?value.toString():undefined}[type]
,"#text":String(type==="checkbox"?String(value)==="true":(type==="date")?clock(value,"datetime"):(type==="text"&&value&&String(value))||
(array(value)?value[0]:compound(value)?Object.keys(value)[0]:value)||"")
}:undefined
],ul:type!=="text"?type==="date"?clockwork(value):{li:list(value)}:undefined
}));
});
if(this)
label.filter(Boolean).map(label=>
{let input=this.querySelector("span[name="+label.for+"]");
if(!label.span)
input?.parentNode.childNodes.forEach(node=>
label[node.nodeName.toLowerCase()]=node);
let past=input?.textContent;
if(something(past))
label.span[1]["#text"]=past;
let elements=this.querySelectorAll("span[role=textbox]");
let reference=input?.closest("label")||
Array.from(elements).reverse().find(input=>input.closest("label"))?.closest("label")||
this.lastChild;
let entry=document({label});
if(input?.id==="message")
// more preservation logic needed.
(entry.querySelector("ul")||entry.appendChild(entry.ownerDocument.createElement("ul")))?.append(...input.closest("label").querySelector("ul")?.childNodes||[]);
insert(entry,input?"over":"after",reference);
if(label.span.type=="text")
this.querySelector("[name="+label.for+"]")?.dispatchEvent(new window.Event("input",{bubbles:true}));
return [Array.from(entry.parentNode.children).indexOf(entry),entry];
}).forEach(([order,node],index,labels)=>node.parentNode.insertBefore(node
,labels.slice(index+1).find(([next])=>next<order)?.[1]||node.nextSibling));
return {label};
};
export function fill(fields)
{if(!simple(fields))
return compose(Array.from
,infer("filter",input=>!fields||input.parentNode.classList.contains(fields))
,infer("map",input=>[input.getAttribute("name"),input.textContent])
,Object.fromEntries)(this.querySelectorAll("span[role=textbox]"));
if(fields)
Object.entries(fields||{}).filter(([field,value])=>
!compound(value)&&this.querySelector("[name="+field+"]")).forEach(([field,value])=>
this.querySelector("span[name="+field+"]").textContent=value);
return fill.call(this,this.getAttribute("method"));
};
export function media(resource,{source,...fields}={})
{if(is(ArrayBuffer)(resource))
resource=new Uint8Array(resource);
if(pdflike(resource))
return print(resource);
if(is(Uint8Array)(resource)||resource.constructor.name==="Buffer")
resource=new TextDecoder("utf-8").decode(resource);
return simple(resource)
?document({span:{style:"white-space:pre;","#text":JSON.stringify(resource,null,2)}})
:resource.startsWith("<")
?window.document.createRange().createContextualFragment(resource)
:parse(resource,semiotics);
};
export function dispatch(form)
{return document(
{"img":
{onload:"!function expect(){setTimeout(tick=>(typeof dispatch=='undefined'?expect:dispatch).call(this,event),500)}.call(this)"
,src:"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
,"data-subject":JSON.stringify(form)
,class:"defer"
}
});
};
export function reference(title,source,layout,elements={audio:["mp3"],video:["mp4","webm"],img:["png","jpg","svg","gif"]})
{let url=/^http/.test(source)?source:[window.location.origin,source.replace(/^\/*/,"")].join("/");
let [extension]=/[^\.]+$/.exec(new URL(url).pathname)||[];
let tag=layout||extension&&Object.keys(elements).find(key=>
elements[key].includes(extension))||"a";
let target=/^#/.test(source)?"":undefined;
return document(
{[tag]:
{id:title
,class:"reference",title,alt:title||source,href:source,src:source,controls:"on",target
,"#text":(title||source).replace(/_/g," ")
}
});
};
export function hypertext(body,title,favicon,scripts,styles=[])
{scripts=[scripts].flat().filter(actions=>!compound(actions)||!activate(body,actions));
let script=[scripts.map(src=>
[typeof src==="function"?{"#text":proceduralize(src)}:/^\./.test(src)?{src}:{"#text":src}
,{type:"module",defer:true}
].reduce(merge)),body.script||[]].flat();
let [link,style]=[styles].flat().reduce((nodes,style,index)=>
nodes[index=+/{|}/.test(style)].push(index?{"#text":style}:{rel:"stylesheet",type:"text/css",href:style})&&nodes
,[[],[]]);
link.push({rel:"icon",type:"image/svg+xml",href:favicon||"favicon.ico"})
return {html:
{lang:"en"
,head:
{title:{"#text":title}
//,"base":{"href":"/"}
,meta:
[{charset:"utf-8"}
,{"http-equiv":"content-language",content:"en-us"}
,{"http-equiv":"Content-Type",content:"text/html;charset=UTF-8"}
,{name:"theme-color",content:"#000000"}
,{name:"description",content:title}
,{name:"viewport",content:"width=device-width, initial-scale=1"}
],link,style,script
//,{"#text":"setInterval(done=>fetch('/authority',{method:'POST',headers:sessionStorage.getItem('authority')}).then(done=>console.log(done)),1000*60)"}
}
,body
} };
};
export function insert(fragment,place,target)
{if(!fragment)return target;
let {over,before,after,under}={[place]:true};
if(fragment instanceof Promise)
return infer(insert)(...arguments);
//:compose(document,infer(insert,place,target),drop(0,0,fragment,"over"),insert)(wheel);
console.info(globalThis.window?{fragment,[place]:target}:{fragment:fragment.nodeName,[place]:target.nodeName});
if(generator(fragment))
return collect(each.call(fragment,fragment=>
insert(fragment,...Array.from(arguments).slice(1))));
let orphan=fragment instanceof window.DocumentFragment;
let fragments=[orphan?Array.from(fragment.childNodes):fragment].flat();
if(under)
return Array.from(target.childNodes).map(child=>destroy(child))
,provide(fragments.map(fragment=>target.appendChild(fragment)));
let [sibling,edge]=before?["previous","prepend"]:["next","appendChild"];
let method=target[sibling+"Sibling"]?"insertBefore":edge;
if(target.parentNode)
target.parentNode[method](fragment.documentElement||fragment,before?target:target.nextSibling);
if(over&&fragment!==target)
destroy(target);
return provide(fragments);
};
export function throttle(fragment,progress=0)
{if(!fragment?.simulation)return fragment;
//if(!fragment.simulation||!fragment.simulation.nodes().length)return fragment;
return new Promise(resolve=>setTimeout(time=>resolve(fragment),2000)).then(fragment=>
{//let size=fragment.querySelectorAll("g.node").length;
//if(size>progress||!size)
for(let simulation of [fragment.simulation].flat())
if(note(Math.floor((1-simulation.alpha())*100),"% throttling "+fragment.getAttribute("title")).next().value<10)
return throttle(fragment);
else fragment.simulation.stop();
return fragment;
});
};
export function qualify(node)
{// extract css selectors from node/fragment, or vice versa.
when(defined)(node);
if(string(node))
return record(
[node.match(/[#\.][^#\.\[\]]+/g)?.reduce((node,selector)=>
merge(node,{[["id","class"]["#.".indexOf(selector[0])]]:[selector.slice(1)]})
,{})||{}
,node.match(/\[[^=]+?=?.*?\]/g)?.reduce((node,selector)=>
merge(node,Object.assign(Array(2).fill(undefined),selector.slice(1,-1).split("=")).reduce((attribute,value)=>(
{[attribute]:value})))
,{})||{}
].reduce(merge)
,node.match(/^[^#\.\[\]]+/)||[]);
let name=node.nodeName?.toLowerCase()||"";
let selectors=name?{id:"#",classList:"."}:{id:'#',class:'.',classed:'.'};
let attributes=Array.from(node.attributes||[]).filter(({name})=>
!["id","class","style"].includes(name.toLowerCase())&&!name.startsWith("on")).map(({name,value})=>
"["+[name,value].join("='")+"']").join("");
return name+Object.entries(selectors).flatMap(([attribute,selector])=>
[attribute==="classList"?Array.from(node[attribute]):["class","className"].includes(attribute)?node[attribute]?.split(' '):node[attribute]].flat().filter(value=>
string(value)&&value?.length).map(value=>selector+value)).join('')+attributes;
};
export function ascend(selector,descendants=new Set())
{let fragment=this instanceof window.Node;
let selection=!fragment&&!simple(this);
let node=fragment?this:selection?this.node():this;
if((selection||fragment)&&!defined(selector))selector="svg";
let limited=numeric(selector);
if(limited&&!selector)
return [node];
let matching=!limited&&(!/[\.#]/.test(selector)
?node.nodeName.toLowerCase()===selector
:functor(selector)
?selector(node)
:fragment
?node.matches(selector)
:// match selectors on node.
[qualify(qualify(node)),prune.call({"":qualify(selector)},({1:value})=>
Object.keys(value).every(field=>["id","class"].includes(field))?value:undefined,1,1)
].map(Object.entries).reduce(([[nodename,node]],[[name,selector]])=>
(!name||nodename===name)&&
Object.entries(selector).every(([field,value])=>
value.every(value=>node[field]?.includes(value)))));
if(matching)
return [node];
let parent=fragment||selection?node.parentNode:node.parent;
return !descendants.has(node)&&parent
?[...ascend.call(parent,limited?selector-1:selector,descendants.add(node)),node]
:[node];
};
export function print(file)
{return resolve(
["/mozilla_2010_pdf_viewer_brightspace.js"
,"/mozilla_2010_pdf_link_service_brightspace.js"
,"/mozilla_2010_pdf_brightspace.js"
]).then(function([{PDFViewer},{PDFLinkService},pdf])
{pdf.default.GlobalWorkerOptions.workerSrc="/mozilla_2010_pdf_worker_brightspace.js";
let viewer=new PDFViewer(
{linkService:new PDFLinkService(),renderer:"svg"
,textLayerMode:0,disableRange:true,forceRendering:true
,container:document({div:
{class:"pdfjs",style:"margin:auto;height:670px;overflow:scroll;"
,div:{id:"viewer"}
}})
});
viewer.linkService.setViewer(viewer);
pdf.getDocument(file).promise.then(combine
(viewer.setDocument.bind(viewer)
,compose(1,"getPage",1,"getViewport",combine("width","height")
,(width,height)=>viewer.container.append(document({style:{"#text":css({"div.pdfjs":
{"&>div#viewer":
{width:"100%",height:"100%"
,"&>div.page":
{margin:"auto",width:"100% !important",height:"unset !important","aspect-ratio":width/height
,"background-image":"url('/icon/blackboard.png')"
,"&>.loadingIcon":{content:"",fill:"red","border-radius":"50%",width:"20px",height:"20px"}
,"&~div.page>div.canvasWrapper>svg image":{opacity:0.3}
,"&>div.canvasWrapper":
{width:"unset !important",height:"unset !important"
,"&>svg":{width:"100% !important",height:"auto !important"}
,"&>svg tspan":{fill:"var(--text,#dbd1b4)"}
,"&>svg image":{opacity:0.3}
,"&>svg path":{fill:"rgba(33,33,33,0.533)"}
}
}
}
}})}})))
)).catch(note);
return viewer.container;
});
};
export var progress=
{div:{class:"progress",style:{"#text":css({".progress":
{position:"absolute",width:"100%",height:"100%"
,background:"linear-gradient(transparent 0%,rgba(33,150,243,0.25) 75%,transparent 100%)"
,animation:"wave 3s ease 1s infinite"
},"@keyframes wave":
{"0%":{height:0,transform:"translate(0,-100%)",opacity:0}
,"50%":{opacity:0.25},"100%":{transform:"translate(0,100%)",opacity:0}
}})}}
};
export function image(source,alt)
{if(/image/i.test(source?.nodeName))return source;
let src=is(Blob)(source)?URL.createObjectURL(source):source
return revert((resolve,reject,src,alt)=>compose.call
(document({img:{}})//crossOrigin:"anonymous"}})
,{onload(){if(/^blob:/.test(this.src))URL.revokeObjectURL(this.src);resolve(this,...arguments);}
,onerror(){if(/^blob:/.test(this.src))URL.revokeObjectURL(this.src);reject(this,...arguments);}
,src,alt
},Object.assign
,globalThis.window?undefined:infer("dispatchEvent",new window.Event("load"))
))(src,alt);
//if(!colors[color])svg.select("circle#"+id).attr("fill",["rgb(",...new Vibrant(this).swatches()["Vibrant"].rgb].reduce((hex,hue,index)=>hex+hue+(index<2?",":")")));
};
export function canvas(image)
{let {naturalWidth:width,naturalHeight:height}=image;
let canvas=document({canvas:
{role:"img","aria-label":image.getAttribute("alt")
,"data-source":image.getAttribute("src")
,width,height
}});
let frame=canvas.getContext("2d");
if(!frame)
document.call(canvas
,{style:"background:repeating-linear-gradient(135deg,black,black 2px,transparent 2px,transparent 4px"
});
else frame.drawImage(image,0,0);
return canvas;
};
export function vector(node)
{if(node.nodeName.toLowerCase()=="svg")
return node;
let attributes=demarkup(node);
let {r,x,y,cx,cy,dx,dy,width,height}=attributes;
let font=Number(attributes["font-size"]?.replace(/[^0-9\.]*/g,""));
let align=attributes["text-anchor"];
//if(!isNaN(font))document.call(node,{dy:(Number(dy)||0)+font});
x=cx?cx-r:x||0;
y=cy?cy-r:y||0;
width=width||r*2||font||0;
height=height||r*2||font||0;
let rotation=detransform(node,"rotate")*180/Math.PI;
let transform="rotate("+rotation+")";
if(rotation)document.call(node,{transform:""});
return document
({svg:
{id:node.closest("g")?.getAttribute("id")
,viewBox:[x,y,width,height].join(" ")
,width,height,x,y
,style:"overflow:visible"
,...rotation&&{transform}
,.../svg$/.test(node.namespaceURI)
?{node}
:{foreignObject:
{x,y,width,height
,node
}
}
}
}
);
};
export var stringify=node=>node.innerHTML||
Array.from(node.childNodes).map(function outerXML({nodeType,nodeName,attributes,childNodes})
{let tag=()=>"<"+nodeName+
Array.from(attributes).map(({nodeName,nodeValue})=>" "+nodeName+"=\""+(nodeValue||"").toString()+"\"").join("")+
(childNodes.length?">"+Array.from(childNodes).map(outerXML).join("")+"</"+nodeName+">":"/>");
let text=()=>nodeValue;
let cdata=()=>"<![CDATA["+nodeValue+"]]>";
let value={1:tag,3:text,4:cdata}[node.nodeType];
return value?value():"";
}).join("");
export function detransform(node,value)
{if(!node)return;
let computed=
window.getComputedStyle(node).transform?.split("(")[1]?.split(")")[0].split(", ").map((value,index)=>(
{[["cos","sin","asin"][index]]:Number(value)})).reduce(merge);
if(computed)
return value=="rotate"
?Math.acos(computed?.cos||Math.PI/2)*(computed?.sin>0?-1:1)
:computed;
let defined=
node.getAttribute("transform")?.split(/\(|\)/).map((piece,index,split)=>
index%2?[split[index-1],-Number(piece)*Math.PI/180]:false).filter(Boolean);
if(!defined)
return undefined;
defined=Object.fromEntries(defined);
return defined[value]??defined;
};
export function snap()
{let {width:limitx,height:limity}=this.parentNode.getBoundingClientRect();
let {left,top,width,height}=this.getBoundingClientRect();
let overflow=[-left,-top,left+width-limitx,top+height-limity];
overflow.forEach(whether(major(0),(overflow,index)=>
this.style[index%2?"top":"left"]=Number(this.style[index%2?"top":"left"].match(/\d+/)?.[0])+overflow*(index<2||-1)+"px",infer()));
};
export function drillresize({width,height})
{// use in svg resizeobserver until SVG resize becomes observable:
// https://stackoverflow.com/questions/65565149/how-to-apply-resizeobserver-to-svg-element
let [x,y]=this.getAttribute("viewBox").split(" ").map(Number);
let attributes=vectorspace(x,y,width,height);
let polyfill=
{foreignObject:
{width,height
,canvas:{style:Object.entries({width,height}).map(entry=>entry.join(":")+"px").join(";")}
}
};
return Object.assign(attributes,polyfill);
};
export function stretch(target,extend)
{if(!this||!target)return;
if(target.nodeType===11)return;
let style=size=>({style:Object.entries(size).map(entry=>entry.join(":")).join(";")});
let resize=([{target,contentRect:{width,height}}])=>
document.call(this,(extend||style)({width,height}));
let observer=new ResizeObserver(resize);
observer.observe(target);
// if(/svg/i.test(target.nodeName))
// (observer=new ResizeObserver(([{contentRect:{width,height}}])=>
// document.call(target,vectorspace(...
// [target.getAttribute("viewBox").split(" "),[width,height]].reduce((viewbox,size)=>
// viewbox.splice(2,2,...size)&&viewbox)))&&
// resize([{target,contentRect:{width,height}}]))
// ).observe(target.parentNode);
return observer;
};
export var vectorspace=(x,y,width,height)=>(
{viewBox:[x,y,width,height].join(" ")
,width,height
});
export var deselect=compose(when(string),/[^\w]/g,"_","replace");
export async function error(request)
{when(is(Error))(this);
if(!request.headers?.referer?.endsWith(request.url))
return this;
let style=await css({body:{background:"black",color:color.red},"div#frame":layout.middle});
let report=compose.call({center:{"#text":this.stack}},"Error","/svg/worm/document",[],[style],hypertext,document);
let body=report.outerHTML;
report.innerHTML="";
return {body,status:500,type:mime("html")};
};
export async function consume([source,common],index)
{return compose
(buffer(compose(fetch,"json"),fail=>({fail}))
,feed=>({common,source,...["items","posts","data"].some(field=>field in feed)?feed:
{items:Object.entries(feed).map(([source,common])=>({source,common}))
}})
)(source);
};
export function syndicate({source,common,...feed})
{return either("items","posts","data",swap([]))(feed).map(next=>
Object.assign(next
,{author:next.author?.name||common?.author?.name||source.substring(0,source.search(/_\d\d/)).replace("_"," & ")
,avatar:common?.icon||next.avatar||next.author?.avatar_URL||feed.feed?.image
,post:either("createdTime","pubDate","created_time","date",swap(0))(next)||next.common?.put||
next.source?.substring(next.source.search(/_\d\d/)+1,next.source?.search(/\d\d_/)+2).split("").map((digit,index,date)=>
{if([3,6].includes(index))date.splice(index+1,0,"-");return digit;
}).join("")
,source:next.id||next.site_ID||next.source
,title:next.title||next.message||next.source?.substring(next.source?.search(/\d\d_/)+3).replace(/\.txt/g,"").replace(/_/g," ")
,content:next.content
,media:next.enclosure&&next.enclosure.link
})).sort(({post:past},{post:next})=>[next,past].map(time=>
new Date(clock(time,"datetime")).getTime()).reduce((next,past)=>next-past)).reverse();
};
export async function* feed({name,icon,pub,sub},{source})
{let items=Object.entries(pub).map(([source,common])=>({source,common}));
let feed=await compose.call
({source:"pub",feed:{image:icon},items,common:{icon,author:{name}}}
,combine(author,compose(each(syndicate),provide,each(article)))
,collect,"flat",infer("reduce",compose(pass("appendChild"),crop(1)))
);
yield feed;
let peer=document({div:{}});
yield peer;
await compose(Object.entries,provide,each(compose(consume,author,peer.append.bind(peer))),collect)(sub);
};
async function author({source,common,...feed},index)
{let src=common?.icon||feed?.feed?.image;
let material=prune.call(layout.material,([field,value],{length})=>
field==="&:hover"?{...value,animation:"blink .5s ease-in"}:value);
let author=document(
{span:
{class:"feed",source:common?.source||source
,style:index?undefined:{"#text":css(
{"@keyframes blink":{"0%":{"box-shadow":"black 0 0 10px"},"33%":{"box-shadow":"var(--text) 0 0 10px"},"66%":{"box-shadow":"black 0 0 20px"},"100%":{"box-shadow":"revert-layer"}}
,".feed":
{...material,display:"inline-block",overflow:"hidden","vertical-align":"middle"
,"max-width":"20em",transition:".3s",background:"#202020","border-radius":"1.5em"
,position:"relative"
}
})}
,span:
{class:"title",style:index?undefined:{"#text":css({".feed>.title":
{display:"block",cursor:"pointer",padding:"0.5em","text-align":"center"
,"&>span":
{"white-space":"pre-wrap",color:"var(--note)"
,"&:first-of-type":{color:"var(--text)","&:hover":layout.text.glow,"&+span":{display:"block","text-align":"left"}}
}
,"& canvas":{width:"2em",height:"2em","border-radius":"1em","vertical-align":"middle","&+span:before":{content:"' '"}}
,"& span[role=link]":{display:"block","text-align":"right",color:"var(--note)","font-style":"italic","&:hover":layout.text.glow,"&:before":{content:"' - '"}}
}})}
,span:await
[common?.author?.name||common?.title||feed?.feed?.author||feed?.feed?.title,feed?.feed?.description||common?.description].reduce(async(author,description)=>
[{class:"author"
,canvas:src&&await buffer(compose(image,canvas),swap(undefined))(src)
,span:{"#text":author?.replace(/&/g,match=>({"&":"&"}[match]))}
}
,author!==description&&description&&
{class:"spell"
,"#text":description,style:"display:none"
,link:await compose(address=>link&&link(address))(feed?.feed?.link)
}
].flat())
}
}
});
capture.call(author,"/feed");
return author;
};
export function link(source,title)
{return document({span:{role:"link",source,"#text":title||source}});
};
export async function article(item,index)
{return document(
{style:index?undefined:
{"#text":await css({".article":
{color:"#b71c1c",display:"block","white-space":"pre-wrap",cursor:"pointer",padding:"0.5em",position:"relative","z-index":2
,"&>canvas":{"border-radius":"50%",height:"1em",width:"1em","vertical-align":"bottom"}
,"&>span":{color:"var(--text)",display:"block"}
,"&:hover>span":layout.text.glow
,"&+span":{"text-align":"left","& img":{"max-width":"100%",height:"auto"},"& audio":layout.audio}
}})
}
,span:
{span:
{class:"article",id:item.source,source:item.source,platform:item.platform,index:String(index)
,...metamarkup(item.common)
,canvas:await compose(image,canvas)(item.avatar,item.author)
,"#text":" "+(item.post?clock(item.post,"date"):item.name.substring(5,13))
,span:{"#text":item.title+"\n"}
}
}
});
};
export function stylerules(selector)
{return Array.from(window.document.styleSheets).flatMap(({rules})=>
Array.from(rules)).filter(({selectorText})=>selectorText?.includes(selector));
};
export async function message({icon,name,put,message},index)
{let {length:styles}=stylerules(".message");
let style=styles?undefined:{"#text":css({".message":layout.message})};
return (
{class:"message","data-index":String(index)
,style
,span:
[{canvas:await buffer
(compose(icon&&fetch,digest,whether(is(Blob),compose(image,canvas),infer()))
,swap({role:"img"})
)(icon)
}
,{span:
[{class:"title",span:[{class:"name","#text":name},{class:"time","#text":clock(put,"dateminute")}]}
,{"#text":message}
]}
]});
};
export async function featurefacebook()
{let module=await import("//connect.facebook.net/en_US/sdk.js");
let {default:svg}=await resolve("/Blik_2020_svg.json");
let {default:awesome}=await resolve("/blessochampion_2019_awesomesvgs.json");
return new Promise(resolve=>
window.fbAsyncInit=function()
{FB.init({appId:"281250585888156",autoLogAppEvents:true,status:false,xfbml:true,version:"v4.0"});
FB.AppEvents.logPageView();
FB.getLoginStatus(function(response)
{window.document.csss[0].addRule("#facebook","position:absolute;bottom:20px;right:15vw;font-size:30px;color:#757575;font-weight:900;transform:rotate(-10deg);line-height:0.8em;cursor:pointer;white-space:pre;");
window.document.styleSheets[0].addRule("#facebook svg","fill:#757575;position:absolute;right:-35px;top:0;bottom:0;margin-top:auto;margin-bottom:auto;width:30px;transform:none;")
let facebook=document(
{"div":
{"id":"facebook","title":"authorize access to featured facebook posts"
,"svg":{...svg.arrow_curved.svg,"style":"position:absolute;width:48px;bottom:-66px;right:-20px;fill:#757575;transform:rotate(6deg)"}}
,"#text":"Feature \nfacebook?"+awesome["fab fa-facebook-square"].replace("<svg ","<svg width='10px' ")
});
facebook.connected=response.status==="connected";
!function connectfacebook(click)
{facebook.onclick=null;
let facebooklogo=facebook.removeChild(facebook.lastChild);
insert(null,facebook.lastChild,true);
let settle=function(response)
{facebook.connected=response.status==="connected";
facebook.replaceChild(window.document.createTextNode(facebook.connected?"Forget \nfacebook":"Feature \nfacebook?"),facebook.childNodes[1]);
facebook.onclick=connectfacebook;
facebook.replaceChild(facebooklogo,facebook.lastChild);//spin();
}
if(click.srcElement)(facebook.connected?FB.logout:FB.login)(settle,{scope:'user_posts'})
else settle(click);
}(response);
resolve(facebook)
})
}).then(facebook=>facebook)
};
export async function charge(actions,syntax)
{return compose
({exports:{actions}
,procedures:[proceduralize(dispose)]
},merge,serialize,text=>({type:"module","#text":text})
)(syntax);
};
export var actions=
{body:
{load(event)
{if(this!==event.target.body)
// ignore propagated load events.
return;
this.querySelectorAll("canvas[role=img]").forEach(canvas=>
canvas.dispatchEvent(new canvas.ownerDocument.defaultView.Event("contextrestored",{bubbles:true})));
this.querySelectorAll("[actions]").forEach(scope=>
(capture.call(scope,scope.getAttribute("actions"))
,scope.dispatchEvent(new scope.ownerDocument.defaultView.Event("contextrestored"))
));
socket("/peer");
},popstate(event)
{//note(event);this.document.forms[0]?.dispatchEvent(new Event("submit"));
},async message(event)
{let {data:message}=event;
console.info("send",message);
if(this.ownerDocument.defaultView.socket?.readyState===3)
await socket("/peer");
this.ownerDocument.defaultView.socket?.send(JSON.stringify(message));
}}
,"canvas[role=img]":
{contextrestored(event)
{let [src,alt]=["data-source","aria-label"].map(this.getAttribute.bind(this));
compose(image,canvas,infer(insert,"over",this))(src,alt);
}}
,"span[role=link]":
{click(){this.ownerDocument.defaultView.open(this.getAttribute("source"),this.classList.contains("redirect")?undefined:"_blank")}
}
,".defer":
{load(event)
{if(!this.dataset.subject)
return;
let subject=JSON.parse(this.dataset.subject);
compose(combine(compose("source",fetch,digest),infer()),transform,"over",this,insert)(subject);
}}
,".reference":{click(){expand.call(this,...arguments);}}
,"#extend":
{keydown(event)
{event.stopPropagation();
event.preventDefault();
let {target,keyCode}=event;
let {enter}=keyboard(keyCode);
if(!enter)return;
let value=target.textContent;
if(Array.from(value).every(is(".")))
return this.dispatchEvent(new Event("submit",{bubbles:true}));
let form=this.closest("form");
let method=form.getAttribute("method");
fragment.form.call(form,{[method]:annotate({[value]:""},labels)});
target.textContent="...";
}}
,".spell":{click(){spell(this);}}
,".field":{click({target}){form.call(target.closest("form"),{extend:{key:"",value:""}})}}
,".carousel":
{scroll({target})
{let timeout=target.timeout=setTimeout(tick=>
{if(target.timeout!==timeout)return;
delete target.timeout;
let to=
[target.scrollLeft,target.getBoundingClientRect().width
].reduce((offset,width)=>Math.round(offset/width)*width);
let duration=500;
!function animateScroll(start,change,time,increment)
{time+=increment;
time/=span/2;
if(time<1)
target.scrollLeft=delta/2*time*time+start;
else
target.scrollLeft=-delta/2*(--time*(time-2)-1)+start;
if(currentTime<duration)
setTimeout(tick=>animateScroll(start,change,currentTime,increment),increment);
}(target.scrollLeft,to-target.scrollLeft,0,20);
},100);
}}
};
export async function socket(actions)
{var {default:peer}=await import(actions);
var {protocol,host}=window.location;
return revert((resolve,reject,socket)=>
Object.assign(window
,{socket:Object.assign(new WebSocket(socket)
,{async onopen({target})
{console.warn("Websocket open: ",target);
let {author:name}=cookies(window.document.cookie);
if(name)
this.send(JSON.stringify({action:"sign",name}));
resolve(this);
},onmessage(event)
{let message=JSON.parse(event.data);
if(message.action!=="check")
console.log("receive",message);
peer[message.action]?.call(this,message,window);
},onerror({target}){console.warn("Websocket not available at "+target.url);reject(target);}
,onclose({target}){console.warn("Websocket closed: ",target);}
})
}))(["ws",/s/.test(protocol)?"s":"","://",host].join(""));
};
export function keyboard(code)
{let codes=
{enter:13,escape:27,space:32,leftright:[37,39],updown:[38,40],backspace:8,tab:9
,shift:16,ctrl:17,alt:18,caps:20,end:35,home:36,insert:45,delete:46
,...Object.fromEntries(
[Array.from({length:10},(number,index)=>index)
,Array.from("abcdefghijklmnopqrstuvwxyz")
].flat().map((key,index)=>[key,(index>9?55:48)+index]))
};
if(string(code))
return codes[code];
let [key]=Object.entries(codes).find(({1:codes})=>[codes].flat().includes(code))||[];
return key?{[key]:true}:{};
};
export function hydrate(fragment)
{// to be used in element's style onload event to dispatch associated script actions as event attributes.
let module=Array.from(fragment.parentNode.childNodes).find(node=>
node.nodeName?.toLowerCase()==="script").textContent;
let expose="postMessage(Object.values(actions).flatMap(Object.keys));";
let blob=new Blob([module,expose],{type:mime("js")});
let {Worker,URL}=fragment.ownerDocument.defaultView;
let worker=new Worker(URL.createObjectURL(blob),{type:"module"});
compose
(revert(function(onmessage,worker){Object.assign(worker,{onmessage,onerror:console.error})})
,({data:namespace})=>activate(fragment.parentNode
,{[qualify(fragment.parentNode)]:Object.fromEntries(namespace.map(name=>[name,Function]))})
)(worker);
};
export function select(actions)
{// extract actions associated with node/fragment.
let [scope]=Object.entries(actions).map(unfold).find(match.bind(this))||[{}];
return scope;
function unfold([selector,scope])
{return [qualify(selector),scope].reduce((selector,scope)=>
[scope,Object.values(selector).every(simple)
?Object.entries(selector).shift()
:["",selector]
]).flat();
};
function match([scope,name,selector])
{let nodename=this.nodeName?.toLowerCase()||"body";
let namematch=!name||name===nodename;
return namematch&&Object.entries(selector).flatMap(([attribute,value])=>
[value].flat().map(value=>[attribute,value])).every(([attribute,value])=>
attribute==="class"
?this.nodeName
?this.classList?.contains(value)
:[this[attribute]].flat().flatMap(list=>list.split(" ")).includes(value)
:this[attribute]===value);
};
};
export function focus(node)
{combine
(compose(drop(1),node,node.textContent.length,combine("setStart","collapse"))
,"removeAllRanges","addRange"
)(node.ownerDocument.defaultView.getSelection(),node.ownerDocument.createRange());
};
export function expose(window)
{// assign critical globals to be loaded synchronously before document (socket, worker, modules).
// common procedure in deferred scripts, so no return statement.
Promise.all(["/Blik_2023_interface.js","/Blik_2023_inference.js","/Blik_2023_search.js","/Blik_2023_fragment.js"].map(module=>
import(module))).then((
[{resolve,cookies}
,{note,provide,collect,record,infer,tether,compose,combine,either,whether,drop,crop,swap,slip,match,is,not,has,simple}
,{merge,prune,search}
,{css}
])=>Object.assign(window
,{resolve,cookies
,note,provide,collect,record,infer,tether,compose,combine,either,whether,drop,crop,swap,slip,match,is,not,has,simple
,merge,prune,search
,css
}));
Object. assign(window
,{worker:import("/Blik_2023_interface.js").then(({delegate})=>delegate("/worker")).then(worker=>
Object.assign(window,{worker})).catch(fail=>
Object.assign(window,{worker:console.warn("Worker not available at /worker.")}))
,dispatch(event,buffering)
{// deprecated in favor of capture.call(fragment,actions).
// rarely needed for unpropagated server-rendered events like focus/blur.
// explicit stopPropagation should be reproduced with event target conditions on scopes
// (eg. {form:{input({target}){if(target)return;}}}).
// if(!select||!actions)
// // asynchronizing event dispatch unblocks its synchronous default.
// return buffering||event.defaultPrevented||event.preventDefault()||
// console.warn("buffering "+event.type+" event on",this)
// ,setTimeout(window.dispatch.bind(this,event,true),500);
// console.info({[event.type]:event.target,scope:this});
// let scope=select.call(this,actions);
// let action=event.type.replace(/[A-Z]+/g,match=>match.slice(-1).toLowerCase());
// scope[action]?.call(this,event);
}});
};
export function capture(module)
{// register events to be routed to actions scoped by selector (eg. {#form:{submit(){}}}).
if(!globalThis.window)
// Re-invoke on client to capture events.
return this.setAttribute("actions",module),this;
let exclusion=
[["motion","orientation","orientationabsolute"].map(sensor=>"device"+sensor)
,["start","run","end","cancel"].map(state=>"transition"+state)
].flat().map(event=>"on"+event);
let inclusion=["focusout","focusin","message"].map(event=>"on"+event);
let lead=["/","./"].find(lead=>module.startsWith(lead));
let route=module.replace(lead,"").split("/").filter(Boolean);
let actions=import(lead+route.shift()).then(module=>
Object.assign(["default"],route).reduce((module,field)=>module[field],module));
let refer=defer.bind(actions),deferred=new Set([heritage(this).filter(event=>
event.startsWith?.("on")&&!exclusion.includes(event)),inclusion].flat());
deferred.forEach(event=>this.addEventListener(event.slice(2),refer,{passive:false}));
actions.then(actions=>
new Set(Object.values(actions).flatMap(Object.keys)).forEach(event=>
this.addEventListener(event,delegate.bind(actions),{passive:false}))).then(ready=>
deferred.forEach(event=>this.removeEventListener(event.slice(2),refer)));
console.groupCollapsed("routing all propagated events to actions from scope: ",{fragment:this});
console.log({[globalThis.window.location.origin+lead+module]:actions});
console.groupEnd();
return this;
};
export function delegate(event)
{let target=event.target.document?.body||event.target.body||event.target;
if(target.nodeName==="#text")target=target.parentNode;
let scopes=Object.entries(this).filter(([selector,actions])=>
actions[event.type]&&target.closest(selector));
scopes.map(([selector,actions])=>
[target.closest(selector),actions[event.type]]).forEach(([scope,action])=>
console.log({[event.type]:target,scope})||
action.call(scope,event));
};
export function defer(event)
{// asynchronizing event dispatch unblocks its synchronous default unless prevented.
this.then(actions=>delegate.call(actions,event));
event.preventDefault();