-
Notifications
You must be signed in to change notification settings - Fork 74
/
lens_converter.js
2483 lines (2126 loc) · 75.6 KB
/
lens_converter.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
"use strict";
var _ = require("underscore");
var util = require("../substance/util");
var errors = util.errors;
var ImporterError = errors.define("ImporterError");
var Article = require("../article");
var NlmToLensConverter = function(options) {
this.options = options || NlmToLensConverter.DefaultOptions;
};
NlmToLensConverter.Prototype = function() {
this._annotationTypes = {
"bold": "strong",
"italic": "emphasis",
"monospace": "code",
"sub": "subscript",
"sup": "superscript",
"sc": "custom_annotation",
"underline": "underline",
"ext-link": "link",
"xref": "",
"email": "link",
"named-content": "",
"inline-formula": "inline-formula",
"uri": "link"
};
// mapping from xref.refType to node type
this._refTypeMapping = {
"bibr": "citation_reference",
"fig": "figure_reference",
"table": "figure_reference",
"supplementary-material": "figure_reference",
"other": "figure_reference",
"list": "definition_reference",
};
// mapping of contrib type to human readable names
// Can be overriden in specialized converter
this._contribTypeMapping = {
"author": "Author",
"author non-byline": "Author",
"autahor": "Author",
"auther": "Author",
"editor": "Editor",
"guest-editor": "Guest Editor",
"group-author": "Group Author",
"collab": "Collaborator",
"reviewed-by": "Reviewer",
"nominated-by": "Nominator",
"corresp": "Corresponding Author",
"other": "Other",
"assoc-editor": "Associate Editor",
"associate editor": "Associate Editor",
"series-editor": "Series Editor",
"contributor": "Contributor",
"chairman": "Chairman",
"monographs-editor": "Monographs Editor",
"contrib-author": "Contributing Author",
"organizer": "Organizer",
"chair": "Chair",
"discussant": "Discussant",
"presenter": "Presenter",
"guest-issue-editor": "Guest Issue Editor",
"participant": "Participant",
"translator": "Translator"
};
this.isAnnotation = function(type) {
return this._annotationTypes[type] !== undefined;
};
this.isParagraphish = function(node) {
for (var i = 0; i < node.childNodes.length; i++) {
var el = node.childNodes[i];
if (el.nodeType !== Node.TEXT_NODE && !this.isAnnotation(el.tagName.toLowerCase())) return false;
}
return true;
};
this.test = function(xml, documentUrl) {
/* jshint unused:false */
return true;
};
// Helpers
// --------
this.getName = function(nameEl) {
if (!nameEl) return "N/A";
var names = [];
var surnameEl = nameEl.querySelector("surname");
var givenNamesEl = nameEl.querySelector("given-names");
var suffix = nameEl.querySelector("suffix");
if (givenNamesEl) names.push(givenNamesEl.textContent);
if (surnameEl) names.push(surnameEl.textContent);
if (suffix) return [names.join(" "), suffix.textContent].join(", ");
return names.join(" ");
};
this.toHtml = function(el) {
if (!el) return "";
var tmp = document.createElement("DIV");
tmp.appendChild(el.cloneNode(true));
return tmp.innerHTML;
};
this.mmlToHtmlString = function(el) {
var html = this.toHtml(el);
html = html.replace(/<(\/)?mml:([^>]+)>/g, "<$1$2>");
return html;
};
this.selectDirectChildren = function(scopeEl, selector) {
// Note: if the ':scope' pseudo class was supported by more browsers
// it would be the correct selector based solution.
// However, for now we do simple filtering.
var result = [];
var els = scopeEl.querySelectorAll(selector);
for (var i = 0; i < els.length; i++) {
var el = els[i];
if (el.parentElement === scopeEl) result.push(el);
}
return result;
};
// ### The main entry point for starting an import
this.import = function(input) {
var xmlDoc;
// Note: when we are using jqueries get("<file>.xml") we
// magically get a parsed XML document already
if (_.isString(input)) {
var parser = new DOMParser();
xmlDoc = parser.parseFromString(input,"text/xml");
} else {
xmlDoc = input;
}
this.sanitizeXML(xmlDoc);
// Creating the output Document via factore, so that it is possible to
// create specialized NLMImporter later which would want to instantiate
// a specialized Document type
var doc = this.createDocument();
// For debug purposes
window.doc = doc;
// A deliverable state which makes this importer stateless
var state = this.createState(xmlDoc, doc);
// Note: all other methods are called corresponding
return this.document(state, xmlDoc);
};
// Sometimes we need to deal with unconsistent XML
// When overwriting this function in your custom converter
// you can solve those issues in a preprocessing step instead of adding
// hacks in the main converter code
this.sanitizeXML = function(xmlDoc) {
/* jshint unused:false */
};
this.createState = function(xmlDoc, doc) {
return new NlmToLensConverter.State(this, xmlDoc, doc);
};
// Overridden to create a Lens Article instance
this.createDocument = function() {
var doc = new Article();
return doc;
};
this.show = function(state, nodes) {
_.each(nodes, function(n) {
this.showNode(state, n);
}, this);
};
this.extractDate = function(dateEl) {
if (!dateEl) return null;
var year = dateEl.querySelector("year");
var month = dateEl.querySelector("month");
var day = dateEl.querySelector("day");
var res = [year.textContent];
if (month) res.push(month.textContent);
if (day) res.push(day.textContent);
return res.join("-");
};
this.extractPublicationInfo = function(state, article) {
var doc = state.doc;
var articleMeta = article.querySelector("article-meta");
var pubDate = articleMeta.querySelector("pub-date");
var history = articleMeta.querySelectorAll("history date");
// Journal title
//
var journalTitle = article.querySelector("journal-title");
// DOI
//
// <article-id pub-id-type="doi">10.7554/eLife.00003</article-id>
var articleDOI = article.querySelector("article-id[pub-id-type=doi]");
// Related article if exists
//
// TODO: can't there be more than one?
var relatedArticle = article.querySelector("related-article");
// Article information
var articleInfo = this.extractArticleInfo(state, article);
// Create PublicationInfo node
// ---------------
var pubInfoNode = {
"id": "publication_info",
"type": "publication_info",
"published_on": this.extractDate(pubDate),
"journal": journalTitle ? journalTitle.textContent : "",
"related_article": relatedArticle ? relatedArticle.getAttribute("xlink:href") : "",
"doi": articleDOI ? articleDOI.textContent : "",
"article_info": articleInfo.id,
// TODO: 'article_type' should not be optional; we need to find a good default implementation
"article_type": "",
// Optional fields not covered by the default implementation
// Implement config.enhancePublication() to complement the data
// TODO: think about how we could provide good default implementations
"keywords": [],
"links": [],
"subjects": [],
"supplements": [],
"history": [],
// TODO: it seems messy to have this in the model
// Instead it would be cleaner to add 'custom': 'object' field
"research_organisms": [],
// TODO: this is in the schema, but seems to be unused
"provider": "",
};
for (var i = 0; i < history.length; i++) {
var dateEl = history[i];
var historyEntry = {
type: dateEl.getAttribute('date-type'),
date: this.extractDate(dateEl)
};
pubInfoNode.history.push(historyEntry);
}
doc.create(pubInfoNode);
doc.show("info", pubInfoNode.id, 0);
this.enhancePublicationInfo(state, pubInfoNode);
};
this.extractArticleInfo = function(state, article) {
// Initialize the Article Info object
var articleInfo = {
"id": "articleinfo",
"type": "paragraph",
};
var doc = state.doc;
var nodes = [];
// Reviewing editor
nodes = nodes.concat(this.extractEditor(state, article));
// Datasets
nodes = nodes.concat(this.extractDatasets(state, article));
// Includes meta information (such as impact statement for eLife)
nodes = nodes.concat(this.extractCustomMetaGroup(state, article));
// Acknowledgments
nodes = nodes.concat(this.extractAcknowledgements(state, article));
// License and Copyright
nodes = nodes.concat(this.extractCopyrightAndLicense(state, article));
// Notes (Footnotes + Author notes)
nodes = nodes.concat(this.extractNotes(state, article));
articleInfo.children = nodes;
doc.create(articleInfo);
return articleInfo;
};
// Get reviewing editor
// --------------
// TODO: it is possible to have multiple editors. This does only show the first one
// However, this would be easy: just querySelectorAll and have 'Reviewing Editors' as heading when there are multiple nodes found
this.extractEditor = function(state, article) {
var nodes = [];
var doc = state.doc;
var editor = article.querySelector("contrib[contrib-type=editor]");
if (editor) {
var content = [];
var name = this.getName(editor.querySelector('name'));
if (name) content.push(name);
var inst = editor.querySelector("institution");
if (inst) content.push(inst.textContent);
var country = editor.querySelector("country");
if (country) content.push(country.textContent);
var h1 = {
"type": "heading",
"id": state.nextId("heading"),
"level": 3,
"content": "Reviewing Editor"
};
doc.create(h1);
nodes.push(h1.id);
var t1 = {
"type": "text",
"id": state.nextId("text"),
"content": content.join(", ")
};
doc.create(t1);
nodes.push(t1.id);
}
return nodes;
};
//
// Extracts major datasets
// -----------------------
this.extractDatasets = function(state, article) {
var nodes = [];
var doc = state.doc;
var datasets = article.querySelectorAll('sec');
for (var i = 0;i <datasets.length;i++){
var data = datasets[i];
var type = data.getAttribute('sec-type');
if (type === 'datasets') {
var h1 = {
"type" : "heading",
"id" : state.nextId("heading"),
"level" : 3,
"content" : "Major Datasets"
};
doc.create(h1);
nodes.push(h1.id);
var ids = this.datasets(state, util.dom.getChildren(data));
for (var j=0;j < ids.length;j++) {
if (ids[j]) {
nodes.push(ids[j]);
}
}
}
}
return nodes;
};
var _capitalized = function(str, all) {
if (all) {
return str.split(' ').map(function(s){
return _capitalized(s);
}).join(' ');
} else {
return str.charAt(0).toUpperCase() + str.slice(1);
}
};
this.capitalized = function(str, all) {
return _capitalized(str, all);
};
//
// Extracts Acknowledgements
// -------------------------
this.extractAcknowledgements = function(state, article) {
var nodes = [];
var doc = state.doc;
var acks = article.querySelectorAll("ack");
if (acks && acks.length > 0) {
_.each(acks, function(ack) {
var title = ack.querySelector('title');
var header = {
"type" : "heading",
"id" : state.nextId("heading"),
"level" : 3,
"content" : title ? this.capitalized(title.textContent.toLowerCase(), "all") : "Acknowledgements"
};
doc.create(header);
nodes.push(header.id);
// There may be multiple paragraphs per ack element
var pars = this.bodyNodes(state, util.dom.getChildren(ack), {
ignore: ["title"]
});
_.each(pars, function(par) {
nodes.push(par.id);
});
}, this);
}
return nodes;
};
//
// Extracts footnotes that should be shown in article info
// ------------------------------------------
//
// Needs to be overwritten in configuration
this.extractNotes = function(/*state, article*/) {
var nodes = [];
return nodes;
};
// Can be overridden by custom converter to ignore <meta-name> values.
// TODO: Maybe switch to a whitelisting approach, so we don't show
// nonsense. See HighWire implementation
this.__ignoreCustomMetaNames = [];
this.extractCustomMetaGroup = function(state, article) {
var nodeIds = [];
var doc = state.doc;
var customMetaEls = article.querySelectorAll('article-meta-group custom-meta');
if (customMetaEls.length === 0) return nodeIds;
for (var i = 0; i < customMetaEls.length; i++) {
var customMetaEl = customMetaEls[i];
var metaNameEl = customMetaEl.querySelector('meta-name');
var metaValueEl = customMetaEl.querySelector('meta-value');
if (!_.include(this.__ignoreCustomMetaNames, metaNameEl.textContent)) {
var header = {
"type" : "heading",
"id" : state.nextId("heading"),
"level" : 3,
"content" : ""
};
header.content = this.annotatedText(state, metaNameEl, [header.id, 'content']);
doc.create(header);
var bodyNodes = this.paragraphGroup(state, metaValueEl);
nodeIds.push(header.id);
nodeIds = nodeIds.concat(_.pluck(bodyNodes, 'id'));
}
}
return nodeIds;
};
//
// Extracts Copyright and License Information
// ------------------------------------------
this.extractCopyrightAndLicense = function(state, article) {
var nodes = [];
var doc = state.doc;
var license = article.querySelector("permissions");
if (license) {
var h1 = {
"type" : "heading",
"id" : state.nextId("heading"),
"level" : 3,
"content" : "Copyright & License"
};
doc.create(h1);
nodes.push(h1.id);
// TODO: this is quite messy. We should introduce a dedicated note for article info
// and do that rendering related things there, e.g., '. ' separator
var par;
var copyright = license.querySelector("copyright-statement");
if (copyright) {
par = this.paragraphGroup(state, copyright);
if (par && par.length) {
nodes = nodes.concat( _.map(par, function(p) { return p.id; } ) );
// append '.' only if there is none yet
if (copyright.textContent.trim().slice(-1) !== '.') {
// TODO: this needs to be more robust... what if there are no children
var textid = _.last(_.last(par).children);
doc.nodes[textid].content += ". ";
}
}
}
var lic = license.querySelector("license");
if (lic) {
for (var child = lic.firstElementChild; child; child = child.nextElementSibling) {
var type = util.dom.getNodeType(child);
if (type === 'p' || type === 'license-p') {
par = this.paragraphGroup(state, child);
if (par && par.length) {
nodes = nodes.concat( _.pluck(par, 'id') );
}
}
}
}
}
return nodes;
};
this.extractCover = function(state, article) {
var doc = state.doc;
var docNode = doc.get("document");
var cover = {
id: "cover",
type: "cover",
title: docNode.title,
authors: [], // docNode.authors,
abstract: docNode.abstract
};
// Create authors paragraph that has contributor_reference annotations
// to activate the author cards
_.each(docNode.authors, function(contributorId) {
var contributor = doc.get(contributorId);
var authorsPara = {
"id": "text_"+contributorId+"_reference",
"type": "text",
"content": contributor.name
};
doc.create(authorsPara);
cover.authors.push(authorsPara.id);
var anno = {
id: state.nextId("contributor_reference"),
type: "contributor_reference",
path: ["text_" + contributorId + "_reference", "content"],
range: [0, contributor.name.length],
target: contributorId
};
doc.create(anno);
}, this);
// Move to elife configuration
// -------------------
// <article-categories>
// <subj-group subj-group-type="display-channel">...</subj-group>
// <subj-group subj-group-type="heading">...</subj-group>
// </article-categories>
// <article-categories>
// <subj-group subj-group-type="display-channel">
// <subject>Research article</subject>
// </subj-group>
// <subj-group subj-group-type="heading">
// <subject>Biophysics and structural biology</subject>
// </subj-group>
// </article-categories>
this.enhanceCover(state, cover, article);
doc.create(cover);
doc.show("content", cover.id, 0);
};
// Note: Substance.Article supports only one author.
// We use the first author found in the contribGroup for the 'creator' property.
this.contribGroup = function(state, contribGroup) {
var i;
var contribs = contribGroup.querySelectorAll("contrib");
for (i = 0; i < contribs.length; i++) {
this.contributor(state, contribs[i]);
}
// Extract on-behalf-of element and stick it to the document
var doc = state.doc;
var onBehalfOf = contribGroup.querySelector("on-behalf-of");
if (onBehalfOf) doc.on_behalf_of = onBehalfOf.textContent.trim();
};
this.affiliation = function(state, aff) {
var doc = state.doc;
var institution = aff.querySelector("institution");
var country = aff.querySelector("country");
var label = aff.querySelector("label");
var department = aff.querySelector("addr-line named-content[content-type=department]");
var city = aff.querySelector("addr-line named-content[content-type=city]");
// TODO: this is a potential place for implementing a catch-bin
// For that, iterate all children elements and fill into properties as needed or add content to the catch-bin
var affiliationNode = {
id: state.nextId("affiliation"),
type: "affiliation",
source_id: aff.getAttribute("id"),
label: label ? label.textContent : null,
department: department ? department.textContent : null,
city: city ? city.textContent : null,
institution: institution ? institution.textContent : null,
country: country ? country.textContent: null
};
doc.create(affiliationNode);
};
this.contributor = function(state, contrib) {
var doc = state.doc;
var id = state.nextId("contributor");
var contribNode = {
id: id,
source_id: contrib.getAttribute("id"),
type: "contributor",
name: "",
affiliations: [],
fundings: [],
bio: [],
// Not yet supported... need examples
image: "",
deceased: false,
emails: [],
contribution: "",
members: []
};
// Extract contrib type
var contribType = contrib.getAttribute("contrib-type");
// Assign human readable version
contribNode["contributor_type"] = this._contribTypeMapping[contribType];
// Extract role
var role = contrib.querySelector("role");
if (role) {
contribNode["role"] = role.textContent;
}
// Search for author bio and author image
var bio = contrib.querySelector("bio");
if (bio) {
_.each(util.dom.getChildren(bio), function(par) {
var graphic = par.querySelector("graphic");
if (graphic) {
var imageUrl = graphic.getAttribute("xlink:href");
contribNode.image = imageUrl;
} else {
var pars = this.paragraphGroup(state, par);
if (pars.length > 0) {
contribNode.bio = [ pars[0].id ];
}
}
}, this);
}
// Deceased?
if (contrib.getAttribute("deceased") === "yes") {
contribNode.deceased = true;
}
// Extract ORCID
// -----------------
//
// <uri content-type="orcid" xlink:href="http://orcid.org/0000-0002-7361-560X"/>
var orcidURI = contrib.querySelector("uri[content-type=orcid]");
if (orcidURI) {
contribNode.orcid = orcidURI.getAttribute("xlink:href");
}
// Extracting equal contributions
var nameEl = contrib.querySelector("name");
if (nameEl) {
contribNode.name = this.getName(nameEl);
} else {
var collab = contrib.querySelector("collab");
// Assuming this is an author group
if (collab) {
contribNode.name = collab.textContent;
} else {
contribNode.name = "N/A";
}
}
this.extractContributorProperties(state, contrib, contribNode);
// HACK: for cases where no explicit xrefs are given per
// contributor we assin all available affiliations
if (contribNode.affiliations.length === 0) {
contribNode.affiliations = state.affiliations;
}
// HACK: if author is assigned a conflict, remove the redundant
// conflict entry "The authors have no competing interests to declare"
// This is a data-modelling problem on the end of our input XML
// so we need to be smart about it in the converter
if (contribNode.competing_interests.length > 1) {
contribNode.competing_interests = _.filter(contribNode.competing_interests, function(confl) {
return confl.indexOf("no competing") < 0;
});
}
if (contrib.getAttribute("contrib-type") === "author") {
doc.nodes.document.authors.push(id);
}
doc.create(contribNode);
doc.show("info", contribNode.id);
};
this._getEqualContribs = function (state, contrib, contribId) {
var result = [];
var refs = state.xmlDoc.querySelectorAll("xref[rid="+contribId+"]");
// Find xrefs within contrib elements
_.each(refs, function(ref) {
var c = ref.parentNode;
if (c !== contrib) result.push(this.getName(c.querySelector("name")));
}, this);
return result;
};
this.extractContributorProperties = function(state, contrib, contribNode) {
var doc = state.doc;
// Extract equal contributors
var equalContribs = [];
var compInterests = [];
// extract affiliations stored as xrefs
var xrefs = contrib.querySelectorAll("xref");
_.each(xrefs, function(xref) {
if (xref.getAttribute("ref-type") === "aff") {
var affId = xref.getAttribute("rid");
var affNode = doc.getNodeBySourceId(affId);
if (affNode) {
contribNode.affiliations.push(affNode.id);
state.used[affId] = true;
}
} else if (xref.getAttribute("ref-type") === "other") {
// FIXME: it seems *very* custom to interprete every 'other' that way
// TODO: try to find and document when this is applied
console.log("FIXME: please add documentation about using 'other' as indicator for extracting an awardGroup.");
var awardGroup = state.xmlDoc.getElementById(xref.getAttribute("rid"));
if (!awardGroup) return;
var fundingSource = awardGroup.querySelector("funding-source");
if (!fundingSource) return;
var awardId = awardGroup.querySelector("award-id");
awardId = awardId ? ", "+awardId.textContent : "";
// Funding source nodes are looking like this
//
// <funding-source>
// National Institutes of Health
// <named-content content-type="funder-id">http://dx.doi.org/10.13039/100000002</named-content>
// </funding-source>
//
// and we only want to display the first text node, excluding the funder id
var fundingSourceName = fundingSource.childNodes[0].textContent;
contribNode.fundings.push([fundingSourceName, awardId].join(''));
} else if (xref.getAttribute("ref-type") === "corresp") {
var correspId = xref.getAttribute("rid");
var corresp = state.xmlDoc.getElementById(correspId);
if (!corresp) return;
// TODO: a corresp element allows *much* more than just an email
// Thus, we are leaving this like untouched, so that it may be grabbed by extractAuthorNotes()
// state.used[correspId] = true;
var email = corresp.querySelector("email");
if (!email) return;
contribNode.emails.push(email.textContent);
} else if (xref.getAttribute("ref-type") === "fn") {
var fnId = xref.getAttribute("rid");
var fnElem = state.xmlDoc.getElementById(fnId);
var used = true;
if (fnElem) {
var fnType = fnElem.getAttribute("fn-type");
switch (fnType) {
case "con":
contribNode.contribution = fnElem.textContent;
break;
case "conflict":
compInterests.push(fnElem.textContent.trim());
break;
case "present-address":
contribNode.present_address = fnElem.querySelector("p").textContent;
break;
case "equal":
console.log("FIXME: isn't fnElem.getAttribute(id) === fnId?");
equalContribs = this._getEqualContribs(state, contrib, fnElem.getAttribute("id"));
break;
case "other":
// HACK: sometimes equal contribs are encoded as 'other' plus special id
console.log("FIXME: isn't fnElem.getAttribute(id) === fnId?");
if (fnElem.getAttribute("id").indexOf("equal-contrib")>=0) {
equalContribs = this._getEqualContribs(state, contrib, fnElem.getAttribute("id"));
} else {
used = false;
}
break;
default:
used = false;
}
if (used) state.used[fnId] = true;
}
} else {
// TODO: this is a potential place for implementing a catch-bin
// For that, we could push the content of the referenced element into the contrib's catch-bin
console.log("Skipping contrib's xref", xref.textContent);
}
}, this);
// Extract member list for person group
// eLife specific?
// ----------------
if (compInterests.length > 1) {
compInterests = _.filter(compInterests, function(confl) {
return confl.indexOf("no competing") < 0;
});
}
contribNode.competing_interests = compInterests;
var memberList = contrib.querySelector("xref[ref-type=other]");
if (memberList) {
var memberListId = memberList.getAttribute("rid");
var members = state.xmlDoc.querySelectorAll("#"+memberListId+" contrib");
contribNode.members = _.map(members, function(m) {
return this.getName(m.querySelector("name"));
}, this);
}
contribNode.equal_contrib = equalContribs;
contribNode.competing_interests = compInterests;
};
// Parser
// --------
// These methods are used to process XML elements in
// using a recursive-descent approach.
// ### Top-Level function that takes a full NLM tree
// Note: a specialized converter can derive this method and
// add additional pre- or post-processing.
this.document = function(state, xmlDoc) {
var doc = state.doc;
var article = xmlDoc.querySelector("article");
if (!article) {
throw new ImporterError("Expected to find an 'article' element.");
}
// recursive-descent for the main body of the article
this.article(state, article);
this.postProcess(state);
// Rebuild views to ensure consistency
_.each(doc.containers, function(container) {
container.rebuild();
});
return doc;
};
this.postProcess = function(state) {
this.postProcessAnnotations(state);
};
this.postProcessAnnotations = function(state) {
// Creating the annotations afterwards, to make sure
// that all referenced nodes are available
for (var i = 0; i < state.annotations.length; i++) {
var anno = state.annotations[i];
if (anno.target) {
var targetNode = state.doc.getNodeBySourceId(anno.target);
if (targetNode) {
anno.target = targetNode.id;
} else {
// NOTE: I've made this silent because it frequently occurs that no targetnode is
// available (e.g. for inline formulas)
// console.log("Could not lookup targetNode for annotation", anno);
}
}
state.doc.create(state.annotations[i]);
}
};
// Article
// --------
// Does the actual conversion.
//
// Note: this is implemented as lazy as possible (ALAP) and will be extended as demands arise.
//
// If you need such an element supported:
// - add a stub to this class (empty body),
// - add code to call the method to the appropriate function,
// - and implement the handler here if it can be done in general way
// or in your specialized importer.
this.article = function(state, article) {
var doc = state.doc;
// Assign id
var articleId = article.querySelector("article-id");
// Note: Substance.Article does only support one id
if (articleId) {
doc.id = articleId.textContent;
} else {
// if no id was set we create a random one
doc.id = util.uuid();
}
// Extract glossary
this.extractDefinitions(state, article);
// Extract authors etc.
this.extractAffilitations(state, article);
this.extractContributors(state, article);
// Same for the citations, also globally
this.extractCitations(state, article);
// Make up a cover node
this.extractCover(state, article);
// Extract ArticleMeta
this.extractArticleMeta(state, article);
// Populate Publication Info node
this.extractPublicationInfo(state, article);
var body = article.querySelector("body");
if (body) {
this.body(state, body);
}
this.extractFigures(state, article);
this.enhanceArticle(state, article);
};
this.extractDefinitions = function(state /*, article*/) {
var defItems = state.xmlDoc.querySelectorAll("def-item");
_.each(defItems, function(defItem) {
var term = defItem.querySelector("term");
var def = defItem.querySelector("def");
// using hwp:id as a fallback MCP articles don't have def.id set
var id = def.id || def.getAttribute("hwp:id") || state.nextId('definition');
var definitionNode = {
id: id,
type: "definition",
title: term.textContent,
description: def.textContent
};
state.doc.create(definitionNode);
state.doc.show("definitions", definitionNode.id);
});
};
// #### Front.ArticleMeta
//
this.extractArticleMeta = function(state, article) {
var articleMeta = article.querySelector("article-meta");
if (!articleMeta) {
throw new ImporterError("Expected element: 'article-meta'");
}
// <article-id> Article Identifier, zero or more
var articleIds = articleMeta.querySelectorAll("article-id");
this.articleIds(state, articleIds);
// <title-group> Title Group, zero or one
var titleGroup = articleMeta.querySelector("title-group");
if (titleGroup) {
this.titleGroup(state, titleGroup);
}
// <pub-date> Publication Date, zero or more
var pubDates = articleMeta.querySelectorAll("pub-date");
this.pubDates(state, pubDates);
this.abstracts(state, articleMeta);