-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhlib.ts
1806 lines (1625 loc) · 55.1 KB
/
hlib.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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
export type httpOpts = {
method: string
url: string
headers: any
params: any
}
export type httpResponse = {
response: any
status: number
}
export type annotation = {
id: string
authority: string
url: string
created: string,
displayName: string,
updated: string
title: string
refs: string[]
isReply: boolean
isPagenote: boolean
user: string
text: string
prefix: string
exact: string
suffix: string
start: number
end: number
tags: string[]
group: string
target: object
document: object
}
export type textPositionSelector = {
type: string
start: number
end: number
}
export type textQuoteSelector = {
type: string
exact: string
prefix?: string
suffix?: string
}
export type inputFormArgs = {
element: HTMLElement // attach to this element
name: string // name of the field
id: string // id + 'Form' is used as a class attr and as id of input element
value: string // initial value of input element
onchange: EventHandlerNonNull// handler
type?: string // usually '' but can be e.g. 'password'
msg?: string // help message for the field
}
export type settings = {[index: string]:string} & {
// facets
user: string
group: string
url: string
wildcard_uri: string
tag: string
any:string
// settings
max: string
service: string
exactTagSearch: string
expanded: string
addQuoteContext: string
}
export type toggler = {
togglerTitle: string
togglerUnicodeChar: string
}
export const expandToggler:toggler = {
togglerTitle: 'collapse',
togglerUnicodeChar: '\u{25bc}'
}
export const collapseToggler:toggler = {
togglerTitle: 'expand',
togglerUnicodeChar: '\u{25b6}'
}
const defaultSettings:settings = {
// facets
user: '',
group: 'all',
url: '',
wildcard_uri: '',
tag: '',
any: '',
// settings
max: '50',
service: 'https://hypothes.is',
exactTagSearch: 'false',
expanded: 'false',
addQuoteContext: 'false'
}
export const formUrlStorageSyncEvent = new Event('formUrlStorageSync')
export const defaultControlledTags = 'tag1, tag2, tag3'
const clearInputEvent = new Event('clearInput')
const settings = settingsFromLocalStorage()
export function getSettings() {
return settings
}
export function getDefaultSettings() {
return defaultSettings
}
export function updateSetting(name:string, value:string) {
if (name === 'max' && ! value) {
value = defaultSettings.max
}
settings[name] = value
}
export function settingsFromLocalStorage() : settings {
let value
try {
value = localStorage.getItem('h_settings') as string
} catch (e) { // not accessible from a web worker
return defaultSettings
}
const settings = ! value
? getDefaultSettings() as settings
: JSON.parse(value) as settings
return settings
}
export function settingsToLocalStorage(settings: settings) {
localStorage.setItem('h_settings', JSON.stringify(settings))
}
export function settingsToUrl(settings: settings) {
let url = new URL(location.href)
function setOrDelete(settingName:string, settingValue:string, isBoolean?: boolean) {
// prep
if (isBoolean && settingValue === 'false') {
settingValue = ''
}
// rule
if (settingValue) {
url.searchParams.set(settingName, settingValue.toString())
} else {
url.searchParams.delete(settingName)
}
// exceptions
if (settingName === 'group' && settingValue === 'all') {
url.searchParams.delete(settingName)
}
}
// facets
setOrDelete('user', settings.user)
setOrDelete('group', settings.group)
setOrDelete('url', settings.url)
setOrDelete('wildcard_uri', settings.wildcard_uri)
setOrDelete('tag', settings.tag)
setOrDelete('any', settings.any)
// settings
setOrDelete('max', settings.max)
setOrDelete('exactTagSearch', settings.exactTagSearch, true)
setOrDelete('expanded', settings.expanded, true)
setOrDelete('addQuoteContext', settings.addQuoteContext, true)
// special
url.searchParams.delete('service')
url.searchParams.delete('subjectUserTokens')
history.pushState(null, '', url.href)
}
/** Promisified XMLHttpRequest
* This predated fetch() and now wraps it.
* */
export function httpRequest(opts: httpOpts):Promise<httpResponse> {
return new Promise( (resolve, reject) => {
const input = new Request(opts.url)
const init:any = {
method: opts.method,
headers: opts.headers
}
const method = opts.method.toLowerCase()
if (method !== 'get' && method !== 'head') {
init.body = opts.params
}
fetch(input, init)
.then( fetchResponse => {
return fetchResponse.text()
.then(text => {
return {
status: fetchResponse.status,
response: text,
headers: fetchResponse.headers,
}
})
})
.then( finalResponse => {
resolve ( finalResponse )
})
.catch(reason => {
console.error('rejected', opts, reason)
reject(reason)
})
})
}
/** Wrapper for `/api/search` */
export function search(params: any, progressId?: string): Promise<any> {
function _search(params: any, after: string, annos: object[], replies: object[], progressId?: string) {
return new Promise ( (resolve, reject) => {
let max = 2000
if (params.max) {
max = params.max
}
let limit = 200
if (max <= limit) {
limit = max
}
if (progressId) {
getById(progressId).innerHTML += '.'
}
const separateReplies = params._separate_replies==='true' ? '&_separate_replies=true' : ''
const afterClause = after ? `&search_after=${encodeURIComponent(after)}` : ''
let opts: httpOpts = {
method: 'get',
url: `${getSettings().service}/api/search?limit=${limit}${separateReplies}${afterClause}`,
headers: {},
params: {}
}
const facets = [ 'group', 'user', 'tag', 'url', 'wildcard_uri', 'any']
facets.forEach(function(facet) {
if (params[facet]) {
const encodedValue = encodeURIComponent(params[facet])
opts.url += `&${facet}=${encodedValue}`
}
})
opts = setApiTokenHeaders(opts)
httpRequest(opts)
.then(function(data) {
const response = JSON.parse(data.response)
let _annos: any[] = response.rows
let _replies = _annos.filter(a => { return a.hasOwnProperty('references') })
const replyIds = _replies.map(r => { return r.id })
_annos = _annos.filter(a => {
return replyIds.indexOf(a.id) < 0
})
annos = annos.concat(_annos)
replies = replies.concat(_replies)
const total = annos.length + replies.length
if (response.rows.length === 0 || total >= max) {
const result:any = [annos, replies]
resolve(result)
} else {
const sentinel = response.rows.slice(-1)[0].updated
resolve(_search(params, sentinel, annos, replies, progressId))
}
})
.catch( reason => {
reject(reason)
})
})
}
return new Promise (resolve => {
const annos: object[] = []
const replies: object[] = []
const after:string = ''
resolve(_search(params, after, annos, replies, progressId))
})
}
export type gatheredResult = {
updated: string
title: string
annos: annotation[]
replies: annotation[]
}
export type gatheredResults = Map<string, gatheredResult>
/** Organize a set of annotations, from /api/search, by url */
export function gatherAnnotationsByUrl(rows: any[]) : gatheredResults {
const results = new Map() as gatheredResults
for (let i = 0; i < rows.length; i++) {
const anno = parseAnnotation(rows[i]) // parse the annotation
const url = anno.url.replace(/\/$/, '') // strip trailing slash
if ( !results.has(url) ) {
results.set(url, {
updated: anno.updated,
title: anno.title,
annos: [],
replies: []
} as gatheredResult
)}
const result = results.get(url)
if (result) {
if (anno.updated > result.updated) {
result.updated = anno.updated
}
if (anno.isReply) {
result.replies.push(anno)
} else {
result.annos.push(anno)
}
results.set(url, result)
}
}
return results
}
/** Parse a row returned from `/api/search` */
export function parseAnnotation(row: any): annotation {
const id = row.id
const authority = row.user.match(/@(.+)/)[1]
const url = row.uri
const created = row.created.slice(0, 19)
const updated = row.updated.slice(0, 19)
const group = row.group
let title = url
const refs = row.references ? row.references : []
const user = row.user.replace('acct:', '').replace('@hypothes.is', '')
const displayName = row.user_info.display_name
let prefix = ''
let exact = ''
let suffix = ''
let start
let end
if (row.target && row.target.length) {
const selectors = row.target[0].selector
if (selectors) {
for (let i = 0; i < selectors.length; i++) {
let selector = selectors[i]
if (selector.type === 'TextQuoteSelector') {
prefix = selector.prefix
exact = selector.exact
suffix = selector.suffix
}
if (selector.type === 'TextPositionSelector') {
start = selector.start
end = selector.end
}
}
}
}
const text = row.text ? row.text : ''
const tags = row.tags
try {
title = row.document.title
if (typeof title === 'object') {
title = title[0]
} else {
title = url
}
} catch (e) {
title = url
}
const isReply = refs.length > 0
const isPagenote = row.target && !row.target[0].hasOwnProperty('selector')
const r: annotation = {
id: id,
authority: authority,
url: url,
created: created,
updated: updated,
title: title,
refs: refs,
isReply: isReply,
isPagenote: isPagenote,
user: user,
displayName: displayName,
text: text,
prefix: prefix,
exact: exact,
suffix: suffix,
start: start,
end: end,
tags: tags,
group: group,
target: row.target,
document: row.document
}
return r
}
/** Parse the `target` of a row returned from `/api/search` */
export function parseSelectors(target: any): object {
const parsedSelectors: any = {}
const firstTarget = target[0]
if (firstTarget) {
const selectors = firstTarget.selector
if (selectors) {
const textQuote = selectors.filter(function(x: any) {
return x.type === 'TextQuoteSelector'
})
if (textQuote.length) {
parsedSelectors['TextQuote'] = {
exact: textQuote[0].exact,
prefix: textQuote[0].prefix,
suffix: textQuote[0].suffix
}
}
const textPosition = selectors.filter(function(x: any) {
return x.type === 'TextPositionSelector'
})
if (textPosition.length) {
parsedSelectors['TextPosition'] = {
start: textPosition[0].start,
end: textPosition[0].end
}
}
const range = selectors.filter(function(x: any) {
return x.type === 'RangeSelector'
})
if (range.length) {
parsedSelectors['Range'] = {
startContainer: range[0].startContainer,
endContainer: range[0].endContainer
}
}
}
}
return parsedSelectors
}
/** Get url parameters */
export function gup(name: string, str?: string): string {
if (!str) {
str = window.location.href
} else {
str = '?' + str
}
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]')
const regexS = '[\\?&]' + name + '=([^&#]*)'
const regex = new RegExp(regexS)
const results = regex.exec(str)
if (results == null) {
return ''
} else {
return results[1]
}
}
export function getById(id: string): HTMLElement {
return document.getElementById(id) as HTMLElement
}
export function appendBody(element: HTMLElement) {
document.body.appendChild(element)
}
export function getDomainFromUrl(url: string): string {
let a = document.createElement('a')
a.href = url
return a.hostname
}
/** Add a token authorization header to the options that govern an `httpRequest`.
* If the token isn't passed as a param, try getting it from local storage.
*/
export function setApiTokenHeaders(opts: httpOpts, token?: string): httpOpts {
if (!token) {
token = getToken()
}
if (token) {
opts.headers = {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json;charset=utf-8'
}
}
return opts
}
/** Acquire a Hypothesis API token */
export function getToken() {
return getTokenFromLocalStorage()
}
/** Save a Hypothesis API token. */
export function setToken() {
setLocalStorageFromForm('tokenForm', 'h_token')
location.href = location.href
}
/** Acquire a Hypothesis group id */
export function getGroup() {
const group = getSettings().group
return group != '' ? group : '__world__'
}
export function syncContainer(name: string) {
return function() {
syncUrlAndLocalStorageFromForm(`${name}Container`)
}
}
function syncUrlAndLocalStorageFromForm(formId: string) {
const form = getById(formId)
const keyElement = form.querySelector('.formLabel') as HTMLElement
const key = keyElement.innerText
const inputElement = form.querySelector('input') as HTMLInputElement
let value:string
if (inputElement.type === 'checkbox') {
value = inputElement.checked ? 'true' : 'false'
} else
value = inputElement.value
updateSetting(key, value)
settingsToUrl(getSettings())
settingsToLocalStorage(getSettings())
form.dispatchEvent(formUrlStorageSyncEvent)
}
/** Save value of a form field. */
export function setLocalStorageFromForm(formId: string, storageKey: string) {
const element = getById(formId) as HTMLInputElement
localStorage.setItem(storageKey, element.value)
}
/** Helper for `createAnnotationPayload`. */
export function createPermissions(username: string, group: string) {
const permissions = {
read: [ 'group:' + group ],
update: [ 'acct:' + username + '@hypothes.is' ],
delete: [ 'acct:' + username + '@hypothes.is' ]
}
return permissions
}
/** Helper for `createAnnotationPayload` */
export function createTextQuoteSelector(exact: string, prefix: string, suffix: string): textQuoteSelector {
const tqs: textQuoteSelector = {
type: 'TextQuoteSelector',
exact: exact,
prefix: '',
suffix: ''
}
if (prefix) {
tqs.prefix = prefix
}
if (suffix) {
tqs.suffix = suffix
}
return tqs
}
/** Helper for `createAnnotationPayload` */
export function createTextPositionSelector(start: number, end: number): textPositionSelector {
const tps: textPositionSelector = {
type: 'TextPositionSelector',
start: start,
end: end
}
return tps
}
/** Form the JSON payload that creates an annotation.
*
* Expects an object with these keys:
* ```
* uri: Target to which annotation will post
* exact, prefix, suffix: Info for TextQuoteSelector, only exact is required
* start, stop: Info for TextPositionSelector, optional
* username: Hypothesis username
* group: Hypothesis group (use `__world__` for Public, ignored if you are posting a reply)
* text: Body of annotation (could be markdown or html)
* tags: Hypothesis tags
* references: Array of ids. To post a reply: [ '{threadRootId}' ]
* extra: Extra data, invisible to user but available through H API
* ```
*/
export function createAnnotationPayload(params: any): string {
// uri, exact, username, group, text, tags, references, extra
let textQuoteSelector
let textPositionSelector
if (params.exact) {
// we have minimum info need for a TextQuoteSelector
textQuoteSelector = createTextQuoteSelector(params.exact, params.prefix, params.suffix)
}
if (params.start && params.end) {
textPositionSelector = createTextPositionSelector(params.start, params.end)
}
const target: any = {
source: params.uri
}
if (textQuoteSelector) {
// we have minimum info for an annotation target
const selectors: object[] = [ textQuoteSelector ]
if (textPositionSelector) {
// we can also use TextPosition
selectors.push(textPositionSelector)
}
target['selector'] = selectors
}
const payload: any = {
target: [ target ],
uri: params.uri,
group: params.group,
permissions: createPermissions(params.username, params.group),
text: params.text,
document: {
title: [ params.uri ]
},
tags: params.tags ? params.tags : []
}
if (params.references) {
payload.references = params.references
}
if (params.extra) {
payload.extra = params.extra
}
return JSON.stringify(payload)
}
/** Create an annotation */
export function postAnnotation(payload: string, token: string) : Promise<httpResponse> {
const url = `${getSettings().service}/api/annotations`
let opts: httpOpts = {
method: 'post',
params: payload,
url: url,
headers: {}
}
opts = setApiTokenHeaders(opts, token)
return httpRequest(opts)
}
/** Create an annotation and redirect to the annotated page,
* optionally with a client-side query.
*/
export function postAnnotationAndRedirect(payload: string, token: string, queryFragment?: string) {
return postAnnotation(payload, token)
.then(data => {
const _data:any = data
const status:number = _data.status
if (status != 200) {
alert(`hlib status ${status}`)
return
}
const response = JSON.parse(_data.response)
let url = response.uri
if (queryFragment) {
url += '#' + queryFragment
}
location.href = url
})
.catch((e) => {
console.error(e)
})
}
export function getAnnotation(id: string, token: string) {
const url = `${getSettings().service}/api/annotations/${id}`
let opts: httpOpts = {
method: 'get',
params: {},
url: url,
headers: {}
}
opts = setApiTokenHeaders(opts, token)
return httpRequest(opts)
}
export function updateAnnotation(id: string, token: string, payload: string) {
const url = `${getSettings().service}/api/annotations/${id}`
let opts: httpOpts = {
method: 'put',
params: payload,
url: url,
headers: {}
}
opts = setApiTokenHeaders(opts, token)
return httpRequest(opts)
}
export function deleteAnnotation(id: string, token: string) {
const url = `${getSettings().service}/api/annotations/${id}`
let opts: httpOpts = {
method: 'delete',
url: url,
headers: {},
params: {}
}
opts = setApiTokenHeaders(opts, token)
return httpRequest(opts)
}
/** Input form for an API token, remembered in local storage. */
export function createApiTokenInputForm(element: HTMLElement) {
const tokenArgs: inputFormArgs = {
element: element,
name: 'Hypothesis API token',
id: 'token',
value: getToken(),
onchange: setToken,
type: 'password',
msg:
`Find it by logging in <a title="Your Hypothesis account" target="_token" href="${getSettings().service}/profile/developer">here</a>`
}
createNamedInputForm(tokenArgs)
}
export function createInputForm(name: string, handler: EventHandlerNonNull, element: HTMLElement, type?: string, msg?: string) {
const params: inputFormArgs = {
element: element,
name: name,
id: `${name}`,
value: getSettings()[name],
onchange: handler,
type: type ? type : '',
msg: msg ? msg : ''
}
createNamedInputForm(params)
}
export function createUserInputForm(element: HTMLElement, msg?: string) {
if (! msg) {
msg = 'For search, not authentication'
}
const name = 'user'
createInputForm(name, syncContainer(name), element, '', msg)
}
export function createUrlInputForm(element: HTMLElement) {
const name = 'url'
createInputForm(name, syncContainer(name), element, '', 'URL of annotated document')
}
export function createWildcardUriInputForm(element: HTMLElement) {
const name = 'wildcard_uri'
createInputForm(name, syncContainer(name), element, '', 'e.g. https://www.nytimes.com/*')
}
export function createTagInputForm(element: HTMLElement, msg?: string) {
const name = 'tag'
createInputForm(name, syncContainer(name), element, '', msg)
}
export function createAnyInputForm(element: HTMLElement, msg?: string) {
const name = 'any'
createInputForm(name, syncContainer(name), element, '', msg)
}
export function createMaxInputForm(element: HTMLElement, msg?: string) {
const name = 'max'
createInputForm(name, syncContainer(name), element, '', msg)
}
export function createExactTagSearchCheckbox(element: HTMLElement) {
const name = 'exactTagSearch'
createInputForm(name, syncContainer(name), element, 'checkbox')
}
export function createAddQuoteContextCheckbox(element: HTMLElement) {
const name = 'addQuoteContext'
createInputForm(name, syncContainer(name), element, 'checkbox')
}
export function createExpandedCheckbox(element: HTMLElement) {
const name = 'expanded'
createInputForm(name, syncContainer(name), element, 'checkbox')
}
export function createLmsModeCheckbox(element: HTMLElement) {
const name = 'lmsMode'
createInputForm(name, syncContainer(name), element, 'checkbox')
}
/** Create an input field with a handler to save the changed value,
* optionally with a default value, optionally with a type (e.g. password).
* Should be renamed to createUrlAndStorageSyncedInputForm
*/
export function createNamedInputForm(args: inputFormArgs) {
const { element, name, id, value, onchange, type, msg } = args
const _type = type ? `type="${type}"` : ''
let _value = ''
let _checked
if (type !== 'checkbox') {
_value = `value="${value}"`
} else {
_checked = value === 'true' ? `checked="true"` : ''
}
let form
if (type !== 'checkbox') {
form = `
<div class="formLabel">${name}</div>
<div class="${id}Form"><input ondrop="dropHandler(event)" ${_type} ${_value}
id="${id}Form"></input><a title="clear input" class="clearInput"> x</a></div>
<div class="formMessage">${msg}</div>`
} else {
form = `
<div class="checkboxContainer">
<div class="formLabel">${name}</div>
<div class="${id}Form"><input type="${type}" ${_checked} id="${id}Form"></div>
</div>
<div class="formMessage"></div>`
}
element.innerHTML += form
const inputElement = element.querySelector('input') as HTMLElement
inputElement.onchange = onchange
if (type !== 'checkbox') {
const clearElement = element.querySelector('.clearInput') as HTMLAnchorElement
clearElement.onclick = clearInput
}
return element // return value used for testing
}
/** Create a simple input field. */
export function createFacetInputForm(e: HTMLElement, facet: string, msg?: string, value?: string) {
if (!msg) { msg = '' }
if (!value) { value = '' }
const form = `
<div class="formLabel">${facet}</div>
<div class="${facet}Form"><input value="${value}" id="${facet}Form"></input></div>
<div class="formMessage">${msg}</div>`
e.innerHTML += form
return e // for testing
}
export function setSelectedGroup(selectId:string) {
const selectedGroup = getSelectedGroup(selectId)
updateSetting('group', selectedGroup)
const settings = getSettings()
settingsToLocalStorage(settings)
settingsToUrl(settings)
}
export function getSelectedGroupInfo(selectId?:string) {
let _selector = selectId ? selectId : 'groupsList'
_selector = '#' + _selector
const groupSelector = document.querySelector(_selector) as HTMLSelectElement
const options:HTMLOptionsCollection = groupSelector.options
const selectedGroup = options[options.selectedIndex].value
const selectedGroupName = options[options.selectedIndex].innerText
return {
selectedGroup: selectedGroup,
selectedGroupName: selectedGroupName
}
}
export function getSelectedGroup(selectId?:string) {
return getSelectedGroupInfo(selectId).selectedGroup
}
export function getSelectedGroupName(selectId?:string) {
return getSelectedGroupInfo(selectId).selectedGroupName
}
/** Create a Hypothesis group picker. */
export function createGroupInputForm(e: HTMLElement, selectId?: string) {
return new Promise( (resolve,reject) => {
const _selectId:string = selectId ? selectId : 'groupsList'
function createGroupSelector(groups: any, selectId?: string) {
localStorage.setItem('h_groups', JSON.stringify(groups))
const currentGroup = getGroup()
let options = ''
groups.forEach(function(g: any) {
let selected = ''
if (currentGroup == g.id) {
selected = 'selected'
}
options += `<option ${selected} value="${g.id}">${g.name}</option>\n`
})
const selector = `
<select id="${_selectId}">
${options}
</select>`
return selector
}
const token = getToken()
let opts: httpOpts = {
method: 'get',
url: `${getSettings().service}/api/profile`,
headers: {},
params: {}
}
opts = setApiTokenHeaders(opts, token)
httpRequest(opts)
.then((data:any) => {
const wrappedSetSelectedGroup = function () {
return setSelectedGroup(_selectId)
}
const response: any = JSON.parse(data.response)
let msg = ''
if (!token) {
msg = 'Add token and <a href="javascript:location.href=location.href">refresh</a> to see all groups here'
}
const form = `
<div class="formLabel">group</div>
<div class="inputForm">${createGroupSelector(response.groups, _selectId)}</div>
<div class="formMessage">${msg}</div>`
e.innerHTML += form
const groupPicker = getById(_selectId) as HTMLSelectElement
groupPicker.onchange = wrappedSetSelectedGroup
return data
})
.then (data => {
resolve(data)
})
.catch((e) => {
reject(e)
})
})
}
/** Render a list of tags. By default, the links work as in ${settings.service}judell/facet.
* Use the optional `urlPrefix` with `${settings.service}/search?q=tag:` to override
* with links to the Hypothesis viewer.
*/
export function formatTags(tags: string[], urlPrefix?: string): string {
const formattedTags: string[] = []
tags.forEach(function(tag) {
const url = urlPrefix ? urlPrefix + tag : `./?tag=${tag}`
const formattedTag = `<a target="_tag" href="${url}"><span class="annotationTag">${tag}</span></a>`
formattedTags.push(formattedTag)
})
return formattedTags.join('')
}
/** Format an annotation as a row of a CSV export. */
export function csvRow(level: number, anno: any): string {
let fields = [
level.toString(),
anno.created,
anno.updated,
anno.url,
anno.user,
anno.id,
anno.group,
anno.tags.join(', '),
anno.exact,
anno.text
]
fields.push(`https://hyp.is/${anno.id}`) // add hyp.is link
fields.push(`${anno.url}#annotations:${anno.id}`) // add direct link
fields = fields.map(function(field) {
if (field) {
field = field.replace(/&/g, '&') // the resulting text will be added as html to the dom
field = field.replace(/</g, '<')
field = field.replace(/\s+/g, ' ') // normalize whitespace
field = field.replace(/"/g, '""') // escape double quotes
field = field.replace(/\r?\n|\r/g, ' ') // remove cr lf
field = `"${field}"` // quote the field
}
return field
})
return fields.join(',')
}
/** Render an annotation card. */
export function showAnnotation(anno: annotation, level: number, params: any) {
if (!params) {
params = {}
}
const { addQuoteContext, copyIdButton, externalLink, tagUrlPrefix } = params