-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathwidgets.js
More file actions
1756 lines (1604 loc) · 64.3 KB
/
widgets.js
File metadata and controls
1756 lines (1604 loc) · 64.3 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
/**
* General purpose utility functions used in the panes
* oshani@csail.mit.edu
*
* Includes form-oriented widgets timbl@w3.org
*
* sign-in sign-up widgets are in signin.js
*
* Note... For pointers to posssible text-editing code, see
* http://stackoverflow.com/questions/6756407/what-contenteditable-editors
*/
// var aclModule = require('./acl.js')
var widgetModule = module.exports = {}
var UI = {
icons: require('./iconBase.js'),
log: require('./log'),
ns: require('./ns'),
store: require('./store'),
utils: require('./utils'),
widgets: widgetModule
}
//var UI.ns = require('./ns.js')
// var utilsModule = require('./utils')
// var aclControlModule = require('./acl-control')
// paneUtils = {}
widgetModule.field = {} // Form field functions by URI of field type.
widgetModule.clearElement = function (ele) {
while (ele.firstChild) {
ele.removeChild(ele.firstChild)
}
return ele
}
// To figure out the log URI from the full URI used to invoke the reasoner
widgetModule.extractLogURI = function (fullURI) {
var logPos = fullURI.search(/logFile=/)
var rulPos = fullURI.search(/&rulesFile=/)
return fullURI.substring(logPos + 8, rulPos)
}
// @@@ This needs to be changed to local timee
widgetModule.shortDate = function (str) {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
if (!str) return '???'
var month = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
try {
var now = new Date()
var nowZ = $rdf.term(now).value
// var n = now.getTimezoneOffset() // Minutes
if (str.slice(0, 10) === nowZ.slice(0, 10)) return str.slice(11, 16)
if (str.slice(0, 4) === nowZ.slice(0, 4)) {
return (month[parseInt(str.slice(5, 7), 10) - 1] + ' ' + parseInt(str.slice(8, 10), 10))
}
return str.slice(0, 10)
} catch (e) {
return 'shortdate:' + e
}
}
widgetModule.formatDateTime = function (date, format) {
return format.split('{').map(function (s) {
var k = s.split('}')[0]
var width = {'Milliseconds': 3, 'FullYear': 4}
var d = {'Month': 1}
return s ? ('000' + (date['get' + k]() + (d[k] || 0))).slice(-(width[k] || 2)) + s.split('}')[1] : ''
}).join('')
}
widgetModule.timestamp = function () {
return widgetModule.formatDateTime(new Date(), '{FullYear}-{Month}-{Date}T{Hours}:{Minutes}:{Seconds}.{Milliseconds}')
}
widgetModule.shortTime = function () {
return widgetModule.formatDateTime(new Date(), '{Hours}:{Minutes}:{Seconds}.{Milliseconds}')
}
widgetModule.newThing = function (store) {
var now = new Date()
// http://www.w3schools.com/jsref/jsref_obj_date.asp
return $rdf.sym(store.uri + '#' + 'id' + ('' + now.getTime()))
}
// ///////////////////// Handy UX widgets
// Sets the best name we have and looks up a better one
//
widgetModule.setName = function (element, x) {
var kb = UI.store
var ns = UI.ns
var findName = function (x) {
var name = kb.any(x, ns.vcard('fn')) || kb.any(x, ns.foaf('name')) ||
kb.any(x, ns.vcard('organization-name'))
return name ? name.value : null
}
var name = x.sameTerm(ns.foaf('Agent')) ? 'Everyone' : findName(x)
element.textContent = name || UI.utils.label(x)
if (!name && x.uri) { // Note this is only a fetch, not a lookUP of all sameAs etc
kb.fetcher.nowOrWhenFetched(x, undefined, function (ok) {
element.textContent = (ok ? '' : '? ') + (findName(x) || UI.utils.label(x))
})
}
}
// Set of suitable images
widgetModule.imagesOf = function (x, kb) {
var ns = UI.ns
return (kb.each(x, ns.sioc('avatar'))
.concat(kb.each(x, ns.foaf('img')))
.concat(kb.each(x, ns.vcard('logo')))
.concat(kb.each(x, ns.vcard('photo')))
.concat(kb.each(x, ns.foaf('depiction'))))
}
// Best logo or avater or photo etc to represent someone or some group etc
//
widgetModule.setImage = function (element, x) {
var kb = UI.store
var ns = UI.ns
var iconDir = UI.icons.iconBase
//var fallback = iconDir + 'noun_15059.svg' // Person
var fallback = iconDir + 'noun_10636.svg' // Circle
var findImage = function (x) {
if (x.sameTerm(ns.foaf('Agent')) || x.sameTerm(ns.rdf('Resource'))) {
return iconDir + 'noun_98053.svg' // Globe
}
var image = kb.any(x, ns.sioc('avatar')) ||
kb.any(x, ns.foaf('img')) ||
kb.any(x, ns.vcard('logo')) ||
kb.any(x, ns.vcard('hasPhoto')) ||
kb.any(x, ns.vcard('photo')) ||
kb.any(x, ns.foaf('depiction'))
return image ? image.uri : null
}
var findImageByClass = function (x) {
var types = kb.findTypeURIs(x)
if (ns.solid('AppProvider').uri in types) {
return iconDir + 'noun_15177.svg' // App
}
if (x.uri && x.uri.split('/').length === 4 && !(x.uri.split('/')[1]) && !(x.uri.split('/')[3])) {
return iconDir + 'noun_15177.svg' // App -- this is an origin
}
if (ns.solid('AppProviderClass').uri in types) {
return iconDir + 'noun_144.svg' // App Whitelist @@@ ICON (three apps ?)
}
if (ns.vcard('Group').uri in types || ns.rdfs('Class').uri in types) {
return iconDir + 'noun_339237.svg' // Group of people
}
if (ns.vcard('Individual').uri in types ||
ns.foaf('Person').uri in types) {
return iconDir + 'noun_339237.svg' // Group of people
}
if (ns.vcard('AddressBook').uri in types) {
return iconDir + 'noun_15695.svg'
}
if (ns.meeting('Meeting').uri in types) {
return iconDir + 'noun_66617.svg'
}
return fallback
}
var uri = findImage(x)
element.setAttribute('src', uri || findImageByClass(x))
if (!uri && x.uri) {
kb.fetcher.nowOrWhenFetched(x, undefined, function (ok) {
element.setAttribute('src', findImage(x) || findImageByClass(x))
})
}
}
// Delete button with a check you really mean it
//
// @@ Supress check if command key held down?
//
widgetModule.deleteButtonWithCheck = function (dom, container, noun, deleteFunction) {
var delButton = dom.createElement('button')
container.appendChild(delButton)
delButton.textContent = '-'
container.setAttribute('class', 'hoverControl') // See tabbedtab.css (sigh global CSS)
delButton.setAttribute('class', 'hoverControlHide')
delButton.setAttribute('style', 'color: red; margin-right: 0.3em; foat:right; text-align:right')
delButton.addEventListener('click', function (e) {
container.removeChild(delButton) // Ask -- are you sure?
var cancelButton = dom.createElement('button')
cancelButton.textContent = 'cancel'
container.appendChild(cancelButton).addEventListener('click', function (e) {
container.removeChild(sureButton)
container.removeChild(cancelButton)
container.appendChild(delButton)
}, false)
var sureButton = dom.createElement('button')
sureButton.textContent = 'Delete ' + noun
container.appendChild(sureButton).addEventListener('click', function (e) {
container.removeChild(sureButton)
container.removeChild(cancelButton)
deleteFunction()
}, false)
}, false)
return delButton
}
// A TR to repreent a draggable person, etc in a list
//
//
widgetModule.personTR = function (dom, pred, obj, options) {
var tr = dom.createElement('tr')
options = options || {}
tr.predObj = [pred.uri, obj.uri]
var td1 = tr.appendChild(dom.createElement('td'))
var td2 = tr.appendChild(dom.createElement('td'))
var td3 = tr.appendChild(dom.createElement('td'))
var agent = obj
var image = td1.appendChild(dom.createElement('img'))
td1.setAttribute('style', 'width:4em; padding:0.5em; height: 4em;')
td2.setAttribute('style', 'text-align:left;')
td3.setAttribute('style', 'width:2em; padding:0.5em; height: 4em;')
image.setAttribute('style', 'width: 3em; height: 3em; margin: 0.1em; border-radius: 1em;')
widgetModule.setImage(image, agent)
widgetModule.setName(td2, agent)
if (options.deleteFunction) {
widgetModule.deleteButtonWithCheck(dom, td3, 'person', options.deleteFunction)
}
if (options.link !== false) {
var anchor = td3.appendChild(dom.createElement('a'))
anchor.setAttribute('href', obj.uri)
anchor.classList.add('HoverControlHide')
var linkImage = anchor.appendChild(dom.createElement('img'))
linkImage.setAttribute('src', UI.icons.originalIconBase + 'go-to-this.png')
td3.appendChild(dom.createElement('br'))
}
if (options.draggable !== false) { // default is on
tr.setAttribute('draggable', 'true') // allow a person to be dragged to diff role
tr.addEventListener('dragstart', function (e) {
tr.style.fontWeight = 'bold'
// e.dataTransfer.dropEffect = 'move'
// e.dataTransfer.effectAllowed = 'all' // same as default
e.dataTransfer.setData('text/uri-list', obj.uri)
e.dataTransfer.setData('text/plain', obj.uri)
e.dataTransfer.setData('text/html', tr.outerHTML)
console.log('Dragstart: ' + tr + ' -> ' + obj + 'de: ' + e.dataTransfer.dropEffect)
}, false)
tr.addEventListener('drag', function (e) {
e.preventDefault()
e.stopPropagation()
// e.dataTransfer.dropEffect = 'copy'
// e.dataTransfer.setData("text/uri-list", obj)
console.log('Drag: dropEffect: ' + e.dataTransfer.dropEffect)
}, false)
// icons/go-to-this.png
tr.addEventListener('dragend', function (e) {
tr.style.fontWeight = 'normal'
console.log('Dragend dropeffect: ' + e.dataTransfer.dropEffect)
console.log('Dragend: ' + tr + ' -> ' + obj)
}, false)
}
return tr
}
// ///////////////////////////////////////////////////////////////////////
/* Form Field implementations
**
*/
/* Group of different fields
**
*/
widgetModule.field[UI.ns.ui('Form').uri] =
widgetModule.field[UI.ns.ui('Group').uri] = function (
dom, container, already, subject, form, store, callback) {
var kb = UI.store
var box = dom.createElement('div')
box.setAttribute('style', 'padding-left: 2em; border: 0.05em solid brown;') // Indent a group
var ui = UI.ns.ui
container.appendChild(box)
// Prevent loops
var key = subject.toNT() + '|' + form.toNT()
if (already[key]) { // been there done that
box.appendChild(dom.createTextNode('Group: see above ' + key))
var plist = [$rdf.st(subject, UI.ns.owl('sameAs'), subject)] // @@ need prev subject
UI.outline.appendPropertyTRs(box, plist)
return box
}
// box.appendChild(dom.createTextNode("Group: first time, key: "+key))
var already2 = {}
for (var x in already) already2[x] = 1
already2[key] = 1
var parts = kb.each(form, ui('part'))
if (!parts) {
box.appendChild(widgetModule.errorMessageBlock(dom,
'No parts to form! '))
return dom
}
var p2 = widgetModule.sortBySequence(parts)
var eles = []
var original = []
for (var i = 0; i < p2.length; i++) {
var field = p2[i]
var t = widgetModule.bottomURI(field) // Field type
if (t === ui('Options').uri) {
var dep = kb.any(field, ui('dependingOn'))
if (dep && kb.any(subject, dep)) original[i] = kb.any(subject, dep).toNT()
}
var fn = widgetModule.fieldFunction(dom, field)
var itemChanged = function (ok, body) {
if (ok) {
for (var j = 0; j < p2.length; j++) { // This is really messy.
var field = (p2[j])
var t = widgetModule.bottomURI(field) // Field type
if (t === ui('Options').uri) {
var dep = kb.any(field, ui('dependingOn'))
// if (dep && kb.any(subject, dep) && (kb.any(subject, dep).toNT() != original[j])) { // changed
if (1) { // assume changed
var newOne = fn(dom, box, already, subject, field, store, callback)
box.removeChild(newOne)
box.insertBefore(newOne, eles[j])
box.removeChild(eles[j])
original[j] = kb.any(subject, dep).toNT()
eles[j] = newOne
}
}
}
}
callback(ok, body)
}
eles.push(fn(dom, box, already2, subject, field, store, itemChanged))
}
return box
}
/* Options: Select one or more cases
**
*/
widgetModule.field[UI.ns.ui('Options').uri] = function (
dom, container, already, subject, form, store, callback) {
var kb = UI.store
var box = dom.createElement('div')
// box.setAttribute('style', 'padding-left: 2em; border: 0.05em dotted purple;') // Indent Options
var ui = UI.ns.ui
container.appendChild(box)
var dependingOn = kb.any(form, ui('dependingOn'))
if (!dependingOn) {
dependingOn = UI.ns.rdf('type')
} // @@ default to type (do we want defaults?)
var cases = kb.each(form, ui('case'))
if (!cases) {
box.appendChild(widgetModule.errorMessageBlock(dom,
'No cases to Options form. '))
}
var values
if (dependingOn.sameTerm(UI.ns.rdf('type'))) {
values = kb.findTypeURIs(subject)
} else {
var value = kb.any(subject, dependingOn)
if (value === undefined) {
box.appendChild(widgetModule.errorMessageBlock(dom,
"Can't select subform as no value of: " + dependingOn))
} else {
values = {}
values[value.uri] = true
}
}
// @@ Add box.refresh() to sync fields with values
for (var i = 0; i < cases.length; i++) {
var c = cases[i]
var tests = kb.each(c, ui('for')) // There can be multiple 'for'
for (var j = 0; j < tests.length; j++) {
if (values[tests[j].uri]) {
var field = kb.the(c, ui('use'))
if (!field) {
box.appendChild(widgetModule.errorMessageBlock(dom,
"No 'use' part for case in form " + form))
return box
} else {
widgetModule.appendForm(dom, box, already, subject, field, store, callback)
}
break
}
}
}
return box
}
/* Multiple similar fields (unordered)
**
*/
widgetModule.field[UI.ns.ui('Multiple').uri] = function (
dom, container, already, subject, form, store, callback) {
var kb = UI.store
kb.updater = kb.updater || new $rdf.UpdateManager(kb)
var box = dom.createElement('table')
// We don't indent multiple as it is a sort of a prefix o fthe next field and has contents of one.
// box.setAttribute('style', 'padding-left: 2em; border: 0.05em solid green;') // Indent a multiple
var ui = UI.ns.ui
var i
container.appendChild(box)
var property = kb.any(form, ui('property'))
if (!property) {
box.appendChild(widgetModule.errorMessageBlock(dom,
'No property to multiple: ' + form)) // used for arcs in the data
return box
}
var min = kb.any(form, ui('min')) // This is the minimum number -- default 0
min = min ? min.value : 0
var max = kb.any(form, ui('max')) // This is the minimum number
max = max ? max.value : 99999999
var element = kb.any(form, ui('part')) // This is the form to use for each one
if (!element) {
box.appendChild(widgetModule.errorMessageBlock(dom, 'No part to multiple: ' + form))
return box
}
var count = 0
// box.appendChild(dom.createElement('h3')).textContent = "Fields:".
var body = box.appendChild(dom.createElement('tr'))
var tail = box.appendChild(dom.createElement('tr'))
var img = tail.appendChild(dom.createElement('img'))
img.setAttribute('src', UI.icons.originalIconBase + 'tango/22-list-add.png') // blue plus
img.setAttribute('style', 'margin: 0.2em;') // blue plus
img.title = 'Click to add one or more ' + UI.utils.label(property)
var prompt = tail.appendChild(dom.createElement('span'))
var addItem = function (e, object) {
UI.log.debug('Multiple add: ' + object)
++count
if (!object) object = widgetModule.newThing(store)
var tr = box.insertBefore(dom.createElement('tr'), tail)
var itemDone = function (ok, body) {
if (ok) { // @@@ Check IT hasnt alreday been written in
if (!kb.holds(subject, property, object)) {
var ins = [$rdf.st(subject, property, object, store)]
kb.updater.update([], ins, linkDone)
}
} else {
tr.appendChild(widgetModule.errorMessageBlock(dom, 'Multiple: item failed: ' + body))
callback(ok, body)
}
}
var linkDone = function (uri, ok, body) {
return callback(ok, body)
}
var fn = widgetModule.fieldFunction(dom, element)
// box.appendChild(dom.createTextNode('multiple object: '+object ))
fn(dom, body, already, object, element, store, itemDone)
}
var values = kb.each(subject, property)
prompt.textContent = (values.length === 0 ? 'Add one or more ' : 'Add more ') +
UI.utils.label(property)
values.map(function (obj) { addItem(null, obj) })
for (i = values.length; i < min; i++) {
addItem() // Add blanks if less than minimum
}
tail.addEventListener('click', addItem, true) // img.addEventListener('click', addItem, true)
return box
}
/* Text field
**
*/
// For possible date popups see e.g. http://www.dynamicdrive.com/dynamicindex7/jasoncalendar.htm
// or use HTML5: http://www.w3.org/TR/2011/WD-html-markup-20110113/input.date.html
//
widgetModule.fieldParams = {}
widgetModule.fieldParams[UI.ns.ui('ColorField').uri] = {
'size': 9 }
widgetModule.fieldParams[UI.ns.ui('ColorField').uri].pattern =
/^\s*#[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]([0-9a-f][0-9a-f])?\s*$/
widgetModule.fieldParams[UI.ns.ui('DateField').uri] = {
'size': 20, 'type': 'date', 'dt': 'date'}
widgetModule.fieldParams[UI.ns.ui('DateField').uri].pattern =
/^\s*[0-9][0-9][0-9][0-9](-[0-1]?[0-9]-[0-3]?[0-9])?Z?\s*$/
widgetModule.fieldParams[UI.ns.ui('DateTimeField').uri] = {
'size': 20, 'type': 'date', 'dt': 'dateTime'}
widgetModule.fieldParams[UI.ns.ui('DateTimeField').uri].pattern =
/^\s*[0-9][0-9][0-9][0-9](-[0-1]?[0-9]-[0-3]?[0-9])?(T[0-2][0-9]:[0-5][0-9](:[0-5][0-9])?)?Z?\s*$/
widgetModule.fieldParams[UI.ns.ui('TimeField').uri] = {
'size': 10, 'type': 'time', 'dt': 'time'}
widgetModule.fieldParams[UI.ns.ui('TimeField').uri].pattern =
/^\s*([0-2]?[0-9]:[0-5][0-9](:[0-5][0-9])?)\s*$/
widgetModule.fieldParams[UI.ns.ui('IntegerField').uri] = {
'size': 12, 'style': 'text-align: right', 'dt': 'integer' }
widgetModule.fieldParams[UI.ns.ui('IntegerField').uri].pattern =
/^\s*-?[0-9]+\s*$/
widgetModule.fieldParams[UI.ns.ui('DecimalField').uri] = {
'size': 12, 'style': 'text-align: right', 'dt': 'decimal' }
widgetModule.fieldParams[UI.ns.ui('DecimalField').uri].pattern =
/^\s*-?[0-9]*(\.[0-9]*)?\s*$/
widgetModule.fieldParams[UI.ns.ui('FloatField').uri] = {
'size': 12, 'style': 'text-align: right', 'dt': 'float' }
widgetModule.fieldParams[UI.ns.ui('FloatField').uri].pattern =
/^\s*-?[0-9]*(\.[0-9]*)?((e|E)-?[0-9]*)?\s*$/
widgetModule.fieldParams[UI.ns.ui('SingleLineTextField').uri] = { }
widgetModule.fieldParams[UI.ns.ui('NamedNodeURIField').uri] = { namedNode: true}
widgetModule.fieldParams[UI.ns.ui('TextField').uri] = { }
widgetModule.fieldParams[UI.ns.ui('PhoneField').uri] = { 'size': 12, 'uriPrefix': 'tel:' }
widgetModule.fieldParams[UI.ns.ui('PhoneField').uri].pattern =
/^\s*\+?[ 0-9-]+[0-9]\s*$/
widgetModule.fieldParams[UI.ns.ui('EmailField').uri] = { 'size': 20, 'uriPrefix': 'mailto:' }
widgetModule.fieldParams[UI.ns.ui('EmailField').uri].pattern =
/^\s*.*@.*\..*\s*$/ // @@ Get the right regexp here
widgetModule.field[UI.ns.ui('PhoneField').uri] =
widgetModule.field[UI.ns.ui('EmailField').uri] =
widgetModule.field[UI.ns.ui('ColorField').uri] =
widgetModule.field[UI.ns.ui('DateField').uri] =
widgetModule.field[UI.ns.ui('DateTimeField').uri] =
widgetModule.field[UI.ns.ui('TimeField').uri] =
widgetModule.field[UI.ns.ui('NumericField').uri] =
widgetModule.field[UI.ns.ui('IntegerField').uri] =
widgetModule.field[UI.ns.ui('DecimalField').uri] =
widgetModule.field[UI.ns.ui('FloatField').uri] =
widgetModule.field[UI.ns.ui('TextField').uri] =
widgetModule.field[UI.ns.ui('SingleLineTextField').uri] =
widgetModule.field[UI.ns.ui('NamedNodeURIField').uri] = function (
dom, container, already, subject, form, store, callback) {
var ui = UI.ns.ui
var kb = UI.store
var box = dom.createElement('tr')
container.appendChild(box)
var lhs = dom.createElement('td')
lhs.setAttribute('class', 'formFieldName')
lhs.setAttribute('style', ' vertical-align: middle;')
box.appendChild(lhs)
var rhs = dom.createElement('td')
rhs.setAttribute('class', 'formFieldValue')
box.appendChild(rhs)
var property = kb.any(form, ui('property'))
if (!property) {
box.appendChild(dom.createTextNode('Error: No property given for text field: ' + form))
return box
}
lhs.appendChild(widgetModule.fieldLabel(dom, property, form))
var uri = widgetModule.bottomURI(form)
var params = widgetModule.fieldParams[uri]
if (params === undefined) params = {} // non-bottom field types can do this
var style = params.style || 'font-size: 100%; margin: 0.1em; padding: 0.1em;'
// box.appendChild(dom.createTextNode(' uri='+uri+', pattern='+ params.pattern))
var field = dom.createElement('input')
rhs.appendChild(field)
field.setAttribute('type', params.type ? params.type : 'text')
var size = kb.any(form, ui('size')) // Form has precedence
field.setAttribute('size', size ? '' + size : (params.size ? '' + params.size : '20'))
var maxLength = kb.any(form, ui('maxLength'))
field.setAttribute('maxLength', maxLength ? '' + maxLength : '4096')
store = store || widgetModule.fieldStore(subject, property, store)
var obj = kb.any(subject, property, undefined, store)
if (!obj) {
obj = kb.any(form, ui('default'))
if (obj) kb.add(subject, property, obj, store)
}
if (obj) {
field.value = obj.value || obj.uri
}
field.setAttribute('style', style)
field.addEventListener('keyup', function (e) {
if (params.pattern) {
field.setAttribute('style', style + (
field.value.match(params.pattern)
? 'color: green;' : 'color: red;')) }
}, true)
field.addEventListener('change', function (e) { // i.e. lose focus with changed data
if (params.pattern && !field.value.match(params.pattern)) return
field.disabled = true // See if this stops getting two dates from fumbling e.g the chrome datepicker.
field.setAttribute('style', style + 'color: gray;') // pending
var ds = kb.statementsMatching(subject, property) // remove any multiple values
// var newObj = params.uriPrefix ? kb.sym(params.uriPrefix + field.value.replace(/ /g, ''))
// : kb.literal(field.value, params.dt)
var result
if (params.namedNode) {
result = kb.sym(field.value)
} else {
result = params.parse ? params.parse(field.value) : field.value
}
var is = $rdf.st(subject, property, result , store) // @@ Explicitly put the datatype in.
kb.updater.update(ds, is, function (uri, ok, body) {
if (ok) {
field.disabled = false
field.setAttribute('style', 'color: black;')
} else {
box.appendChild(widgetModule.errorMessageBlock(dom, body))
}
callback(ok, body)
})
}, true)
return box
}
/* Multiline Text field
**
*/
widgetModule.field[UI.ns.ui('MultiLineTextField').uri] = function (
dom, container, already, subject, form, store, callback) {
var ui = UI.ns.ui
var kb = UI.store
var property = kb.any(form, ui('property'))
if (!property) {
return widgetModule.errorMessageBlock(dom,
'No property to text field: ' + form)
}
container.appendChild(widgetModule.fieldLabel(dom, property, form))
store = widgetModule.fieldStore(subject, property, store)
var box = widgetModule.makeDescription(dom, kb, subject, property, store, callback)
// box.appendChild(dom.createTextNode('<-@@ subj:'+subject+', prop:'+property))
container.appendChild(box)
return box
}
/* Boolean field
**
*/
widgetModule.field[UI.ns.ui('BooleanField').uri] = function (
dom, container, already, subject, form, store, callback) {
var ui = UI.ns.ui
var kb = UI.store
var property = kb.any(form, ui('property'))
if (!property) {
return container.appendChild(widgetModule.errorMessageBlock(dom,
'No property to boolean field: ' + form))
}
var lab = kb.any(form, ui('label'))
if (!lab) lab = UI.utils.label(property, true) // Init capital
store = widgetModule.fieldStore(subject, property, store)
var state = kb.any(subject, property)
if (state === undefined) { state = false } // @@ sure we want that -- or three-state?
// UI.log.debug('store is '+store)
var ins = $rdf.st(subject, property, true, store)
var del = $rdf.st(subject, property, false, store)
var box = widgetModule.buildCheckboxForm(dom, kb, lab, del, ins, form, store)
container.appendChild(box)
return box
}
/* Classifier field
**
** Nested categories
**
** @@ To do: If a classification changes, then change any dependent Options fields.
*/
widgetModule.field[UI.ns.ui('Classifier').uri] = function (
dom, container, already, subject, form, store, callback) {
var kb = UI.store
var ui = UI.ns.ui
var category = kb.any(form, ui('category'))
if (!category) {
return widgetModule.errorMessageBlock(dom, 'No category for classifier: ' + form)
}
UI.log.debug('Classifier: store=' + store)
var checkOptions = function (ok, body) {
if (!ok) return callback(ok, body)
/*
var parent = kb.any(undefined, ui('part'), form)
if (!parent) return callback(ok, body)
var kids = kb.each(parent, ui('part')); // @@@@@@@@@ Garbage
kids = kids.filter(function(k){return kb.any(k, ns.rdf('type'), ui('Options'))})
if (kids.length) UI.log.debug('Yes, found related options: '+kids[0])
*/
return callback(ok, body)
}
var box = widgetModule.makeSelectForNestedCategory(dom, kb, subject, category, store, checkOptions)
container.appendChild(box)
return box
}
/* Choice field
**
** Not nested. Generates a link to something from a given class.
** Optional subform for the thing selected.
** Alternative implementatons caould be:
** -- pop-up menu (as here)
** -- radio buttons
** -- auto-complete typing
**
** Todo: Deal with multiple. Maybe merge with multiple code.
*/
widgetModule.field[UI.ns.ui('Choice').uri] = function (
dom, container, already, subject, form, store, callback) {
var ui = UI.ns.ui
var ns = UI.ns
var kb = UI.store
var p
var box = dom.createElement('tr')
container.appendChild(box)
var lhs = dom.createElement('td')
box.appendChild(lhs)
var rhs = dom.createElement('td')
box.appendChild(rhs)
var property = kb.any(form, ui('property'))
if (!property) {
return widgetModule.errorMessageBlock(dom, 'No property for Choice: ' + form)
}
lhs.appendChild(widgetModule.fieldLabel(dom, property, form))
var from = kb.any(form, ui('from'))
if (!from) {
return widgetModule.errorMessageBlock(dom, "No 'from' for Choice: " + form)
}
var subForm = kb.any(form, ui('use')) // Optional
var possible = []
var opts = { 'multiple': multiple, 'nullLabel': np, 'disambiguate': false }
possible = kb.each(undefined, ns.rdf('type'), from)
for (var x in kb.findMembersNT(from)) {
possible.push(kb.fromNT(x))
// box.appendChild(dom.createTextNode("RDFS: adding "+x))
} // Use rdfs
// UI.log.debug("%%% Choice field: possible.length 1 = "+possible.length)
if (from.sameTerm(ns.rdfs('Class'))) {
for (p in widgetModule.allClassURIs()) possible.push(kb.sym(p))
// UI.log.debug("%%% Choice field: possible.length 2 = "+possible.length)
} else if (from.sameTerm(ns.rdf('Property'))) {
possibleProperties = widgetModule.propertyTriage()
for (p in possibleProperties.op) possible.push(kb.fromNT(p))
for (p in possibleProperties.dp) possible.push(kb.fromNT(p))
opts.disambiguate = true // This is a big class, and the labels won't be enough.
} else if (from.sameTerm(ns.owl('ObjectProperty'))) {
possibleProperties = widgetModule.propertyTriage()
for (p in possibleProperties.op) possible.push(kb.fromNT(p))
opts.disambiguate = true
} else if (from.sameTerm(ns.owl('DatatypeProperty'))) {
possibleProperties = widgetModule.propertyTriage()
for (p in possibleProperties.dp) possible.push(kb.fromNT(p))
opts.disambiguate = true
}
var object = kb.any(subject, property)
function addSubForm (ok, body) {
object = kb.any(subject, property)
widgetModule.fieldFunction(dom, subForm)(dom, rhs, already,
object, subForm, store, callback)
}
var multiple = false
// box.appendChild(dom.createTextNode('Choice: subForm='+subForm))
var possible2 = widgetModule.sortByLabel(possible)
var np = '--' + UI.utils.label(property) + '-?'
if (kb.any(form, ui('canMintNew'))) {
opts['mint'] = '* New *' // @@ could be better
opts['subForm'] = subForm
}
var selector = widgetModule.makeSelectForOptions(
dom, kb, subject, property,
possible2, opts, store, callback)
rhs.appendChild(selector)
if (object && subForm) addSubForm(true, '')
return box
}
// Documentation - non-interactive fields
//
widgetModule.fieldParams[UI.ns.ui('Comment').uri] = {
'element': 'p',
'style': 'padding: 0.1em 1.5em; color: brown; white-space: pre-wrap;'}
widgetModule.fieldParams[UI.ns.ui('Heading').uri] = {
'element': 'h3', 'style': 'font-size: 110%; color: brown;' }
widgetModule.field[UI.ns.ui('Comment').uri] =
widgetModule.field[UI.ns.ui('Heading').uri] = function (
dom, container, already, subject, form, store, callback) {
var ui = UI.ns.ui
var kb = UI.store
var contents = kb.any(form, ui('contents'))
if (!contents) contents = 'Error: No contents in comment field.'
var uri = widgetModule.bottomURI(form)
var params = widgetModule.fieldParams[uri]
if (params === undefined) { params = {} }; // non-bottom field types can do this
var box = dom.createElement('div')
container.appendChild(box)
var p = box.appendChild(dom.createElement(params['element']))
p.textContent = contents
var style = kb.any(form, ui('style'))
if (style === undefined) { style = params.style ? params.style : '' }
if (style) p.setAttribute('style', style)
return box
}
// /////////////////////////////////////////////////////////////////////////////
// Event Handler for links within solid apps.
//
// Note that native links have consraints in Firefox, they
// don't work with local files for instance (2011)
//
widgetModule.openHrefInOutlineMode = function (e) {
e.preventDefault()
e.stopPropagation()
var target = UI.utils.getTarget(e)
var uri = target.getAttribute('href')
if (!uri) console.log('No href found \n')
// subject term, expand, pane, solo, referrer
// dump('click on link to:' +uri+'\n')
if (UI.outline){
UI.outline.GotoSubject(UI.store.sym(uri), true, undefined, true, undefined)
} else if (window && window.UI && window.UI.outline ){
window.UI.outline.GotoSubject(UI.store.sym(uri), true, undefined, true, undefined)
} else {
console.log("ERROR: Can't access outline manager in this config")
}
//UI.outline.GotoSubject(UI.store.sym(uri), true, undefined, true, undefined)
}
// We make a URI in the annotation store out of the URI of the thing to be annotated.
//
// @@ Todo: make it a personal preference.
//
widgetModule.defaultAnnotationStore = function (subject) {
if (subject.uri === undefined) return undefined
var s = subject.uri
if (s.slice(0, 7) !== 'http://') return undefined
s = s.slice(7) // Remove
var hash = s.indexOf('#')
if (hash >= 0) s = s.slice(0, hash) // Strip trailing
else {
var slash = s.lastIndexOf('/')
if (slash < 0) return undefined
s = s.slice(0, slash)
}
return UI.store.sym('http://tabulator.org/wiki/annnotation/' + s)
}
widgetModule.fieldStore = function (subject, predicate, def) {
var sts = UI.store.statementsMatching(subject, predicate)
if (sts.length === 0) return def // can used default as no data yet
if (sts.length > 0 && sts[0].why.uri && UI.store.updater.editable(sts[0].why.uri, UI.store)) {
return UI.store.sym(sts[0].why.uri)
}
return null // Can't edit
}
widgetModule.allClassURIs = function () {
var set = {}
UI.store.statementsMatching(undefined, UI.ns.rdf('type'), undefined)
.map(function (st) { if (st.object.uri) set[st.object.uri] = true })
UI.store.statementsMatching(undefined, UI.ns.rdfs('subClassOf'), undefined)
.map(function (st) {
if (st.object.uri) set[st.object.uri] = true
if (st.subject.uri) set[st.subject.uri] = true
})
UI.store.each(undefined, UI.ns.rdf('type'), UI.ns.rdfs('Class'))
.map(function (c) { if (c.uri) set[c.uri] = true })
return set
}
// Figuring which propertites could by be used
//
widgetModule.propertyTriage = function () {
var possibleProperties = {}
// if (possibleProperties === undefined) possibleProperties = {}
var kb = UI.store
var dp = {}
var op = {}
var no = 0
var nd = 0
var nu = 0
var pi = kb.predicateIndex // One entry for each pred
for (var p in pi) {
var object = pi[p][0].object
if (object.termType === 'Literal') {
dp[p] = true
nd++
} else {
op[p] = true
no++
}
} // If nothing discovered, then could be either:
var ps = kb.each(undefined, UI.ns.rdf('type'), UI.ns.rdf('Property'))
for (var i = 0; i < ps.length; i++) {
p = ps[i].toNT()
UI.log.debug('propertyTriage: unknown: ' + p)
if (!op[p] && !dp[p]) { dp[p] = true; op[p] = true; nu++ }
}
possibleProperties.op = op
possibleProperties.dp = dp
UI.log.info('propertyTriage: ' + no + ' non-lit, ' + nd + ' literal. ' + nu + ' unknown.')
return possibleProperties
}
widgetModule.fieldLabel = function (dom, property, form) {
var lab = UI.store.any(form, UI.ns.ui('label'))
if (!lab) lab = UI.utils.label(property, true) // Init capital
if (property === undefined) { return dom.createTextNode('@@Internal error: undefined property') }
var anchor = dom.createElement('a')
if (property.uri) anchor.setAttribute('href', property.uri)
anchor.setAttribute('style', 'color: #3B5998; text-decoration: none;') // Not too blue and no underline
anchor.textContent = lab
return anchor
}
/* General purpose widgets
**
*/
widgetModule.errorMessageBlock = function (dom, msg, backgroundColor) {
var div = dom.createElement('div')
div.setAttribute('style', 'padding: 0.5em; border: 0.5px solid black; background-color: ' +
(backgroundColor || '#fee') + '; color:black;')
div.textContent = msg
return div
}
widgetModule.bottomURI = function (x) {
var kb = UI.store
var ft = kb.findTypeURIs(x)
var bot = kb.bottomTypeURIs(ft) // most specific
var bots = []
for (var b in bot) bots.push(b)
// if (bots.length > 1) throw "Didn't expect "+x+" to have multiple bottom types: "+bots
return bots[0]
}
widgetModule.fieldFunction = function (dom, field) {
var uri = widgetModule.bottomURI(field)
var fun = widgetModule.field[uri]
UI.log.debug('paneUtils: Going to implement field ' + field + ' of type ' + uri)
if (!fun) {
return function () {
return widgetModule.errorMessageBlock(dom, 'No handler for field ' + field + ' of type ' + uri)
}
}
return fun
}
// A button for editing a form (in place, at the moment)
//
// When editing forms, make it yellow, when editing thr form form, pink
// Help people understand how many levels down they are.
//
widgetModule.editFormButton = function (dom, container, form, store, callback) {
var b = dom.createElement('button')
b.setAttribute('type', 'button')
b.innerHTML = 'Edit ' + UI.utils.label(UI.ns.ui('Form'))
b.addEventListener('click', function (e) {
var ff = widgetModule.appendForm(dom, container,
{}, form, UI.ns.ui('FormForm'), store, callback)
ff.setAttribute('style', UI.ns.ui('FormForm').sameTerm(form)
? 'background-color: #fee;' : 'background-color: #ffffe7;')
container.removeChild(b)
}, true)
return b
}
// A button for jumping
//
widgetModule.linkButton = function (dom, object) {
var b = dom.createElement('button')
b.setAttribute('type', 'button')
b.textContent = 'Goto ' + UI.utils.label(object)
b.addEventListener('click', function (e) {
// b.parentNode.removeChild(b)
UI.outline.GotoSubject(object, true, undefined, true, undefined)
}, true)
return b
}
widgetModule.removeButton = function (dom, element) {
var b = dom.createElement('button')
b.setAttribute('type', 'button')
b.textContent = '✕' // MULTIPLICATION X