-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathiframe.ts
468 lines (413 loc) · 15.1 KB
/
iframe.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
import * as hlib from '../hlib/hlib' // this will be commented out in the shipping bundle
let params:any = decodeURIComponent(hlib.gup('params'))
params = JSON.parse(params)
const widget = hlib.getById('widget') as HTMLElement
const controlsContainer = hlib.getById('controlsContainer') as HTMLElement
const format = params.format
delete params.format
const sortBy = params.sortBy
delete params.sortBy
const iconColor = '#2c1409b5'
const exportControlStyle = `style="display:inline; width:1.8em; height:1.8em; margin-left:1em; fill:${iconColor}"`
const externalLinkStyle = `style="display:inline; width:.6em; height:.6em; margin-left:2px;margin-top:3px; fill:${iconColor}"`
let htmlBuffer = ''
const subjectUserTokens = hlib.getSubjectUserTokensFromLocalStorage()
hlib.getById('svgDefs').outerHTML = hlib.svgIcons
enum annoOrReplyCounterId {
annoCount = 'annoCount',
replyCount = 'replyCount'
}
enum counterDirection {
up,
down
}
Object.keys(params).forEach(function (key) {
if (params[key] === '') {
delete params[key]
}
if (params.group && params.group === 'all') {
delete params.group
}
})
showParams()
hlib.getById('progress').innerText = 'fetching annotations '
hlib.search(params, 'progress')
.then( data => {
processSearchResults(data[0], data[1])
})
.catch( _ => {
alert(`Cannot search for those parameters: ${JSON.stringify(params)}`)
})
function showParams() {
let _params = Object.assign({}, params)
const excluded = [
'_separate_replies',
'controlledTags',
'exactTagSearch',
'expanded',
'group',
'searchReplies',
'service',
'subjectUserTokens',
]
excluded.forEach(param => {
delete _params[param]
})
let title = hlib.syntaxColorParams(_params, excluded)
title = title.slice(0, -1)
if (title) {
hlib.getById('title').innerHTML += title
} else {
hlib.getById('title').style.display = 'none'
}
}
function exactTagSearch(annos:any[]) {
if (params.exactTagSearch==='false') {
return annos
}
if (!params.tag) {
return annos
}
const checkedAnnos:any[] = []
const queryTag = params.tag
annos.forEach(anno => {
const _tags = anno.tags.map(function(t:string) { return t.toLowerCase() })
if (_tags.indexOf(queryTag.toLowerCase()) > -1) {
checkedAnnos.push(anno)
} else {
const counterId = anno.isReply ? annoOrReplyCounterId.replyCount : annoOrReplyCounterId.annoCount
decrementAnnoOrReplyCount(counterId)
}
})
return checkedAnnos
}
async function processSearchResults (annoRows:any[], replyRows:any[]) {
hlib.getById('title').innerHTML += `
annotations <span id="${annoOrReplyCounterId.annoCount}">${annoRows.length}</span>,
replies <span id="${annoOrReplyCounterId.replyCount}">${replyRows.length}</span>`
if ( annoRows.length == 0 && replyRows.length == 0 ) {
hlib.getById('progress').innerText = ''
hlib.getById('widget').innerHTML = `
<p>Nothing found for this query.
<p>Please try removing or altering one or more filters.
`
hlib.getById('widget').style.display= 'block'
return
}
annoRows = exactTagSearch(annoRows)
replyRows = exactTagSearch(replyRows)
let csv = ''
const json:any[] = []
const combined = annoRows.concat(replyRows)
const gatheredResults = hlib.gatherAnnotationsByUrl(combined)
const reversedUrls = reverseChronUrls(gatheredResults)
let cardCounter = 0
for (let i = 0; i < reversedUrls.length; i++ ) {
const url = reversedUrls[i]
await renderCardsForUrl(url)
}
styleWidget(csv, json)
showToggleAndDownloadControls()
if (format === 'html') {
const expanded = isExpanded()
if (expanded) {
setExpanderCollapse()
hlib.getById('expander').click()
} else {
hlib.collapseAll()
}
}
widget.style.display = 'block'
hlib.getById('progress').innerHTML = ''
async function renderCardsForUrl(url: string) {
cardCounter++
const resultsForUrl = gatheredResults.get(url) !
const annosForUrl: hlib.annotation[] = resultsForUrl.annos
const repliesForUrl: hlib.annotation[] = resultsForUrl.replies
const perUrlCount = annosForUrl.length + repliesForUrl.length
if (format === 'html') {
htmlBuffer += showUrlResults(cardCounter, 'widget', url, perUrlCount, resultsForUrl.title)
}
let cardsHTMLBuffer = ''
let promises = missingReplyPromises(annosForUrl.concat(repliesForUrl))
promises = promises.map(p => p.catch( e => e ))
let missingAnnoOrReplyResults:hlib.httpResponse[] = await Promise.all(promises)
missingAnnoOrReplyResults.forEach(result => {
if (result && result.status == 200 ) {
const annoOrReply = hlib.parseAnnotation(JSON.parse(result.response))
if ( annoOrReply.isReply) {
repliesForUrl.push(annoOrReply)
adjustAnnoOrReplyCount(annoOrReplyCounterId.replyCount, counterDirection.up)
} else {
annosForUrl.push(annoOrReply)
adjustAnnoOrReplyCount(annoOrReplyCounterId.annoCount, counterDirection.up)
}
}
})
let all = organizeReplies(annosForUrl, repliesForUrl)
all.forEach(anno => {
let level = anno.isReply ? anno.refs.length : 0
if (format === 'html') {
const externalLinkIcon = renderIcon('icon-external-link', externalLinkStyle)
const externalLink = `<a target="_standalone" href="https://hypothes.is/a/${anno.id}" title="view/edit/reply">${externalLinkIcon}</a>`
let cardsHTML = hlib.showAnnotation(
anno,
level,
{
externalLink: externalLink,
addQuoteContext: hlib.getSettings().addQuoteContext === 'true'
})
if (params.any) {
const regex = new RegExp(params.any, 'g')
cardsHTML = cardsHTML.replace(regex, `<span class="searchHit">${params.any}</span>`)
}
cardsHTMLBuffer += cardsHTML
}
else if (format === 'csv') {
let _row = document.createElement('div')
_row.innerHTML = hlib.csvRow(level, anno)
csv += _row.innerText + '\n'
}
else if (format === 'json') {
anno.text = anno.text.replace(/</g, '<')
json.push(anno)
}
})
htmlBuffer = htmlBuffer.replace(`CARDS_${cardCounter}`, cardsHTMLBuffer)
}
function missingReplyPromises(all: hlib.annotation[]) : Promise<hlib.httpResponse>[] {
const allIds:string[] = all.map(function (anno: hlib.annotation) {
return anno.id
})
let refIds = [] as string[]
all.forEach(function (anno: hlib.annotation) {
anno.refs.forEach(refId =>{
if (refIds.indexOf(refId) < 0) {
refIds.push(refId)
}
})
})
const promises = [] as Promise<hlib.httpResponse>[]
for (let refId of refIds) {
if (allIds.indexOf(refId) < 0) {
promises.push(hlib.getAnnotation(refId, hlib.getToken()))
}
}
return promises
}
function styleWidget(csv: string, json: any[]) {
if (format === 'html') {
hlib.getById('widget').innerHTML = htmlBuffer
}
else if (format === 'csv') {
widget.style.whiteSpace = 'pre'
widget.style.overflowX = 'scroll'
widget.innerText = csv
}
else if (format === 'json') {
widget.style.whiteSpace = 'pre'
widget.innerText = JSON.stringify(json, null, 2)
}
}
function showUrlResults (counter:number, eltId:string, url:string, count:number, doctitle:string):string {
const host = new URL(url).host
const headingCounter = `counter_${counter}`
const { togglerTitle, togglerUnicodeChar } = getToggler()
const output = `<h1 id="heading_${headingCounter}" class="urlHeading">
<a title="${togglerTitle}" href="javascript:hlib.toggle('${headingCounter}')"> <span class="toggle">${togglerUnicodeChar}</span></a>
<span class="counter"> ${count} </span>
<a class="urlTitle" title="visit ${url}" target="annotatedPage" href="${url}">${doctitle}</a>
<span class="host">${host}</span>
</h1>
<div id="cards_${headingCounter}">
CARDS_${counter}
</div>`
return output
}
function reverseChronUrls (results: hlib.gatheredResults) {
function reverseByUpdate(a:string, b:string) {
const resultA = results.get(a) !
const resultB = results.get(b) !
return new Date(resultB.updated).getTime() - new Date(resultA.updated).getTime()
}
const urls = Array.from(results.keys())
urls.sort(reverseByUpdate)
return urls
}
function findRepliesForId(id: string, replies: any[]) {
const _replies = replies.filter( _reply => {
return _reply.refs.indexOf(id) != -1
})
return _replies
}
function organizeReplies(annosForUrl:hlib.annotation[], repliesForUrl:hlib.annotation[]) : hlib.annotation[] {
function ascendingByUpdate(a:hlib.annotation, b:hlib.annotation) {
return new Date(a.updated).getTime() - new Date(b.updated).getTime()
}
function reverseByUpdate(a:hlib.annotation, b:hlib.annotation) {
return new Date(b.updated).getTime() - new Date(a.updated).getTime()
}
function byLocation(a:hlib.annotation, b:hlib.annotation) {
const aStart = a.start ? a.start : 9999999999
const bStart = b.start ? b.start : -9999999999
return aStart - bStart
}
annosForUrl.sort(sortBy === 'recency' ? reverseByUpdate: byLocation)
const _annos = [] as hlib.annotation[]
annosForUrl.forEach(function (annoForUrl) {
_annos.push(annoForUrl)
const repliesForAnno = findRepliesForId(annoForUrl.id, repliesForUrl)
repliesForAnno.sort(ascendingByUpdate)
repliesForAnno.forEach(function (reply:hlib.annotation) {
_annos.push(reply)
})
})
repliesForUrl.forEach(function (reply:hlib.annotation) {
const ids = _annos.map(_anno => { return _anno.id } )
const index = ids.indexOf(reply.id)
if ( index < 0 ) {
_annos.splice(index, 0, reply)
}
})
return _annos
}
}
function isExpanded() {
return hlib.getSettings().expanded === 'true'
}
function setExpanderExpand() {
const expander = hlib.getById('expander')
expander.onclick = setExpanderCollapse
expander.innerText = hlib.expandToggler.togglerUnicodeChar
expander.title = hlib.expandToggler.togglerTitle
hlib.expandAll()
}
function setExpanderCollapse() {
const expander = hlib.getById('expander')
expander.onclick = setExpanderExpand
expander.innerText = hlib.collapseToggler.togglerUnicodeChar
expander.title = hlib.collapseToggler.togglerTitle
hlib.collapseAll()
}
function getToggler() : hlib.toggler {
const togglerTitle = isExpanded() ? hlib.expandToggler.togglerTitle : hlib.collapseToggler.togglerTitle
const togglerUnicodeChar = isExpanded() ? hlib.expandToggler.togglerUnicodeChar : hlib.collapseToggler.togglerUnicodeChar
return {
togglerTitle: togglerTitle,
togglerUnicodeChar: togglerUnicodeChar
}
}
function showToggleAndDownloadControls() {
const downloaderIcon = renderIcon('icon-floppy', exportControlStyle)
if (format === 'html') {
const { togglerTitle, togglerUnicodeChar } = getToggler()
controlsContainer.innerHTML = `
<span title="${togglerTitle}" class="toggleMajor" id="expander">${togglerUnicodeChar}</span>
<span class="downloader">${downloaderIcon}</span>`
const expander = hlib.getById('expander') as HTMLSpanElement
expander.onclick = isExpanded() ? setExpanderCollapse : setExpanderExpand
const downloader = document.querySelector('.downloader') as HTMLSpanElement
downloader.onclick = downloadHTML
} else {
controlsContainer.innerHTML = `<span class="downloader">${downloaderIcon}</span>`
const downloader = document.querySelector('.downloader') as HTMLSpanElement
downloader.onclick = format === 'csv' ? downloadCSV : downloadJSON
}
}
function downloadHTML () {
function rebaseLinks(links: NodeListOf<HTMLAnchorElement>) {
links.forEach(link => {
link.href = link.href
})
}
const head = document.head
const body = document.body
const controlsContainer = body.querySelector('#controlsContainer') as HTMLElement
controlsContainer.remove()
const pencils = body.querySelectorAll('.icon-pencil')
pencils.forEach(pencil => { pencil.remove() })
rebaseLinks(body.querySelectorAll('.user a'))
rebaseLinks(body.querySelectorAll('.annotationTags a'))
const html = `<html>${head.outerHTML}${body.outerHTML}</html>`
hlib.download(html, 'html')
location.href = location.href
}
function downloadCSV () {
let csvOutput = '"level","created","updated","url","user","id","group","tags","quote","text","relay link","direct link"\n'
csvOutput += widget.innerText
hlib.download(csvOutput, 'csv')
}
function downloadJSON () {
const jsonOutput = '[' + widget.innerText + ']'
hlib.download(jsonOutput, 'json')
}
function renderIcon(iconClass:string, style?: string) {
const _style = style ? style : `style="display:block"`
return `<svg ${style} class="${iconClass}"><use xlink:href="#${iconClass}"></use></svg>`
}
function deleteAnnotation(domAnnoId: string) {
if (! window.confirm("Really delete this annotation?")) {
return
}
const card = hlib.getById(domAnnoId) as HTMLElement
const userElement = card.querySelector('.user') as HTMLElement
const username = getUserName(userElement)
const token = subjectUserTokens.get(username) || ''
async function _delete() {
const annoId = annoIdFromDomAnnoId(domAnnoId)
const r = await hlib.deleteAnnotation(annoId, token)
const response = JSON.parse(r.response)
if (response.deleted) {
const cardCounter = card.closest('div[id*="cards_counter"') as HTMLElement
const urlCounter = cardCounter.previousElementSibling as HTMLHeadingElement
hlib.getById(domAnnoId).remove()
decrementPerUrlCount(urlCounter.id)
} else {
alert (`unable to delete, ${r.response}`)
}
}
_delete()
}
function annoIdFromDomAnnoId(domAnnoId:string) {
return domAnnoId.replace(/^_/,'')
}
function getUserName(userElement: HTMLElement) {
return userElement.innerText.trim()
}
function adjustAnnoOrReplyCount(id:annoOrReplyCounterId, direction:counterDirection) {
const counterElement = hlib.getById(id) as HTMLSpanElement
let count:number = parseInt(counterElement.innerText)
if (direction === counterDirection.up) {
count++
} else {
count--
}
counterElement.innerText = count.toString()
}
function incrementAnnoOrReplyCount(id:annoOrReplyCounterId) {
adjustAnnoOrReplyCount(id, counterDirection.up)
}
function decrementAnnoOrReplyCount(id:annoOrReplyCounterId) {
adjustAnnoOrReplyCount(id, counterDirection.down)
}
function adjustPerUrlCount(urlCounterId:string, direction:counterDirection) {
const urlHeading = hlib.getById(urlCounterId)
const counterElement = urlHeading.querySelector('.counter') as HTMLElement
let counter = parseInt(counterElement.innerText)
if (direction === counterDirection.up) {
counter++
} else {
counter--
}
if (counter == 0) {
urlHeading.remove()
} else {
counterElement.innerText = ` ${counter}`
}
}
function incrementPerUrlCount(urlCounterId:string) {
adjustPerUrlCount(urlCounterId, counterDirection.up)
}
function decrementPerUrlCount(urlCounterId:string) {
adjustPerUrlCount(urlCounterId, counterDirection.down)
}