1
0
mirror of https://github.com/wbbaddons/Tims-Chat.git synced 2024-12-22 21:40:08 +00:00
Tims-Chat/files_wcf/js/Bastelstu.be/Chat/Ui/MessageStream.js

399 lines
11 KiB
JavaScript
Raw Normal View History

2018-08-16 22:30:59 +00:00
/*
2021-02-04 22:04:35 +00:00
* Copyright (c) 2010-2021 Tim Düsterhus.
2018-08-16 22:30:59 +00:00
*
* Use of this software is governed by the Business Source License
* included in the LICENSE file.
*
2022-09-17 14:23:02 +00:00
* Change Date: 2026-09-17
2018-08-16 22:30:59 +00:00
*
* On the date above, in accordance with the Business Source
* License, use of this software will be governed by version 2
* or later of the General Public License.
*/
2020-11-01 16:41:19 +00:00
define([
'../Helper',
'WoltLabSuite/Core/Date/Util',
'WoltLabSuite/Core/Dom/Change/Listener',
'WoltLabSuite/Core/Language',
'WoltLabSuite/Core/User',
'WoltLabSuite/Core/Dom/Traverse',
'../DataStructure/EventEmitter',
'../DataStructure/RedBlackTree/Tree',
], function (
Helper,
DateUtil,
DomChangeListener,
Language,
User,
DOMTraverse,
EventEmitter,
Tree
) {
'use strict'
2018-08-16 22:30:59 +00:00
const enableAutoscroll = Symbol('enableAutoscroll')
2020-11-01 16:41:19 +00:00
const DEPENDENCIES = []
2018-08-16 22:30:59 +00:00
class MessageStream {
constructor() {
this.stream = elById('chatMessageStream')
this.scrollContainer = elBySel('.scrollContainer', this.stream)
2020-11-01 16:41:19 +00:00
this[enableAutoscroll] = true
2018-08-16 22:30:59 +00:00
this.lastScrollPosition = undefined
2020-11-01 16:41:19 +00:00
this.nodeMap = new WeakMap()
this.positions = new Tree()
2018-08-16 22:30:59 +00:00
}
get enableAutoscroll() {
return this[enableAutoscroll]
}
set enableAutoscroll(value) {
this[enableAutoscroll] = value
if (this[enableAutoscroll]) {
this.scrollToBottom()
}
}
bootstrap() {
this.scrollContainer.addEventListener('copy', this.onCopy.bind(this))
2020-11-01 16:41:19 +00:00
this.scrollContainer.addEventListener(
'scroll',
Helper.throttle(this.onScroll, 100, this),
{ passive: true }
)
2018-08-16 22:30:59 +00:00
}
getDateMarker(date) {
const dateMarker = elCreate('li')
dateMarker.classList.add('dateMarker')
const time = elCreate('time')
time.innerText = DateUtil.formatDate(date)
time.setAttribute('datetime', DateUtil.format(date, 'Y-m-d'))
dateMarker.appendChild(time)
return dateMarker
}
onDifferentDays(a, b) {
return DateUtil.format(a, 'Y-m-d') !== DateUtil.format(b, 'Y-m-d')
}
ingest(messages) {
2020-11-01 16:41:19 +00:00
let scrollTopBefore = this.enableAutoscroll
? 0
: this.scrollContainer.scrollTop
2018-08-16 22:30:59 +00:00
let prependedHeight = 0
2020-11-01 16:41:19 +00:00
const ul = elBySel('ul', this.scrollContainer)
2018-08-16 22:30:59 +00:00
const first = ul.firstElementChild
2020-11-01 16:41:19 +00:00
const ingested = messages.map(
function (item) {
let currentScrollHeight = 0
const li = elCreate('li')
// Allow messages types to not render a messages
// This can be used for status messages like ChatUpdate
let fragment
if ((fragment = item.getMessageType().render(item)) === false) return
if (
fragment.querySelector(
`.userMention[data-user-id="${User.userId}"]`
)
)
li.classList.add('mentioned')
li.appendChild(fragment)
li.classList.add('chatMessageBoundary')
li.setAttribute('id', `message-${item.messageID}`)
li.dataset.objectType = item.objectType
li.dataset.userId = item.userID
if (item.isOwnMessage()) li.classList.add('own')
if (item.isDeleted) li.classList.add('tombstone')
const position = this.positions.insert(item.messageID)
if (position[1] !== undefined) {
const sibling = elById(`message-${position[1]}`)
if (!sibling) throw new Error('Unreachable')
let nodeBefore, nodeAfter
let dateMarkerBetween = false
if (position[0] === 'LEFT') {
nodeAfter = sibling
2018-08-16 22:30:59 +00:00
nodeBefore = sibling.previousElementSibling
2020-11-01 16:41:19 +00:00
if (nodeBefore && nodeBefore.classList.contains('dateMarker')) {
elRemove(nodeBefore)
nodeBefore = sibling.previousElementSibling
}
} else if (position[0] === 'RIGHT') {
nodeBefore = sibling
2018-08-16 22:30:59 +00:00
nodeAfter = sibling.nextElementSibling
2020-11-01 16:41:19 +00:00
if (nodeAfter && nodeAfter.classList.contains('dateMarker')) {
elRemove(nodeAfter)
nodeAfter = sibling.nextElementSibling
}
} else {
throw new Error('Unreachable')
2018-08-16 22:30:59 +00:00
}
2020-11-01 16:41:19 +00:00
const messageBefore = this.nodeMap.get(nodeBefore)
if (nodeBefore && !messageBefore) throw new Error('Unreachable')
const messageAfter = this.nodeMap.get(nodeAfter)
if (nodeAfter && !messageAfter) throw new Error('Unreachable')
2018-08-16 22:30:59 +00:00
2020-11-01 16:41:19 +00:00
if (!this.enableAutoscroll && nodeAfter)
currentScrollHeight = this.scrollContainer.scrollHeight
2018-08-16 22:30:59 +00:00
2020-11-01 16:41:19 +00:00
let context = nodeAfter
if (nodeAfter) nodeAfter.classList.remove('first')
if (messageBefore) {
if (this.onDifferentDays(messageBefore.date, item.date)) {
const dateMarker = this.getDateMarker(item.date)
ul.insertBefore(dateMarker, nodeAfter)
2018-08-16 22:30:59 +00:00
li.classList.add('first')
2020-11-01 16:41:19 +00:00
} else {
if (
messageBefore.objectType !== item.objectType ||
!item.getMessageType().joinable(messageBefore, item)
) {
li.classList.add('first')
}
2018-08-16 22:30:59 +00:00
}
2020-11-01 16:41:19 +00:00
} else {
li.classList.add('first')
2018-08-16 22:30:59 +00:00
}
2020-11-01 16:41:19 +00:00
if (messageAfter) {
if (this.onDifferentDays(messageAfter.date, item.date)) {
const dateMarker = this.getDateMarker(messageAfter.date)
ul.insertBefore(dateMarker, nodeAfter)
context = dateMarker
2018-08-16 22:30:59 +00:00
nodeAfter.classList.add('first')
2020-11-01 16:41:19 +00:00
} else {
if (
messageAfter.objectType !== item.objectType ||
!item.getMessageType().joinable(item, messageAfter)
) {
nodeAfter.classList.add('first')
}
2018-08-16 22:30:59 +00:00
}
}
2020-11-01 16:41:19 +00:00
ul.insertBefore(li, context)
2018-08-16 22:30:59 +00:00
2020-11-01 16:41:19 +00:00
if (!this.enableAutoscroll && nodeAfter) {
prependedHeight +=
this.scrollContainer.scrollHeight - currentScrollHeight
}
} else {
li.classList.add('first')
ul.insertBefore(li, null)
2018-08-16 22:30:59 +00:00
}
2020-11-01 16:41:19 +00:00
this.nodeMap.set(li, item)
2018-08-16 22:30:59 +00:00
2020-11-01 16:41:19 +00:00
return { node: li, message: item }
}.bind(this)
)
2018-08-16 22:30:59 +00:00
2020-11-01 16:41:19 +00:00
if (ingested.some((item) => item != null)) {
2018-08-16 22:30:59 +00:00
if (this.enableAutoscroll) {
this.scrollToBottom()
2020-11-01 16:41:19 +00:00
} else {
2018-08-16 22:30:59 +00:00
this.stream.classList.add('activity')
this.scrollContainer.scrollTop = scrollTopBefore + prependedHeight
}
}
DomChangeListener.trigger()
this.emit('ingested', ingested)
}
scrollToBottom() {
this.scrollContainer.scrollTop = this.scrollContainer.scrollHeight
this.stream.classList.remove('activity')
}
onScroll() {
const { scrollTop, scrollHeight, clientHeight } = this.scrollContainer
const distanceFromTop = scrollTop
const distanceFromBottom = scrollHeight - scrollTop - clientHeight
let direction = 'down'
2020-11-01 16:41:19 +00:00
if (
this.lastScrollPosition != null &&
scrollTop < this.lastScrollPosition
) {
direction = 'up'
2018-08-16 22:30:59 +00:00
}
if (direction === 'up') {
if (distanceFromBottom > 7) {
this.emit('scrollUp')
}
if (distanceFromTop <= 7) {
this.emit('reachedTop')
2020-11-01 16:41:19 +00:00
} else if (distanceFromTop <= 300) {
2018-08-16 22:30:59 +00:00
this.emit('nearTop')
}
2020-11-01 16:41:19 +00:00
} else if (direction === 'down') {
2018-08-16 22:30:59 +00:00
if (distanceFromTop > 7) {
this.emit('scrollDown')
}
if (distanceFromBottom <= 7) {
this.scrollToBottom()
this.emit('reachedBottom')
2020-11-01 16:41:19 +00:00
} else if (distanceFromBottom <= 300) {
2018-08-16 22:30:59 +00:00
this.emit('nearBottom')
}
}
this.lastScrollPosition = scrollTop
}
onCopy(event) {
const selection = window.getSelection()
// Similar to selecting nothing
if (selection.isCollapsed) return
// Get the first and last node in the selection
let originalStart, start, end, originalEnd
start = originalStart = selection.getRangeAt(0).startContainer
2021-09-17 13:14:39 +00:00
end = originalEnd = selection.getRangeAt(
selection.rangeCount - 1
).endContainer
2018-08-16 22:30:59 +00:00
const startOffset = selection.getRangeAt(0).startOffset
2020-11-01 16:41:19 +00:00
const endOffset = selection.getRangeAt(selection.rangeCount - 1).endOffset
2018-08-16 22:30:59 +00:00
// The Traverse module needs nodes of the Element type, the selected elements could be of type Text
2020-11-01 16:41:19 +00:00
while (!(start instanceof Element) && start.parentNode)
start = start.parentNode
2018-08-16 22:30:59 +00:00
while (!(end instanceof Element) && end.parentNode) end = end.parentNode
2020-11-01 16:41:19 +00:00
if (!start || !end)
throw new Error('Unexpected error, no element nodes in selection')
2018-08-16 22:30:59 +00:00
// Try to find the starting li element in the selection
if (!start.id || start.id.indexOf('message-') !== 0) {
start = DOMTraverse.parentBySel(start, "li[id^='message']", this.stream)
}
// Try to find the ending li element in the selection
if (!end.id || end.id.indexOf('message-') !== 0) {
end = DOMTraverse.parentBySel(end, "li[id^='message']", this.stream)
}
// Do not select a message if we selected only a new line
2020-11-01 16:41:19 +00:00
if (
originalStart instanceof Text &&
originalStart.textContent.substring(startOffset) === ''
) {
2018-08-16 22:30:59 +00:00
start = DOMTraverse.next(start)
}
// The selection went outside of the stream container, end at the last li element
if (end === null) {
end = elBySel('ul > li:last-child', this.stream)
}
// Discard the selection, we selected only whitespace between two messages
if (start === end && endOffset === 0) return
// Do not include the ending message if there is no visible selection
if (start !== end && endOffset === 0) {
end = DOMTraverse.prev(end)
}
2020-11-01 16:41:19 +00:00
const elements = []
let next = start
2018-08-16 22:30:59 +00:00
do {
elements.push(next)
if (next === end) break
2020-11-01 16:41:19 +00:00
} while ((next = DOMTraverse.next(next)))
2018-08-16 22:30:59 +00:00
// Only apply our custom formatting when selecting multiple or whole messages
if (elements.length === 1) {
const range = document.createRange()
range.setStart(originalStart, startOffset)
range.setEnd(originalEnd, endOffset)
2020-11-01 16:41:19 +00:00
if (
!Helper.rangeSpansTextContent(
range,
start.querySelector('.chatMessage')
)
)
return
2018-08-16 22:30:59 +00:00
}
try {
2020-11-01 16:41:19 +00:00
event.clipboardData.setData(
'text/plain',
elements
.map((el, index, arr) => {
const message = this.nodeMap.get(el)
2018-08-16 22:30:59 +00:00
2020-11-01 16:41:19 +00:00
if (el.classList.contains('dateMarker'))
return `== ${el.textContent.trim()} ==`
2018-08-16 22:30:59 +00:00
2020-11-01 16:41:19 +00:00
if (!message) return
2020-11-01 16:41:19 +00:00
if (el.classList.contains('tombstone')) {
return `[${message.formattedTime}] ${Language.get(
'chat.messageType.be.bastelstu.chat.messageType.tombstone.message'
)}`
}
2018-08-16 22:30:59 +00:00
2020-11-01 16:41:19 +00:00
const elem = elBySel('.chatMessage', el)
let body
if (
typeof (body = message
.getMessageType()
.renderPlainText(message)) === 'undefined' ||
body === false
) {
body = Helper.getTextContent(elem)
.replace(/\t+/g, '\t') // collapse multiple tabs
.replace(/ +/g, ' ') // collapse multiple spaces
.replace(/([\t ]*\n){2,}/g, '\n') // collapse line consisting of tabs, spaces and newlines
.replace(/^[\t ]+|[\t ]+$/gm, '') // remove leading and trailing whitespace per line
}
2018-08-16 22:30:59 +00:00
2020-11-01 16:41:19 +00:00
return `[${message.formattedTime}] <${
message.username
}> ${body.trim()}`
})
.filter((x) => x)
.join('\n')
)
2018-08-16 22:30:59 +00:00
event.preventDefault()
2020-11-01 16:41:19 +00:00
} catch (e) {
2018-08-16 22:30:59 +00:00
console.error('Unable to use the clipboard API')
console.error(e)
}
}
}
EventEmitter(MessageStream.prototype)
MessageStream.DEPENDENCIES = DEPENDENCIES
return MessageStream
2020-11-01 16:41:19 +00:00
})