-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
references.ts
475 lines (398 loc) · 18.7 KB
/
references.ts
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
import { renderExplicitDate, formatNumberString, asAttr, isolate, ifSet } from './helpers';
import { BiblioRef, Reference, Date, Author, LStr, Periodical, referenceValidator, Book } from './references-schema';
import ordinal from 'ordinal';
import ISBN from 'isbn3';
export function renderReference(ref: BiblioRef): string {
const { id, type } = ref;
let extraItemTypes = "";
if ('volume' in ref) {
extraItemTypes += ' https://schema.org/PublicationVolume';
}
return renderWarningsAndNotes(ref)
+ `<p itemscope itemtype="${itemtypes[type]}${extraItemTypes}" id="ref-${id}" itemprop="citation">`
+ renderAuthors(ref)
+ renderDate(ref)
+ renderTitle(ref)
+ renderEditor(ref)
+ renderTranslator(ref)
+ renderSeries(ref, '; ', '')
+ '. '
+ renderPatentBits(ref)
+ renderContainer(ref)
+ (ref.type === 'thesis' ? ` ${ref.genre}, ` : '')
+ (('publisher' in ref || 'publisher-place' in ref)
? `<span itemprop="publisher" itemscope itemtype="https://schema.org/Organization">${renderPublisher(ref)}</span>`
: '')
+ renderISBN(ref)
+ '</p>';
}
const itemtypes = {
'article-journal': 'https://schema.org/ScholarlyArticle',
'paper-conference': 'https://schema.org/ScholarlyArticle',
'book': 'https://schema.org/Book',
'thesis': 'https://schema.org/Thesis',
'webpage': 'https://schema.org/WebPage',
'manuscript': 'https://schema.org/Manuscript',
'document': 'https://schema.org/CreativeWork',
'article-newspaper': 'https://schema.org/Article',
'article-magazine': 'https://schema.org/Article',
'chapter': 'https://schema.org/Chapter',
'patent': 'https://schema.org/CreativeWork',
} as const;
function renderWarningsAndNotes(reference: Reference) {
let result = '';
if (reference.warnings) {
result += `<aside class="reference-warning footnote">${reference.warnings}</aside>`;
}
if (reference.notes) {
result += `<aside class="reference-note footnote">${reference.notes}</aside>`;
}
return result;
};
function renderPatentBits(reference: Reference) {
if (reference.type !== 'patent') return '';
const filed = reference.filed ? renderExplicitDate(reference.filed, false) : '';
const issued = reference.issued ? renderExplicitDate(reference.issued, false) : '';
return (
(reference.patentNumber
? `Patent ${formatNumberString(reference.patentNumber)}${ifSet(reference.applicationNumber, ` (application ${formatNumberString(reference.applicationNumber || "")}`)}.`
: ifSet(reference.applicationNumber, `Patent application ${formatNumberString(reference.applicationNumber || "")}.`))
+ ifSet(filed, ` Filed ${filed}.`)
+ ifSet(issued, ` Issued ${issued}.`)
);
}
function renderSeries(ref: Reference, lead: string, trail: string) {
if (!('series' in ref) || !ref.series) {
return '';
}
const s = ref.series;
let title = renderLStr(s.title, 'span', {itemprop: 'name'}, {itemprop: 'alternateName'});
if (s.URL) {
title = `<a href="${s.URL}" itemprop="url">${title}</a>`;
}
return lead
+ `<span itemscope itemtype="https://schema.org/BookSeries" itemprop="isPartOf">`
+ title
+ ifSet(s.ISSN, i => ` (<abbr class="initialism">ISSN</abbr> <span itemprop="issn">${i}</span>)`)
+ [
ifSet(s.volume, v => ` volume ${v}`),
ifSet(s.number, n => ` number ${n}`)
].filter(x => x).join(', ')
+ ifSet(s.editor, e => `, series editor${e.length > 1 ? 's' : ''} ${renderPeople(e, false, false, 'editor')}`)
+ '</span>'
+ trail;
}
function renderTitle(reference: Reference) {
const archiveURL =
'archive-URL' in reference
? ` [<a itemprop="archivedAt" href="${reference['archive-URL']}">archived</a>]`
: '';
let linkedTitle: LStr = '';
if (reference.URL) {
if (typeof reference.title === 'string') {
linkedTitle = `<a itemprop="url" href="${reference.URL}">${reference.title}</a>`;
} else {
linkedTitle = {
value: `<a itemprop="url" href="${reference.URL}">${reference.title.value}</a>`,
lang: reference.title.lang,
alt: reference.title.alt,
};
}
} else {
linkedTitle = reference.title;
}
if (reference.type === 'book' || reference.type === 'thesis') {
return renderLStr(linkedTitle, 'cite', {itemprop: 'name'}, {itemprop: 'alternateName'})
+ archiveURL
+ ifSet(reference.volume, v =>
` volume <span itemprop="volumeNumber">${formatNumberString(v)}</span>`
+ (('volume-title' in reference && reference['volume-title']) ? `: ‘${renderLStr(reference['volume-title'], 'span', {})}’` : '')
)
+ ('edition' in reference && reference['edition'] ? ` (<span itemprop="bookEdition">${ordinal(reference['edition'])} edition</span>)` : '');
} else {
return '‘'
+ renderLStr(linkedTitle, 'span', { itemprop: 'name headline' }, { itemprop: 'alternateName'})
+ '’'
+ archiveURL;
}
}
function renderBook(book: Book, itemprop: string) {
const extraItemTypes = 'volume' in book ? ' https://schema.org/PublicationVolume' : ''
return `<span itemscope itemtype="${itemtypes.book}${extraItemTypes}" itemprop="${itemprop}">`
+ renderTitle(book)
+ ('author' in book && book.author ? ', ' + renderPeople(book.author, false, false, 'author') : '')
+ ('editor' in book && book.editor ? ', edited by ' + renderPeople(book.editor, false, false, 'editor') : '')
+ renderSeries(book, '; ', '')
+ '. '
+ `<span itemprop="publisher" itemscope itemtype="https://schema.org/Organization">${renderPublisher(book)}</span>`
+ renderISBN(book)
+ '</span>';
}
export function renderLStr(lStr: LStr, tag: string, attributes: Record<string, string|undefined>, altAttributes?: Record<string, string|undefined>) {
const value = typeof lStr == 'string' ? lStr : lStr.value;
const lang = typeof lStr == 'string' ? undefined : lStr.lang;
const atts = Object.entries(attributes).map(([k, v]) => asAttr(k, v)).join('');
const result = isolate(`<${tag}${atts}${asAttr('lang', lang)}>${value}</${tag}>`);
if (typeof lStr == 'object' && lStr.alt) {
const attributes =
altAttributes
? Object.entries(altAttributes).map(([k, v]) => asAttr(k, v)).join('')
: '';
return result + ` [<span${attributes}>${lStr.alt}</span>]`;
}
return result;
}
const renderAuthors = (reference: Reference) => {
if (reference.author) {
return `${renderPeople(reference.author, true, false, 'author')} `;
} else if ('editor' in reference && reference.editor) {
const plural = reference.editor.length > 1 ? 's' : '';
return `${renderPeople(reference.editor, true, false, 'editor')} (editor${plural}) `;
} else if ('publisher' in reference && reference.publisher) {
return `<span itemscope itemtype="https://schema.org/Organization" itemprop="author">`
+ renderLStr(reference.publisher, 'span', {itemprop: 'name', class: 'noun'}, {itemprop: 'alternateName'})
+ '</span> (publisher) ';
/*
} else if ('in' in reference && 'publisher' in reference.in && reference.in.publisher) {
return `<span itemscope itemtype="https://schema.org/Organization" itemprop="author">`
+ renderLStr(reference.in.publisher, 'span', {itemprop: 'name', class: 'noun'})
+ '</span> ';
*/
} else {
return `<i>Anonymous</i> `;
}
}
function renderTranslator(reference: Reference) {
if ('translator' in reference && reference.translator) {
return `, translated by ${renderPeople(reference.translator, false, false, 'translator')}`;
}
return '';
}
function renderEditor(reference: Reference) {
if (reference.author !== undefined) {
// if author was not present we would have shown editor as author
if ('editor' in reference && reference.editor) {
return `, edited by ${renderPeople(reference.editor, false, false, 'editor')}`;
}
}
return '';
}
const renderPeople = (as: readonly Author[], reverseFirst: boolean, period: boolean, itemprop: string) => {
const renderFamily = (a: Author, ix: number) =>
`<span itemprop="familyName">${a.family}</span>${ifSet(period && ix === (as.length - 1) && !a.family?.endsWith('.'), '.')}`;
const renderGiven = (a: Author, ix: number) =>
`<span itemprop="givenName">${a.given}</span>${ifSet(period && reverseFirst && ix === 0 && ix === (as.length - 1) && !a.given.endsWith('.'), '.')}`;
// Japanese and Chinese names should be last-name first
const reverseName = (a: Author) => a.lang === undefined ? false : (a.lang.startsWith('zh') || a.lang.startsWith('ja'));
// if using Latin script we still need a space between, otherwise we don’t
const isLatn = (a: Author) => a.lang === undefined || a.lang.endsWith("-Latn");
const hiddenName = (a: Author) => `<meta itemprop="name" content="${reverseName(a) ? `${a.family || ''}${isLatn(a) ? ' ' : ''}${a.given}` : `${a.given} ${a.family || ''}`}" />`;
const altName = (a: Author) => {
if (!a.alt) {
return '';
}
return ' [' + renderLStr(a.alt, 'span', {class: 'noun', itemprop: 'alternateName'}) + ']';
}
return as.map((a, ix) => (
ifSet(ix > 0, (ix === as.length - 1) ? `${ifSet(as.length > 2, ',')} and ` : ", ")
+ `<span itemscope itemtype="http://schema.org/Person"${asAttr('itemprop', itemprop)}${asAttr('lang', a.lang)} class="noun">`
+ hiddenName(a)
+ ifSet(a.url, u => `<a href="${u}" itemprop="sameAs">`)
+ ((reverseFirst && ix === 0)
? ifSet(a.family, () => `${isolate(renderFamily(a, ix))}, `) + isolate(renderGiven(a, ix))
: isolate(
reverseName(a)
? `${ifSet(a.family, () => `${renderFamily(a, ix)}`)}${isLatn(a) ? ' ' : ''}${renderGiven(a, ix)}`
: `${renderGiven(a, ix)}${ifSet(a.family, () => ` ${renderFamily(a, ix)}`)}`))
+ ifSet(a.url, '</a>')
+ altName(a)
+ `</span>`
)).join('');
};
const renderISBN = (reference: Reference) => {
const isbn = 'ISBN' in reference ? reference.ISBN : undefined;
if (!isbn) {
return '';
}
const parsed = ISBN.audit(isbn);
if (!parsed.validIsbn) {
console.error(parsed);
throw new Error("Invalid ISBN: " + isbn);
}
const formattedISBN = ISBN.hyphenate(isbn.toString());
return `<abbr class="initialism">ISBN</abbr>: <a href="https://www.worldcat.org/isbn/${formattedISBN}"><span itemprop="isbn">${formattedISBN}</span></a>. `;
};
const renderDate = (reference: Reference) => {
const issued =
'issued' in reference
? reference.issued
: 'in' in reference
? reference.in.issued
: undefined;
if (issued) {
const originalDate =
'original-date' in reference && reference['original-date']
? reference['original-date']
: 'in' in reference && 'original-date' in reference.in && reference.in['original-date']
? reference.in['original-date']
: undefined;
const original =
originalDate
? `, originally published ${typeof originalDate === 'number' ? originalDate : originalDate.year}`
: '';
const year = typeof issued === 'number' ? issued : issued.year;
const circa = (typeof issued !== 'number' && issued.circa) ? '<abbr title="circa">c.</abbr> ' : '';
const oldStyle = (typeof issued !== 'number' && issued.OS) ? ' [<abbr title="old-style">OS</abbr>]' : '';
return `(<time itemprop="datePublished" dateTime="${toIsoDate(issued)}">${circa}${year}</time>${oldStyle}${original}). `;
}
// patents might only have been filed
if ('filed' in reference) {
const { filed } = reference;
const year = typeof filed === 'number' ? filed : filed.year;
return `(<time itemprop="datePublished" dateTime="${toIsoDate(filed)}">${year}</time>). `;
}
return '(n.d.). ';
}
function toIsoDate(ymd: Date) {
// TODO: this should use ymd.OS to convert to Gregorian dates
if (typeof ymd == "number") {
return ymd;
}
let result = `${ymd.year}`;
if ('month' in ymd) {
result += `-${ymd.month.toString().padStart(2, '0')}`;
if ('day' in ymd) {
result += `-${ymd.day.toString().padStart(2, '0')}`;
}
}
return result;
}
function lstrValue(l: LStr) {
if (typeof l === 'string') {
return l;
}
return l.value;
}
const renderPublisher = (reference: { publisher?: LStr, ['publisher-place']?: string}) => {
let result = '';
const publisher = 'publisher' in reference ? reference.publisher : undefined;
if (publisher) {
result = renderLStr(publisher, 'span', {itemprop: 'name', class: 'noun'}, {itemprop: 'alternateName'});
}
// (p) => `<span class="noun"${asAttr('lang', reference['publisher-lang'])}>${p}</span>${reference['publisher-place'] ? ': ' : (p.endsWith('.') ? ' ' : '. ')}`)
const publisherPlace = 'publisher-place' in reference ? reference['publisher-place'] : undefined;
if (publisherPlace) {
const prefix = result != '' ? ': ' : '';
result += `${prefix}<span itemprop="location">${publisherPlace}</span>. `;
} else {
if (publisher && !lstrValue(publisher).endsWith('.')) {
result += '. ';
}
}
return result;
};
function renderPeriodical(id: string, p: Periodical): string {
// if date is more specific than a year, show it
let datePart = '';
if (typeof p.issued === 'object' && 'month' in p.issued) {
const dateString = renderExplicitDate(p.issued, true);
datePart = ifSet(dateString, `, <time itemprop="datePublished" dateTime="${toIsoDate(p.issued)}">${dateString}</time>`);
}
if (p.issue && p.volume) {
const { issue, volume } = p;
return (
`<span itemscope itemtype="http://schema.org/Periodical" itemid="${`#${id}-periodical`}">`
+ `<link itemprop="publisher" href="${`#${id}-publisher`}" />`
+ renderLStr(p.title, 'cite', {itemprop: 'name'}, {itemprop: 'alternateName'})
+ `</span>`
+ ' '
+ `<span itemscope itemtype="http://schema.org/PublicationVolume" itemid="${`#${id}-volume`}">`
+ `<link itemprop="isPartOf" href="${`#${id}-periodical`}" />`
+ `<abbr title="volume">vol.</abbr> `
+ `<span itemprop="volumeNumber">${formatNumberString(volume)}</span>`
+ `</span>`
+ ' '
+ `<span itemprop="isPartOf" itemscope itemtype="http://schema.org/PublicationIssue">`
+ `<link itemprop="isPartOf" href="${`#${id}-volume`}" />`
+ `(<span itemprop="issueNumber">${formatNumberString(issue)}</span>)`
+ datePart
+ `</span>`
);
}
if (p.issue) {
const { issue } = p;
return (
`<span itemscope itemtype="http://schema.org/Periodical" itemid="${`#${id}-periodical`}">`
+ `<link itemprop="publisher" href="${`#${id}-publisher`}" />`
+ renderLStr(p.title, 'cite', {itemprop: 'name'}, {itemprop: 'alternateName'})
+ `</span>`
+ ' '
+ `<span itemprop="isPartOf" itemscope itemtype="http://schema.org/PublicationIssue">`
+ `<link itemprop="isPartOf" href="${`#${id}-periodical`}" />`
+ `(<span itemprop="issueNumber">${formatNumberString(issue)}</span>)`
+ datePart
+ `</span>`
);
}
if (p.volume) {
const { volume } = p;
return (
`<span itemscope itemtype="http://schema.org/Periodical" itemid="${`#${id}-periodical`}">`
+ `<link itemprop="publisher" href="${`#${id}-publisher`}" />`
+ renderLStr(p.title, 'cite', {itemprop: 'name'}, {itemprop: 'alternateName'})
+ `</span>`
+ ' '
+ `<span itemprop="isPartOf" itemscope itemtype="http://schema.org/PublicationVolume">`
+ `<link itemprop="isPartOf" href="${`#${id}-periodical`}" />`
+ `<abbr title="volume">vol.</abbr> `
+ `<span itemprop="volumeNumber">${formatNumberString(volume)}</span>`
+ datePart
+ `</span>`
);
}
// neither volume nor issue
return (
`<span itemprop="isPartOf" itemscope itemtype="http://schema.org/Periodical">`
+ `<link itemprop="publisher" href="${`#${id}-publisher`}" />`
+ renderLStr(p.title, 'cite', {itemprop: 'name'}, {itemprop: 'alternateName'})
+ datePart
+ `</span>`
);
}
function renderContainer(reference: BiblioRef) {
const { id } = reference;
switch (reference.type) {
case 'webpage':
if ('container-title' in reference && reference['container-title']) {
return ` <span itemscope itemtype="http://schema.org/WebSite" itemprop="isPartOf">`
+ '<i>'
+ renderLStr(reference['container-title'], 'span', {itemprop: 'name'}, {itemprop: 'alternateName'})
+ '</i>'
+ `</span>. `;
}
return '';
case 'chapter':
case 'paper-conference':
const prefix = 'page' in reference && reference.page
? `${isNaN(+reference.page) ? "Pages" : "Page"} <span itemprop="pagination">${reference.page}</span> in `.replace('-', '–')
: " In ";
return prefix + renderBook(reference.in, 'isPartOf');
case 'article-magazine':
case 'article-newspaper':
case 'article-journal':
const pageSuffix =
('page' in reference && reference.page)
? `: ${isNaN(+reference.page) ? "pages" : "page"} <span itemprop="pagination">${reference.page}</span>. `.replace('-', '–') // promote hyphen to en-dash
: '. ';
const publisher = renderPublisher(reference.in);
const editor = ('editor' in reference.in && reference.in.editor)
? 'Edited by ' + renderPeople(reference.in.editor, false, false, 'editor') + '. '
: '';
return renderPeriodical(id, reference.in)
+ pageSuffix
+ editor
+ `<span itemscope itemtype="https://schema.org/Organization" itemid="#${id}-publisher">${publisher}</span>`;
default:
return '';
}
}