/
z2csl.js
327 lines (285 loc) · 9.81 KB
/
z2csl.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
Zotero.Z2CSL = {
cslVars: null,
init: function() {
//load utilities.js so we can fetch the CSL mappings
var context = { Zotero: {}, XRegExp: {} };
Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
.getService(Components.interfaces.mozIJSSubScriptLoader)
.loadSubScript("chrome://zotero/content/xpcom/utilities/schema.js", context);
this.cslTypeMap = Zotero.Schema.CSL_TYPE_MAPPINGS;
this.cslFieldMap = Zotero.Schema.CSL_TEXT_MAPPINGS;
if (Zotero.version.charAt(0)<5) {
// In Zotero 4.0 version instead of versionNumber is used
// see https://github.com/zotero/zotero/blob/4.0/chrome/content/zotero/xpcom/utilities.js#L1515
this.cslFieldMap["version"] = ["version"];
}
this.cslDateMap = Zotero.Schema.CSL_DATE_MAPPINGS;
this.cslCreatorMap = Zotero.Schema.CSL_NAME_MAPPINGS;
},
exportMappings: function() {
var map = {name:'map', childNodes:[] };
this.debug("Compiling header...");
//add current Zotero version and date of creation
map.childNodes.push({ name:'zoteroVersion',
attributes: { value: Zotero.version }
});
map.childNodes.push({ name:'date',
attributes: { value: (new Date()).toUTCString()}
});
var type, fields, baseField;
var nodes = [];
this.debug("Creating item type map...");
this.debug("Checking on debug")
this.zoteroTypes = Zotero.ItemTypes.getTypes();
for(var i=0, n=this.zoteroTypes.length; i<n; i++) {
type = {name:'typeMap',
attributes:{
zType:this.zoteroTypes[i].name,
cslType:this.cslTypeMap[this.zoteroTypes[i].name]
},
childNodes:[]
};
this.debug("* Adding fields for " + this.zoteroTypes[i].name);
fields = Zotero.ItemFields.getItemTypeFields(this.zoteroTypes[i].id);
var fieldMap, baseField;
for(var j=0, m=fields.length; j<m; j++) {
fieldMap = {
name:'field',
attributes:{
label:Zotero.ItemFields.getLocalizedString(this.zoteroTypes[i].id,fields[j]),
value:Zotero.ItemFields.getName(fields[j])
}
};
//Also retrieve base field so we can map to CSL
if(!Zotero.ItemFields.isBaseField(fields[j])) {
baseField = Zotero.ItemFields.getBaseIDFromTypeAndField(this.zoteroTypes[i].id, fields[j]);
if(baseField !== false) {
fieldMap.attributes.baseField = Zotero.ItemFields.getName(baseField);
}
}
type.childNodes.push(fieldMap);
}
//add valid creator types
this.debug("* Adding creator types");
var creators = Zotero.CreatorTypes.getTypesForItemType(this.zoteroTypes[i].id);
var primaryID = Zotero.CreatorTypes.getPrimaryIDForType(this.zoteroTypes[i].id);
var creator, creatorNodes;
if(creators.length) {
creatorNodes = {name:'field', attributes:{ value:'creator'}, childNodes: []};
for(var j=0, m=creators.length; j<m; j++) {
creator = {
name:'creatorType',
attributes:{
label:Zotero.getString('creatorTypes.' + creators[j].name),
value:creators[j].name
}
};
//1 is author anyway
if(primaryID != 1 && creators[j].id == primaryID) {
creator.attributes.baseField = 'author';
}
creatorNodes.childNodes.push(creator);
}
type.childNodes.push(creatorNodes);
}
nodes.push(type);
}
map.childNodes.push({name:'zTypes', childNodes:nodes}) ;
this.debug("Mapping zotero fields to CSL...");
nodes = [];
var f;
for(f in this.cslFieldMap) {
for(var i=0, n=this.cslFieldMap[f].length; i<n; i++) {
nodes.push({name:'map', attributes:{zField: this.cslFieldMap[f][i], cslField: f}});
}
}
//add dates
this.debug("...adding date fields...");
for(f in this.cslDateMap) {
nodes.push({name:'map', attributes:{zField: this.cslDateMap[f], cslField: f}});
}
map.childNodes.push({name:'cslFieldMap', childNodes:nodes});
//add csl creator map
this.debug("Mapping creators...");
nodes = [];
for(f in this.cslCreatorMap) {
nodes.push({name:'map', attributes:{zField: f, cslField: this.cslCreatorMap[f]}});
}
map.childNodes.push({name:'cslCreatorMap', childNodes:nodes});
//add internal remapping that occurs within citeproc.js
//see http://forums.zotero.org/discussion/26312/csl-variables-used-in-zotero-but-not-in-documentation/
this.debug("Adding re-mappings...");
nodes = [];
nodes.push({ name:'remap', attributes:{
citeprocField: 'shortTitle',
cslUsage: 'title-short or <text variable="title" form="short"/>',
descKey: 'title-short'
}});
nodes.push({ name:'remap', attributes:{
citeprocField: 'journalAbbreviation',
cslUsage: 'container-title-short or <text variable="container-title" form="short"/>',
descKey: 'container-title-short'
}});
map.childNodes.push({name:'citeprocJStoCSLmap', childNodes:nodes});
this.debug("Fetching CSL variable descriptions...");
var me = this;
this.retrieveCSLVariables(function(cslVars) {
map.childNodes.push(cslVars);
me.writeFile(me.jsonToXML(map));
});
},
writeFile: async function(data) {
//output XML data
this.debug("Opening File Picker...");
const FilePicker = require('zotero/filePicker').default;
let fp = new FilePicker();
fp.init(window, "Select a file to save to", fp.modeSave);
fp.appendFilters(fp.filterAll);
// fp.appendFilters("XML", ".xml");
let res = await fp.show();
if (res != fp.returnCancel) {
this.debug("Writing data to file...");
this.debug(data)
var file = fp.file;
await Zotero.File.putContentsAsync(file, data);
}
this.debug("Done");
},
retrieveCSLVariables: function(callback) {
if(this.cslVars) callback(this.cslVars);
var url = 'https://docs.citationstyles.org/en/stable/specification.html';
var me = this;
Zotero.HTTP.processDocuments(url, function(doc) {
me.debug("...got data from server...");
var cslVars = { name: 'cslVars', childNodes: [] };
var namespaces = {"xhtml": "http://www.w3.org/1999/xhtml"};
//types
me.debug("* getting type descriptions...");
var types = Zotero.Utilities.xpath(doc, '//xhtml:div[@id="appendix-iii-types"]/xhtml:ul/xhtml:li', namespaces);
var t = { name: 'itemTypes', childNodes: [] };
for(var i=0, n=types.length; i<n; i++) {
t.childNodes.push({
name: 'type',
attributes: { name: types[i].textContent }
});
}
cslVars.childNodes.push(t);
//variables
me.debug("* getting variable descriptions...");
var variables = Zotero.Utilities.xpath(doc, '//xhtml:div[@id="appendix-iv-variables"]', namespaces)[0];
if(!variables) throw new Error('Could not locate CSL variables');
var varXPath = {
standard: './xhtml:div[@id="standard-variables"]/xhtml:dl/*[self::xhtml:dt or self::xhtml:dd]',
number: './/xhtml:div[@id="number-variables"]/xhtml:dl/*[self::xhtml:dt or self::xhtml:dd]',
date: './xhtml:div[@id="date-variables"]/xhtml:dl/*[self::xhtml:dt or self::xhtml:dd]',
name: './xhtml:div[@id="name-variables"]/xhtml:dl/*[self::xhtml:dt or self::xhtml:dd]'
};
var vars = { name: 'vars', childNodes: [] };
/**
* At the time of writing, the following are not found on citationstyles.org page.
* We add a description to them later, but make sure we don't overwrite or double-up
* on these fields
* see http://forums.zotero.org/discussion/26312/csl-variables-used-in-zotero-but-not-in-documentation/
*/
me.debug("* adding missing descriptions...");
var missing = {
'language': {
type: 'standard',
description: 'Language code. Not intended for display purposes.'
}
};
var m, node;
for(var v in varXPath) {
var vbt = Zotero.Utilities.xpath(variables, varXPath[v], namespaces);
for(var i=0, n=vbt.length; i<n; i+=2) {
node = {
name: 'var',
attributes: {
name: vbt[i].textContent,
type: v,
description: me.escapeQuotes(
Zotero.Utilities.trimInternal(vbt[i+1].textContent)
)
}
};
//remove missing items that were found
if(missing[node.attributes.name]) {
delete missing[node.attributes.name];
}
vars.childNodes.push(node);
}
}
//fill in missing fields
for(var field in missing) {
vars.childNodes.push({
name: 'var',
attributes: {
name: field,
type: missing[field].type,
description: missing[field].description
}
});
}
cslVars.childNodes.push(vars);
me.cslVars = cslVars;
callback(cslVars);
},
null,
function(e) {
throw e;
}
);
},
escapeQuotes: function(str) {
return str.replace(/"/g, '"');
},
jsonToXML: function(obj, indent) {
if(typeof(attributes) != 'object') {
attributes = {};
}
var indentDelim = ' '; //two spaces
var xml = '';
//top level
if(typeof(indent) == 'undefined') {
xml += '<?xml version="1.0" encoding="UTF-8"?>\n<?xml-stylesheet type="text/xsl" href="typeMap.xsl"?>\n\n';
indent = '';
} else {
indent += indentDelim;
}
xml += indent + '<' + obj.name;
var attr;
if(obj.attributes) {
for(attr in obj.attributes) {
xml += ' ' + attr + '="' + this.stringify(obj.attributes[attr]) + '"';
}
}
if(obj.value || obj.childNodes) {
xml += '>';
if(obj.value) {
xml += this.stringify(obj.value);
} else if(obj.childNodes) {
xml += '\n';
for(var i=0, n=obj.childNodes.length; i<n; i++) {
xml += this.jsonToXML(obj.childNodes[i], indent) + '\n';
}
xml += indent;
}
xml += '</' + obj.name + '>';
} else {
xml += ' />';
}
return xml;
},
stringify: function(obj) {
if(typeof(obj) == 'undefined' || typeof(obj) == 'null') {
return '';
} else {
return '' + obj;
}
},
debug: function(msg) {
Zotero.debug("z2csl: " + msg);
}
};
// Initialize the utility
window.addEventListener('load', function(e) { Zotero.Z2CSL.init(); }, false);