-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
417 lines (362 loc) · 13.2 KB
/
index.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Just BibTeX</title>
<style>
/* Catppuccin Theme (Mocha variant) */
:root {
--base: #1e1e2e;
/* Base background */
--text: #cdd6f4;
/* Primary text */
--accent: #89b4fa;
/* Accent color for buttons and links */
--accent-hover: #74a7f8;
/* Accent color on hover */
--surface: #313244;
/* Surface color for input fields */
--surface-hover: #45475a;
/* Surface color on hover */
--muted: #6c7086;
/* Muted text */
--error: #f38ba8;
/* Error messages */
}
body {
font-family: sans-serif;
margin: 20px;
background-color: var(--base);
color: var(--text);
}
h1 {
color: var(--text);
margin-bottom: 20px;
}
textarea {
width: 100%;
height: 350px;
border: 1px solid var(--surface);
padding: 10px;
font-family: monospace;
font-size: 14px;
background-color: var(--base);
color: var(--text);
border-radius: 8px;
resize: vertical;
}
#doiInput {
width: 60%;
padding: 10px;
font-size: 16px;
border: 1px solid var(--surface);
border-radius: 8px;
background-color: var(--base);
color: var(--text);
margin-right: 10px;
}
#doiInput::placeholder {
color: var(--muted);
}
button {
font-size: 16px;
padding: 10px 20px;
cursor: pointer;
background-color: var(--accent);
color: var(--base);
border: none;
border-radius: 8px;
transition: background-color 0.2s ease;
}
button:hover {
background-color: var(--accent-hover);
}
.entry {
margin: 10px 0;
}
#entries {
margin-top: 20px;
}
/* Additional styling for buttons inside #entries */
#entries button {
margin-top: 10px;
margin-right: 10px;
}
/* Error message styling */
.error {
color: var(--error);
margin-top: 10px;
}
/* Footer styling */
footer {
margin-top: auto;
text-align: center;
padding: 20px 0;
color: var(--muted);
font-size: 14px;
}
footer a {
color: var(--muted);
text-decoration: none;
transition: color 0.2s ease;
}
footer a:hover {
color: var(--accent);
}
/* GitHub icon styling */
.github-icon {
width: 16px;
height: 16px;
fill: currentColor;
vertical-align: text-bottom;
}
</style>
</head>
<body>
<h1>Just BibTeX</h1>
<input id="doiInput" type="text" placeholder="Enter DOI, arXiv URL, or Journal URL" />
<button onclick="addBibtex()">Fetch Bibtex & Add</button>
<div id="entries"></div>
<!-- Footer -->
<footer>
<a href="https://github.com/ParticularlyPythonicBS/justBibTex" target="_blank" rel="noopener noreferrer">
<!-- GitHub icon -->
<svg class="github-icon" viewBox="0 0 16 16" aria-hidden="true">
<path fill-rule="evenodd"
d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z" />
</svg>
<span>View on GitHub</span>
</a>
</footer>
<script>
function formatBibtex(bib) {
return bib
.replace(/\r\n/g, '\n')
.replace(/\n{2,}/g, '\n\n')
.trim();
}
function loadEntries() {
const saved = localStorage.getItem('bibtexEntries');
return saved ? JSON.parse(saved) : [];
}
function saveEntries(entries) {
localStorage.setItem('bibtexEntries', JSON.stringify(entries));
}
function generateCitationKey(bibtex) {
// Extract the author field
const authorMatch = bibtex.match(/author\s*=\s*{([^}]+)}/);
if (!authorMatch) throw new Error('Author field not found in BibTeX.');
// Extract the first author's name
const authors = authorMatch[1].split(' and ');
const firstAuthor = authors[0].trim();
// Handle "Lastname, Firstname" format
let lastname;
if (firstAuthor.includes(',')) {
// If the name is in "Lastname, Firstname" format
lastname = firstAuthor.split(',')[0].trim();
} else {
// If the name is in "Firstname Lastname" format
const parts = firstAuthor.split(' ');
lastname = parts[parts.length - 1].trim();
}
// Remove non-alphabetic characters from the last name
lastname = lastname.replace(/[^a-zA-Z]/g, '');
// Extract the year field
const yearMatch = bibtex.match(/year\s*=\s*{([^}]+)}/);
if (!yearMatch) throw new Error('Year field not found in BibTeX.');
const year = yearMatch[1].trim();
// Extract the title field
const titleMatch = bibtex.match(/title\s*=\s*{([^}]+)}/);
if (!titleMatch) throw new Error('Title field not found in BibTeX.');
const title = titleMatch[1].trim();
// Extract the first useful word from the title
const stopWords = new Set(['the', 'a', 'an', 'in', 'on', 'at', 'for', 'of', 'and', 'or', 'to', 'with']);
const words = title.split(/\s+/);
let firstUsefulWord = '';
for (const word of words) {
const cleanedWord = word.replace(/[^a-zA-Z]/g, '').toLowerCase();
if (cleanedWord && !stopWords.has(cleanedWord)) {
firstUsefulWord = cleanedWord;
break;
}
}
if (!firstUsefulWord) {
// If no useful word is found, use the first word
firstUsefulWord = words[0].replace(/[^a-zA-Z]/g, '').toLowerCase();
}
// Generate the citation key
return `${lastname.toLowerCase()}${year}${firstUsefulWord}`;
}
async function fetchBibtexFromDOI(doi) {
// Fetch BibTeX from DOI
const bibtexResponse = await fetch(`https://doi.org/${encodeURIComponent(doi)}`, {
headers: { Accept: 'application/x-bibtex' },
});
if (!bibtexResponse.ok) throw new Error('BibTeX not found for this DOI.');
let bibtex = await bibtexResponse.text();
// Generate the citation key
const citationKey = generateCitationKey(bibtex);
// Replace the existing citation key with the standardized one
bibtex = bibtex.replace(/@(\w+){[\w-]+/, `@$1{${citationKey}`);
// Fetch summary using CrossRef API
const crossrefUrl = `https://api.crossref.org/works/${doi}`;
const crossrefResponse = await fetch(crossrefUrl);
if (!crossrefResponse.ok) throw new Error('Failed to fetch summary.');
const crossrefData = await crossrefResponse.json();
const abstractBlock = crossrefData.message.abstract || null;
if (abstractBlock) {
const abstractMatch = abstractBlock.match(/<jats:p>(.*?)<\/jats:p>/);
const abstract = abstractMatch ? abstractMatch[1] : null;
// Add abstract to BibTeX
if (abstract) {
bibtex = bibtex.replace(/\}\s*$/, `,\n abstract = {${abstract}}\n}`);
}
}
return bibtex;
}
async function fetchBibtexFromArxiv(arxivId) {
const response = await fetch(`https://export.arxiv.org/api/query?id_list=${arxivId}`);
if (!response.ok) throw new Error('Failed to fetch arXiv metadata.');
const text = await response.text();
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(text, 'text/xml');
const entry = xmlDoc.querySelector('entry');
if (!entry) throw new Error('No arXiv entry found.');
const title = entry.querySelector('title').textContent.replace(/\n/g, ' ').trim();
const authors = Array.from(entry.querySelectorAll('author name')).map(
(el) => el.textContent.trim()
);
const published = new Date(entry.querySelector('published').textContent);
const year = published.getFullYear();
const summary = entry.querySelector('summary').textContent.trim();
// Generate the citation key
const citationKey = generateCitationKey(
`author = {${authors.join(' and ')}}\nyear = {${year}}\ntitle = {${title}}`
);
const bibtex = `@article{${citationKey},
title = {${title}},
author = {${authors.join(' and ')}},
year = {${year}},
eprint = {${arxivId}},
archivePrefix = {arXiv},
primaryClass = {${entry.querySelector('category').getAttribute('term')}},
journal = {arXiv:${arxivId}},
url = {https://arxiv.org/abs/${arxivId}},
abstract = {${summary}}
}`;
return bibtex;
}
async function fetchBibtexFromUrl(url) {
// Extract DOI from the URL if possible
const doiMatch = url.match(/10\.\d{4,}\/\S+/);
if (doiMatch) {
return await fetchBibtexFromDOI(doiMatch[0]);
}
// Fallback: Use CrossRef API to fetch BibTeX
const response = await fetch(`https://api.crossref.org/works/${encodeURIComponent(url)}/transform/application/x-bibtex`);
if (!response.ok) throw new Error('BibTeX not found for this URL.');
let bibtex = await response.text();
// Generate the citation key
const citationKey = generateCitationKey(bibtex);
// Replace the existing citation key with the standardized one
bibtex = bibtex.replace(/@\w+{[\w-]+/, `@article{${citationKey}`);
// Fetch summary using CrossRef API
const crossrefUrl = `https://api.crossref.org/works/${encodeURIComponent(url)}`;
const crossrefResponse = await fetch(crossrefUrl);
if (!crossrefResponse.ok) throw new Error('Failed to fetch summary.');
const crossrefData = await crossrefResponse.json();
const abstractBlock = crossrefData.message.abstract || null;
if (abstractBlock) {
const abstractMatch = abstractBlock.match(/<jats:p>(.*?)<\/jats:p>/);
const abstract = abstractMatch ? abstractMatch[1] : null;
// Add abstract to BibTeX
if (abstract) {
bibtex = bibtex.replace(/\}\s*$/, `,\n abstract = {${abstract}}\n}`);
}
}
return bibtex;
}
async function addBibtex() {
const input = document.getElementById('doiInput').value.trim();
if (!input) {
alert('Please enter a DOI, arXiv URL, or Journal URL.');
return;
}
try {
let bibtex;
if (/^10\.\d{4,}\/\S+$/.test(input)) {
// Handle DOI
bibtex = await fetchBibtexFromDOI(input);
} else if (/arxiv\.org\/abs\/|^arxiv:/i.test(input)) {
// Handle arXiv URL or ID
const arxivId = input.match(/(\d{4}\.\d{4,5}(v\d+)?)/)?.[0];
if (!arxivId) throw new Error('Invalid arXiv URL or ID.');
bibtex = await fetchBibtexFromArxiv(arxivId);
}
else {
// Handle journal URLs
bibtex = await fetchBibtexFromUrl(input);
}
const entries = loadEntries();
if (entries.includes(bibtex)) {
alert('This entry already exists.');
return;
}
entries.push(bibtex);
saveEntries(entries);
renderEntries();
document.getElementById('doiInput').value = ''; // Clear input
} catch (err) {
alert(err.message);
}
}
function renderEntries() {
const container = document.getElementById('entries');
container.innerHTML = '';
const entries = loadEntries().map(formatBibtex);
const combined = entries.join('\n\n');
const textarea = document.createElement('textarea');
textarea.value = combined;
container.appendChild(textarea);
// Copy button
const copyBtn = document.createElement('button');
copyBtn.textContent = 'Copy';
copyBtn.onclick = () => {
navigator.clipboard.writeText(textarea.value);
};
container.appendChild(copyBtn);
// Download button
const downloadBtn = document.createElement('button');
downloadBtn.textContent = 'Download';
downloadBtn.onclick = () => {
const blob = new Blob([textarea.value], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'bibtex_entries.bib';
a.click();
URL.revokeObjectURL(url);
};
container.appendChild(downloadBtn);
}
// Handle URL-based DOI
async function handleUrlDoi() {
const path = window.location.pathname.slice(1); // Remove leading slash
if (/^10\.\d{4,}\/\S+$/.test(path)) {
try {
const bibtex = await fetchBibtexFromDOI(path);
const entries = [bibtex];
saveEntries(entries);
renderEntries();
} catch (err) {
alert(err.message);
}
}
}
window.onload = () => {
handleUrlDoi(); // Check for DOI in URL
renderEntries(); // Render existing entries
};
</script>
</body>
</html>