-
Notifications
You must be signed in to change notification settings - Fork 1
/
infinite.js
871 lines (786 loc) · 27.4 KB
/
infinite.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
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
/**
* Contains the [[infiniteMessageArea]] class
* @packageDocumentation
*/
import { authn } from '../authn/index'
import * as debug from '../debug'
import { icons } from '../iconBase'
import { store } from '../logic'
import { media } from '../media/index'
import * as ns from '../ns'
import * as pad from '../pad'
import { DateFolder } from './dateFolder'
import { renderMessage, creatorAndDate } from './message'
import { findBookmarkDocument } from './bookmarks'
import * as $rdf from 'rdflib' // pull in first avoid cross-refs
import * as style from '../style'
import * as utils from '../utils'
import * as widgets from '../widgets'
const UI = { authn, icons, ns, media, pad, $rdf, store, style, utils, widgets }
/* global alert */
const SERVER_MKDIRP_BUG = true
export async function createIfNotExists (doc, contentType = 'text/turtle', data = '') {
const fetcher = UI.store.fetcher
let response
try {
response = await fetcher.load(doc)
} catch (err) {
if (err.response.status === 404) {
debug.log(
'createIfNotExists: doc does NOT exist, will create... ' + doc
)
try {
response = await fetcher.webOperation('PUT', doc.uri, {
data,
contentType
})
} catch (err) {
debug.log('createIfNotExists doc FAILED: ' + doc + ': ' + err)
throw err
}
delete fetcher.requested[doc.uri] // delete cached 404 error
// debug.log('createIfNotExists doc created ok ' + doc)
return response
} else {
debug.log(
'createIfNotExists doc load error NOT 404: ' + doc + ': ' + err
)
throw err
}
}
// debug.log('createIfNotExists: doc exists, all good: ' + doc)
return response
}
export function desktopNotification (str) {
// Let's check if the browser supports notifications
if (!('Notification' in window)) {
debug.warn('This browser does not support desktop notification')
} else if (Notification.permission === 'granted') {
// Let's check whether notification permissions have already been granted
// eslint-disable-next-line no-new
new Notification(str)
} else if (Notification.permission !== 'denied') {
// Otherwise, we need to ask the user for permission
Notification.requestPermission().then(function (permission) {
// If the user accepts, let's create a notification
if (permission === 'granted') {
// eslint-disable-next-line no-new
new Notification(str)
}
})
}
// At last, if the user has denied notifications, and you
// want to be respectful there is no need to bother them any more.
}
/**
* Common code for a chat (discussion area of messages about something)
* This version runs over a series of files for different time periods
*
* Parameters for the whole chat like its title are stored on
* index.ttl#this and the chats messages are stored in YYYY/MM/DD/chat.ttl
*/
export async function infiniteMessageArea (dom, kb, chatChannel, options) {
kb = kb || UI.store
const ns = UI.ns
const WF = $rdf.Namespace('http://www.w3.org/2005/01/wf/flow#')
const DCT = $rdf.Namespace('http://purl.org/dc/terms/')
// const POSIX = $rdf.Namespace('http://www.w3.org/ns/posix/stat#')
options = options || {}
const newestFirst = options.newestFirst === '1' || options.newestFirst === true // hack for now
const dateFolder = new DateFolder(chatChannel, 'chat.ttl')
options.authorAboveContent = true
// var participation // An object tracking users use and prefs
const messageBodyStyle = UI.style.messageBodyStyle
// var messageBodyStyle = 'white-space: pre-wrap; width: 90%; font-size:100%; border: 0.07em solid #eee; padding: .2em 0.5em; margin: 0.1em 1em 0.1em 1em;'
// 'font-size: 100%; margin: 0.1em 1em 0.1em 1em; background-color: white; white-space: pre-wrap; padding: 0.1em;'
const div = dom.createElement('div')
let menuButton
const statusArea = div.appendChild(dom.createElement('div'))
const userContext = { dom, statusArea, div: statusArea } // logged on state, pointers to user's stuff
let me
const updater = UI.store.updater
/** Does a file exist on the web?
* @returns {Boolean}
*/
/*
async function documentExists (doc) {
try {
await kb.fetcher.load(doc)
} catch (err) {
if (err.response.status === 404) {
return false
} else {
debug.log('documentExists: doc load error NOT 404: ' + doc + ': ' + err)
throw err
}
}
return true
}
*/
/* Form for a new message
*/
function newMessageForm (messageTable) {
const form = dom.createElement('tr')
const lhs = dom.createElement('td')
const middle = dom.createElement('td')
const rhs = dom.createElement('td')
form.appendChild(lhs)
form.appendChild(middle)
form.appendChild(rhs)
form.AJAR_date = '9999-01-01T00:00:00Z' // ISO format for field sort
let field, sendButton
async function sendMessage (text) {
const now = new Date()
await addNewTableIfNewDay(now)
if (!text) {
field.setAttribute('style', messageBodyStyle + 'color: #bbb;') // pendingedit
field.disabled = true
}
const sts = []
const timestamp = '' + now.getTime()
const dateStamp = $rdf.term(now)
const chatDocument = dateFolder.leafDocumentFromDate(now)
const message = kb.sym(chatDocument.uri + '#' + 'Msg' + timestamp)
const content = kb.literal(text || field.value)
// if (text) field.value = text No - don't destroy half-finsihed user input
sts.push(
new $rdf.Statement(chatChannel, ns.wf('message'), message, chatDocument)
)
sts.push(
new $rdf.Statement(message, ns.sioc('content'), content, chatDocument)
)
sts.push(
new $rdf.Statement(message, DCT('created'), dateStamp, chatDocument)
)
if (me) {
sts.push(
new $rdf.Statement(message, ns.foaf('maker'), me, chatDocument)
)
}
function sendComplete () {
const bindings = {
'?msg': message,
'?content': content,
'?date': dateStamp,
'?creator': me
}
renderMessage(liveMessageTable, bindings, false, options, userContext) // not green
if (!text) {
field.value = '' // clear from out for reuse
field.setAttribute('style', messageBodyStyle)
field.disabled = false
field.scrollIntoView(newestFirst) // allign bottom (top)
field.focus() // Start typing next line immediately
field.select()
}
}
if (
SERVER_MKDIRP_BUG &&
(kb.fetcher.requested[chatDocument.uri] === undefined ||
kb.fetcher.requested[chatDocument.uri] === 404)
) {
debug.log(
'@@@ SERVER_MKDIRP_BUG: Should only happen once: create chat file: ' +
chatDocument
)
await createIfNotExists(chatDocument)
}
try {
await updater.update([], sts)
} catch (err) {
form.appendChild(
UI.widgets.errorMessageBlock(dom, 'Error writing message: ' + err)
)
return
}
sendComplete()
} // sendMessage
form.appendChild(dom.createElement('br'))
// DRAG AND DROP
function droppedFileHandler (files) {
const base = messageTable.chatDocument.dir().uri
UI.widgets.uploadFiles(
kb.fetcher,
files,
base + 'Files',
base + 'Pictures',
async function (theFile, destURI) {
// @@@@@@ Wait for eachif several
await sendMessage(destURI)
}
)
}
// When a set of URIs are dropped on the field
const droppedURIHandler = async function (uris) {
for (const uri of uris) {
await sendMessage(uri)
}
}
// When we are actually logged on
function turnOnInput () {
if (options.menuHandler && menuButton) {
const menuOptions = {
me,
dom,
div,
newBase: messageTable.chatDocument.dir().uri
}
menuButton.addEventListener(
'click',
event => {
options.menuHandler(event, chatChannel, menuOptions)
},
false
)
}
// Turn on message input
creatorAndDate(lhs, me, '', null)
field = dom.createElement('textarea')
middle.innerHTML = ''
middle.appendChild(field)
field.rows = 3
// field.cols = 40
field.setAttribute('style', messageBodyStyle + 'background-color: #eef;')
// Trap the Enter BEFORE it is used ti make a newline
field.addEventListener(
'keydown',
async function (e) {
// User preference?
if (e.keyCode === 13) {
if (!e.altKey) {
// Alt-Enter just adds a new line
await sendMessage()
}
}
},
false
)
UI.widgets.makeDropTarget(field, droppedURIHandler, droppedFileHandler)
rhs.innerHTML = ''
sendButton = UI.widgets.button(
dom,
UI.icons.iconBase + 'noun_383448.svg',
'Send'
)
sendButton.setAttribute('style', UI.style.buttonStyle + 'float: right;')
sendButton.addEventListener('click', _event => sendMessage(), false)
rhs.appendChild(sendButton)
const chatDocument = dateFolder.leafDocumentFromDate(new Date())
let imageDoc
function getImageDoc () {
imageDoc = kb.sym(
chatDocument.dir().uri + 'Image_' + Date.now() + '.png'
)
return imageDoc
}
async function tookPicture (imageDoc) {
if (imageDoc) {
await sendMessage(imageDoc.uri)
}
}
middle.appendChild(
UI.media.cameraButton(dom, kb, getImageDoc, tookPicture)
)
UI.pad.recordParticipation(chatChannel, chatChannel.doc()) // participation =
} // turn on inpuut
const context = { div: middle, dom: dom }
UI.authn.logIn(context).then(context => {
me = context.me
turnOnInput()
Object.assign(context, userContext)
findBookmarkDocument(context).then(context => {
debug.log('Bookmark file: ' + context.bookmarkDocument)
})
})
return form
}
// ///////////////////////////////////////////////////////////////////////
function syncMessages (about, messageTable) {
const displayed = {}
let ele, ele2
for (ele = messageTable.firstChild; ele; ele = ele.nextSibling) {
if (ele.AJAR_subject) {
displayed[ele.AJAR_subject.uri] = true
}
}
const messages = kb
.statementsMatching(
about,
ns.wf('message'),
null,
messageTable.chatDocument
)
.map(st => {
return st.object
})
const stored = {}
messages.forEach(function (m) {
stored[m.uri] = true
if (!displayed[m.uri]) {
addMessage(m, messageTable)
}
})
// eslint-disable-next-line space-in-parens
for (ele = messageTable.firstChild; ele;) {
ele2 = ele.nextSibling
if (ele.AJAR_subject && !stored[ele.AJAR_subject.uri]) {
messageTable.removeChild(ele)
}
ele = ele2
}
for (ele = messageTable.firstChild; ele; ele = ele.nextSibling) {
if (ele.AJAR_subject) {
// Refresh thumbs up etc
UI.widgets.refreshTree(ele) // Things inside may have changed too
}
}
} // syncMessages
function addMessage (message, messageTable) {
const bindings = {
'?msg': message,
'?creator': kb.any(message, ns.foaf('maker')),
'?date': kb.any(message, DCT('created')),
'?content': kb.any(message, ns.sioc('content'))
}
renderMessage(
messageTable,
bindings,
messageTable.fresh,
options,
userContext
) // fresh from elsewhere
}
// ////////
/* Add a new messageTable at the top/bottom
*/
async function insertPreviousMessages (backwards) {
const extremity = backwards ? earliest : latest
let date = extremity.messageTable.date // day in mssecs
date = await dateFolder.loadPrevious(date, backwards) // backwards
debug.log(
`insertPreviousMessages: from ${
backwards ? 'backwards' : 'forwards'
} loadPrevious: ${date}`
)
if (!date && !backwards && !liveMessageTable) {
await appendCurrentMessages() // If necessary skip to today and add that
}
if (!date) return true // done
let live = false
if (!backwards) {
const todayDoc = dateFolder.leafDocumentFromDate(new Date())
const doc = dateFolder.leafDocumentFromDate(date)
live = doc.sameTerm(todayDoc) // Is this todays?
}
const newMessageTable = await createMessageTable(date, live)
extremity.messageTable = newMessageTable // move pointer to earliest
if (backwards ? newestFirst : !newestFirst) {
// put on bottom or top
div.appendChild(newMessageTable)
} else {
// put on top as we scroll back
div.insertBefore(newMessageTable, div.firstChild)
}
return live // not done
}
/* Remove message tables earlier than this one
*/
function removePreviousMessages (backwards, messageTable) {
if (backwards ? newestFirst : !newestFirst) {
// it was put on bottom
while (messageTable.nextSibling) {
div.removeChild(messageTable.nextSibling)
}
} else {
// it was put on top as we scroll back
while (messageTable.previousSibling) {
div.removeChild(messageTable.previousSibling)
}
}
const extr = backwards ? earliest : latest
extr.messageTable = messageTable
}
/* Load and render message table
** @returns DOM element generates
*/
async function createMessageTable (date, live) {
debug.log(' createMessageTable for ' + date)
const chatDocument = dateFolder.leafDocumentFromDate(date)
try {
await kb.fetcher.load(chatDocument)
} catch (err) {
const messageTable = dom.createElement('table')
const statusTR = messageTable.appendChild(dom.createElement('tr')) // ### find status in exception
if (err.response && err.response.status && err.response.status === 404) {
debug.log('Error 404 for chat file ' + chatDocument)
return renderMessageTable(date, live) // no mssage file is fine.. will be craeted later
// statusTR.appendChild(UI.widgets.errorMessageBlock(dom, 'no message file', 'white'))
} else {
debug.log('*** Error NON 404 for chat file ' + chatDocument)
statusTR.appendChild(UI.widgets.errorMessageBlock(dom, err, 'pink'))
}
return statusTR
}
return renderMessageTable(date, live)
}
function renderMessageTable (date, live) {
let scrollBackButton
let scrollForwardButton
/// ///////////////// Scroll down adding more above
async function extendBackwards () {
const done = await insertPreviousMessages(true)
if (done) {
if (scrollBackButton) {
scrollBackButton.firstChild.setAttribute(
'src',
UI.icons.iconBase + 'noun_T-Block_1114655_000000.svg'
) // T
scrollBackButton.disabled = true
}
messageTable.initial = true
} else {
messageTable.extendedBack = true
}
setScrollBackButtonIcon()
return done
}
function setScrollBackButtonIcon () {
if (!scrollBackButton) {
return
}
const sense = messageTable.extendedBack ? !newestFirst : newestFirst
const scrollBackIcon = messageTable.initial
? 'noun_T-Block_1114655_000000.svg'
: getScrollbackIcon(sense)
scrollBackButton.firstChild.setAttribute(
'src',
UI.icons.iconBase + scrollBackIcon
)
function getScrollbackIcon (sense) {
return sense ? 'noun_1369241.svg' : 'noun_1369237.svg'
}
}
async function scrollBackButtonHandler (_event) {
if (messageTable.extendedBack) {
removePreviousMessages(true, messageTable)
messageTable.extendedBack = false
setScrollBackButtonIcon()
} else {
await extendBackwards()
}
}
/// ////////////// Scroll up adding more below
async function extendForwards () {
const done = await insertPreviousMessages(false)
if (done) {
scrollForwardButton.firstChild.setAttribute(
'src',
UI.icons.iconBase + 'noun_T-Block_1114655_000000.svg'
)
scrollForwardButton.disabled = true
messageTable.final = true
} else {
messageTable.extendedForwards = true
}
setScrollForwardButtonIcon()
return done
}
function setScrollForwardButtonIcon () {
const sense = messageTable.extendedForwards ? !newestFirst : newestFirst // noun_T-Block_1114657_000000.svg
const scrollForwardIcon = messageTable.final
? 'noun_T-Block_1114657_000000.svg'
: getScrollForwardButtonIcon(sense)
scrollForwardButton.firstChild.setAttribute(
'src',
UI.icons.iconBase + scrollForwardIcon
)
function getScrollForwardButtonIcon (sense) {
return !sense ? 'noun_1369241.svg' : 'noun_1369237.svg'
}
}
async function scrollForwardButtonHandler (_event) {
if (messageTable.extendedForwards) {
removePreviousMessages(false, messageTable)
messageTable.extendedForwards = false
setScrollForwardButtonIcon()
} else {
await extendForwards() // async
latest.messageTable.scrollIntoView(newestFirst)
}
}
/// ///////////////////////
const messageTable = dom.createElement('table')
messageTable.extendBackwards = extendBackwards // Make function available to scroll stuff
messageTable.extendForwards = extendForwards // Make function available to scroll stuff
messageTable.date = date
const chatDocument = dateFolder.leafDocumentFromDate(date)
messageTable.chatDocument = chatDocument
messageTable.fresh = false
messageTable.setAttribute('style', 'width: 100%;') // fill that div!
if (live) {
messageTable.final = true
liveMessageTable = messageTable
latest.messageTable = messageTable
const tr = newMessageForm(messageTable)
if (newestFirst) {
messageTable.insertBefore(tr, messageTable.firstChild) // If newestFirst
} else {
messageTable.appendChild(tr) // not newestFirst
}
messageTable.inputRow = tr
}
/// ///// Infinite scroll
//
// @@ listen for swipe past end event not just button
if (options.infinite) {
const scrollBackButtonTR = dom.createElement('tr')
const scrollBackButtonCell = scrollBackButtonTR.appendChild(
dom.createElement('td')
)
// up traingles: noun_1369237.svg
// down triangles: noun_1369241.svg
const scrollBackIcon = newestFirst
? 'noun_1369241.svg'
: 'noun_1369237.svg' // down and up arrows respoctively
scrollBackButton = UI.widgets.button(
dom,
UI.icons.iconBase + scrollBackIcon,
'Previous messages ...'
)
scrollBackButtonCell.style = 'width:3em; height:3em;'
scrollBackButton.addEventListener('click', scrollBackButtonHandler, false)
messageTable.extendedBack = false
scrollBackButtonCell.appendChild(scrollBackButton)
setScrollBackButtonIcon()
const dateCell = scrollBackButtonTR.appendChild(dom.createElement('td'))
dateCell.style =
'text-align: center; vertical-align: middle; color: #888; font-style: italic;'
dateCell.textContent = UI.widgets.shortDate(date.toISOString(), true) // no time, only date
// @@@@@@@@@@@ todo move this button to other end of message cell, o
const scrollForwardButtonCell = scrollBackButtonTR.appendChild(
dom.createElement('td')
)
const scrollForwardIcon = newestFirst
? 'noun_1369241.svg'
: 'noun_1369237.svg' // down and up arrows respoctively
scrollForwardButton = UI.widgets.button(
dom,
UI.icons.iconBase + scrollForwardIcon,
'Later messages ...'
)
scrollForwardButtonCell.appendChild(scrollForwardButton)
scrollForwardButtonCell.style = 'width:3em; height:3em;'
scrollForwardButton.addEventListener(
'click',
scrollForwardButtonHandler,
false
)
messageTable.extendedForward = false
setScrollForwardButtonIcon()
messageTable.extendedForwards = false
if (!newestFirst) {
// opposite end from the entry field
messageTable.insertBefore(scrollBackButtonTR, messageTable.firstChild) // If not newestFirst
} else {
messageTable.appendChild(scrollBackButtonTR) // newestFirst
}
}
const sts = kb.statementsMatching(null, WF('message'), null, chatDocument)
if (!live && sts.length === 0) {
// not todays
// no need buttomns at the moment
// messageTable.style.visibility = 'collapse' // Hide files with no messages
}
sts.forEach(st => {
addMessage(st.object, messageTable)
})
messageTable.fresh = true
// loadMessageTable(messageTable, chatDocument)
messageTable.fresh = false
return messageTable
} // renderMessageTable
async function addNewTableIfNewDay (now) {
// let now = new Date()
// @@ Remove listener from previous table as it is now static
const newChatDocument = dateFolder.leafDocumentFromDate(now)
if (!newChatDocument.sameTerm(latest.messageTable.chatDocument)) {
// It is a new day
if (liveMessageTable.inputRow) {
liveMessageTable.removeChild(liveMessageTable.inputRow)
delete liveMessageTable.inputRow
}
const oldChatDocument = latest.messageTable.chatDocument
await appendCurrentMessages()
// Adding a link in the document will ping listeners to add the new block too
if (
!kb.holds(
oldChatDocument,
ns.rdfs('seeAlso'),
newChatDocument,
oldChatDocument
)
) {
const sts = [
$rdf.st(
oldChatDocument,
ns.rdfs('seeAlso'),
newChatDocument,
oldChatDocument
)
]
updater.update([], sts, function (ok, body) {
if (!ok) {
alert('Unable to link old message block to new one.' + body)
}
})
}
}
}
/*
function messageCount () {
var n = 0
const tables = div.children
for (let i = 0; i < tables.length; i++) {
n += tables[i].children.length - 1
// debug.log(' table length:' + tables[i].children.length)
}
return n
}
*/
/* Add the live message block with entry field for today
*/
async function appendCurrentMessages () {
const now = new Date()
const chatDocument = dateFolder.leafDocumentFromDate(now)
/* Don't actually make the documemnt until a message is sent @@@@@ WHEN SERVER FIXED
* currently server won't patch to a file ina non-existent directory
*/
/*
if (SERVER_MKDIRP_BUG) {
try {
await createIfNotExists(chatDocument)
} catch (e) {
div.appendChild(UI.widgets.errorMessageBlock(
dom, 'Problem accessing chat file: ' + e))
return
}
}
*/
/// ///////////////////////////////////////////////////////////
const messageTable = await createMessageTable(now, true)
div.appendChild(messageTable)
div.refresh = function () {
// only the last messageTable is live
addNewTableIfNewDay(new Date()).then(() => {
syncMessages(chatChannel, messageTable)
desktopNotification(chatChannel)
})
} // The short chat version fors live update in the pane but we do it in the widget
kb.updater.addDownstreamChangeListener(chatDocument, div.refresh) // Live update
liveMessageTable = messageTable
latest.messageTable = liveMessageTable
return messageTable
}
let liveMessageTable
const earliest = { messageTable: null } // Stuff about each end of the loaded days
const latest = { messageTable: null }
let lock = false
async function loadMoreWhereNeeded (event, fixScroll) {
if (lock) return
lock = true
const freeze = !fixScroll
const magicZone = 150
// const top = div.scrollTop
// const bottom = div.scrollHeight - top - div.clientHeight
let done
while (
div.scrollTop < magicZone &&
earliest.messageTable &&
!earliest.messageTable.initial &&
earliest.messageTable.extendBackwards
) {
// If this has been called before the element is actually in the
// user's DOM tree, then this scrollTop check won't work -> loop forever
// https://github.com/solid/solid-ui/issues/366
if (div.scrollHeight === 0) {
// console.log(' chat/loadMoreWhereNeeded: trying later...')
setTimeout(loadMoreWhereNeeded, 2000) // couple be less
lock = false
return // abandon now, do later
}
// console.log(' chat/loadMoreWhereNeeded: Going now')
const scrollBottom = div.scrollHeight - div.scrollTop
debug.log('infinite scroll: adding above: top ' + div.scrollTop)
done = await earliest.messageTable.extendBackwards()
if (freeze) {
div.scrollTop = div.scrollHeight - scrollBottom
}
if (fixScroll) fixScroll()
if (done) break
}
while (
options.selectedMessage && // we started in the middle not at the bottom
div.scrollHeight - div.scrollTop - div.clientHeight < magicZone && // we are scrolled right to the bottom
latest.messageTable &&
!latest.messageTable.final && // there is more data to come
latest.messageTable.extendForwards
) {
const scrollTop = div.scrollTop
debug.log(
'infinite scroll: adding below: bottom: ' +
(div.scrollHeight - div.scrollTop - div.clientHeight)
)
done = await latest.messageTable.extendForwards() // then add more data on the bottom
if (freeze) {
div.scrollTop = scrollTop // while adding below keep same things in view
}
if (fixScroll) fixScroll()
if (done) break
}
lock = false
}
async function loadInitialContent () {
function yank () {
selectedMessageTable.selectedElement.scrollIntoView({ block: 'center' })
}
// During initial load ONLY keep scroll to selected thing or bottom
function fixScroll () {
if (options.selectedElement) {
options.selectedElement.scrollIntoView({ block: 'center' }) // align tops or bottoms
} else {
if (liveMessageTable.inputRow.scrollIntoView) {
liveMessageTable.inputRow.scrollIntoView(newestFirst) // align tops or bottoms
}
}
}
let live, selectedDocument
if (options.selectedMessage) {
selectedDocument = options.selectedMessage.doc()
const now = new Date()
const todayDocument = dateFolder.leafDocumentFromDate(now)
live = todayDocument.sameTerm(selectedDocument)
}
let selectedMessageTable
if (options.selectedMessage && !live) {
const selectedDate = dateFolder.dateFromLeafDocument(selectedDocument)
selectedMessageTable = await createMessageTable(selectedDate, live)
div.appendChild(selectedMessageTable)
earliest.messageTable = selectedMessageTable
latest.messageTable = selectedMessageTable
yank()
setTimeout(yank, 1000) // @@ kludge - restore position distubed by other cHANGES
} else {
// Live end
await appendCurrentMessages()
earliest.messageTable = liveMessageTable
latest.messageTable = liveMessageTable
}
await loadMoreWhereNeeded(null, fixScroll)
div.addEventListener('scroll', loadMoreWhereNeeded)
if (options.solo) {
document.body.addEventListener('scroll', loadMoreWhereNeeded)
}
}
await loadInitialContent()
return div
}