Skip to content

Instantly share code, notes, and snippets.

@seanmcn
Created March 12, 2015 05:29
Show Gist options
  • Save seanmcn/935c30eb42c84368feca to your computer and use it in GitHub Desktop.
Save seanmcn/935c30eb42c84368feca to your computer and use it in GitHub Desktop.
CitationsJS
define(['jquery','citeproc'],function(require){
var cite = {};
var citations = {};
cite.renderCitations = function(){
var cslScheme = $("#id-from-csl-scheme-dropdown").val();
renderBib(cslScheme);
}
// Get the citations that we are supposed to render, in the CSL-json format, I switched async to false here for my setup, btu true is probably fine
$.ajax({
async: true,
type: 'GET',
url: '/citations/data/',
success: function(data) {
if(data != 'error') {
citations = data;
}
else {
citations = null;
}
}
});
// Initialize a system object, which contains two methods needed by the
// engine.
var citeprocSys = {
// Given a language tag in RFC-4646 form, this method retrieves the
// locale definition file. This method must return a valid *serialized*
// CSL locale. (In other words, an blob of XML as an unparsed string. The
// processor will fail on a native XML object or buffer).
retrieveLocale: function (lang){
$.ajax({
async: false,
type: 'GET',
url: '/vendor/citeproc-js/locale/locales-' + lang + '.xml',
success: function(data) {
if(data != 'error') {
locale = data;
}
else {
locale = null;
}
}
});
return locale;
},
// Given an identifier, this retrieves one citation item. This method
// must return a valid CSL-JSON object.
retrieveItem: function(id){
return citations[id];
}
};
// Given the identifier of a CSL style, this function instantiates a CSL.Engine
// object that can render citations in that style.
function getProcessor(styleID) {
var styleAsText;
// Here we are just using jQuery again to get the CSL files we've downloaded
$.ajax({
async: true,
type: 'GET',
url: '/csl/'+styleID + '.csl',
success: function(data) {
if(data) {
styleAsText = data;
}
else {
styleAsText = null;
}
}
});
// Instantiate and return the engine
return new CSL.Engine(citeprocSys, styleAsText);
};
// This runs at document ready, and renders the bibliography
function renderBib(cslScheme) {
var bibDivs = document.getElementsByClassName('bib-div-class');
for (var i = 0, ilen = bibDivs.length; i < ilen; ++i) {
var bibDiv = bibDivs[i];
var citeproc = getProcessor(cslScheme);
var itemIDs = [];
for (var key in citations) {
itemIDs.push(key);
}
citeproc.updateItems(itemIDs);
var bibResult = citeproc.makeBibliography();
bibDiv.innerHTML = bibResult[1].join('\n');
}
}
return cite;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment