forked from bergie/VIE
-
Notifications
You must be signed in to change notification settings - Fork 1
/
vie.js
1268 lines (1108 loc) · 47.7 KB
/
vie.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// VIE - Vienna IKS Editables
// (c) 2011 Henri Bergius, IKS Consortium
// VIE may be freely distributed under the MIT license.
// For all details and documentation:
// http://wiki.iks-project.eu/index.php/VIE
(function() {
// [VIE](http://wiki.iks-project.eu/index.php/VIE) enables you to make
// [RDFa](http://en.wikipedia.org/wiki/RDFa) -annotated content on your
// web pages editable.
//
// For example, if your page contains the following mark-up:
//
// <p xmlns:dc="http://purl.org/dc/elements/1.1/"
// about="http://www.example.com/books/wikinomics">
// In his latest book
// <cite property="dc:title">Wikinomics</cite>,
// <span property="dc:creator">Don Tapscott</span>
// explains deep changes in technology,
// demographics and business.
// The book is due to be published in
// <span property="dc:date" content="2006-10-01">October 2006</span>.
// </p>
//
// Then with VIE you can get a proper Backbone Model object for
// that. First scan your page for RDFa entities:
//
// VIE.RDFaEntities.getInstances();
//
// And then just access the entity by subject:
//
// var myBook = VIE.EntityManager.getBySubject('<http://www.example.com/books/wikinomics>');
// alert(myBook.get('dc:title')); // "Wikinomics"
//
// Properties of the entity may also be modified, and these changes
// will also happen on the page itself:
//
// myBook.set({'dc:title':'Wikinomics, Second Edition'});
//
// You can also access the entities via the `VIE.EntityManager.entities` Backbone Collection.
//
// Initial setup
// -------------
//
// The VIE library is fully contained inside a `VIE` namespace. The
// namespace is available in both CommonJS and the browser.
var VIE;
if (typeof exports !== 'undefined') {
VIE = exports;
} else {
VIE = this.VIE = {};
}
// ### Handle dependencies
//
// VIE tries to load its dependencies automatically.
// Please note that this autoloading functionality only works on the server.
// On browser Backbone needs to be included manually.
// Require [underscore.js](http://documentcloud.github.com/underscore/)
// using CommonJS require if it isn't yet loaded.
//
// On node.js underscore.js can be installed via:
//
// npm install underscore
if (!_ && (typeof require !== 'undefined')) { _ = require('underscore')._; }
if (!_) {
throw 'VIE requires underscore.js to be available';
}
// Require [Backbone.js](http://documentcloud.github.com/backbone/)
// using CommonJS require if it isn't yet loaded.
//
// On node.js Backbone.js can be installed via:
//
// npm install backbone
if (!Backbone && (typeof require !== 'undefined')) { Backbone = require('backbone'); }
if (!Backbone) {
throw 'VIE requires Backbone.js to be available';
}
// Require [jQuery](http://jquery.com/) using CommonJS require if it
// isn't yet loaded.
//
// On node.js jQuery can be installed via:
//
// npm install jquery
if (!jQuery && (typeof require !== 'undefined')) { jQuery = require('jquery'); }
if (!jQuery) {
throw 'VIE requires jQuery to be available';
}
// VIE.EntityManager
// -------------
//
// VIE.EntityManager keeps track of all RDFa entities loaded via VIE. This
// means that entities matched by a common subject can be treated as singletons.
//
// It is possible to access all loaded entities via the
// `VIE.EntityManager.entities` Backbone Collection.
VIE.EntityManager = {
entities: null,
initializeCollection: function() {
if (VIE.EntityManager.entities === null) {
VIE.EntityManager.entities = new VIE.RDFEntityCollection();
}
},
// ### VIE.EntityManager.getBySubject
//
// It is possible to get an entity that has been loaded from the page
// via the `getBySubject` method. If the entity cannot be found this method
// will return `null`.
//
// The entities accessed this way are singletons, so multiple calls to same
// subject will all return the same `VIE.RDFEntity` instance.
//
// Subjects may be either wrapped in `<` and `>` or not.
//
// Example:
//
// var myBook = VIE.EntityManager.getBySubject('<http://www.example.com/books/wikinomics>');
getBySubject: function(subject) {
VIE.EntityManager.initializeCollection();
if (typeof subject === 'string' &&
VIE.RDFa._isReference(subject)) {
subject = VIE.RDFa._fromReference(subject);
}
if (typeof subject === 'object')
{
return VIE.EntityManager.entities.detect(function(item) {
if (item.id === subject) {
return true;
}
return false;
});
}
return VIE.EntityManager.entities.get(subject);
},
// ### VIE.EntityManager.getByType
//
// Get list of RDF Entities matching the given type.
getByType: function(type) {
VIE.EntityManager.initializeCollection();
if (VIE.RDFa._isReference(type)) {
type = VIE.RDFa._fromReference(type);
}
return VIE.EntityManager.entities.select(function(entity) {
if (entity.type === type) {
return true;
}
return false;
});
},
// ### VIE.EntityManager.getPredicate
//
// Get requested predicate from all loaded entities.
getPredicate: function(predicate) {
var predicates = [];
_.forEach(VIE.EntityManager.entities.pluck('dcterms:hasPart'), function(property) {
if (property) {
predicates.push(property);
}
});
return predicates;
},
// ### VIE.EntityManager.getByJSONLD
//
// Another way to get or load entities is by passing EntityManager a valid
// JSON-LD object.
//
// This can be either called with a JavaScript object representing JSON-LD,
// or with a JSON-LD string.
//
// Example:
//
// var json = '{"@": "<http://www.example.com/books/wikinomics>","dc:title": "Wikinomics","dc:creator": "Don Tapscott","dc:date": "2006-10-01"}';
// var objectInstance = VIE.EntityManager.getByJSONLD(json);
getByJSONLD: function(jsonld, options) {
VIE.EntityManager.initializeCollection();
var entityInstance;
var properties;
if (typeof jsonld !== 'object') {
try {
jsonld = jQuery.parseJSON(jsonld);
} catch (e) {
return null;
}
}
// The entities accessed this way are singletons, so multiple calls
// to same subject (`@` in JSON-LD) will all return the same
// `VIE.RDFEntity` instance.
if (typeof jsonld['@'] !== 'undefined') {
entityInstance = VIE.EntityManager.getBySubject(jsonld['@']);
}
if (entityInstance) {
properties = VIE.EntityManager._JSONtoProperties(jsonld, entityInstance.attributes, entityInstance.id);
entityInstance.set(properties, options);
if (!entityInstance.type &&
typeof jsonld.a !== 'undefined') {
entityInstance.type = VIE.RDFa._fromReference(jsonld.a);
}
return entityInstance;
}
properties = VIE.EntityManager._JSONtoProperties(jsonld, {}, VIE.EntityManager._normalizeSubject(jsonld['@']));
entityInstance = new VIE.RDFEntity(properties);
// Namespace prefixes are handled by the `#` property of JSON-LD.
// We map this to the `namespaces` property of our `VIE.RDFEntity`
// instance.
if (typeof jsonld['#'] !== 'undefined') {
entityInstance.namespaces = jsonld['#'];
}
// Types are handled by the `a` property of JSON-LD. We map this
// to the `type` property of our `VIE.RDFEntity` instance.
if (typeof jsonld.a !== 'undefined') {
entityInstance.type = VIE.RDFa._fromReference(jsonld.a);
}
// Normalize the subject, handling both proper JSON-LD and JSON-LD
// anonymous entities extracted from RDFa
entityInstance.id = VIE.EntityManager._normalizeSubject(jsonld['@']);
VIE.EntityManager.registerModel(entityInstance);
return entityInstance;
},
// ### VIE.EntityManager.getByRDFJSON
//
// Another way to get or load entities is by passing EntityManager a valid
// RDF/JSON object.
//
// This can be either called with a JavaScript object representing JSON-LD,
// or with a JSON-LD string.
//
// Example:
//
// var rdfjson = '{"<http://www.example.com/books/wikinomics>": {"dc:title": "Wikinomics","dc:creator": "Don Tapscott","dc:date": "2006-10-01"}}';
// var objectInstance = VIE.EntityManager.getByRDFJSON(rdfjson);
getByRDFJSON: function(rdfjson, options){
VIE.EntityManager.initializeCollection();
var entityInstance;
var simpleProperties = {};
if (typeof rdfjson !== 'object') {
try {
rdfjson = jQuery.parseJSON(rdfjson);
} catch (e) {
return null;
}
}
_.each(rdfjson, function(properties, entityUri){
// Simplify rdfjson
_(properties).each(function(propertyValues, key){
key = '<' + key + '>';
simpleProperties[key] = _(propertyValues).map(function(value){
return value.value;
});
simpleProperties[key] = _(simpleProperties[key]).uniq();
if(simpleProperties[key].length == 1)
simpleProperties[key] = simpleProperties[key][0];
});
entityInstance = VIE.EntityManager.getBySubject(entityUri);
if (entityInstance) {
entityInstance.set(simpleProperties, options);
return entityInstance;
}
entityInstance = new VIE.RDFEntity(simpleProperties);
entityInstance.id = entityUri;
VIE.EntityManager.registerModel(entityInstance);
return entityInstance;
})
},
// All new entities must be added to the `entities` collection.
registerModel: function(model) {
model.id = VIE.EntityManager._normalizeSubject(model.id);
if (VIE.EntityManager.entities.indexOf(model) === -1) {
VIE.EntityManager.entities.add(model);
}
},
_normalizeSubject: function(subject) {
// Subjects are handled by the `@` property of JSON-LD. We map this
// to the `id` property of our `VIE.RDFEntity` instance.
if (typeof subject === 'string') {
if (VIE.RDFa._isReference(subject)) {
subject = VIE.RDFa._fromReference(subject);
}
return subject;
}
// When handling anonymous entities coming from RDFa, we keep their
// containing element as the ID so they can be matched
if (typeof subject === 'object') {
return subject;
}
return undefined;
},
// Create a list of Models for referenced properties
_referencesToModels: function(value) {
if (!_.isArray(value)) {
value = [value];
}
var models = [];
_.forEach(value, function(subject) {
models.push(VIE.EntityManager.getByJSONLD({
'@': subject
}));
});
return models;
},
// Helper for cleaning up JSON-LD so that it can be used as properties
// of a Backbone Model.
_JSONtoProperties: function(jsonld, instanceProperties, instanceId) {
var properties;
var references;
var property;
properties = jQuery.extend({}, jsonld);
delete properties['@'];
delete properties.a;
delete properties['#'];
_.each(properties, function(propertyValue, property) {
if (VIE.RDFa._isReference(propertyValue) ||
typeof propertyValue === 'object') {
references = VIE.EntityManager._referencesToModels(propertyValue);
if (instanceProperties[property] instanceof VIE.RDFEntityCollection) {
// Object already has this reference collection, keep it
// and add new references
jQuery.each(references, function() {
if (instanceProperties[property].indexOf(this) === -1) {
instanceProperties[property].add(this);
}
});
properties[property] = instanceProperties[property];
}
else {
properties[property] = new VIE.RDFEntityCollection(references);
if (instanceId) {
properties[property].subject = VIE.EntityManager._normalizeSubject(instanceId);
properties[property].predicate = property;
}
}
}
});
return properties;
},
// Helper for removing existing information about loaded entities.
cleanup: function() {
VIE.EntityManager.entities = new VIE.RDFEntityCollection();
}
};
// VIE.RDFEntity
// -------------
//
// VIE.RDFEntity defines a common [Backbone Model](http://documentcloud.github.com/backbone/#Model)
// for RDF entities handled in VIE.
//
// Attributes that are references to other entities are exposed as
// `VIE.RDFEntityCollection` objects containing those entities.
VIE.RDFEntity = Backbone.Model.extend({
namespaces: {},
type: '',
// Get the subject of a RDF entity. For persistent entities full URL
// subjects will be returned wrapped in `<` and `>`.
// For non-persistent entities an anonymous `_:bnodeX` will be returned,
// with `X` matching the local `cid` number of the entity instance.
//
// CURIEs will be returned as-is.
getSubject: function() {
if (typeof this.id === 'string') {
if (this.id.substr(0, 7) === 'http://' || this.id.substr(0, 4) === 'urn:') {
return VIE.RDFa._toReference(this.id);
}
return this.id;
}
return this.cid.replace('c', '_:bnode');
},
// VIE's entities have a method for generating [JSON-LD](http://json-ld.org/)
// representations of themselves. JSON-LD is a lightweight format for handling
// Linked Data (RDF) information.
//
// Using the book example from above, we could call:
//
// myBook.toJSONLD();
//
// And we would get a JSON object looking like the following:
//
// {
// '@': '<http://www.example.com/books/wikinomics>',
// 'dc:title': 'Wikinomics',
// 'dc:creator': 'Don Tapscott',
// 'dc:date': '2006-10-01'
// }
//
// Calling `JSON.stringify()` for this object would produce:
//
//
// {
// "@": "<http://www.example.com/books/wikinomics>",
// "dc:title": "Wikinomics",
// "dc:creator": "Don Tapscott",
// "dc:date": "2006-10-01"
// }
toJSONLD: function() {
var instance = this;
var instanceLD = {};
var property;
_.each(instance.attributes, function(attributeValue, property) {
attributeValue = instance.get(property);
if (attributeValue instanceof VIE.RDFEntityCollection) {
instanceLD[property] = attributeValue.map(function(referenceInstance) {
return referenceInstance.getSubject();
});
} else {
instanceLD[property] = attributeValue;
}
});
instanceLD['@'] = instance.getSubject();
if (instance.namespaces.length > 0) {
instanceLD['#'] = instance.namespaces;
}
if (instance.type) {
instanceLD.a = VIE.RDFa._toReference(instance.type);
}
return instanceLD;
}
});
// VIE.RDFEntityCollection
// -----------------------
//
// VIE.RDFEntityCollection defines a common [Backbone Collection](http://documentcloud.github.com/backbone/#Collection)
// for references to RDF entities handled in VIE.
VIE.RDFEntityCollection = Backbone.Collection.extend({
model: VIE.RDFEntity,
initialize: function() {
this.bind('add', this.registerItem);
},
registerItem: function(entityInstance, collection) {
if (collection === VIE.EntityManager.entities) {
return;
}
_.each(entityInstance.attributes, function(propertyValue, property) {
if(property == 'id') return true;
if (VIE.RDFa._isReference(propertyValue)) {
var references = VIE.EntityManager._referencesToModels(propertyValue);
entityInstance.attributes[property] = new VIE.RDFEntityCollection(references);
}
});
VIE.EntityManager.registerModel(entityInstance);
}
});
// VIE.RDFaEntities
// -------------
//
// VIE.RDFaEntities provide mapping between RDFa on a page and Backbone Views.
// When you load RDFa entities from a page, new `VIE.RDFEntity` objects will
// be instantiated for them, and the DOM element the RDFa comes from will
// be registered as a `VIE.RDFaView` instance.
//
// If you're working with RDFa -annotated content and want to access it as
// Backbone Models, then VIE.RDFaEntities is the main access point.
VIE.RDFaEntities = {
// RDFaEntities manages a list of Views so that every view instance will be
// a singleton.
Views: [],
CollectionViews: [],
// ### VIE.RDFaEntities.getInstance
//
// The `getInstance` method can be used for retrieving a single Backbone
// Model for a given RDFa -annotated DOM element. It accepts
// [jQuery selectors](http://api.jquery.com/category/selectors/)
// and returns a `VIE.RDFEntity` instance matching the content. If no valid
// RDFa entities can be found from the element, then it returns `null`.
//
// Example:
//
// var myBook = VIE.RDFaEntities.getInstance('p[about]');
// alert(myBook.get('dc:title')); // "Wikinomics"
getInstance: function(element) {
element = jQuery(element);
var entityInstance;
var jsonld;
jsonld = VIE.RDFa.readEntity(element);
if (!jsonld) {
return null;
}
entityInstance = VIE.EntityManager.getByJSONLD(jsonld);
VIE.RDFaEntities._registerView(entityInstance, element);
return entityInstance;
},
_getViewInstance: function(element, collection) {
var viewInstance;
var viewArray = VIE.RDFaEntities.Views;
element = jQuery(element);
if (collection) {
viewArray = VIE.RDFaEntities.CollectionViews;
}
jQuery.each(viewArray, function() {
if (this.el.get(0) === element.get(0)) {
viewInstance = this;
return false;
}
});
return viewInstance;
},
// Helper for registering views for a collection
_registerCollectionView: function(collectionInstance, element) {
var viewInstance;
var template;
element = jQuery(element);
// Check whether we already have a View instantiated for the DOM element
viewInstance = VIE.RDFaEntities._getViewInstance(element, true);
if (viewInstance) {
return viewInstance;
}
template = element.children(':first-child');
viewInstance = new VIE.RDFaCollectionView({
collection: collectionInstance,
model: collectionInstance.model,
el: element,
elementTemplate: template,
tagName: element.get(0).nodeName
});
VIE.RDFaEntities.CollectionViews.push(viewInstance);
return viewInstance;
},
// Helper for registering views for an entity
_registerView: function(entityInstance, element, refreshCollections) {
var viewInstance;
element = jQuery(element);
// Check whether we already have a View instantiated for the DOM element
viewInstance = VIE.RDFaEntities._getViewInstance(element);
if (viewInstance) {
return viewInstance;
}
viewInstance = new VIE.RDFaView({
model: entityInstance,
el: element,
tagName: element.get(0).nodeName
});
VIE.RDFaEntities.Views.push(viewInstance);
// Find collection elements, and create collection views for them
_.each(entityInstance.attributes, function(attributeValue, property) {
attributeValue = entityInstance.get(property);
if (attributeValue instanceof VIE.RDFEntityCollection) {
jQuery.each(VIE.RDFa._getElementByPredicate(property, element), function() {
VIE.RDFaEntities._registerCollectionView(attributeValue, this);
if (refreshCollections) {
attributeValue.trigger('refresh', attributeValue);
}
});
}
});
return viewInstance;
},
// ### VIE.RDFaEntities.getInstances
//
// Get a list of Backbone Model instances for all RDFa-marked content in
// an element. The method accepts [jQuery selectors](http://api.jquery.com/category/selectors/)
// as argument. If no selector is given, then the whole HTML document will
// be searched.
//
// Example:
//
// var allInstances = VIE.RDFaEntities.getInstances();
// alert(allInstances[0].get('dc:title')); // "Wikinomics"
getInstances: function(element) {
var entities = [];
var entity;
if (typeof element === 'undefined') {
element = jQuery(document);
}
jQuery(VIE.RDFa.subjectSelector, element).add(jQuery(element).filter(VIE.RDFa.subjectSelector)).each(function() {
entity = VIE.RDFaEntities.getInstance(this);
if (entity) {
entities.push(entity);
}
});
return entities;
},
// Helper for removing existing references to Views loaded for RDFa entities.
cleanup: function() {
VIE.RDFaEntities.Views = [];
}
};
// VIE.RDFaView
// -------------
//
// VIE.RDFaView defines a common [Backbone View](http://documentcloud.github.com/backbone/#View)
// for all RDFa -annotated elements on a page that have been loaded as
// `VIE.RDFEntity` objects.
//
// In normal operation, the RDFaView objects are automatically handled by
// `VIE.RDFaEntities`.
VIE.RDFaView = Backbone.View.extend({
// We ensure view gets updated when properties of the Entity change.
initialize: function() {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
},
// Rendering a view means writing the properties of the Entity back to
// the element containing our RDFa annotations.
render: function() {
VIE.RDFa.writeEntity(this.el, this.model.toJSONLD());
return this;
}
});
// VIE.RDFaCollectionView
// ----------------------
//
// VIE.RDFaCollectionView defines a common Backbone View for Collection properties
VIE.RDFaCollectionView = Backbone.View.extend({
elementTemplate: null,
// Ensure the collection view gets updated when items get added or removed
initialize: function() {
this.elementTemplate = this.options.elementTemplate;
_.bindAll(this, 'addItem', 'removeItem', 'refreshItems');
this.collection.bind('add', this.addItem);
this.collection.bind('remove', this.removeItem);
this.collection.bind('refresh', this.refreshItems);
},
// When a collection is refreshed, we empty the collection list and
// add each child separately
refreshItems: function(collectionInstance) {
var collectionView = this;
jQuery(this.el).empty();
collectionInstance.forEach(function(itemInstance) {
collectionView.addItem(itemInstance, collectionInstance);
});
},
// When adding new items we create a new element of the child type
// and append it to the list.
addItem: function(itemInstance, collection) {
if (collection !== this.collection) {
return;
}
if (!this.elementTemplate ||
this.elementTemplate.length === 0) {
return;
}
var itemView = VIE.RDFaEntities._registerView(itemInstance, VIE.RDFa._cloneElement(this.elementTemplate), true);
var itemViewElement = itemView.render().el;
if (itemInstance.id &&
typeof itemInstance.id === 'string') {
VIE.RDFa.setSubject(itemViewElement, itemInstance.id);
} else {
itemInstance.id = itemViewElement.get(0);
}
// Figure out where to place the element based on its order
var itemOrder = this.collection.indexOf(itemInstance);
var childElements = jQuery(this.el).children();
if (childElements.length === 0 ||
itemOrder > childElements.length - 1)
{
jQuery(this.el).append(itemViewElement);
} else {
jQuery(this.el).children().each(function(index, element) {
if (index >= itemOrder) {
jQuery(element).before(itemViewElement);
return false;
}
});
}
this.trigger('add', itemView);
itemViewElement.show();
// If the new instance doesn't yet have an identifier, bind it to
// the HTML representation of itself. This safeguards from duplicates.
if (!itemInstance.id) {
itemInstance.id = VIE.RDFa.getSubject(itemViewElement);
}
// Ensure we catch all inferred predicates. We add these via JSONLD
// so the references get properly Collectionized.
jQuery(itemViewElement).parent('[rev]').each(function() {
var properties = {
'@': itemInstance.id
};
var predicate = jQuery(this).attr('rev');
properties[predicate] = VIE.RDFa.getSubject(this);
VIE.EntityManager.getByJSONLD(properties);
});
},
// When removing items from Collection we remove their views from the DOM.
removeItem: function(itemInstance) {
// Try to find it from DOM
jQuery(VIE.RDFa.subjectSelector, this.el).filter(function() {
if (VIE.RDFa.getSubject(this) === VIE.RDFa._toReference(itemInstance.id)) {
return true;
}
}).each(function() {
jQuery(this).remove();
});
return;
}
});
// VIE.RDFa
// --------
//
// RDFa reading and writing utilities. VIE.RDFa acts as a mapping tool between
// [JSON-LD](http://json-ld.org/) -encoded RDF triples and RDFa -annotated content
// on a page.
VIE.RDFa = {
Namespaces: {},
// By default we look for RDF subjects based on elements that have a
// `about`, `typeof` or `src` attribute. In addition, the full HTML page
// is regarded as a valid subject.
//
// For more specialized scenarios this can be overridden:
//
// VIE.RDFa.subjectSelector = '[about]';
subjectSelector: '[about],[typeof],[src],html',
// By default we look for RDF predicates based on elements that have a
// `property` or `rel` attribute.
//
// For more specialized scenarios this can be overridden:
//
// VIE.RDFa.predicateSelector = '[property]';
predicateSelector: '[property],[rel]',
// ### VIE.RDFa.getSubject
//
// Get the RDF subject for an element. The method accepts
// [jQuery selectors](http://api.jquery.com/category/selectors/) as
// arguments. If no argument is given, then the _base URL_ of the
// page is used.
//
// Returns the subject as a string if one can be found, and if the
// given element has no valid subjects returns `undefined`.
//
// Example:
//
// var subject = VIE.RDFa.getSubject('p[about]');
// alert(subject); // <http://www.example.com/books/wikinomics>
getSubject: function(element) {
if (typeof document !== 'undefined') {
if (element === document) {
return document.baseURI;
}
}
var subject;
jQuery(element).closest(VIE.RDFa.subjectSelector).each(function() {
if (jQuery(this).attr('about')) {
subject = jQuery(this).attr('about');
return true;
}
if (jQuery(this).attr('src')) {
subject = jQuery(this).attr('src');
return true;
}
if (jQuery(this).attr('typeof')) {
subject = this;
return true;
}
// We also handle baseURL outside browser context by manually
// looking for the `<base>` element inside HTML head.
if (jQuery(this).get(0).nodeName === 'HTML') {
jQuery(this).find('base').each(function() {
subject = jQuery(this).attr('href');
});
}
});
if (!subject) {
return undefined;
}
if (typeof subject === 'object') {
return subject;
}
return VIE.RDFa._toReference(subject);
},
// Set subject for an element
setSubject: function(element, subject) {
if (jQuery(element).attr('src')) {
return jQuery(element).attr('src', subject);
}
jQuery(element).attr('about', subject);
},
// Get predicate for an element
getPredicate: function(element) {
var propertyName;
element = jQuery(element);
propertyName = element.attr('property');
if (!propertyName) {
propertyName = element.attr('rel');
}
return propertyName;
},
// ### VIE.RDFa.readEntity
//
// Get a JSON-LD object for an RDFa-marked entity in
// an element. The method accepts [jQuery selectors](http://api.jquery.com/category/selectors/)
// as argument. If the element contains no RDFa entities, the this method
// returns `null`.
//
// Example:
//
// var jsonld = VIE.RDFa.readEntity('p[about]');
//
// Would return a JSON-LD object looking like the following:
//
// {
// '@': '<http://www.example.com/books/wikinomics>',
// 'dc:title': 'Wikinomics',
// 'dc:creator': 'Don Tapscott',
// 'dc:date': '2006-10-01'
// }
readEntity: function(element) {
var entity;
var subject;
var namespaces = {};
var namespace;
var type;
var propertyName;
subject = VIE.RDFa.getSubject(element);
entity = VIE.RDFa._getElementProperties(subject, element, false);
if (jQuery.isEmptyObject(entity)) {
return null;
}
// We also try to resolve namespaces used in the RDFa entity. If they
// can be found, we will write them to the `#` property of the object.
for (propertyName in entity) {
if (entity.hasOwnProperty(propertyName)) {
var propertyParts = propertyName.split(':');
if (propertyParts.length === 2) {
namespace = VIE.RDFa._resolveNamespace(propertyParts[0], element);
if (namespace) {
namespaces[propertyParts[0]] = namespace;
}
}
}
}
if (!jQuery.isEmptyObject(namespaces)) {
entity['#'] = namespaces;
}
// If the RDF type is defined, that will be set to the [`a` property](http://json-ld.org/spec/latest/#specifying-the-type)
// of the JSON-LD object.
type = VIE.RDFa._getElementValue(element, 'typeof');
if (type) {
entity.a = VIE.RDFa._toReference(type);
}
entity['@'] = subject;
return entity;
},
// ### VIE.RDFa.readEntities
//
// Get a list of JSON-LD objects for RDFa-marked entities in
// an element. The method accepts [jQuery selectors](http://api.jquery.com/category/selectors/)
// as argument. If no selector is given, then the whole HTML document will
// be searched.
//
// Example:
//
// var jsonldEntities = VIE.RDFa.readEntities();
// JSON.stringify(jsonldEntities[0]);
//
// Would produce something like:
//
// {
// "@": "<http://www.example.com/books/wikinomics>",
// "dc:title": "Wikinomics",
// "dc:creator": "Don Tapscott",
// "dc:date": "2006-10-01"
// }
readEntities: function(element) {
var entities = [];
var entity;
if (typeof element === 'undefined') {
element = jQuery(document);
}
jQuery(VIE.RDFa.subjectSelector, element).add(jQuery(element).filter(VIE.RDFa.subjectSelector)).each(function() {
entity = VIE.RDFa.readEntity(this);
if (entity) {
entities.push(entity);
}
});
return entities;
},
// ### VIE.RDFa.writeEntity
//
// Write the contents of a JSON-LD object into the given DOM element. This
// method accepts [jQuery selectors](http://api.jquery.com/category/selectors/)
// as arguments.
//
// Only properties matching RDFa-annotated predicates found from
// the selected DOM element will be written.
writeEntity: function(element, jsonld) {
VIE.RDFa.findPredicateElements(VIE.RDFa.getSubject(element), element, true).each(function() {
var propertyElement = jQuery(this);
var propertyName = propertyElement.attr('property');
if (typeof jsonld[propertyName] === 'undefined') {
jsonld[propertyName] = propertyName;
}
// Before writing to DOM we check that the value has actually changed.
if (VIE.RDFa._readPropertyValue(propertyName, propertyElement) !== jsonld[propertyName]) {
VIE.RDFa._writePropertyValue(propertyElement, jsonld[propertyName]);
}