-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathREADME.html
841 lines (754 loc) · 26.7 KB
/
README.html
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
<html>
<head>
<meta charset="UTF-8">
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>📘</text></svg>">
<script src="https://unpkg.com/@hpcc-js/[email protected]/dist/index.min.js"></script>
<script> var hpccWasm = window["@hpcc-js/wasm"]; </script>
<script src="https://cdn.jsdelivr.net/gh/dash14/svg-pan-zoom/dist/svg-pan-zoom.min.js"></script>
</head>
<body>
<style>
html, body, main { width: 100vw; height: 100vh; margin: 0;}
main {
display: grid;
grid-template-areas:
"beam target"
"create target";
grid-template-columns: 1fr 5fr;
grid-template-rows: 3fr 1fr;
}
#beam {grid-area:beam; background-color:palegreen;}
#create {grid-area:create; background-color:bisque;}
#target {grid-area:target; overflow:scroll;}
#beam, #create {
margin:4px;
padding:8px;
overflow-y: scroll;
}
#beam input, label {cursor:pointer;}
</style>
<main>
<div id="beam" ondrop="drop(event)" ondragover="over(event)" ondragenter="over(event)">
<div id="beamlist" onchange="dochoose(event)"></div>
</div>
<div id="target" ondrop="drop(event)" ondragover="over(event)" ondragenter="over(event)">
</div>
<div id="create" ondrop="drop(event)" ondragover="over(event)" ondragenter="over(event)">
<div style="padding:16px; font-size:large;">Learn more about<br>
<a href=http://search.dojo.fed.wiki/solo-super-collaborator.html target=_blank>
Browsing Relations</a>
<p>
<button onclick=dogroup(event)>group</button>
<button onclick=dodownload(event)>download</button></p>
</div>
</main>
<script type=module>
const croquet = {}
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms))
// Croquet ► Module:creating ► start View:beam
const creating = {
index: -1,
start: (graph) => {
creating.index = croquet.view.beam().length
croquet.view.newPoems([{name:graph.nodes[0].type+'⋯',graph}])
},
update: (graph) => {
croquet.view.updatePoem(creating.index, graph, '⋯')
},
finish: (graph) => {
croquet.view.updatePoem(creating.index, graph, '')
creating.index = -1
}
}
window.over = function (event) {
event.preventDefault()
}
window.drop = async function (event) {
event.preventDefault();
switch (event.target.closest('div[ondrop]').id) {
// Drop ► Window:drop ► add View:beam
case "beam":
const poems = [
...await dropl(event, '.jsonl'),
...await drop(event, '.graph.json'),
...await dropu(event)
]
for (const poem of poems) {
croquet.view.newPoems([poem])
await delay(60)
console.log('poem',poem)
}
break
case "create":
injector.schema((await drop(event, '.schema.json'))[0].graph)
injector.create(window.create, creating)
break
// Drop ► Window:drop ► add View:target
case "target":
const poemz = [
...await dropl(event, '.jsonl'),
...await drop(event, '.graph.json')
]
const json = composite(poemz).graph.stringify(null,2)
croquet.view.nextdownload = [json, 'target.graph.json', 'application/json']
display(poemz)
recommend(poemz)
break
default:
console.log('Failed to dispatch', event.target)
}
}
const inst = ({nodes,rels}) => {return new Graph(nodes, rels)}
window.addEventListener('target',event => {
const graph = inst(event.detail)
croquet.view.nextdownload = [graph.stringify(null,2), 'target.graph.json', 'application/json']
display([{name:'target',graph}])
})
// Click ► View:beam ► add View:target ► recomment View:beam
window.dochoose = function (event) {
croquet.view.nextdownload = null
const checked = [...window.beam.querySelectorAll('input[type=checkbox]:checked')]
const beam = croquet.view.beam()
const chosen = checked.map(e => Object.assign({index:e.value},beam[e.value]))
display(chosen)
recommend(chosen)
}
function recommend(chosen) {
const vocabulary = new Set()
const hash = node => `${node.type}: ${node.props.name || ''}`
for (const poem of chosen) {
for (const node of poem.graph.nodes) {
vocabulary.add(hash(node))
}
}
const similar = graph => {
for (const node of graph.nodes) {
if (vocabulary.has(hash(node))) return true
}
return false
}
const beam = croquet.view.beam()
window.beam.querySelectorAll('input[type=checkbox]').forEach(elem => {
const color = !elem.checked && similar(beam[elem.value].graph) ? 'darkorange' : 'black'
elem.nextElementSibling.style.color = color
})
}
let drawing = false
// let siminterval = null
let panSVG = null
const panZoom = {}
async function display(chosen) {
if(!drawing){
drawing = true
// Click ► View:beam ► compose Graph:chose
const complex = composite(chosen)
try {
if (document.querySelector('#target svg')) {
// Click ► Graph:compose ► Graph:dotify
panZoom.pan = panSVG.getPan()
panZoom.zoom = panSVG.getZoom()
panZoom.size = {
width: document.querySelector('#target svg').width.baseVal.valueInSpecifiedUnits,
height: document.querySelector('#target svg').height.baseVal.valueInSpecifiedUnits
}
}
const dot = dotify(complex)
window.dot = dot
hpccWasm.graphviz.layout(window.dot, "svg", "dot").then(svg => {
// Click ► Graph:ditify ► Target:svg
target.innerHTML = svg;
drawing = false
hoverbold(target)
const targetBounds = { width: document.querySelector('#target').clientWidth, height: document.querySelector('#target').clientHeight }
const svgBounds = { width: document.querySelector('#target svg').clientWidth, height: document.querySelector('#target svg').clientHeight }
let svgElement = document.querySelector('#target svg')
panSVG = svgPanZoom(svgElement)
document.querySelector('#target svg').style.height = "100%"
document.querySelector('#target svg').style.width = "100%"
if (targetBounds.width < svgBounds.width || targetBounds.height < svgBounds.height) {
panSVG.resize()
}
panSVG.fit()
panSVG.center()
if (panZoom.size &&
panZoom.size.width == document.querySelector('#target svg').width.baseVal.valueInSpecifiedUnits &&
panZoom.size.height == document.querySelector('#target svg').height.baseVal.valueInSpecifiedUnits) {
panSVG.zoom(panZoom.zoom)
panSVG.pan(panZoom.pan)
}
})
} catch (err) {
console.log('display error', err)
drawing = false
}
// await delay(500);
// const nodes = Object.fromEntries([...target.querySelectorAll('.node')]
// .map(node => [node.querySelector('title').textContent,node]))
// const neq = (a,b) => a.type == b.type && a.props.name == b.props.name
// const name = node => `${node.type}:${node.props.name}`
// for(const cid in nodes){
// if(complex.graph.nodes[cid].type != 'Variable') break
// nodes[cid].addEventListener('click',event => {
// event.preventDefault()
// event.stopPropagation()
// const picks = chosen.filter(entry =>
// entry.graph.nodes.find(node =>
// neq(node, complex.graph.nodes[cid])))
// const pick = picks[0]
// const nid = pick.graph.nodes.findIndex(node => neq(node,complex.graph.nodes[cid]))
// const g = complex.graph
// const n = g.nodes[cid]
// console.log(pick.index, pick.name, cid, nid, name(n))
// window.props = complex.graph.nodes[cid].props
// window.save = () => croquet.view.updatePoem(pick.index,pick.graph,"*")
// const slide = () => `<input type=range min=0 max=100 value=50 style="width: 100%">`
// const nslide = (n,p) => n.props.hasOwnProperty(p) ? `${n.props.name} ${p}: <span>${n.props[p]}</span>${slide()}` : ''
// const rslide = (r,rate) => r.props.hasOwnProperty(rate) ? `${r.type} ${rate}: <span>${r.props[rate]}</span>${slide()}` : ''
// controls.innerHTML = `<p>
// ${['wax','wane'].map(p => nslide(n,p)).join('')}
// ${n.in.map(rid => {const r = g.rels[rid]; return rslide(r,'orate')}).join('')}
// ${n.out.map(rid => {const r = g.rels[rid]; return rslide(r,'irate')}).join('')}
// `
} else {
console.log('display: skipping', chosen)
}
}
const uniq = (value, index, self) => self.indexOf(value) === index
class Graph {
constructor(nodes=[], rels=[]) {
this.nodes = nodes;
this.rels = rels;
}
addNode(type, props={}){
const obj = {type, in:[], out:[], props};
this.nodes.push(obj);
return this.nodes.length-1;
}
addRel(type, from, to, props={}) {
const obj = {type, from, to, props};
this.rels.push(obj);
const rid = this.rels.length-1;
this.nodes[from].out.push(rid)
this.nodes[to].in.push(rid);
return rid;
}
tally(){
const tally = list => list.reduce((s,e)=>{s[e.type] = s[e.type] ? s[e.type]+1 : 1; return s}, {});
return { nodes:tally(this.nodes), rels:tally(this.rels)};
}
size(){
return this.nodes.length + this.rels.length;
}
static load(obj) {
// let obj = await fetch(url).then(res => res.json())
return new Graph(obj.nodes, obj.rels)
}
static async fetch(url) {
const obj = await fetch(url).then(res => res.json())
return Graph.load(obj)
}
static async read(path) {
const json = await Deno.readTextFile(path);
const obj = JSON.parse(json);
return Graph.load(obj)
}
n(type=null, props={}) {
let nids = Object.keys(this.nodes).map(key => +key)
if (type) nids = nids.filter(nid => this.nodes[nid].type == type)
for (const key in props) nids = nids.filter(nid => this.nodes[nid].props[key] == props[key])
return new Nodes(this, nids)
}
stringify(...args) {
const obj = { nodes: this.nodes, rels: this.rels }
return JSON.stringify(obj, ...args)
}
}
// read named graph files that have been dropped by event
export async function drop (event,sufix) {
const want = files(event).filter(file =>
file.name.endsWith(sufix) &&
file.type === 'application/json')
const concepts = []
for (const file of want) {
const name = file.name.replace(sufix,'')
const graph = await file.text()
.then(text => JSON.parse(text))
.then(inst)
concepts.push({name, graph})
}
return concepts
}
export async function dropl (event,sufix) {
const want = files(event).filter(file =>
file.name.endsWith(sufix))
const concepts = []
for (const file of want) {
const text = await file.text()
text.trim().split(/\n/).forEach(line => {
const {name,graph} = JSON.parse(line)
concepts.push({name,graph:inst(graph)})
})
}
return concepts
}
export async function dropu (event) {
const want = strings(event)
const concepts = []
for (const file of want) {
const filename = await file
const name = filename.split(/\//).reverse()[0].split(/\./)[0]
const graph = await fetch(filename)
.then(res => res.json())
.then(inst)
concepts.push({name,graph})
}
return concepts
}
function files(event) {
if (event.dataTransfer.items) {
return [...event.dataTransfer.items]
.filter(item => item.kind === 'file')
.map(item => item.getAsFile())
} else {
return [...event.dataTransfer.files]
}
}
function strings(event) {
if (event.dataTransfer.items) {
return [...event.dataTransfer.items]
.filter(item => item.kind === 'string')
.filter(item => item.type === 'text/uri-list')
.map(item => {return new Promise(res => item.getAsString(res))})
} else {
return [...event.dataTransfer.files]
}
}
// aggregate multiple graphs into a single graph
function composite(concepts) {
const merged = {nids:[]}
const comp = new Graph()
for (const concept of concepts) {
const {name,graph} = concept
merge(comp,graph,name)
}
return {graph:comp, merged}
function merge(comp,incr,source) {
function mergeprops(into,from) {
const keys = Object.keys(into)
.concat(Object.keys(from))
.filter(uniq)
for (const key of keys) {
if (into[key]) {
// if (from[key] && into[key] != from[key]) {
// window.result.innerHTML +=
// `<div style="font-size:small; padding:4px; background-color:#fee; border-radius:4px; border:1px solid #aaa;">
// conflict for "${key}" property<br>
// choosing "${into[key]}" over "${from[key]}"</div>`
// }
}
else {
if(from[key]) {
into[key] = from[key]
}
}
}
}
const nids = {} // incr => comp
incr.nodes.forEach((node,id) => {
const match = comp.nodes.find(each =>
each.type == node.type &&
each.props.name == node.props.name)
if(match) {
nids[id] = comp.nodes.findIndex(node => node === match)
merged.nids.push(nids[id])
mergeprops(match.props, node.props)
} else {
nids[id] = comp.addNode(node.type,node.props)
}
})
incr.rels.forEach(rel => {
const match = comp.rels.find(each =>
each.type == rel.type &&
each.from == nids[rel.from] &&
each.to == nids[rel.to]
)
if(match) {
mergeprops(match.props, rel.props)
} else {
rel.props.source = source
comp.addRel(rel.type, nids[rel.from], nids[rel.to], rel.props)
}
})
}
}
// render graph as dot input to graphviz
function dotify(complex) {
const inputs = ["read", "get", "first"]
const {graph, merged} = complex
const tip = props => Object.entries(props).filter(e => e[1]).map(e => `${e[0]}: ${e[1]}`).join("\\n")
const layout = graph.nodes
.filter(node => node.type == 'Graphviz' && node.props.layout)
.map(node => node.props.layout)
const emphasis = graph.nodes
.filter(node => node.type == 'Graphviz' && node.props.emphasis)
.map(node => node.props.emphasis)
?.reverse()[0] || {}
console.log('dotify',emphasis)
window.graph = graph
const nodes = graph.nodes.map((node,id) => {
const icon = node.props.url ? " 🔗" : node.props.tick ? " ☐" : ""
const label = `${node.type}\\n${node.props.name}${icon}`
const color = emphasis[node.type] || ''
return `${id} [label="${label}" ${color} ${(node.props.url||node.props.tick)?`URL="${node.props.url||'#'}" target="_blank"`:''} tooltip="${tip(node.props)}"]`
})
// if inputs.include?r['type']
// file.puts "#{r['to']} -> #{r['from']} [#{props} dir=back]"
// else
// file.puts "#{r['from']} -> #{r['to']} [#{props}]"
// end
const edges = graph.rels.map(rel => {
const color = emphasis[rel.type] || ''
if (inputs.includes(rel.type))
return `${rel.to}->${rel.from} [label="${rel.type}" ${color} labeltooltip="${tip(rel.props)}" dir=back]`
else
return `${rel.from}->${rel.to} [label="${rel.type}" ${color} labeltooltip="${tip(rel.props)}"]`
})
return [
'digraph {',
'overlap = false; splines=true',
`layout = ${layout.reverse()[0]||'dot'};`,
'node [shape=box style=filled fillcolor=gold penwidth=2]',
...merged.nids,
'node [fillcolor=palegreen penwidth=1]',
...nodes,
...edges,
'}'].join("\n")
}
// embolden lines from graphviz svg nodes on hover
function hoverbold(div,select='both') {
let rels = [] // [[edge, from, to], ...]
const title = target => target.querySelector('title').textContent.replace(/\\n/g,' ')
div.querySelectorAll('.edge').forEach(edge => rels.push([edge, ...title(edge).split('->')]))
const trace = (node,doit) => {
console.log()
const related = io => rels.filter(row => row[io]==node)
switch (select) {
case 'output':
related(1).map(row => doit(row[0]))
break
case 'input':
related(2).map(row => doit(row[0]))
break
case 'both':
related(1).map(row => doit(row[0]))
related(2).map(row => doit(row[0]))
break
case 'most':
let o = related(1).length
let i = related(2).length
related(o>i?1:2).map(row => doit(row[0]))
break
}
}
const feature = (event,width) => {
if(width==3) console.log([...event.target.querySelectorAll('text')].map(e => e.innerHTML).join(" "))
}
const stroke = width => {
const adjust = edge => edge.setAttribute('stroke-width',width)
return event => {feature(event,width); return trace(title(event.target), adjust)}
}
div.querySelectorAll('.node').forEach(node => {
node.addEventListener('mouseenter',stroke(3))
node.addEventListener('mouseleave',stroke(1))
})
}
class BeamModel {
init() {
this.views = new Map();
this.participants = 0;
this.history = []; // { viewId, html } items
this.beam = []; //{name, graph}
this.lastPostTime = null;
this.inactivity_timeout_ms = 60 * 1000 * 20; // constant
croquet.model = this
}
static types() {
return {
"Graph": Graph
};
}
viewJoin(viewId) {
const existing = this.views.get(viewId);
if (!existing) {
const nickname = this.randomName();
this.views.set(viewId, nickname);
}
this.participants++;
this.publish("viewInfo", "refresh");
}
viewExit(viewId) {
this.participants--;
this.views.delete(viewId);
this.publish("viewInfo", "refresh");
}
newName(opt) {
this.views.set(opt.viewId, opt.nickname)
this.publish("viewInfo", "refresh")
}
newPost(post) {
const postingView = post.viewId;
const nick = this.views.get(postingView);
const chat = this.escape(post.chat);
this.addToHistory({ viewId: postingView, nick, chat });
this.lastPostTime = this.now();
this.future(this.inactivity_timeout_ms).resetIfInactive();
}
updatePoem(opt) {
const poem = this.beam[opt.index]
const name = opt.graph.nodes[0].props.name || opt.graph.nodes[0].type || ''
poem.name = name+opt.suffix
poem.graph = opt.graph
this.publish("beam", "refresh")
}
removePoems(indices) {
for (const index of indices.reverse()) {
this.beam.splice(index,1)
}
this.publish("beam", "refresh")
window.beam.querySelectorAll('input').forEach(e => e.checked = false)
}
addToHistory(item){
this.history.push(item);
if (this.history.length > 100) this.history.shift();
this.publish("history", "refresh");
}
addToBeam(poems) {
this.beam.push(...poems)
// this.publish("beam", "refresh")
croquet.view.refreshBeam()
}
resetIfInactive() {
if (this.lastPostTime !== this.now() - this.inactivity_timeout_ms) return;
this.resetHistory("due to inactivity");
}
resetHistory(reason) {
this.history = [{ nick:'system', chat: `reset ${reason}` }];
if (reason == "at user request") this.beam = []
this.lastPostTime = null;
this.publish("history", "refresh");
this.publish("beam", "refresh")
}
escape(text) { // Clean up text to remove html formatting characters
return text.replace("&", "&").replace("<", "<").replace(">", ">");
}
randomName() {
return emoji[Math.floor(Math.random() * emoji.length)]
}
}
// BeamModel.register("BeamModel");
croquet.model = new BeamModel()
croquet.model.init()
class BeamView {
constructor(model) {
// super(model);
this.model = model;
croquet.view = this
this.recall = []
this.nextdownload = null
this.refreshHistory();
this.refreshViewInfo();
this.refreshBeam()
beam.addEventListener('keydown',this.narrowBeam)
beam.addEventListener('keyup',this.narrowBeam)
}
newPoems(poems) {
poems.forEach(poem => poem.date = Date.now())
// this.publish("input", "newPoems", poems)
croquet.model.addToBeam(poems)
}
updatePoem(index, graph, suffix) {
this.publish("input", "updatePoem", {index,graph,suffix})
}
refreshViewInfo() {
// console.log('users', this.model.participants, 'at', new Date().toLocaleTimeString())
// members.innerText = [...this.model.views.values()].join(" ")
}
refreshHistory() {
// textOut.innerHTML = this.model.history
// .map(item => `${item.nick}: ${item.chat}`).join("<br>");
// textOut.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"})
}
refreshBeam() {
const now = (new Date).getTime()
const sections = [
{date: now-1000*60*60*24*365*100, period: 'Years'},
{date: now-1000*60*60*24*365, period: 'a Year'},
{date: now-1000*60*60*24*91, period: 'a Season'},
{date: now-1000*60*60*24*7*31, period: 'a Month'},
{date: now-1000*60*60*24*7, period: 'a Week'},
{date: now-1000*60*60*24, period: 'a Day'},
{date: now-1000*60*60, period: 'an Hour'},
{date: now-1000*60, period: 'a Minute'},
{date: now, period: 'Seconds'}
]
this.nextdownload = null
const want = [...window.beamlist.querySelectorAll('input[type=checkbox]:checked')]
.map(e => +e.value)
console.log('refreshBeam',want)
// if (!want.length) window.dochoose({})
const names = this.model.beam.map(poem => poem.name || poem.graph.nodes[0].type)
let then = 1
window.beamlist.innerHTML = names
.map((n,i) => {
const poem = this.model.beam[i]
let sep = ''
for (const section of sections) {
if (then && poem.date && then<section.date && poem.date>=section.date) {
sep = `<div><font color=gray>Within ${section.period}</font></div>`
}
}
then = poem.date || 1
const hover = poem.date ? `title="${new Date(poem.date).toLocaleString()}"` : ''
const number = `<sup>${poem.graph.nodes.length}</sup>`
return `${sep}<div><font color=gray size=1>${i}</font>
<input type=checkbox value=${i} id=n${i} ${want.includes(i)?'checked':''}>
<label for=n${i} ${hover}>${n}${number}</label></div>`
})
.join("\n")
const last = window.beamlist.querySelector('div:last-of-type')
if(last) last.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"})
}
narrowBeam(event) {
if(event.key === 'Shift') {
const items = window.beamlist.querySelectorAll('input[type=checkbox]')
const checked = window.beamlist.querySelectorAll('input[type=checkbox]:checked')
if (event.type==='keydown' && checked.length) {
items.forEach(item => {
if(!item.checked && item.nextElementSibling.style.color != 'darkorange')
item.parentElement.style.display='none'
})
} else {
items.forEach(item => {
item.parentElement.style.display='block'
})
}
}
}
newFace(view, event) {
const face = Math.floor(Math.random() * emoji.length)
document.cookie = `face=${face};samesite`
view.publish('input','newName',{viewId:this.viewId, nickname:emoji[face]})
}
beam() {
return this.model.beam
}
}
function download(string, file, mime='text/json') {
var data = `data:${mime};charset=utf-8,` + encodeURIComponent(string)
var anchor = document.createElement('a')
anchor.setAttribute("href", data)
anchor.setAttribute("download", file)
document.body.appendChild(anchor) // required for firefox
anchor.click()
anchor.remove()
}
croquet.view = new BeamView(croquet.model)
function addLines (text) {
text.trim().split(/\n/).forEach(async line => {
const {name,graph} = JSON.parse(line)
croquet.view.newPoems([{name,graph:inst(graph)}])
await delay(60)
})
}
function addGraphs (graphs) {
graphs.forEach(async graphx => {
// const {name,graph} = graphx
console.log({graphx})
croquet.view.newPoems(graphx.map(({name,graph}) => ({name,graph:inst(graph)})))
await delay(60)
})
}
const params = new URLSearchParams(location.search)
for(const [param,string] of params) {
switch (param) {
case 'read':
addLines(await fetch(string).then(res => res.text()))
break
case 'add':
addLines(atob(string))
break
case 'scan':
const page = await fetch(string).then(res => res.json())
const graphs = page.story.find(item => item.graphs).graphs
addGraphs(graphs)
break
case 'assets':
const page2 = await fetch(string).then(res => res.json())
const items = page2.story.filter(item => item.type == 'assets')
const assets = await Promise.all(items.map(item =>{
const host = string.split('/').slice(0,-1).join('/')
const folder = item.text.split("\n")[0]
const url = `${host}/plugin/assets/list?assets=${folder}`
return fetch(url)
.then(req => req.json())
.then(list => list.files
.filter(file => file.endsWith('.graph.json'))
.map(file => `${host}/assets/${folder}/${file}`))
}))
const files = assets.flat()
const graphs2 = await Promise.all(files.map(asset =>
fetch(asset)
.then(req => req.json())
.then(graph => ({name:graph.nodes[0].props.name,graph}))))
addGraphs([graphs2])
break
default:
console.log("Can't handle param named", param)/URLSearchParams
}
}
window.dogroup = event => {
const s=window.target.getBoundingClientRect();
const nids = [...window.target.getElementsByClassName('node')]
.filter(node=>{
const r=node.getBoundingClientRect();
return r.x>s.x && r.x+r.width<s.x+s.width &&
r.y>s.y && r.y+r.height<s.y+s.height})
.map(node=>+node.querySelector('title').textContent)
console.log('nids',...nids)
const rids = window.graph.rels
.map((rel,i) => nids.includes(rel.from) && nids.includes(rel.to) ? i : null)
.filter(rid => rid !== null)
console.log('rids',...rids)
const nodes = nids.map(nid => {
const node = window.graph.nodes[nid]
node.in = node.in.map(rid => rids.indexOf(rid)).filter(rid => rid >= 0)
node.out = node.out.map(rid => rids.indexOf(rid)).filter(rid => rid >= 0)
return node
})
const rels = rids.map(rid => {
const rel = window.graph.rels[rid]
rel.from = nids.indexOf(rel.from)
rel.to = nids.indexOf(rel.to)
return rel
})
const graph = new Graph(nodes,rels)
const name = new Date().toLocaleTimeString()
console.log(name,graph)
croquet.view.newPoems([{name,graph}])
}
window.dodownload = event => {
if (croquet.view.nextdownload) {
download(...croquet.view.nextdownload)
} else {
const poems = [...window.beamlist.querySelectorAll('input[type=checkbox]:checked')]
.map(e => croquet.view.beam()[+e.value])
const poem = composite(poems)
const filename = poems
.map(poem => poem.name.replace(/[^a-zA-Z0-9]/g,''))
.filter(uniq).sort().join('-') + '.graph.json'
download(poem.graph.stringify(null,2),filename,'application/json')
}
}
</script>
</body>
</html>