|
| 1 | +async function convertBiblio(config, _, utils) { |
| 2 | + const bibResponse = await fetch("citations.bib"); |
| 3 | + const bibContent = bibResponse.status < 400 ? await bibResponse.text() : ""; |
| 4 | + if (!bibContent.trim()) { |
| 5 | + utils.showWarning("Unable to retrieve BibTeX data; skipping citations processing."); |
| 6 | + return; |
| 7 | + } |
| 8 | + |
| 9 | + const Cite = require("citation-js"); |
| 10 | + const cite = await Cite.async(bibContent).catch((error) => { |
| 11 | + utils.showError("Error parsing citations", { details: error.message }); |
| 12 | + return null; |
| 13 | + }); |
| 14 | + if (!cite) return; |
| 15 | + |
| 16 | + const htmlMap = {}; |
| 17 | + cite |
| 18 | + .format("bibliography", { |
| 19 | + template: "APA", |
| 20 | + lang: "en-US", |
| 21 | + format: "html", |
| 22 | + hyperlinks: true, |
| 23 | + asEntryArray: true, |
| 24 | + nosort: true, |
| 25 | + // Add distinct tokens to easily extract content from surrounding div |
| 26 | + prepend: "__BEGIN__", |
| 27 | + append: "__END__", |
| 28 | + }) |
| 29 | + .forEach(([id, html], i) => { |
| 30 | + const { title, URL } = cite.data[i]; |
| 31 | + // TODO: citeproc-js uses <i> for journal/volume; do we want to replace/remove? |
| 32 | + let replacedHtml = html |
| 33 | + .replace(/^.*__BEGIN__/, "") |
| 34 | + .replace(/__END__[\s\S]*$/, "") |
| 35 | + .replace(/<a href/, "URL: <a href") |
| 36 | + // Add <cite> and link around title to match standard ReSpec behavior |
| 37 | + .replace(title, `<cite>${URL ? `<a href="${URL}">` : ""}${title}${URL ? "</a>" : ""}</cite>`); |
| 38 | + htmlMap[id] = replacedHtml; |
| 39 | + }); |
| 40 | + |
| 41 | + // Populate localBiblio enough for ReSpec to populate dl; contents of each dd will be replaced |
| 42 | + config.localBiblio = {}; |
| 43 | + for (const entry of cite.data) { |
| 44 | + config.localBiblio[entry.id] = { |
| 45 | + href: entry.URL, |
| 46 | + title: entry.title, |
| 47 | + // Allow access to preferred HTML representation in postProcess |
| 48 | + toString: () => htmlMap[entry.id], |
| 49 | + }; |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +function renderBiblio(config, _, utils) { |
| 54 | + for (const [id, entry] of Object.entries(config.localBiblio)) { |
| 55 | + const dd = document.querySelector(`dt#bib-${id.toLowerCase()} + dd`); |
| 56 | + if (dd) dd.innerHTML = entry.toString(); |
| 57 | + } |
| 58 | +} |
0 commit comments