-
Notifications
You must be signed in to change notification settings - Fork 46
/
annotations.js
451 lines (378 loc) · 15.8 KB
/
annotations.js
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
Annotations = {
basePathname: "/metadata/annotation/",
annotatedLinkFullClass: "link-annotated",
annotatedLinkPartialClass: "link-annotated-partial"
};
Annotations = { ...Annotations,
/***********/
/* General.
*/
isAnnotatedLink: (link) => {
return link.classList.containsAnyOf([ Annotations.annotatedLinkFullClass, Annotations.annotatedLinkPartialClass ]);
},
isAnnotatedLinkFull: (link) => {
return link.classList.contains(Annotations.annotatedLinkFullClass);
},
isAnnotatedLinkPartial: (link) => {
return link.classList.contains(Annotations.annotatedLinkPartialClass);
},
allAnnotatedLinksInContainer: (container) => {
return Array.from(container.querySelectorAll("a[class*='link-annotated']")).filter(link => Annotations.isAnnotatedLink(link));
},
/* Returns the target identifier: the relative url (for local links),
or the full URL (for foreign links).
Used for loading annotations, and caching reference data.
*/
targetIdentifier: (target) => {
return (target.hostname == location.hostname
? target.pathname + target.hash
: (target instanceof HTMLAnchorElement
? target.getAttribute("href")
: target.href));
},
shouldLocalizeContentFromLink: (link) => {
return false;
},
/***********/
/* Caching.
*/
// Convenience method.
cachedDocumentForLink: (link) => {
return (Annotations.cachedReferenceDataForLink(link)?.document ?? null);
},
loadingFailedString: "LOADING_FAILED",
/* Storage for retrieved and cached annotations.
*/
cachedReferenceData: { },
referenceDataCacheKeyForLink: (link) => {
return Annotations.targetIdentifier(link);
},
cachedReferenceDataForLink: (link) => {
return Annotations.cachedReferenceData[Annotations.referenceDataCacheKeyForLink(link)];
},
cacheReferenceDataForLink: (referenceData, link) => {
Annotations.cachedReferenceData[Annotations.referenceDataCacheKeyForLink(link)] = referenceData;
},
/* Returns true iff cached reference data exists for the given link.
*/
// Called by: Extracts.setUpAnnotationLoadEventsWithin (extracts-annotations.js)
cachedDataExists: (link) => {
let referenceData = Annotations.cachedReferenceDataForLink(link);
return ( referenceData != null
&& referenceData != Annotations.loadingFailedString);
},
/* Returns cached annotation reference data for a given link, or else
either “LOADING_FAILED” (if loading the annotation was attempted but
failed) or null (if the annotation has not been loaded).
*/
referenceDataForLink: (link) => {
return Annotations.cachedReferenceDataForLink(link);
},
/***********/
/* Loading.
*/
/* Returns the URL of the annotation resource for the given link.
*/
// Called by: Annotations.load
// Called by: Annotations.cachedAPIResponseForLink
// Called by: Annotations.cacheAPIResponseForLink
sourceURLForLink: (link) => {
return URLFromString( Annotations.basePathname
+ fixedEncodeURIComponent(fixedEncodeURIComponent(Annotations.targetIdentifier(link)))
+ ".html");
},
waitForDataLoad: (link, loadHandler = null, loadFailHandler = null) => {
let referenceData = Annotations.referenceDataForLink(link);
if (referenceData != null) {
if (referenceData == Annotations.loadingFailedString) {
if (loadFailHandler)
loadFailHandler(link);
} else {
if (loadHandler)
loadHandler(link);
}
return;
}
let didLoadHandler = (info) => {
if (loadHandler)
loadHandler(link);
GW.notificationCenter.removeHandlerForEvent("Annotations.annotationLoadDidFail", loadDidFailHandler);
};
let loadDidFailHandler = (info) => {
if (loadFailHandler)
loadFailHandler(link);
GW.notificationCenter.removeHandlerForEvent("Annotations.annotationDidLoad", didLoadHandler);
};
let options = {
once: true,
condition: (info) => info.link == link
};
GW.notificationCenter.addHandlerForEvent("Annotations.annotationDidLoad", didLoadHandler, options);
GW.notificationCenter.addHandlerForEvent("Annotations.annotationLoadDidFail", loadDidFailHandler, options);
},
/* Load and process the annotation for the given link.
*/
// Called by: Extracts.setUpAnnotationLoadEventsWithin (extracts-annotations.js)
load: (link, loadHandler = null, loadFailHandler = null) => {
GWLog("Annotations.load", "annotations.js", 2);
// Get URL of the annotation resource.
let sourceURL = Annotations.sourceURLForLink(link);
// Retrieve, parse, process, and cache the annotation data.
doAjax({
location: sourceURL.href,
onSuccess: (event) => {
let responseDocument = newDocument(event.target.responseText);
// Request the page image thumbnail, to cache it.
let pageImage = responseDocument.querySelector(".page-thumbnail");
if (pageImage)
doAjax({ location: Images.thumbnailURLForImage(pageImage) });
/* Construct and cache a reference data object, then fire the
appropriate event.
*/
let referenceData = Annotations.referenceDataFromParsedAPIResponse(responseDocument, link);
if (referenceData) {
Annotations.cacheReferenceDataForLink(referenceData, link);
GW.notificationCenter.fireEvent("Annotations.annotationDidLoad", {
link: link
});
} else {
Annotations.cacheReferenceDataForLink(Annotations.loadingFailedString, link);
GW.notificationCenter.fireEvent("Annotations.annotationLoadDidFail", {
link: link
});
// Send request to record failure in server logs.
GWServerLogError(sourceURL.href + `--could-not-process`, "problematic annotation");
}
},
onFailure: (event) => {
Annotations.cacheReferenceDataForLink(Annotations.loadingFailedString, link);
GW.notificationCenter.fireEvent("Annotations.annotationLoadDidFail", { link: link });
// Send request to record failure in server logs.
GWServerLogError(sourceURL.href, "missing annotation");
}
});
// Call any provided handlers, if/when appropriate.
if (loadHandler || loadFailHandler)
Annotations.waitForDataLoad(link, loadHandler, loadFailHandler);
},
// Called by: Annotations.load
referenceDataFromParsedAPIResponse: (response, link) => {
let titleLink = response.querySelector([ Annotations.annotatedLinkFullClass,
Annotations.annotatedLinkPartialClass
].map(className => `a.${className}`).join(", "));
// Strip date ranges (if any).
stripDateRangeMetadataInBlock(titleLink);
// On mobile, use mobile-specific link href, if provided.
let titleLinkHref = ( titleLink.dataset.hrefMobile
&& GW.isMobile())
? titleLink.dataset.hrefMobile
: titleLink.href;
// Construct title link class.
let titleLinkClasses = [ "title-link" ];
// Import link classes (excluding certain ones).
titleLinkClasses.push(...(Array.from(titleLink.classList).filter(titleLinkClass => [
"link-annotated",
"link-annotated-partial"
].includes(titleLinkClass) == false)));
// Special handling for links with separate ‘HTML’ URLs.
if ( titleLink.dataset.urlHtml
&& titleLinkClasses.includes("link-live") == false)
titleLinkClasses.push("link-live");
// Special data attributes for the title link.
let titleLinkDataAttributes = [
"urlHtml",
"urlArchive",
"urlOriginal",
"imageWidth",
"imageHeight",
"aspectRatio"
].map(attributeName =>
titleLink.dataset[attributeName]
? `data-${(attributeName.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase())}="${titleLink.dataset[attributeName]}"`
: null
).filter(Boolean);
// Link icon for the title link.
if (titleLink.dataset.linkIcon) {
titleLinkDataAttributes.push(`data-link-icon-type="${(titleLink.dataset.linkIconType)}"`);
titleLinkDataAttributes.push(`data-link-icon="${(titleLink.dataset.linkIcon)}"`);
} else if ( link
&& link.dataset.linkIcon) {
titleLinkDataAttributes.push(`data-link-icon-type="${(link.dataset.linkIconType)}"`)
titleLinkDataAttributes.push(`data-link-icon="${(link.dataset.linkIcon)}"`);
}
// Stringify data attributes.
titleLinkDataAttributes = (titleLinkDataAttributes.length > 0
? titleLinkDataAttributes.join(" ")
: null);
// Author list.
let authorHTML = null;
let authorElement = response.querySelector(".author");
if (authorElement) {
let authorListClass = [ "data-field", ...(authorElement.classList) ].join(" ");
authorHTML = `<span class="${authorListClass}">${authorElement.innerHTML}</span>`
}
// Date.
let dateHTML = null;
let dateElement = response.querySelector(".date");
if (dateElement) {
let dateClass = [ "data-field", ...(dateElement.classList) ].join(" ");
dateHTML = `<span class="${dateClass}" title="${dateElement.textContent}">`
+ dateElement.textContent.replace(/-[0-9][0-9]-[0-9][0-9]$/, "")
+ `</span>`;
}
// Link tags.
let tagsHTML = null;
let tagsElement = response.querySelector(".link-tags");
if (tagsElement) {
let tagsListClass = [ "data-field", ...(tagsElement.classList) ].join(" ");
tagsHTML = `<span class="${tagsListClass}">${tagsElement.innerHTML}</span>`;
}
// The backlinks link (if exists).
let backlinksElement = response.querySelector(".backlinks");
let backlinksHTML = backlinksElement
? `<span
class="data-field aux-links backlinks"
>${backlinksElement.innerHTML}</span>`
: null;
// The similar-links link (if exists).
let similarsElement = response.querySelector(".similars");
let similarsHTML = similarsElement
? `<span
class="data-field aux-links similars"
>${similarsElement.innerHTML}</span>`
: null;
// The link-link-bibliography link (if exists).
let linkbibElement = response.querySelector(".link-bibliography");
let linkbibHTML = linkbibElement
? `<span
class="data-field aux-links link-bibliography"
>${linkbibElement.innerHTML}</span>`
: null;
// All the aux-links (tags, backlinks, similars, link link-bib).
let auxLinksHTML = ([ backlinksHTML, similarsHTML, linkbibHTML ].filter(x => x).join(", ") || null);
if (auxLinksHTML || tagsHTML)
auxLinksHTML = ` (${([ tagsHTML, auxLinksHTML ].filter(x => x).join("; ") || null)})`;
// Combined author, date, & aux-links.
let authorDateAuxHTML = ([ authorHTML, dateHTML, auxLinksHTML ].filter(x => x).join("") || null);
// Abstract (if exists).
let abstractElement = response.querySelector("blockquote");
let abstractHTML = null;
let thumbnailFigureHTML = null;
if (abstractElement) {
let abstractDocument = newDocument(abstractElement.childNodes);
// Request image inversion judgments from invertornot.
requestImageInversionDataForImagesInContainer(abstractDocument);
// Post-process abstract.
Annotations.postProcessAnnotationAbstract(abstractDocument, link);
// Retrieve thumbnail HTML (if set).
thumbnailFigureHTML = abstractDocument.thumbnailFigureHTML;
abstractHTML = abstractDocument.innerHTML;
}
// File includes (if any).
let fileIncludesElement = response.querySelector(".aux-links-transclude-file");
let fileIncludesHTML = null;
if (fileIncludesElement) {
/* Remove any file embed links that lack a valid content
type (e.g., foreign-site links that have not been
whitelisted for embedding).
*/
Transclude.allIncludeLinksInContainer(fileIncludesElement).forEach(includeLink => {
if (Content.contentTypeForLink(includeLink) == null)
includeLink.remove();
});
/* Set special template for file includes of content transforms.
*/
Transclude.allIncludeLinksInContainer(fileIncludesElement).forEach(includeLink => {
if ( Content.isContentTransformLink(includeLink)
&& includeLink.dataset.includeTemplate == null)
includeLink.dataset.includeTemplate = "$annotationFileIncludeTemplate";
});
/* Do not include the file includes section if no valid
include-links remain.
*/
if (isNodeEmpty(fileIncludesElement) == false)
fileIncludesHTML = fileIncludesElement.innerHTML;
}
// Pop-frame title text.
let popFrameTitleLink = titleLink.cloneNode(true);
// Trim quotes from both title usage: because it is positioned & bolded, the quotes add nothing
// (but we leave alone the <em>s in some titles, as generated by the backend, because that is for book titles).
let [ first, last ] = [ popFrameTitleLink.firstTextNode, popFrameTitleLink.lastTextNode ];
if ( /^['"‘“]/.test(first.textContent) == true
&& /['"’”]$/.test(last.textContent) == true) {
first.textContent = first.textContent.slice(1);
last.textContent = last.textContent.slice(0, -1);
}
let popFrameTitleText = popFrameTitleLink.innerHTML;
return {
document: response,
content: {
title: popFrameTitleText,
titleLinkHref: titleLinkHref,
titleLinkClass: titleLinkClasses.join(" "),
titleLinkDataAttributes: titleLinkDataAttributes,
author: authorHTML,
date: dateHTML,
auxLinks: auxLinksHTML,
authorDateAux: authorDateAuxHTML,
abstract: abstractHTML,
thumbnailFigure: thumbnailFigureHTML,
fileIncludes: fileIncludesHTML
},
template: "annotation-blockquote-inside",
linkTarget: (GW.isMobile() ? "_self" : "_blank"),
whichTab: (GW.isMobile() ? "current" : "new"),
tabOrWindow: (GW.isMobile() ? "tab" : "window"),
popFrameTemplate: "annotation-blockquote-not",
popFrameTitleText: popFrameTitleText,
popFrameTitleLinkHref: titleLinkHref
};
},
/* Post-process an already-constructed local annotation
(do HTML cleanup, etc.).
*/
postProcessAnnotationAbstract: (abstractDocument, link = null) => {
// Unwrap extraneous <div>s, if present.
if ( abstractDocument.firstElementChild == abstractDocument.lastElementChild
&& abstractDocument.firstElementChild.tagName == "DIV")
unwrap(abstractDocument.firstElementChild);
// If there’s a “See Also” section, rectify its classes.
let seeAlsoList = abstractDocument.querySelector(_π(".see-also-append", " ", [ "ul", "ol" ]).join(", "));
if (seeAlsoList) {
seeAlsoList.classList.add("aux-links-list", "see-also-list");
let listLabel = previousBlockOf(seeAlsoList, { notBlockElements: [ ".columns" ] });
if (listLabel)
listLabel.classList.add("aux-links-list-label", "see-also-list-label");
}
// Prevent erroneous collapse class.
abstractDocument.querySelectorAll(".aux-links-append.collapse").forEach(auxLinksAppendCollapse => {
auxLinksAppendCollapse.classList.add("bare-content-not");
});
// Unwrap more extraneous <div>s, if present.
let pageDescriptionClass = "page-description-annotation";
let pageDescription = abstractDocument.querySelector(`div.${pageDescriptionClass}`);
if (pageDescription)
pageDescription = unwrap(pageDescription, { moveClasses: [ pageDescriptionClass ] });
// Page thumbnail.
let pageThumbnail = abstractDocument.querySelector("img.page-thumbnail");
if (pageThumbnail) {
// Replace full-size page image with thumbnail.
Images.thumbnailifyImage(pageThumbnail);
// Make page image thumbnail load eagerly instead of lazily.
pageThumbnail.loading = "eager";
pageThumbnail.decoding = "sync";
/* On sufficiently wide viewports, pull out thumbnail figure
for proper floating.
*/
let pageThumbnailFigure = pageThumbnail.closest("figure");
if (GW.mediaQueries.mobileWidth.matches == false) {
abstractDocument.thumbnailFigureHTML = pageThumbnailFigure.outerHTML;
pageThumbnailFigure.remove();
} else if (pageDescription) {
abstractDocument.insertBefore(pageThumbnailFigure, pageDescription.last.nextElementSibling);
}
}
},
};
// Fire load event.
GW.notificationCenter.fireEvent("Annotations.didLoad");