Skip to content

Instantly share code, notes, and snippets.

@abalter
Last active August 28, 2024 20:51
Show Gist options
  • Save abalter/63c49d9dc8a6c96ae0bc023b50c4ce1f to your computer and use it in GitHub Desktop.
Save abalter/63c49d9dc8a6c96ae0bc023b50c4ce1f to your computer and use it in GitHub Desktop.
Process citations in <cite> tags and format them. Also add tooltips to preview the full reference.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.tooltip {
position: relative;
cursor: pointer;
}
.tooltip-content {
display: none;
position: absolute;
background: #fff;
color: #000;
/* padding: 5px; */
/* border-radius: 5px; */
white-space: pre-wrap;
z-index: 1000;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/citation-js/0.7.14/citation.js"></script>
<script src="util.js" type="module"></script>
</head>
<body>
<section>
<h1>Important Text</h1>
<p>Lorem ipsum odor amet, consectetuer adipiscing elit. Sed conubia mauris morbi suscipit dis senectus eleifend
at ligula. Quis interdum etiam imperdiet cursus, eu sollicitudin. Ligula sagittis porttitor sit consequat
vehicula. Litora netus felis aptent consequat odio accumsan rhoncus. Nullam id integer nibh morbi tincidunt
eros nisi fringilla<cite>Loomes2017</cite>. Egestas gravida habitasse arcu quisque metus cursus aliquet
ipsum libero. Viverra inceptos porta montes aenean ullamcorper sollicitudin. Dis odio mus velit sapien
finibus nec nostra. Sapien donec sapien feugiat montes lectus
<cite>Caldwell-Harris2023,GillespieLynch2017</cite>.
</p>
<p>Etiam mauris dignissim a volutpat rutrum auctor ac venenatis. Justo fermentum volutpat taciti maximus
sagittis arcu lobortis. Cras a vitae conubia aliquam dapibus dignissim consequat neque consectetur. Ad
torquent nisi senectus; fames venenatis dolor <cite>Mantzalas2022,Caldwell-Harris2023</cite>. Consectetur
vulputate scelerisque efficitur; aliquet duis risus. Rhoncus risus eget congue leo primis auctor. Vel
penatibus venenatis nostra eu metus posuere pellentesque congue
<cite>Pellicano2014,GillespieLynch2017,Loomes2017</cite>.
</p>
</section>
<section id="bibliography">
<h1>References</h1>
<section id="references-list"></section>
</section>
<script type="module">
import {computePosition, shift, flip, offset} from 'https://cdn.jsdelivr.net/npm/@floating-ui/[email protected]/+esm';
document.addEventListener('DOMContentLoaded', async function () {
//window.onload = async function () {
let Cite = require('citation-js');
console.log(`Cite: ${Cite}`);
// Sample BibTeX string for demonstration
let bibtex = `
@article{Caldwell-Harris2023,
title = {Why {{Autistic Sociality}} Is {{Different}}: {{Reduced Interest}} in {{Competing}} for {{Social Status}}},
shorttitle = {Why {{Autistic Sociality}} Is {{Different}}},
author = {Caldwell-Harris, Catherine L and Schwartz, Anna M},
date = {2023-12-13},
journaltitle = {Ought: The Journal of Autistic Culture},
shortjournal = {Ought: The Journal of Autistic Culture},
volume = {5},
number = {1},
issn = {2833-1508},
doi = {10.9707/2833-1508.1145},
url = {https://scholarworks.gvsu.edu/ought/vol5/iss1/12},
urldate = {2024-07-30},
langid = {english}
}
@article{GillespieLynch2017,
title = {Whose {{Expertise Is It}}? {{Evidence}} for {{Autistic Adults}} as {{Critical Autism Experts}}},
shorttitle = {Whose {{Expertise Is It}}?},
author = {Gillespie-Lynch, Kristen and Kapp, Steven K. and Brooks, Patricia J. and Pickens, Jonathan and Schwartzman, Ben},
date = {2017-03},
journaltitle = {Frontiers in Psychology},
volume = {8},
eprint = {28400742},
eprinttype = {pmid},
pages = {438},
issn = {1664-1078},
doi = {10.3389/fpsyg.2017.00438},
abstract = {Autistic and non-autistic adults' agreement with scientific knowledge about autism, how they define autism, and their endorsement of stigmatizing conceptions of autism has not previously been examined. Using an online survey, we assessed autism knowledge and stigma among 636 adults with varied relationships to autism, including autistic people and nuclear family members. Autistic participants exhibited more scientifically based knowledge than others. They were more likely to describe autism experientially or as a neutral difference, and more often opposed the medical model. Autistic participants and family members reported lower stigma. Greater endorsement of the importance of normalizing autistic people was associated with heightened stigma. Findings suggest that autistic adults should be considered autism experts and involved as partners in autism research.},
pmcid = {PMC5368186}
}
@article{Loomes2017,
title = {What {{Is}} the {{Male-to-Female Ratio}} in {{Autism Spectrum Disorder}}? {{A Systematic Review}} and {{Meta-Analysis}}},
shorttitle = {What {{Is}} the {{Male-to-Female Ratio}} in {{Autism Spectrum Disorder}}?},
author = {Loomes, Rachel and Hull, Laura and Mandy, William Polmear Locke},
date = {2017-06},
journaltitle = {Journal of the American Academy of Child and Adolescent Psychiatry},
volume = {56},
number = {6},
eprint = {28545751},
eprinttype = {pmid},
pages = {466--474},
issn = {1527-5418},
doi = {10.1016/j.jaac.2017.03.013},
abstract = {OBJECTIVE: To derive the first systematically calculated estimate of the relative proportion of boys and girls with autism spectrum disorder (ASD) through a meta-analysis of prevalence studies conducted since the introduction of the DSM-IV and the International Classification of Diseases, Tenth Revision. METHOD: Preferred Reporting Items for Systematic Reviews and Meta-Analyses (PRISMA) guidelines were followed. The Medline, Embase, and PsycINFO databases were searched, and study quality was rated using a risk-of-bias tool. Random-effects meta-analysis was used. The pooled outcome measurement was the male-to-female odds ratio (MFOR), namely the odds of being male in the group with ASD compared with the non-ASD group. In effect, this is the ASD male-to-female ratio, controlling for the male-to-female ratio among participants without ASD. RESULTS: Fifty-four studies were analyzed, with 13,784,284 participants, of whom 53,712 had ASD (43,972 boys and 9,740 girls). The overall pooled MFOR was 4.20 (95\% CI 3.84-4.60), but there was very substantial between-study variability (I2 = 90.9\%). High-quality studies had a lower MFOR (3.32; 95\% CI 2.88-3.84). Studies that screened the general population to identify participants regardless of whether they already had an ASD diagnosis showed a lower MFOR (3.25; 95\% CI 2.93-3.62) than studies that only ascertained participants with a pre-existing ASD diagnosis (MFOR 4.56; 95\% CI 4.10-5.07). CONCLUSION: Of children meeting criteria for ASD, the true male-to-female ratio is not 4:1, as is often assumed; rather, it is closer to 3:1. There appears to be a diagnostic gender bias, meaning that girls who meet criteria for ASD are at disproportionate risk of not receiving a clinical diagnosis.},
langid = {english},
keywords = {autism spectrum disorder,Autism Spectrum Disorder,Cross-Sectional Studies,epidemiology,Female,Humans,Male,male-to-female ratio,meta-analysis,Population Surveillance,sex difference,Sex Factors}
}
@article{Mantzalas2022,
title = {What {{Is Autistic Burnout}}? {{A Thematic Analysis}} of {{Posts}} on {{Two Online Platforms}}},
shorttitle = {What {{Is Autistic Burnout}}?},
author = {Mantzalas, Jane and Richdale, Amanda L. and Adikari, Achini and Lowe, Jennifer and Dissanayake, Cheryl},
date = {2022-03},
journaltitle = {Autism in Adulthood},
volume = {4},
number = {1},
pages = {52--65},
publisher = {Mary Ann Liebert, Inc., publishers},
issn = {2573-9581},
doi = {10.1089/aut.2021.0021},
url = {https://www.liebertpub.com/doi/10.1089/aut.2021.0021},
urldate = {2024-06-07},
abstract = {Background: Compared with adults in the general population, autistic adults are more likely to experience poor mental health, which can contribute to increased suicidality. While the autistic community has long identified autistic burnout as a significant mental health risk, to date, only one study has been published. Early research has highlighted the harmful impact of autistic burnout among autistic adults and the urgent need to better understand this phenomenon. Methods: To understand the lived experiences of autistic adults, we used data scraping to extract public posts about autistic burnout from 2 online platforms shared between 2005 and 2019, which yielded 1127 posts. Using reflexive thematic analysis and an inductive “bottom-up” approach, we sought to understand the etiology, symptoms, and impact of autistic burnout, as well as prevention and recovery strategies. Two autistic researchers with self-reported experience of autistic burnout reviewed the themes and provided insight and feedback. Results: We identified eight primary themes and three subthemes across the data. (1) Systemic, pervasive lack of autism awareness. (1.1) Discrimination and stigma. (2) A chronic or recurrent condition. (3) Direct impact on health and well-being. (4) A life unlived. (5) A blessing in disguise? (6) Self-awareness and personal control influence risk. (6.1) “You need enough balloons to manage the weight of the rocks.” (7) Masking: Damned if you do, damned if you don't. (8) Ask the experts. (8.1) Stronger together. The overarching theme was that a pervasive lack of awareness and stigma about autism underlie autistic burnout. Conclusions: We identified a set of distinct yet interrelated factors that characterize autistic burnout as a recurring condition that can, directly and indirectly, impact autistic people's functioning, mental health, quality of life, and well-being. The findings suggest that increased awareness and acceptance of autism could be key to burnout prevention and recovery.}
}
@article{Pellicano2014,
title = {What Should Autism Research Focus upon? {{Community}} Views and Priorities from the {{United Kingdom}}},
shorttitle = {What Should Autism Research Focus Upon?},
author = {Pellicano, Elizabeth and Dinsmore, Adam and Charman, Tony},
date = {2014-10},
journaltitle = {Autism},
shortjournal = {Autism},
volume = {18},
number = {7},
eprint = {24789871},
eprinttype = {pmid},
pages = {756--770},
issn = {1362-3613},
doi = {10.1177/1362361314529627},
url = {https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4230972/},
urldate = {2024-08-01},
abstract = {The rise in the measured prevalence of autism has been accompanied by much new research and research investment internationally. This study sought to establish whether the pattern of current UK autism research funding maps on to the concerns of the autism community. Interviews and focus groups were conducted with autistic adults, family members, practitioners and researchers to identify their priorities for research. We also captured the views of a large number of stakeholders via an online survey. There was a clear disparity between the United Kingdom’s pattern of funding for autism research and the priorities articulated by the majority of participants. There was general consensus that future priorities for autism research should lie in those areas that make a difference to people’s day-to-day lives. There needs to be greater involvement of the autism community both in priority setting and in research more broadly to ensure that resources reach where they are most needed and can make the most impact.},
pmcid = {PMC4230972}
}`;
console.log(`bibtex: ${bibtex}`);
let fetchFile = async function (url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.text(); // or response.json(), response.blob() etc.
return data; // return the fetched data
} catch (error) {
console.error('There has been a problem with your fetch operation:', error);
}
}
let loadReferences = async function (constructor, library_file) {
let library_data = await fetchFile(library_file);
let library = new Cite(library_data);
return library;
}
let loadStyles = async function (constructor, styles) {
for (const style of styles) { // Use a for...of loop to properly await each fetch
console.log(`CSL Name: ${style.csl_name}, Style Name: ${style.style_name}`);
// const url = `https://raw.githubusercontent.com/citation-style-language/styles/master/${style.csl_name}.csl`;
const url = `https://www.zotero.org/styles/${style.csl_name}`;
console.log(`CSL Filename: ${url}`);
let style_csl = await fetchFile(url); // Await the fetchFile function
console.log(style_csl);
console.log(style.style_name);
constructor.plugins.config.get('@csl').templates.add(style.style_name, style_csl);
}
}
let formatCitation = function (
raw_citation,
type,
format,
template
) {
let formatted_citation = library.format(type, {
entry: raw_citation.split(",").map(x => x.trim()),
format: format,
template: template,
lang: 'en-US'
});
return formatted_citation;
}
// Usage
await loadStyles(Cite, [
{csl_name: 'apa', style_name: 'apa'},
{csl_name: 'american-medical-association', style_name: 'ama'},
{csl_name: 'chicago-author-date', style_name: 'chicago'}
]);
// Create the citation - js
let citationInstance = new Cite(bibtex);
console.log(citationInstance);
function getCitation(citationInstance, citation_id, type, style, format) {
console.log({citationInstance, citation_id, type, style, format});
if (type === "inline") {
return citationInstance.format('citation', {
entry: citation_id,
format: 'html',
template: style,
lang: 'en-US'
});
} else if (type === "bibliography") {
return citationInstance.format('bibliography', {
entry: citation_id,
format: 'text',
template: style,
lang: 'en-US'
});
}
return "";
}
async function formatCitations() {
console.log("formatCitations");
// Find all <cite> elements in the document
const citeElements = document.querySelectorAll('cite');
citeElements.forEach(el => {
const citation_ids = el.innerText.split(',').map(id => id.trim());
// Create inline citation HTML
const inlineCitations = citation_ids.map(id => getCitation(citationInstance, id, "inline", 'chicago', "html")).join(', ');
// Create bibliography list for tooltip
const bibliographyList = citation_ids.map(id => `<li>${getCitation(citationInstance, id, "bibliography", 'apa', "html")}</li>`).join('');
// Replace innerHTML with inline citations
el.innerHTML = inlineCitations;
// Create tooltip content
const tooltipContent = document.createElement('div');
tooltipContent.classList.add('tooltip-content');
tooltipContent.innerHTML = `<ul>${bibliographyList}</ul>`;
// Append tooltip content to the cite element
el.appendChild(tooltipContent);
el.classList.add('tooltip');
// Use Floating UI to manage tooltip position
el.addEventListener('mouseenter', () => {
tooltipContent.style.display = 'block';
computePosition(el, tooltipContent, {
placement: 'top',
middleware: [
offset({mainAxis: 10}), // Correct usage of offset
flip(),
shift({padding: 5})
],
}).then(({x, y}) => {
Object.assign(tooltipContent.style, {
left: `${x}px`,
top: `${y}px`
});
}).catch(error => {
console.error("Error computing position:", error);
});
});
el.addEventListener('mouseleave', () => {
tooltipContent.style.display = 'none';
});
});
}
// Execute the function after the DOM is fully loaded
formatCitations();
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment