-
Notifications
You must be signed in to change notification settings - Fork 4
/
huviz.coffee
8169 lines (7544 loc) · 292 KB
/
huviz.coffee
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
#See for inspiration:
# Collapsible Force Layout
# http://bl.ocks.org/mbostock/1093130
# Force-based label placement
# http://bl.ocks.org/MoritzStefaner/1377729
# Graph with labeled edges:
# http://bl.ocks.org/jhb/5955887
# Multi-Focus Layout:
# http://bl.ocks.org/mbostock/1021953
# Edge Labels
# http://bl.ocks.org/jhb/5955887
#
# Shelf -- around the graph, the ring of nodes which serves as reorderable menu
# Discard Bin -- a jail to contain nodes one does not want to be bothered by
#
# Commands on nodes
# choose/shelve -- graph or remove from graph
# choose - add to graph and show all edges
# unchoose - hide all edges except those to 'chosen' nodes
# this will shelve (or hide if previously hidden)
# those nodes which end up no longer being connected
# to anything
# discard/retrieve -- throw away or recover
# label/unlabel -- shows labels or hides them
# substantiate/redact -- shows source text or hides it
# expand/contract -- show all links or collapse them
#
# TODO(smurp) implement emphasize and deemphasize 'verbs' (we need a new word)
# emphasize: (node,predicate,color) =>
# deemphasize: (node,predicate,color) =>
# pin/unpin
#
# TODO(smurp) break out verbs as instances of class Verb, support loading of verbs
#
# TODO: perhaps there is a distinction to be made between verbs
# and 'actuators' where verbs are the things that people issue
# while actuators (actions?) are the one-or-more things per-verb that
# constitute the implementation of the verb. The motivations are:
# a) that actuators may be shared between verbs
# b) multiple actuators might be needed per verb
# c) there might be applications for actuators other than verbs
# d) there might be update operations against gclui apart from actuators
#
# Immediate Priorities:
# 120) BUG: hidden nodes are hidden but are also detectable via TextCursor
# 118) TASK: add setting for "'chosen' border thickness (px)"
# 116) BUG: stop truncating verbs lists longer than 2 in TextCursor: use grid
# 115) TASK: add ColorTreepicker [+] and [-] boxes for 'show' and 'unshow'
# 114) TASK: make text_cursor show detailed stuff when in Commands and Settings
# 113) TASK: why is CP "Poetry" in abdyma.nq not shelved?
# 107) TASK: minimize hits on TextCursor by only calling it when verbs change
# not whenever @focused_node changes
# 104) TASK: remove no-longer-needed text_cursor calls
# 40) TASK: support search better, show matches continuously
# 79) TASK: support dragging of edges to shelf or discard bin
# 97) TASK: integrate blanket for code coverage http://goo.gl/tH4Ghk
# 93) BUG: toggling a predicate should toggle indirect-mixed on its supers
# 92) BUG: non-empty predicates should not have payload '0/0' after kid click
# 94) TASK: show_msg() during command.run to inform user and prevent clicks
# 95) TASK: get /orlonto.html working smoothly again
# 90) BUG: english is no longer minimal
# 91) BUG: mocha async being misused re done(), so the passes count is wrong
# 86) BUG: try_to_set_node_type: only permit subtypes to override supertypes
# 87) BUG: solve node.type vs node.taxon sync problem (see orlonto)
# 46) TASK: impute node type based on predicates via ontology DONE???
# 53) PERF: should_show_label should not have search_regex in inner loop
# 65) BUG: hidden nodes are not fully ignored on the shelf so shelved nodes
# are not always the focused node
# 68) TASK: optimize update_english
# 69) TASK: figure out ideal root for predicate hierarchy -- owl:Property?
# 70) TASK: make owl:Thing implicit root class
# ie: have Taxons be subClassOf owl:Thing unless replaced
# 72) TASK: consolidate type and taxon links from node?
# 74) TASK: recover from loading crashes with Cancel button on show_state_msg
# 76) TASK: consider renaming graphed_set to connected_set and verbs
# choose/unchoose to graph/ungraph
# 84) TASK: add an unchosen_set containing the graphed but not chosen nodes
#
# Eventual Tasks:
# 85) TASK: move SVG, Canvas and WebGL renderers to own pluggable Renderer subclasses
# 75) TASK: implement real script parser
# 4) TASK: Suppress all but the 6-letter id of writers in the cmd cli
# 14) TASK: it takes time for clicks on the predicate picker to finish;
# showing a busy cursor or a special state for the selected div
# would help the user have faith.
# (Investigate possible inefficiencies, too.)
# AKA: fix bad-layout-until-drag-and-drop bug
# 18) TASK: drop a node on another node to draw their mutual edges only
# 19) TASK: progressive documentation (context sensitive tips and intros)
# 25) TASK: debug wait cursor when slow operations are happening, maybe
# prevent starting operations when slow stuff is underway
# AKA: show waiting cursor during verb execution
# 30) TASK: Stop passing (node, change, old_node_status, new_node_status) to
# Taxon.update_state() because it never seems to be needed
# 35) TASK: get rid of jquery
# 37) TASK: fix Bronte names, ie unicode
# 41) TASK: link to new backend
# 51) TASK: make predicate picker height adjustable
# 55) TASK: clicking an edge for a snippet already shown should add that
# triple line to the snippet box and bring the box forward
# (ideally using css animation to flash the triple and scroll to it)
# 56) TASK: improve layout of the snippet box so the subj is on the first line
# and subsequent lines show (indented) predicate-object pairs for
# each triple which cites the snippet
# 57) TASK: hover over node on shelf shows edges to graphed and shelved nodes
# 61) TASK: make a settings controller for edge label (em) (or mag?)
# 66) BUG: #load+/data/ballrm.nq fails to populate the predicate picker
# 67) TASK: add verbs pin/unpin (using polar coords to record placement)
#
angliciser = require('angliciser').angliciser
uniquer = require("uniquer").uniquer # FIXME rename to make_dom_safe_id
gcl = require('graphcommandlanguage')
#asyncLoop = require('asynchronizer').asyncLoop
CommandController = require('gclui').CommandController
EditController = require('editui').EditController
#FiniteStateMachine = require('fsm').FiniteStateMachine
IndexedDBService = require('indexeddbservice').IndexedDBService
IndexedDBStorageController = require('indexeddbstoragecontroller').IndexedDBStorageController
Edge = require('edge').Edge
GraphCommandLanguageCtrl = require('graphcommandlanguage').GraphCommandLanguageCtrl
GreenerTurtle = require('greenerturtle').GreenerTurtle
Node = require('node').Node
Predicate = require('predicate').Predicate
Taxon = require('taxon').Taxon
TextCursor = require('textcursor').TextCursor
MultiString.set_langpath('en:fr') # TODO make this a setting
# It is as if these imports were happening but they are being stitched in instead
# OnceRunner = require('oncerunner').OnceRunner
# TODO document the other examples of requires that are being "stitched in"
colorlog = (msg, color, size) ->
color ?= "red"
size ?= "1.2em"
console.log("%c#{msg}", "color:#{color};font-size:#{size};")
unpad_md = (txt, pad) ->
# Purpose:
# Remove padding at the beginings of all lines in txt IFF all lines have padding
# Motivation:
# Markdown is very whitespace sensitive but it makes for ugly code
# to not have left padding in large strings.
pad = " "
out_lines = []
in_lines = txt.split("\n")
for line in in_lines
if not (line.startsWith(pad) or line.length is 0)
return txt
out_lines.push(line.replace(/^ /,''))
out = out_lines.join("\n")
return out
wpad = undefined
hpad = 10
tau = Math.PI * 2
distance = (p1, p2) ->
p2 = p2 || [0,0]
x = (p1.x or p1[0]) - (p2.x or p2[0])
y = (p1.y or p1[1]) - (p2.y or p2[1])
Math.sqrt x * x + y * y
dist_lt = (mouse, d, thresh) ->
x = mouse[0] - d.x
y = mouse[1] - d.y
Math.sqrt(x * x + y * y) < thresh
hash = (str) ->
# https://github.com/darkskyapp/string-hash/blob/master/index.js
hsh = 5381
i = str.length
while i
hsh = (hsh * 33) ^ str.charCodeAt(--i)
return hsh >>> 0
convert = (src, srctable, desttable) ->
# convert.js
# http://rot47.net
# Dr Zhihua Lai
srclen = srctable.length
destlen = desttable.length
# first convert to base 10
val = 0
numlen = src.length
i = 0
while i < numlen
val = val * srclen + srctable.indexOf(src.charAt(i))
i++
return 0 if val < 0
# then covert to any base
r = val % destlen
res = desttable.charAt(r)
q = Math.floor(val / destlen)
while q
r = q % destlen
q = Math.floor(q / destlen)
res = desttable.charAt(r) + res
return res
BASE57 = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
BASE10 = "0123456789"
int_to_base = (intgr) ->
convert(""+intgr, BASE10, BASE57)
synthIdFor = (str) ->
# return a short random hash suitable for use as DOM/JS id
return 'h'+int_to_base(hash(str)).substr(0,6)
window.synthIdFor = synthIdFor
unescape_unicode = (u) ->
# pre-escape any existing quotes so when JSON.parse does not get confused
return JSON.parse('"' + u.replace('"', '\\"') + '"')
linearize = (msgRecipient, streamoid) ->
if streamoid.idx is 0
msgRecipient.postMessage({event: 'finish'})
else
i = streamoid.idx + 1
l = 0
while (streamoid.data[i] not '\n')
l++
i++
line = streamoid.data.substr(streamoid.idx, l+1).trim()
msgRecipient.postMessage({event:'line', line:line})
streamoid.idx = i
recurse = () -> linearize(msgRecipient, streamoid)
setTimeout(recurse, 0)
ident = (data) ->
return data
unique_id = (prefix) ->
prefix ?= 'uid_'
return prefix + Math.random().toString(36).substr(2,10)
sel_to_id = (selector) ->
# remove the leading hash to make a selector into an id
return selector.replace(/^\#/,'')
window.log_click = () ->
console.log("%cCLICK", "color:red;font-size:1.8em")
# http://dublincore.org/documents/dcmi-terms/
DC_subject = "http://purl.org/dc/terms/subject"
FOAF_Group = "http://xmlns.com/foaf/0.1/Group"
FOAF_Person = "http://xmlns.com/foaf/0.1/Person"
FOAF_name = "http://xmlns.com/foaf/0.1/name"
OWL_Class = "http://www.w3.org/2002/07/owl#Class"
OWL_Thing = "http://www.w3.org/2002/07/owl#Thing"
OWL_ObjectProperty = "http://www.w3.org/2002/07/owl#ObjectProperty"
RDF_literal = "http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral"
RDF_object = "http://www.w3.org/1999/02/22-rdf-syntax-ns#object"
RDF_type = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"
RDF_Class = "http://www.w3.org/2000/01/rdf-schema#Class"
RDF_subClassOf = "http://www.w3.org/2000/01/rdf-schema#subClassOf"
RDF_a = 'a'
RDFS_label = "http://www.w3.org/2000/01/rdf-schema#label"
SKOS_prefLabel = "http://www.w3.org/2004/02/skos/core#prefLabel"
XL_literalForm = "http://www.w3.org/2008/05/skos-xl#literalForm"
TYPE_SYNS = [RDF_type, RDF_a, 'rdfs:type', 'rdf:type']
THUMB_PREDS = [
'http://dbpedia.org/ontology/thumbnail'
'http://xmlns.com/foaf/0.1/thumbnail']
NAME_SYNS = [
FOAF_name, RDFS_label, 'rdfs:label', 'name', SKOS_prefLabel, XL_literalForm
]
XML_TAG_REGEX = /(<([^>]+)>)/ig
typeSigRE =
# https://regex101.com/r/lKClAg/1
'xsd': new RegExp("^http:\/\/www\.w3\.org\/2001\/XMLSchema\#(.*)$")
# https://regex101.com/r/ccfdLS/3/
'rdf': new RegExp("^http:\/\/www\.w3\.org\/1999\/02\/22-rdf-syntax-ns#(.*)$")
getPrefixedTypeSignature = (typeUri) ->
for prefix, sig of typeSigRE
match = typeUri.match(sig)
if match
return "#{prefix}__#{match[1]}"
return
getTypeSignature = (typeUri) ->
typeSig = getPrefixedTypeSignature(typeUri)
return typeSig
#return (typeSig or '').split('__')[1]
PRIMORDIAL_ONTOLOGY =
subClassOf:
Literal: 'Thing'
# https://www.w3.org/1999/02/22-rdf-syntax-ns
# REVIEW(smurp) ignoring all but the rdfs:Datatype instances
# REVIEW(smurp) should Literal be called Datatype instead?
"rdf__PlainLiteral": 'Literal'
"rdf__HTML": 'Literal'
"rdf__langString": 'Literal'
"rdf__type": 'Literal'
"rdf__XMLLiteral": 'Literal'
# https://www.w3.org/TR/xmlschema11-2/type-hierarchy-201104.png
# https://www.w3.org/2011/rdf-wg/wiki/XSD_Datatypes
# REVIEW(smurp) ideally all the xsd types would fall under anyType > anySimpleType > anyAtomicType
# REVIEW(smurp) what about Built-in list types like: ENTITIES, IDREFS, NMTOKENS ????
"xsd__anyURI": 'Literal'
"xsd__base64Binary": 'Literal'
"xsd__boolean": 'Literal'
"xsd__date": 'Literal'
"xsd__dateTimeStamp": 'date'
"xsd__decimal": 'Literal'
"xsd__integer": "xsd__decimal"
"xsd__long": "xsd__integer"
"xsd__int": "xsd__long"
"xsd__short": "xsd__int"
"xsd__byte": "xsd__short"
"xsd__nonNegativeInteger": "xsd__integer"
"xsd__positiveInteger": "xsd__nonNegativeInteger"
"xsd__unsignedLong": "xsd__nonNegativeInteger"
"xsd__unsignedInt": "xsd__unsignedLong"
"xsd__unsignedShort": "xsd__unsignedInt"
"xsd__unsignedByte": "xsd__unsignedShort"
"xsd__nonPositiveInteger": "xsd__integer"
"xsd__negativeInteger": "xsd__nonPositiveInteger"
"xsd__double": 'Literal'
"xsd__duration": 'Literal'
"xsd__float": 'Literal'
"xsd__gDay": 'Literal'
"xsd__gMonth": 'Literal'
"xsd__gMonthDay": 'Literal'
"xsd__gYear": 'Literal'
"xsd__gYearMonth": 'Literal'
"xsd__hexBinary": 'Literal'
"xsd__NOTATION": 'Literal'
"xsd__QName": 'Literal'
"xsd__string": 'Literal'
"xsd__normalizedString": "xsd_string"
"xsd__token": "xsd__normalizedString"
"xsd__language": "xsd__token"
"xsd__Name": "xsd__token"
"xsd__NCName": "xsd__Name"
"xsd__time": 'Literal'
subPropertyOf: {}
domain: {}
range: {}
label: {} # MultiStrings as values
MANY_SPACES_REGEX = /\s{2,}/g
UNDEFINED = undefined
start_with_http = new RegExp("http", "ig")
ids_to_show = start_with_http
PEEKING_COLOR = "darkgray"
themeStyles =
"light":
"themeName": "theme_white"
"pageBg": "white"
"labelColor": "black"
"shelfColor": "lightgreen"
"discardColor": "salmon"
"nodeHighlightOutline": "black"
"dark":
"themeName": "theme_black"
"pageBg": "black"
"labelColor": "#ddd"
"shelfColor": "#163e00"
"discardColor": "#4b0000"
"nodeHighlightOutline": "white"
id_escape = (an_id) ->
retval = an_id.replace(/\:/g,'_')
retval = retval.replace(/\//g,'_')
retval = retval.replace(new RegExp(' ','g'),'_')
retval = retval.replace(new RegExp('\\?','g'),'_')
retval = retval.replace(new RegExp('\=','g'),'_')
retval = retval.replace(new RegExp('\\.','g'),'_')
retval = retval.replace(new RegExp('\\#','g'),'_')
retval
if true
node_radius_policies =
"node radius by links": (d) ->
d.radius = Math.max(@node_radius, Math.log(d.links_shown.length))
return d.radius
if d.showing_links is "none"
d.radius = @node_radius
else
if d.showing_links is "all"
d.radius = Math.max(@node_radius,
2 + Math.log(d.links_shown.length))
d.radius
"equal dots": (d) ->
@node_radius
default_node_radius_policy = "equal dots"
default_node_radius_policy = "node radius by links"
has_type = (subject, typ) ->
has_predicate_value subject, RDF_type, typ
has_predicate_value = (subject, predicate, value) ->
pre = subject.predicates[predicate]
if pre
objs = pre.objects
oi = 0
while oi <= objs.length
obj = objs[oi]
return true if obj.value is value
oi++
false
is_a_main_node = (d) ->
(BLANK_HACK and d.s.id[7] isnt "/") or (not BLANK_HACK and d.s.id[0] isnt "_")
is_node_to_always_show = is_a_main_node
is_one_of = (itm,array) ->
array.indexOf(itm) > -1
if not is_one_of(2,[3,2,4])
alert "is_one_of() fails"
window.blurt = (str, type, noButton) ->
throw new Error('global blurt() is defunct, use @blurt() on HuViz')
escapeHtml = (unsafe) ->
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
class SettingsWidget
constructor: (@huviz, @inputElem, state) ->
@id = unique_id('widget_')
@inputJQElem = $(@inputElem)
wrap: (html) ->
$(@inputElem).wrap(html)
class UsernameWidget extends SettingsWidget
# https://fontawesome.com/v4.7.0/examples/#animated explains animations fa-spin (continuous) and fa-pulse (8-step)
state_to_state_icon:
bad: 'fa-times' # the username has been tried and failed last use
good: 'fa-check' # the username has been tried and succeeded last use
untried: 'fa-question' # a username has been provided but not yet tried
trying: 'fa-spinner fa-pulse' # performing a lookup with a username which might be bad or good
empty: 'fa-ellipsis-h' # no username present
looking: 'fa-map-marker-alt fa-spin' # performing a lookup with a known good username
state_to_color:
bad: 'red'
good: 'green'
untried: 'orange'
trying: 'orange'
empty: 'grey'
looking: 'green'
constructor: ->
super(arguments...)
@wrap("""<div id="#{@id}" class="geo_input_wrap"></div>""") # style="border:2px solid; padding:2px
#@inputElem.setAttribute('style','border:none')
@widgetJQElem = $('#'+@id)
@widgetJQElem.prepend("""<i class="userIcon fa fa-user-alt"></i><i class="stateIcon fa fa-question"></i>""")
@stateIconJQElem = @widgetJQElem.find('.stateIcon')
@userIconJQElem = @widgetJQElem.find('.userIcon')
@set_state('empty')
set_state: (state) ->
if false and @state and @state is state
console.log("not bothering to change the state to",state,"cause it already is")
return
@state = state
console.log(state, @inputJQElem.val())
stateIcon = @state_to_state_icon[state]
@stateIconJQElem.attr('class', "stateIcon fa " + stateIcon)
color = @state_to_color[state]
@widgetJQElem.css('border-color',color)
@widgetJQElem.css('color',color)
return
class GeoUserNameWidget extends UsernameWidget
constructor: ->
super(arguments...)
@stateIconJQElem.on('click', @huviz.show_geonames_instructions)
@userIconJQElem.on('click', @huviz.show_geonames_instructions)
orlando_human_term =
all: 'All'
chosen: 'Activated'
unchosen: 'Deactivated'
selected: 'Selected'
shelved: 'Shelved'
discarded: 'Discarded'
hidden: 'Hidden'
graphed: 'Graphed'
fixed: 'Pinned'
labelled: 'Labelled'
choose: 'Activate'
unchoose: 'Deactivate'
wander: 'Wander'
walk: 'Walk'
walked: "Walked"
select: 'Select'
unselect: 'Unselect'
label: 'Label'
unlabel: 'Unlabel'
shelve: 'Shelve'
hide: 'Hide'
discard: 'Discard'
undiscard: 'Retrieve'
pin: 'Pin'
unpin: 'Unpin'
unpinned: 'Unpinned'
nameless: 'Nameless'
blank_verb: 'VERB'
blank_noun: 'SET/SELECTION'
hunt: 'Hunt'
load: 'Load'
draw: 'Draw'
undraw: 'Undraw'
connect: 'Connect'
spawn: 'Spawn'
specialize: 'Specialize'
annotate: 'Annotate'
seeking_object: 'Object node'
class Huviz
class_list: [] # FIXME remove
HHH: {}
edges_by_id: {}
edge_count: 0
snippet_db: {}
class_index: {}
hierarchy: {}
default_color: "brown"
DEFAULT_CONTEXT: 'http://universal.org/'
turtle_parser: 'GreenerTurtle'
#turtle_parser: 'N3'
use_canvas: true
use_svg: false
use_webgl: false
#use_webgl: true if location.hash.match(/webgl/)
#use_canvas: false if location.hash.match(/nocanvas/)
nodes: undefined
links_set: undefined
node: undefined
link: undefined
lariat: undefined
verbose: true
verbosity: 0
TEMP: 5
COARSE: 10
MODERATE: 20
DEBUG: 40
DUMP: false
node_radius_policy: undefined
draw_circle_around_focused: true
draw_lariat_labels_rotated: true
run_force_after_mouseup_msec: 2000
nodes_pinnable: true
BLANK_HACK: false
width: undefined
height: 0
cx: 0
cy: 0
snippet_body_em: .7
snippet_triple_em: .8
line_length_min: 4
# TODO figure out how to replace with the default_graph_control
link_distance: 29
fisheye_zoom: 4.0
peeking_line_thicker: 4
show_snippets_constantly: false
charge: -193
gravity: 0.025
snippet_count_on_edge_labels: true
label_show_range: null # @link_distance * 1.1
focus_threshold: 100
discard_radius: 200
fisheye_radius: 300 #null # label_show_range * 5
focus_radius: null # label_show_range
drag_dist_threshold: 5
snippet_size: 300
dragging: false
last_status: undefined
edge_x_offset: 5
shadow_offset: 1
shadow_color: 'DarkGray'
my_graph:
predicates: {}
subjects: {}
objects: {}
# required by green turtle, should be retired
G: {}
local_file_data: ""
search_regex: new RegExp("^$", "ig")
node_radius: 3.2
mousedown_point: false
discard_center: [0,0]
lariat_center: [0,0]
last_mouse_pos: [ 0, 0]
renderStyles = themeStyles.light
display_shelf_clockwise: true
nodeOrderAngle = 0.5
node_display_type = ''
pfm_display: false
pfm_data:
tick:
total_count: 0
prev_total_count: 0
timed_count: []
label: "Ticks/sec."
add_quad:
total_count: 0
prev_total_count: 0
timed_count: []
label: "Add Quad/sec"
hatch:
total_count: 0
prev_total_count: 0
timed_count: []
label: "Hatch/sec"
taxonomy:
total_count: 0
label: "Number of Classes:"
sparql:
total_count: 0
prev_total_count: 0
timed_count: []
label: "Sparql Queries/sec"
p_total_sprql_requests: 0
how_heavy_are: (n, label, cb) ->
memories = []
memories.push(window.performance.memory)
@heavy_things ?= {}
buncha = []
@heavy_things[label] = buncha
for m in [1..n]
retval = cb.call(this,n)
#console.log(retval)
buncha.push(retval)
memories.push(window.performance.memory)
memories.push({})
memories.push({})
[before,after,diff,per] = memories
for k of memories[0]
diff[k] = after[k] - before[k]
per[k] = diff[k] / n
per.what = 'B/'+label
before.what = 'before'
after.what = 'after'
diff.what = 'diff'
#console.log(per)
colorlog(label + ' occupy ' + per.totalJSHeapSize + ' Bytes each')
console.log('eg', retval)
#console.table(memories)
return
how_heavy: (n) ->
# Purpose:
# Find out how many Bytes each of the following objects occupy in RAM.
# Example:
# HVZ[0].how_heavy(100000)
@how_heavy_are(n, 'Array', (x) -> return new Array(100))
@how_heavy_are(n, 'Object', (x) -> return (new Object())[x] = x)
@how_heavy_are(n, 'String', (x) -> return ""+x)
@how_heavy_are(n, 'Random', (x) -> return Math.random())
@how_heavy_are(n, 'SortedSet', (x) -> return SortedSet().named(x))
compose_object_from_defaults_and_incoming: (defs, incoming) ->
# Purpose:
# To return an object with the properties of defs and incoming layered into it in turn
# Intended Use Case:
# It is frequently the case that one wants to have and object with contains
# the default arguments for something and that one also wants the ability to
# pass in another object which contains the specifics for the call.
# This method joins those things together properly (they can even be null)
# to return the amalgamation of the defaults and the incoming arguments.
defs ?= {}
incoming ?= {}
return Object.assign(Object.assign({}, defs), incoming)
default_dialog_args: {width:200, height:200, left:100, top:100, head_bg_color:'blue', classes: "contextMenu temp"}
gen_dialog_html: (contents, id, in_args) ->
args = @compose_object_from_defaults_and_incoming(@default_dialog_args, in_args)
#args = Object.assign(default_args, in_args)
return """<div id="#{id}" class="#{args.classes} #{args.extraClasses}"
style="display:block;top:#{args.top}px;left:#{args.left}px;max-width:#{args.width}px;max-height:#{args.height}px">
<div class="header" style="background-color:#{args.head_bg_color};#{args.style}">
<button class="close_node_details" title="Close"><i class="far fa-window-close"></i></button>
</div>
#{contents}
</div>""" # """ for emacs coffeescript mode
make_dialog: (content_html, id, args) ->
id ?= @unique_id('dialog_')
@addHTML(@gen_dialog_html(content_html, id, args))
elem = document.querySelector('#'+id)
$(elem.querySelector(' .close_node_details')).on('click', @destroy_box)
$(elem).draggable()
return elem
destroy_box: (e) ->
box = e.currentTarget.offsetParent
$(box).remove()
make_markdown_dialog: (markdown, id, args) ->
args ?= {}
args.extraClasses += " markdownDialog"
return @make_dialog(marked(markdown or ''), id, args)
unique_id: (prefix) ->
prefix ?= 'uid_'
return prefix + Math.random().toString(36).substr(2,10)
change_sort_order: (array, cmp) ->
array.__current_sort_order = cmp
array.sort array.__current_sort_order
isArray: (thing) ->
Object::toString.call(thing) is "[object Array]"
cmp_on_name: (a, b) ->
return 0 if a.name is b.name
return -1 if a.name < b.name
1
cmp_on_id: (a, b) ->
return 0 if a.id is b.id
return -1 if a.id < b.id
1
binary_search_on: (sorted_array, sought, cmp, ret_ins_idx) ->
# return -1 or the idx of sought in sorted_array
# if ret_ins_idx instead of -1 return [n] where n is where it ought to be
# AKA "RETurn the INSertion INdeX"
cmp = cmp or sorted_array.__current_sort_order or @cmp_on_id
ret_ins_idx = ret_ins_idx or false
seeking = true
if sorted_array.length < 1
return idx: 0 if ret_ins_idx
return -1
mid = undefined
bot = 0
top = sorted_array.length
while seeking
mid = bot + Math.floor((top - bot) / 2)
c = cmp(sorted_array[mid], sought)
#console.log(" c =",c);
return mid if c is 0
if c < 0 # ie sorted_array[mid] < sought
bot = mid + 1
else
top = mid
if bot is top
return idx: bot if ret_ins_idx
return -1
# Objective:
# Maintain a sorted array which acts like a set.
# It is sorted so insertions and tests can be fast.
# cmp: a comparison function returning -1,0,1
# an integer was returned, ie it was found
# Perform the set .add operation, adding itm only if not already present
#if (Array.__proto__.add == null) Array.prototype.add = add;
# the nodes the user has chosen to see expanded
# the nodes the user has discarded
# the nodes which are in the graph, linked together
# the nodes not displaying links and not discarded
# keep synced with html
# bugged
roughSizeOfObject: (object) ->
# http://stackoverflow.com/questions/1248302/javascript-object-size
objectList = []
stack = [object]
bytes = 0
while stack.length
value = stack.pop()
if typeof value is "boolean"
bytes += 4
else if typeof value is "string"
bytes += value.length * 2
else if typeof value is "number"
bytes += 8
else if typeof value is "object" and objectList.indexOf(value) is -1
objectList.push value
for i of value
stack.push value[i]
bytes
move_node_to_point: (node, point) ->
node.x = point[0]
node.y = point[1]
click_node: (node_or_id) ->
# motivated by testing. Should this also be used by normal click handling?
console.warn("click_node() is deprecated")
if typeof node_or_id is 'string'
node = @nodes.get_by('id', node_or_id)
else
node = node_or_id
@set_focused_node(node)
evt = new MouseEvent "mouseup",
screenX: node.x
screenY: node.y
@canvas.dispatchEvent(evt)
return @
click_verb: (id) ->
verbs = $("#verb-#{id}")
if not verbs.length
throw new Error("verb '#{id}' not found")
verbs.trigger("click")
return @
click_set: (id) ->
if id is 'nodes'
alert("set 'nodes' is deprecated")
console.error("set 'nodes' is deprecated")
else
if not id.endsWith('_set')
id = id + '_set'
sel = "##{id}"
sets = $(sel)
if not sets.length
throw new Error("set '#{id}' not found using selector: '#{sel}'")
sets.trigger("click")
return @
click_predicate: (id) ->
@gclui.predicate_picker.handle_click(id)
return @
click_taxon: (id) ->
$("##{id}").trigger("click")
return @
like_string: (str) =>
# Ideally we'd trigger an actual 'input' event but that is not possible
#$(".like_input").val(str)
@gclui.like_input.val(str)
@gclui.handle_like_input()
#debugger if @DEBUG and str is ""
return @
toggle_expander: (id) ->
@topJQElem.find("##{id} span.expander:first").trigger("click");
return @
doit: ->
@topJQElem.find(".doit_button").trigger("click")
return @
make_cursor_text_while_dragging: (action) ->
if action in ['seeking_object']
drag_or_drop = 'drag'
else
drag_or_drop = 'drop'
return "#{@human_term[drag_or_drop] or drag_or_drop} to #{@human_term[action] or action}"
get_mouse_point: (d3_event) ->
d3_event ?= @mouse_receiver[0][0]
return d3.mouse(d3_event)
should_start_dragging: ->
# We can only know that the users intention is to drag
# a node once sufficient motion has started, when there
# is a focused_node
#console.log "state_name == '" + @focused_node.state.state_name + "' and selected? == " + @focused_node.selected?
#console.log "START_DRAG: \n dragging",@dragging,"\n mousedown_point:",@mousedown_point,"\n @focused_node:",@focused_node
return not @dragging and
@mousedown_point and
@focused_node and
distance(@last_mouse_pos, @mousedown_point) > @drag_dist_threshold
mousemove: =>
@last_mouse_pos = @get_mouse_point()
if @rightClickHold
@text_cursor.continue()
@text_cursor.set_text("Inspect")
if @focused_node
the_node = $("##{@focused_node.lid}")
if the_node.html() then the_node.remove()
@render_node_info_box()
else
if $(".contextMenu.temp") then $(".contextMenu.temp").remove()
else if @should_start_dragging()
@dragging = @focused_node
if @args.drag_start_handler
try
@args.drag_start_handler.call(this, @dragging)
catch e
console.warn(e)
if @editui.is_state('connecting')
if @editui.subject_node isnt @dragging
@editui.set_subject_node(@dragging)
if @dragging.state isnt @graphed_set isnt @rightClickHold
@graphed_set.acquire(@dragging)
if not @rightClickHold
if @dragging
@force.resume() # why?
if not @args.skip_log_tick
console.log "Tick in @force.resume() mousemove"
@move_node_to_point(@dragging, @last_mouse_pos)
if @editui.is_state('connecting')
@text_cursor.pause("", "drop on object node")
else
if @dragging.links_shown.length is 0
action = "choose"
else if @dragging.fixed
action = "unpin"
else
action = "pin"
if (edit_state = @editui.get_state()) isnt 'not_editing'
action = edit_state
else if @in_disconnect_dropzone(@dragging)
action = "shelve"
else if @in_discard_dropzone(@dragging)
action = "discard"
cursor_text = @make_cursor_text_while_dragging(action)
@text_cursor.pause("", cursor_text)
else
# TODO put block "if not @dragging and @mousedown_point and @focused_node and distance" here
if @editui.is_state('connecting')
if @editui.object_node or not @editui.subject_node
if @editui.object_datatype_is_literal
@text_cursor.set_text("click subject node")
else
@text_cursor.set_text("drag subject node")
if @peeking_node?
console.log "PEEKING at node: " + @peeking_node.id
if @focused_node? and @focused_node isnt @peeking_node
pair = [ @peeking_node.id, @focused_node.id ]
#console.log " PEEKING at edge between" + @peeking_node.id + " and " + @focused_node.id
for edge in @peeking_node.links_shown
if edge.source.id in pair and edge.target.id in pair
#console.log "PEEK edge.id is '" + edge.id + "'"
edge.focused = true
@print_edge edge
else
edge.focused = false
@tick("Tick in mousemove")
mousedown: =>
@mousedown_point = @get_mouse_point()
@last_mouse_pos = @mousedown_point
mouseup: =>
window.log_click()
d3_event = @mouse_receiver[0][0]
@mousedown_point = false
point = @get_mouse_point(d3_event)
if d3.event.button is 2 # Right click event so don't alter selected state
@text_cursor.continue()
@text_cursor.set_text("Select")
if @focused_node then $("##{@focused_node.lid}").removeClass("temp")
@rightClickHold = false
return
# if something was being dragged then handle the drop
if @dragging
#@log_mouse_activity('FINISH A DRAG')
@move_node_to_point(@dragging, point)
if @in_discard_dropzone(@dragging)
@run_verb_on_object('discard', @dragging)
else if @in_disconnect_dropzone(@dragging) # TODO rename to shelve_dropzone
@run_verb_on_object('shelve', @dragging)
# @unselect(@dragging) # this might be confusing
else if @dragging.links_shown.length == 0
@run_verb_on_object('choose', @dragging)
else if @nodes_pinnable
if @editui.is_state('connecting') and (@dragging is @editui.subject_node)
console.log "not pinning subject_node when dropping"
else if @dragging.fixed # aka pinned
@run_verb_on_object('unpin', @dragging)
else
@run_verb_on_object('pin', @dragging)
@dragging = false
@text_cursor.continue()
return
if @editui.is_state('connecting') and @focused_node and @editui.object_datatype_is_literal
@editui.set_subject_node(@focused_node)
#console.log("edit mode and focused note and editui is literal")
@tick("Tick in mouseup 1")
return
# this is the node being clickedRDF_literal
if @focused_node # and @focused_node.state is @graphed_set
@perform_current_command(@focused_node)
@tick("Tick in mouseup 2")
return
if @focused_edge
# FIXME do the edge equivalent of @perform_current_command
#@update_snippet() # useful when hover-shows-snippet