-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathowbo.html
More file actions
1340 lines (1237 loc) · 55.7 KB
/
owbo.html
File metadata and controls
1340 lines (1237 loc) · 55.7 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>OWBO</title>
<style>
* {font-family: sans-serif; }
#drop-area { border: 2px dashed #ccc; border-radius: 10px; display:inline-block; margin-top:5px; padding:10px; width:300px }
#drop-area.highlight { border-color: purple }
#onto-name { padding: 5px 2px; font-size: 14px; color: #254468; border-radius: 5px; border: 1px solid #254468; text-align:right }
.owbo_button { background: #254468; border-radius: 5px; color: white; cursor: pointer; font-size: 17px; margin: 0 10px; padding: 8px 10px; text-align: center; text-decoration: none }
.owbo_button:hover { background: #111 }
.owbo_class, .owbo_datatype, .owbo_individual { cursor:pointer; fill:#cde }
.owbo_class { stroke-width:0px; stroke:#000 }
.owbo_individual { stroke-width:0px; stroke:#000; fill:#edc }
.owbo_class:hover, .owbo_datatype:hover, .owbo_individual:hover { stroke-width:1.5px; stroke:#f00 }
.owbo_class:hover { fill:#cde; color:#fff }
.owbo_literal { stroke-width:1px; stroke:#254468; fill: #fff }
.owbo_datatype { stroke-width:1px; stroke:#254468; fill: #fff }
.owbo_class_name { cursor:text }
.topnav { background-color: #cde; font-family: sans-serif; overflow: hidden; padding: 5px }
.done_button {background: #254468; border-radius: 5px; color: white; cursor: pointer; font-size: 17px; margin: 0 10px; padding: 8px 10px; text-align: center; text-decoration: none}
.cancel_button {background: #cde; border-radius: 5px; color: #444; cursor: pointer; font-size: 17px; margin: 0 10px; padding: 8px 10px; text-align: center; text-decoration: none}
.delete_button {background: #fff; border-radius: 5px; border: 1px #444 solid; color: #444; cursor: pointer; font-size: 17px; margin: 0 10px; padding: 8px 10px; text-align: center; text-decoration: none}
.message{margin-bottom: 20px;}
.connect-handle { fill: #254468; opacity: 0; cursor: crosshair; transition: opacity 0.12s; }
.owbo_node_group:hover .connect-handle { opacity: 0.45; }
.connect-handle:hover { opacity: 1 !important; }
body.connecting .owbo_node_group:hover .connect-handle { opacity: 0 !important; transition: none; }
</style>
</head>
<body style="margin:0">
<!-- top bar -->
<!-- <div class="topnav" id="functions">
<a class="owbo_button" href="javascript:showPrefixes();" title="Show prefix mappings">prefixes</a>
<input id="onto-name" type="text" placeholder="ontology filename" value="onto" size="16"/><span style="font-family: sans-serif;"> .ttl</span>
<a class="owbo_button" href="javascript:save();" title="Save to your device as Turtle file">download</a>
<div id="drop-area">
<span style="color: #254468">Load:</span>
<input type="file" id="file-input" style="color:#254468; display:none"/>
<label class="owbo_button" for="file-input">Click or drag</label>
</div>
</div> -->
<!-- prefix dialog -->
<div id="prefixes" style="display: none; position: fixed; top: 20%; left: 20%; width: 60%; background: white;">
<textarea id="prefixes_ta" style="width: 100%; height: 200px; border-radius: 5px; color: #254468">
@base <https://symb.olic.ai/owbo_net#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
</textarea>
<a href="javascript:showPrefixes();" style="float: right; margin-top: 5px; padding: 2px 10px; background: #254468; border-radius: 5px; color: white; text-decoration: none">OK</a>
</div>
<!-- actual drawing area -->
<div id="owbo_board" style="cursor:crosshair; width: 100%; height: 90vh; overflow: auto">
</div>
<!-- footer -->
<div style="position: fixed; bottom: 10px; left: 10px;">
<span style="color:#888">
To save the current network, save the page (ctrl-s). You can also <a style="color: #444" href="javascript:save();">export the network as a Turtle file</a>
or <a style="color: #444" href="javascript:document.getElementById('ttl-file-input').click();">import from a Turtle file</a>.
<input type="file" id="ttl-file-input" accept=".ttl,.turtle" style="display:none" onchange="loadTTL(this.files[0]);this.value=''"/>
OWBO is open source.</span> <a style="color: #444" href="https://github.com/mdaquin/OWBO" target="_blank">GitHub</a>
</div>
<!-- help button and dialog -->
<div style="position: fixed; bottom: 10px; right: 10px;" id="help_button"><a href="javascript:showHelp();" style="color: #254468; font-size: 30px; text-decoration: none;">?</a></div>
<div id="help_dialog" style="display: none; color: #254468; border: 1px #254468 solid; border-radius: 5px; position: fixed; bottom: 10px; right: 50px; max-width: 50vw; padding: 20px;">
<h3 style="margin-left:15px">Commands</h3>
<ul>
<li><strong>Create concept</strong>: Click on the whiteboard</li>
<li><strong>Edit concept</strong>: Click on a concept name to rename or delete it</li>
<li><strong>Create relation</strong>: Hover a concept — drag from one of the edge handles to another concept</li>
<li><strong>Edit relation</strong>: Click on a relation name to rename or delete it</li>
<li><strong>Move concept</strong>: Drag a concept</li>
</ul>
</div>
</body>
<script>
function showTTLImportWarning() {
var existing = document.getElementById('ttl_import_warning');
if (existing) existing.remove();
var div = document.createElement('div');
div.id = 'ttl_import_warning';
div.style.cssText = 'position:fixed;top:20px;left:50%;transform:translateX(-50%);' +
'background:white;color:#254468;border:1px solid #254468;border-radius:5px;' +
'padding:15px 20px;max-width:500px;z-index:1000;box-shadow:0 2px 8px rgba(0,0,0,0.15)';
div.innerHTML = '<strong>Import complete</strong><br><br>' +
'Note: OWBO covers only a subset of OWL/RDF expressivity. ' +
'Axioms not representable as labelled edges between named nodes ' +
'(e.g. complex restrictions, annotations, imports, cardinalities) ' +
'will not appear in the diagram and will be lost if you re-export.<br><br>' +
'<a href="javascript:document.getElementById(\'ttl_import_warning\').remove();" ' +
'style="float:right;background:#254468;color:white;border-radius:5px;padding:5px 14px;text-decoration:none;font-size:14px">OK</a>' +
'<div style="clear:both"></div>';
document.body.appendChild(div);
}
function loadTTL(file) {
if (!file) return;
var reader = new FileReader();
reader.onload = function(e) {
var svgEl = document.getElementsByTagName('svg')[0];
svgEl.innerHTML = '';
svgEl.setAttribute('width', '100%');
svgEl.setAttribute('height', '100%');
existingProp = {};
var parsed = turtleParse(e.target.result);
buildOwboGraph(parsed.triples, parsed.prefixes);
showTTLImportWarning();
};
reader.readAsText(file);
}
function turtleTokenize(text) {
var tokens = [], i = 0, n = text.length;
while (i < n) {
var c = text[i];
if (c === '#') { while (i < n && text[i] !== '\n') i++; continue; }
if (/\s/.test(c)) { i++; continue; }
if (c === '<') {
var j = i + 1;
while (j < n && text[j] !== '>') { if (text[j] === '\\') j++; j++; }
tokens.push({ t: 'uri', v: text.slice(i+1, j) });
i = j + 1; continue;
}
if (c === '"') {
var j = i + 1;
while (j < n && text[j] !== '"') { if (text[j] === '\\') j++; j++; }
var lit = text.slice(i+1, j);
i = j + 1;
if (i+1 < n && text[i] === '^' && text[i+1] === '^') {
i += 2;
if (i < n && text[i] === '<') {
var k = i + 1;
while (k < n && text[k] !== '>') k++;
tokens.push({ t: 'lit', v: lit, dt: text.slice(i+1, k) });
i = k + 1;
} else {
var k = i;
while (k < n && !/[\s,;.\[\]()"<>]/.test(text[k])) k++;
tokens.push({ t: 'lit', v: lit, dt: text.slice(i, k) });
i = k;
}
} else {
if (i < n && text[i] === '@') { var k = i+1; while (k < n && /[a-zA-Z\-]/.test(text[k])) k++; i = k; }
tokens.push({ t: 'lit', v: lit });
}
continue;
}
if ('.,;[]()'.indexOf(c) >= 0) { tokens.push({ t: 'p', v: c }); i++; continue; }
var j = i;
while (j < n && !/[\s,;.\[\]()"<>#]/.test(text[j])) j++;
if (j > i) { tokens.push({ t: 'w', v: text.slice(i, j) }); i = j; continue; }
i++;
}
return tokens;
}
function turtleParse(text) {
var toks = turtleTokenize(text), prefixes = {}, base = '', triples = [];
var bnc = 0, i = 0, n = toks.length;
function peek() { return i < n ? toks[i] : null; }
function consume() { return i < n ? toks[i++] : null; }
function resolve(tok) {
if (!tok) return null;
if (tok.t === 'uri') return '<' + tok.v + '>';
if (tok.t === 'lit') return tok;
if (tok.t === 'w') return tok.v === 'a' ? 'rdf:type' : tok.v;
return null;
}
function parseNode() {
var tok = peek();
if (!tok) return null;
if (tok.t === 'p' && tok.v === '[') {
consume();
var bn = '_:b' + (bnc++);
parsePOL(bn);
if (peek() && peek().t === 'p' && peek().v === ']') consume();
return bn;
}
if (tok.t === 'p' && tok.v === '(') {
consume();
var items = [];
while (peek() && !(peek().t === 'p' && peek().v === ')')) {
var item = parseNode();
if (item !== null) items.push(item);
}
if (peek()) consume();
return { t: 'list', items: items };
}
consume();
return resolve(tok);
}
function parsePOL(subj) {
while (i < n) {
var tok = peek();
if (!tok || (tok.t === 'p' && (tok.v === '.' || tok.v === ']'))) break;
var pred = resolve(consume());
if (!pred) break;
while (i < n) {
var obj = parseNode();
if (obj !== null) triples.push([subj, pred, obj]);
var nxt = peek();
if (!nxt || nxt.t !== 'p') break;
if (nxt.v === ',') { consume(); continue; }
if (nxt.v === ';') { consume(); break; }
break;
}
}
}
while (i < n) {
var tok = peek();
if (!tok) break;
if (tok.t === 'p' && tok.v === '.') { consume(); continue; }
if (tok.t === 'w' && (tok.v === '@prefix' || tok.v === 'prefix')) {
consume();
var pfx = consume(), uri = consume();
if (pfx && uri) prefixes[(pfx.v || '').replace(':', '')] = uri.v || '';
if (peek() && peek().t === 'p' && peek().v === '.') consume();
continue;
}
if (tok.t === 'w' && (tok.v === '@base' || tok.v === 'base')) {
consume();
var uri = consume();
base = uri ? (uri.v || '') : '';
if (peek() && peek().t === 'p' && peek().v === '.') consume();
continue;
}
var subj = parseNode();
if (!subj) { consume(); continue; }
parsePOL(subj);
if (peek() && peek().t === 'p' && peek().v === '.') consume();
}
return { triples: triples, prefixes: prefixes, base: base };
}
function buildOwboGraph(triples) {
var types = {}, bnodes = {}, domains = {}, ranges = {};
var isaEdges = [], namedEdges = [];
function isBlank(s) { return typeof s === 'string' && s.startsWith('_:'); }
function isList(o) { return o && typeof o === 'object' && o.t === 'list'; }
function isLit(o) { return o && typeof o === 'object' && o.t === 'lit'; }
function isUri(s) { return typeof s === 'string' && !isBlank(s); }
function displayName(s) {
if (!s || typeof s !== 'string') return '';
if (s.startsWith('<') && s.endsWith('>')) {
var u = s.slice(1, -1);
return (u.split(/[/#]/).pop() || u).replace(/_/g, ' ');
}
if (s.indexOf(':') !== -1) return s.split(':').pop();
return s;
}
function isSystem(s) {
if (!s || typeof s !== 'string') return true;
if (s.startsWith('owl:') || s.startsWith('rdfs:') || s.startsWith('rdf:') || s.startsWith('xsd:') || s.startsWith('owbo:')) return true;
if (s.startsWith('<http://www.w3.org/2002/07/owl#')) return true;
if (s.startsWith('<http://www.w3.org/2000/01/rdf-schema#')) return true;
if (s.startsWith('<http://www.w3.org/1999/02/22-rdf-syntax-ns#')) return true;
if (s.startsWith('<http://www.w3.org/2001/XMLSchema#')) return true;
if (s.startsWith('<https://mosaik.loria.fr/tool/owbo')) return true;
return false;
}
function isXsd(s) {
return typeof s === 'string' && (s.startsWith('xsd:') ||
s.startsWith('<http://www.w3.org/2001/XMLSchema#'));
}
// Collect blank node properties
for (var t = 0; t < triples.length; t++) {
var s = triples[t][0], p = triples[t][1], o = triples[t][2];
if (!isBlank(s)) continue;
if (!bnodes[s]) bnodes[s] = {};
if (p === 'owl:onProperty') bnodes[s].onProp = o;
if (p === 'owl:hasValue') bnodes[s].hasValue = o;
if (p === 'owl:unionOf' && isList(o)) bnodes[s].union = o.items;
if (p === 'rdf:type') {
var ov = typeof o === 'string' ? o : '';
if (ov.indexOf('Restriction') >= 0) bnodes[s].isRestriction = true;
}
}
// Infer entity types
for (var t = 0; t < triples.length; t++) {
var s = triples[t][0], p = triples[t][1], o = triples[t][2];
if (isBlank(s)) continue;
var oStr = typeof o === 'string' ? o : null;
if (p === 'rdf:type' && oStr) {
if (oStr.indexOf('Class') >= 0) types[s] = 'class';
else if (oStr.indexOf('NamedIndividual') >= 0) types[s] = 'individual';
else if (!isSystem(oStr)) {
if (!types[s]) types[s] = 'individual';
if (!types[oStr]) types[oStr] = 'class';
}
}
if (p === 'rdfs:subClassOf') {
types[s] = 'class';
if (oStr && !isBlank(oStr)) types[oStr] = 'class';
}
if ((p === 'rdfs:domain' || p === 'rdfs:range') && oStr && !isBlank(oStr))
types[oStr] = types[oStr] || 'class';
if (isXsd(s)) types[s] = 'datatype';
}
// Subjects of rdfs:domain/range are properties, not graph nodes
var propSubjects = {};
for (var t = 0; t < triples.length; t++) {
var s = triples[t][0], p = triples[t][1];
if ((p === 'rdfs:domain' || p === 'rdfs:range') && !isBlank(s)) propSubjects[s] = true;
}
// Build edges
for (var t = 0; t < triples.length; t++) {
var s = triples[t][0], p = triples[t][1], o = triples[t][2];
if (!isUri(s) || isSystem(s)) continue;
if (p === 'rdfs:subClassOf') {
if (typeof o === 'string' && !isBlank(o))
isaEdges.push({ from: s, to: o });
else if (isBlank(o) && bnodes[o] && bnodes[o].isRestriction && bnodes[o].onProp && bnodes[o].hasValue) {
var hv = bnodes[o].hasValue;
if (isUri(hv)) {
if (!types[hv]) types[hv] = 'individual';
namedEdges.push({ from: s, to: hv, label: displayName(bnodes[o].onProp) });
}
}
}
if (p === 'rdf:type' && typeof o === 'string' && !isSystem(o) && !isBlank(o))
isaEdges.push({ from: s, to: o });
if (p === 'rdfs:domain' && !isBlank(s)) {
var pn = displayName(s);
if (!domains[pn]) domains[pn] = [];
if (typeof o === 'string' && !isBlank(o)) {
if (domains[pn].indexOf(o) === -1) domains[pn].push(o);
} else if (isBlank(o) && bnodes[o] && bnodes[o].union) {
bnodes[o].union.forEach(function(m) {
if (isUri(m) && domains[pn].indexOf(m) === -1) { domains[pn].push(m); types[m] = types[m] || 'class'; }
});
}
}
if (p === 'rdfs:range' && !isBlank(s)) {
var pn = displayName(s);
if (!ranges[pn]) ranges[pn] = [];
if (typeof o === 'string' && !isBlank(o)) {
if (ranges[pn].indexOf(o) === -1) { ranges[pn].push(o); if (isXsd(o)) types[o] = 'datatype'; }
} else if (isBlank(o) && bnodes[o] && bnodes[o].union) {
bnodes[o].union.forEach(function(m) {
if (isUri(m) && ranges[pn].indexOf(m) === -1) ranges[pn].push(m);
});
}
}
// Direct triples: individual assertions and individual->literal
if (!propSubjects[s] && !isSystem(p)) {
if (isLit(o)) {
var litKey = 'xsd:' + o.v.replace(/ /g, '_');
types[litKey] = 'datatype';
namedEdges.push({ from: s, to: litKey, label: displayName(p) });
} else if (typeof o === 'string' && !isBlank(o) && !isSystem(o) && !propSubjects[o]) {
namedEdges.push({ from: s, to: o, label: displayName(p) });
}
}
}
// Domain/range pairs → named relation edges
for (var pn in domains) {
var doms = domains[pn], rngs = ranges[pn] || [];
for (var d = 0; d < doms.length; d++)
for (var r = 0; r < rngs.length; r++)
namedEdges.push({ from: doms[d], to: rngs[r], label: pn });
}
// Collect all entity keys for rendering
var entities = {};
function addEnt(k) { if (k && isUri(k) && (!isSystem(k) || isXsd(k)) && !propSubjects[k]) entities[k] = true; }
isaEdges.forEach(function(e) { addEnt(e.from); addEnt(e.to); });
namedEdges.forEach(function(e) { addEnt(e.from); addEnt(e.to); });
// Collect stored owbo:x / owbo:y coordinates (saved by a previous OWBO export)
var storedCoords = {};
for (var t = 0; t < triples.length; t++) {
var s = triples[t][0], p = triples[t][1], o = triples[t][2];
if (p !== 'owbo:x' && p !== 'owbo:y') continue;
var val = typeof o === 'object' ? parseFloat(o.v) : parseFloat(o);
if (isNaN(val) || !isUri(s)) continue;
if (!storedCoords[s]) storedCoords[s] = {};
if (p === 'owbo:x') storedCoords[s].x = val;
else storedCoords[s].y = val;
}
// Ensure isolated nodes (coords saved but no edges) are included in entities
for (var sk in storedCoords) { addEnt(sk); }
var keys = Object.keys(entities);
var n = keys.length;
// If every entity has stored coordinates, use them directly and skip layout
var coordCount = 0;
keys.forEach(function(k) { if (storedCoords[k] && storedCoords[k].x !== undefined && storedCoords[k].y !== undefined) coordCount++; });
if (coordCount === n && n > 0) {
var positions = {};
keys.forEach(function(k) { positions[k] = storedCoords[k]; });
var nodeIds = {};
for (var ei = 0; ei < keys.length; ei++) {
var ek = keys[ei], pos = positions[ek];
var name = displayName(ek);
var prevMax = findLastClassNumer();
addClass(pos.x, pos.y, name);
var newId = 'class_' + (prevMax + 1);
nodeIds[ek] = newId;
var circle = document.getElementById(newId + '_circle');
if (circle) {
var tp = types[ek] || 'class';
circle.setAttribute('class', tp === 'individual' ? 'owbo_individual' : tp === 'datatype' ? 'owbo_datatype' : 'owbo_class');
}
}
function makeEdge(fromKey, toKey, label) {
var fId = nodeIds[fromKey], tId = nodeIds[toKey];
if (!fId || !tId) return;
var fc = document.getElementById(fId + '_circle'), tc = document.getElementById(tId + '_circle');
if (!fc || !tc) return;
addProperty(parseFloat(fc.getAttribute('cx')), parseFloat(fc.getAttribute('cy')),
parseFloat(tc.getAttribute('cx')), parseFloat(tc.getAttribute('cy')), fId, tId, label);
}
isaEdges.forEach(function(e) { makeEdge(e.from, e.to, 'isa'); });
namedEdges.forEach(function(e) { makeEdge(e.from, e.to, e.label); });
var svgEl = document.getElementsByTagName('svg')[0];
var bb = svgEl.getBBox();
if (bb.width > 0) {
svgEl.setAttribute('width', Math.round(bb.x + bb.width + 150) + 'px');
svgEl.setAttribute('height', Math.round(bb.y + bb.height + 150) + 'px');
}
return;
}
// Grid layout via simulated annealing:
// Assign nodes to grid cells so that graph-adjacent nodes end up in nearby cells.
var keyIdx = {};
keys.forEach(function(k, i) { keyIdx[k] = i; });
// Build weighted undirected adjacency: isa edges cost 1, named edges cost 2.
// Lower isa weight means isa-connected nodes are seen as closer and cluster together.
var adj = {};
keys.forEach(function(k) { adj[k] = {}; });
isaEdges.forEach(function(e) {
if (adj[e.from] && adj[e.to]) { adj[e.from][e.to] = 1; adj[e.to][e.from] = 1; }
});
namedEdges.forEach(function(e) {
if (adj[e.from] && adj[e.to]) {
if (!adj[e.from][e.to]) adj[e.from][e.to] = 2;
if (!adj[e.to][e.from]) adj[e.to][e.from] = 2;
}
});
// All-pairs Dijkstra (O(n²) per source) for weighted shortest paths
var INF = n * 2;
var D = [];
for (var si = 0; si < n; si++) {
var d = new Array(n).fill(INF);
var visited = new Array(n).fill(false);
d[si] = 0;
for (var step = 0; step < n; step++) {
var u = -1;
for (var j = 0; j < n; j++)
if (!visited[j] && (u === -1 || d[j] < d[u])) u = j;
if (u === -1 || d[u] === INF) break;
visited[u] = true;
var nbrs = Object.keys(adj[keys[u]]);
for (var ki = 0; ki < nbrs.length; ki++) {
var vi = keyIdx[nbrs[ki]];
if (vi !== undefined && d[u] + adj[keys[u]][nbrs[ki]] < d[vi])
d[vi] = d[u] + adj[keys[u]][nbrs[ki]];
}
}
D.push(d);
}
// Grid sized to roughly match screen aspect ratio (~16:9)
var cols = Math.max(1, Math.round(Math.sqrt(n * 16 / 9)));
var rows = Math.max(1, Math.ceil(n / cols));
var gridSize = rows * cols;
// Random initial assignment; empty cells padded at the end
var grid = [];
for (var i = 0; i < n; i++) grid[i] = i;
for (var i = n; i < gridSize; i++) grid[i] = -1;
for (var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = grid[i]; grid[i] = grid[j]; grid[j] = tmp;
}
// Precompute 8-connected neighbor lists for every cell
var cellNbrs = [];
for (var ci = 0; ci < gridSize; ci++) {
var r = Math.floor(ci / cols), c = ci % cols, nb = [];
for (var dr = -1; dr <= 1; dr++)
for (var dc = -1; dc <= 1; dc++)
if ((dr || dc) && r+dr >= 0 && r+dr < rows && c+dc >= 0 && c+dc < cols)
nb.push((r+dr)*cols + (c+dc));
cellNbrs.push(nb);
}
// Cost of one cell: sum of graph distances to its occupied neighbors
function cellCost(ci) {
var ni = grid[ci]; if (ni < 0) return 0;
var nb = cellNbrs[ci], cost = 0;
for (var ki = 0; ki < nb.length; ki++) { var nj = grid[nb[ki]]; if (nj >= 0) cost += D[ni][nj]; }
return cost;
}
// Simulated annealing: swap random cell pairs, accept if it lowers total adjacency cost
var numIter = Math.max(1000, n * n * 4);
var temp = n * 2.0;
var cooling = Math.pow(0.1 / Math.max(temp, 0.2), 1.0 / numIter);
for (var iter = 0; iter < numIter; iter++) {
var ci = Math.floor(Math.random() * gridSize);
var cj = Math.floor(Math.random() * gridSize);
if (ci === cj) continue;
var before = cellCost(ci) + cellCost(cj);
var tmp = grid[ci]; grid[ci] = grid[cj]; grid[cj] = tmp;
var after = cellCost(ci) + cellCost(cj);
if (after > before && Math.random() >= Math.exp((before - after) / temp))
{ tmp = grid[ci]; grid[ci] = grid[cj]; grid[cj] = tmp; } // reject
temp *= cooling;
}
var xSpacing = 200, ySpacing = 140;
var positions = {};
for (var ci = 0; ci < gridSize; ci++) {
var ni = grid[ci]; if (ni < 0) continue;
positions[keys[ni]] = { x: 100 + (ci % cols) * xSpacing, y: 80 + Math.floor(ci / cols) * ySpacing };
}
var nodeIds = {};
for (var ei = 0; ei < keys.length; ei++) {
var ek = keys[ei];
var pos = positions[ek];
var x = pos ? pos.x : startX, y = pos ? pos.y : startY;
var name = ek.startsWith('"') ? ek.slice(1, -1) : displayName(ek);
var prevMax = findLastClassNumer();
addClass(x, y, name);
var newId = 'class_' + (prevMax + 1);
nodeIds[ek] = newId;
var circle = document.getElementById(newId + '_circle');
if (circle) {
var tp = types[ek] || 'class';
circle.setAttribute('class',
tp === 'individual' ? 'owbo_individual' :
tp === 'datatype' ? 'owbo_datatype' : 'owbo_class');
}
}
function makeEdge(fromKey, toKey, label) {
var fId = nodeIds[fromKey], tId = nodeIds[toKey];
if (!fId || !tId) return;
var fc = document.getElementById(fId + '_circle');
var tc = document.getElementById(tId + '_circle');
if (!fc || !tc) return;
addProperty(parseFloat(fc.getAttribute('cx')), parseFloat(fc.getAttribute('cy')),
parseFloat(tc.getAttribute('cx')), parseFloat(tc.getAttribute('cy')),
fId, tId, label);
}
isaEdges.forEach(function(e) { makeEdge(e.from, e.to, 'isa'); });
namedEdges.forEach(function(e) { makeEdge(e.from, e.to, e.label); });
// Resize SVG to fit all content so the board scrollbars appear when needed
var svgEl = document.getElementsByTagName('svg')[0];
var bb = svgEl.getBBox();
if (bb.width > 0) {
svgEl.setAttribute('width', Math.round(bb.x + bb.width + 150) + 'px');
svgEl.setAttribute('height', Math.round(bb.y + bb.height + 150) + 'px');
}
}
// this should be called export
function save() {
events.push({type: "click", caughtby: "save", time: new Date().getTime()})
var data = document.getElementById("prefixes_ta").value
data += "\n@prefix owbo: <https://mosaik.loria.fr/tool/owbo#> . "
data += "\n@prefix owl: <http://www.w3.org/2002/07/owl#> . \n"
const svg = document.getElementsByTagName('svg')[0]
var gs = svg.getElementsByTagName('g')
var classes = {} // should be renamed entities
var properties = {}
for (var g in gs){
if (gs[g] && gs[g].getAttribute){
var id = gs[g].getAttribute('id')
if (id.indexOf("property")==0){
var cl = gs[g].getAttribute("class").split(' ')
properties[id] = {}
properties[id].name = toUri(gs[g].childNodes[4].innerHTML.replace(/ /g, '_'), "property")
properties[id].from = cl[1].substring(9)
properties[id].to = cl[2].substring(9)
} else if (id.indexOf("class")==0){
classes[id] = {}
const circle = document.getElementById(id+"_circle")
classes[id].type = circle.getAttribute('class').replace("owbo_", "")
classes[id].name=toUri(gs[g].childNodes[1].innerHTML.replace(/ /g, '_'), classes[id].type)
classes[id].x=gs[g].childNodes[0].getAttribute('cx')
classes[id].y=gs[g].childNodes[0].getAttribute('cy')
}
}
}
// isa → subClassOf / rdf:type (one triple per edge, unchanged)
for (var p in properties) {
if (properties[p].name == "<isa>") {
if (classes[properties[p].from].type == "class")
data += "\n"+classes[properties[p].from].name+" rdfs:subClassOf "+classes[properties[p].to].name+" . "
else if (classes[properties[p].from].type == "individual")
data += "\n"+classes[properties[p].from].name+" rdf:type "+classes[properties[p].to].name+" . "
}
}
// Class-level properties: group by name so that when multiple edges share
// the same property name, domain and range are expressed as owl:unionOf
// instead of repeated rdfs:domain/rdfs:range (which RDFS reads as intersection).
var classPropsByName = {}
for (var p in properties) {
if (properties[p].name == "<isa>" || !properties[p].name) continue
var from = classes[properties[p].from]
var to = classes[properties[p].to]
if (!from || !to) continue
if (from.type == "class" && (to.type == "class" || to.type == "datatype")) {
var pname = properties[p].name
if (!classPropsByName[pname]) classPropsByName[pname] = { domains: [], ranges: [] }
if (classPropsByName[pname].domains.indexOf(from.name) === -1) classPropsByName[pname].domains.push(from.name)
if (classPropsByName[pname].ranges.indexOf(to.name) === -1) classPropsByName[pname].ranges.push(to.name)
}
}
for (var pname in classPropsByName) {
var domains = classPropsByName[pname].domains
var ranges = classPropsByName[pname].ranges
data += "\n" + pname + " rdfs:domain " + (domains.length === 1
? domains[0]
: "[ a owl:Class ; owl:unionOf ( " + domains.join(" ") + " ) ]") + " . "
data += "\n" + pname + " rdfs:range " + (ranges.length === 1
? ranges[0]
: "[ a owl:Class ; owl:unionOf ( " + ranges.join(" ") + " ) ]") + " . "
}
// Concept → Individual: hasValue restriction on the concept
for (var p in properties) {
if (properties[p].name == "<isa>" || !properties[p].name) continue
var from = classes[properties[p].from]
var to = classes[properties[p].to]
if (!from || !to) continue
if (from.type == "class" && to.type == "individual") {
data += "\n" + from.name + " rdfs:subClassOf" +
" [ a owl:Restriction ; owl:onProperty " + properties[p].name +
" ; owl:hasValue " + to.name + " ] . "
}
}
// Individual-level assertions: direct triples, no grouping needed
for (var p in properties) {
if (properties[p].name == "<isa>" || !properties[p].name) continue
var from = classes[properties[p].from]
var to = classes[properties[p].to]
if (!from || !to) continue
if (from.type == "individual" && (to.type == "individual" || to.type == "datatype")) {
var nname = to.name
if (to.type == "datatype") nname = '"' + to.name.replace("xsd:", "") + '"'
data += "\n" + from.name + " " + properties[p].name + " " + nname + " . "
}
}
for (var p in classes) {
if (!classes[p].name || !classes[p].x || !classes[p].y) continue
data += "\n"+classes[p].name+" owbo:x "+Math.round(parseFloat(classes[p].x))+" . "
data += "\n"+classes[p].name+" owbo:y "+Math.round(parseFloat(classes[p].y))+" . "
}
var file = new Blob([data], {type: "text/plain"});
var filename = "owbo_export.ttl" // document.getElementById("onto-name").value+".ttl"
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file, filename);
} else {
var a = document.createElement("a"),
url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
}
function toUri(s,t){
if (s.indexOf(':')!==-1) return
if (t == "datatype") return "xsd:"+s
else return '<'+s+'>'
}
</script>
<!-- <szzcript src="draganddrop.js"></script> -->
<script>
var DRAG_THRESHOLD = 5;
var pointerState = null;
function toSVGCoords(event) {
var board = document.getElementById('owbo_board');
var rect = board.getBoundingClientRect();
return { x: event.clientX - rect.left + board.scrollLeft,
y: event.clientY - rect.top + board.scrollTop };
}
// Handles all pointer releases on the SVG surface:
// - No active state + released on background → create new concept
// - Active 'connect' drag → complete or cancel relation
// - Active 'node' drag → finish move, redraw attached relations
function svgPointerUp(event) {
hideHelp();
if (!pointerState) {
if (event.target === event.currentTarget) {
// Dismiss any open edit panel before creating a new concept
var openDiags = document.getElementsByClassName('diag')
if (openDiags.length > 0) { closeDiag(); return; }
var sc = toSVGCoords(event); addClass(sc.x, sc.y, undefined);
}
return;
}
if (pointerState.type === 'connect') {
var previewLine = document.getElementById('connect_preview');
if (previewLine) previewLine.remove();
var target = event.target;
var isNode = target && target.classList &&
(target.classList.contains("owbo_class") ||
target.classList.contains("owbo_individual") ||
target.classList.contains("owbo_datatype"));
if (isNode) {
var oc = pointerState.originCircle;
if (oc.parentNode !== target.parentNode) {
addProperty(
parseFloat(oc.getAttribute("cx")),
parseFloat(oc.getAttribute("cy")),
parseFloat(target.getAttribute("cx")),
parseFloat(target.getAttribute("cy")),
oc.parentNode.getAttribute("id"),
target.parentNode.getAttribute("id"),
undefined
);
}
}
document.body.classList.remove('connecting');
pointerState = null;
return;
}
if (pointerState.type === 'node') {
if (pointerState.moved) {
redrawRelationsForNode(pointerState.el.parentNode.getAttribute("id"));
}
pointerState = null;
}
}
function classDragStart(eln, event) {
event.stopPropagation();
var el = document.getElementById(eln);
pointerState = {
type: 'node',
el: el,
startX: event.clientX,
startY: event.clientY,
deltaX: parseInt(el.getAttribute("cx")) - event.clientX,
deltaY: parseInt(el.getAttribute("cy")) - event.clientY,
moved: false
};
}
function classDragOver(event) {
if (!pointerState) return;
if (pointerState.type === 'node') {
var dx = event.clientX - pointerState.startX;
var dy = event.clientY - pointerState.startY;
if (Math.sqrt(dx * dx + dy * dy) > DRAG_THRESHOLD) pointerState.moved = true;
if (pointerState.moved) {
var el = pointerState.el;
el.setAttribute("cx", event.clientX + pointerState.deltaX);
el.setAttribute("cy", event.clientY + pointerState.deltaY);
positionHandles(el.parentNode.getAttribute("id"));
var tel = el.parentNode.childNodes[1];
var mx = parseInt(el.getAttribute("cx"));
var my = parseInt(el.getAttribute("cy"));
tel.setAttribute("x", mx - (tel.getBBox().width / 2));
tel.setAttribute("y", my + (tel.getBBox().height / 4));
}
} else if (pointerState.type === 'connect') {
var pl = document.getElementById('connect_preview');
if (pl) {
var sc = toSVGCoords(event);
pl.setAttribute("x2", sc.x);
pl.setAttribute("y2", sc.y);
}
}
}
function connectHandleStart(groupId, event) {
event.stopPropagation();
var handle = event.target;
var originCircle = document.getElementById(groupId + "_circle");
var previewLine = document.createElementNS("http://www.w3.org/2000/svg", "line");
var sc = toSVGCoords(event);
previewLine.setAttribute("x1", handle.getAttribute("cx"));
previewLine.setAttribute("y1", handle.getAttribute("cy"));
previewLine.setAttribute("x2", sc.x);
previewLine.setAttribute("y2", sc.y);
previewLine.setAttribute("style", "stroke:#254468;stroke-width:1.5px;stroke-dasharray:5 3;pointer-events:none;");
previewLine.setAttribute("id", "connect_preview");
svg.appendChild(previewLine);
pointerState = { type: 'connect', originCircle: originCircle };
document.body.classList.add('connecting');
}
function redrawRelationsForNode(clid) {
var props = document.getElementsByClassName("property_" + clid);
var toremove = [];
for (var p in props)
if (typeof props[p].remove == "function") toremove.push(props[p]);
for (var e in toremove) {
var cls = toremove[e].getAttribute("class").split(" ");
var classID1 = cls[1].substring(9);
var classID2 = cls[2].substring(9);
var x1 = parseInt(document.getElementById(classID1).childNodes[0].getAttribute("cx"));
var y1 = parseInt(document.getElementById(classID1).childNodes[0].getAttribute("cy"));
var x2 = parseInt(document.getElementById(classID2).childNodes[0].getAttribute("cx"));
var y2 = parseInt(document.getElementById(classID2).childNodes[0].getAttribute("cy"));
var label = toremove[e].childNodes[4].innerHTML;
addProperty(x1, y1, x2, y2, classID1, classID2, label);
toremove[e].remove();
}
}
// Backward-compat stub for onpointerup="class_clicked(...)" in saved HTML files.
// The SVG-level onpointerup handles everything; this is a no-op.
function class_clicked() {}
function class_name_clicked(eln, event) {
event.stopPropagation();
var el = document.getElementById(eln);
changeClassName(el, el.innerHTML);
}
function property_name_clicked(eln, event) {
event.stopPropagation();
var el = document.getElementById(eln);
changePropertyName(el, el.innerHTML);
}
function showPrefixes() {
var el = document.getElementById("prefixes");
el.style.display = el.style.display == "block" ? "none" : "block";
}
function showHelp() {
var el = document.getElementById("help_dialog");
el.style.display = el.style.display == "block" ? "none" : "block";
}
function hideHelp() {
document.getElementById("help_dialog").style.display = "none";
}
</script>
<script>
var existingProp = {}
function findLastClassNumer(){
ln = 0
cl = document.getElementsByClassName("owbo_class")
for (var c in cl){
if (cl[c].id){
var n = parseInt(cl[c].id.replace("class_",""))
if (n>ln) ln = n
}
}
cl = document.getElementsByClassName("owbo_individual")
for (var c in cl){
if (cl[c].id){
var n = parseInt(cl[c].id.replace("class_",""))
if (n>ln) ln = n
}
}
cl = document.getElementsByClassName("owbo_datatype")
for (var c in cl){
if (cl[c].id){
var n = parseInt(cl[c].id.replace("class_",""))
if (n>ln) ln = n
}
}
return ln
}
function findLastPropertyNumber(){
ln = 0
pr = document.getElementsByClassName("owbo_property_name")
for (var p in pr){
if (pr[p].id){
var n = parseInt(pr[p].id.replace("property_",""))
if (n>ln) ln = n
}
}
return ln
}
// Position the four connection handles at the cardinal edges of a node's ellipse.
function positionHandles(groupId) {
var circle = document.getElementById(groupId + "_circle");
if (!circle) return;
var cx = parseFloat(circle.getAttribute("cx"));
var cy = parseFloat(circle.getAttribute("cy"));
var rx = parseFloat(circle.getAttribute("rx"));
var ry = parseFloat(circle.getAttribute("ry"));
var positions = { n: [cx, cy - ry], e: [cx + rx, cy], s: [cx, cy + ry], w: [cx - rx, cy] };
for (var dir in positions) {
var h = document.getElementById(groupId + "_handle_" + dir);
if (h) {
h.setAttribute("cx", positions[dir][0]);
h.setAttribute("cy", positions[dir][1]);
}
}
}
// Add four connection handles to an existing node group (used for new nodes and
// for nodes loaded from a previously saved HTML file that pre-dates this feature).
function addHandlesToGroup(groupId) {
var clg = document.getElementById(groupId);
if (!clg) return;
clg.setAttribute("class", "owbo_node_group");
var circle = document.getElementById(groupId + "_circle");
if (circle) circle.setAttribute("onclick", "event.stopPropagation()");
var dirs = ['n', 'e', 's', 'w'];
for (var d = 0; d < dirs.length; d++) {
if (document.getElementById(groupId + "_handle_" + dirs[d])) continue;
var handle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
handle.setAttribute("r", "7");
handle.setAttribute("class", "connect-handle");
handle.id = groupId + "_handle_" + dirs[d];
handle.setAttribute("onpointerdown", "connectHandleStart('" + groupId + "', event)");
handle.setAttribute("onclick", "event.stopPropagation()");
clg.appendChild(handle);
}
positionHandles(groupId);
}
function addClass(mx,my,name){
clcount = findLastClassNumer()+1
console.log("creating class "+clcount)
const clg = document.createElementNS("http://www.w3.org/2000/svg", "g")
clg.setAttribute("id", "class_"+(clcount))
clg.setAttribute("class", "owbo_node_group")
const clcir = document.createElementNS("http://www.w3.org/2000/svg", "ellipse")
clcir.setAttribute("cx", mx)
clcir.setAttribute("cy", my)
clcir.setAttribute("rx", "60")
clcir.setAttribute("ry", "30")
clcir.setAttribute("class", "owbo_class")
clcir.id = clg.id+"_circle"
clcir.setAttribute("onpointerdown", "classDragStart('"+clg.id+"_circle', event)")
clcir.setAttribute("onclick", "event.stopPropagation()")
clg.appendChild(clcir)
const cltext = document.createElementNS("http://www.w3.org/2000/svg", "text")
clname = "New Concept"
if (name) clname = name
cltext.innerHTML= clname
cltext.setAttribute("x", mx)
cltext.setAttribute("y", my)
cltext.setAttribute("style", "fill: #254468")
clg.appendChild(cltext)
svg.appendChild(clg)
var cltl = cltext.getBBox().width
var clth = cltext.getBBox().height
cltext.setAttribute("x", mx-(cltl/2))
cltext.setAttribute("y", my+(clth/4))
cltext.setAttribute("class", "owbo_class_name")
cltext.id = clg.id+"_name"
cltext.setAttribute("onclick", "class_name_clicked('"+clg.id+"_name', event)")
addHandlesToGroup(clg.id)
if (name) {