This commit is contained in:
retoor 2025-07-30 02:51:26 +02:00
parent 6337350b60
commit 59b0494328
2 changed files with 98 additions and 91 deletions

View File

@ -5,64 +5,65 @@
// The code seems to rely on some external dependencies like 'models.Message', 'app', and 'Schedule'. These should be imported or defined elsewhere in your application.
// MIT License: This is free software. Permission is granted to use, copy, modify, and/or distribute this software for any purpose with or without fee. The software is provided "as is" without any warranty.
import {app} from "./app.js";
import { app } from "./app.js";
const LONG_TIME = 1000 * 60 * 20
const LONG_TIME = 1000 * 60 * 20;
export class ReplyEvent extends Event {
constructor(messageTextTarget) {
super('reply', { bubbles: true, composed: true });
this.messageTextTarget = messageTextTarget;
constructor(messageTextTarget) {
super('reply', { bubbles: true, composed: true });
this.messageTextTarget = messageTextTarget;
const newMessage = messageTextTarget.cloneNode(true);
newMessage.style.maxHeight = "0"
messageTextTarget.parentElement.insertBefore(newMessage, messageTextTarget);
// Clone and sanitize message node to text-only reply
const newMessage = messageTextTarget.cloneNode(true);
newMessage.style.maxHeight = "0";
messageTextTarget.parentElement.insertBefore(newMessage, messageTextTarget);
newMessage.querySelectorAll('.embed-url-link').forEach(link => {
link.remove()
})
// Remove all .embed-url-link
newMessage.querySelectorAll('.embed-url-link').forEach(link => link.remove());
newMessage.querySelectorAll('picture').forEach(picture => {
const img = picture.querySelector('img');
if (img) {
picture.replaceWith(img);
}
})
// Replace <picture> with their <img>
newMessage.querySelectorAll('picture').forEach(picture => {
const img = picture.querySelector('img');
if (img) picture.replaceWith(img);
});
newMessage.querySelectorAll('img').forEach(img => {
const src = img.src || img.currentSrc;
img.replaceWith(document.createTextNode(src));
})
// Replace <img> with just their src
newMessage.querySelectorAll('img').forEach(img => {
const src = img.src || img.currentSrc;
img.replaceWith(document.createTextNode(src));
});
newMessage.querySelectorAll('iframe').forEach(iframe => {
const src = iframe.src || iframe.currentSrc;
iframe.replaceWith(document.createTextNode(src));
})
// Replace <iframe> with their src
newMessage.querySelectorAll('iframe').forEach(iframe => {
const src = iframe.src || iframe.currentSrc;
iframe.replaceWith(document.createTextNode(src));
});
newMessage.querySelectorAll('a').forEach(a => {
const href = a.getAttribute('href');
const text = a.innerText || a.textContent;
if (text === href || text === '') {
a.replaceWith(document.createTextNode(href));
} else {
a.replaceWith(document.createTextNode(`[${text}](${href})`));
}
})
// Replace <a> with href or markdown
newMessage.querySelectorAll('a').forEach(a => {
const href = a.getAttribute('href');
const text = a.innerText || a.textContent;
if (text === href || text === '') {
a.replaceWith(document.createTextNode(href));
} else {
a.replaceWith(document.createTextNode(`[${text}](${href})`));
}
});
this.replyText = newMessage.innerText.replaceAll("\n\n", "\n").trim();
newMessage.remove()
}
this.replyText = newMessage.innerText.replaceAll("\n\n", "\n").trim();
newMessage.remove();
}
}
class MessageElement extends HTMLElement {
// static observedAttributes = ['data-uid', 'data-color', 'data-channel_uid', 'data-user_nick', 'data-created_at', 'data-user_uid'];
updateUI() {
if (this._originalChildren === undefined) {
const { color, user_nick, created_at, user_uid} = this.dataset;
const { color, user_nick, created_at, user_uid } = this.dataset;
this.classList.add('message');
this.style.maxWidth = '100%';
this._originalChildren = Array.from(this.children);
this.innerHTML = `
<a class="avatar" style="background-color: ${color || ''}; color: black;" href="/user/${user_uid || ''}.html">
<img class="avatar-img" width="40" height="40" src="/avatar/${user_uid || ''}.svg" alt="${user_nick || ''}" loading="lazy">
@ -72,27 +73,28 @@ class MessageElement extends HTMLElement {
<div class="text"></div>
<div class="time no-select" data-created_at="${created_at || ''}">
<span></span>
<a href="#reply">reply</a></div>
<a href="#reply">reply</a>
</div>
`;
</div>
`;
this.messageDiv = this.querySelector('.text');
if (this._originalChildren && this._originalChildren.length > 0) {
this._originalChildren.forEach(child => {
this.messageDiv.appendChild(child);
});
this._originalChildren.forEach(child => {
this.messageDiv.appendChild(child);
});
}
this.timeDiv = this.querySelector('.time span');
this.replyDiv = this.querySelector('.time a');
this.replyDiv.addEventListener('click', (e) => {
e.preventDefault();
this.dispatchEvent(new ReplyEvent(this.messageDiv));
})
this.replyDiv.addEventListener('click', (e) => {
e.preventDefault();
this.dispatchEvent(new ReplyEvent(this.messageDiv));
});
}
// Sibling logic for user switches and long time gaps
if ((!this.siblingGenerated || this.siblingGenerated !== this.nextElementSibling) && this.nextElementSibling) {
this.siblingGenerated = this.nextElementSibling;
if (this.nextElementSibling?.dataset?.user_uid !== this.dataset.user_uid) {
@ -102,7 +104,7 @@ class MessageElement extends HTMLElement {
const siblingTime = new Date(this.nextElementSibling.dataset.created_at);
const currentTime = new Date(this.dataset.created_at);
if (currentTime.getTime() - siblingTime.getTime() > LONG_TIME) {
if (currentTime.getTime() - siblingTime.getTime() > LONG_TIME) {
this.classList.add('long-time');
} else {
this.classList.remove('long-time');
@ -115,7 +117,7 @@ class MessageElement extends HTMLElement {
updateMessage(...messages) {
if (this._originalChildren) {
this.messageDiv.replaceChildren(...messages)
this.messageDiv.replaceChildren(...messages);
this._originalChildren = messages;
}
}
@ -124,38 +126,26 @@ class MessageElement extends HTMLElement {
this.updateUI();
}
disconnectedCallback() {
}
connectedMoveCallback() {
}
disconnectedCallback() {}
connectedMoveCallback() {}
attributeChangedCallback(name, oldValue, newValue) {
this.updateUI()
this.updateUI();
}
}
class MessageList extends HTMLElement {
constructor() {
super();
app.ws.addEventListener("update_message_text", (data) => {
if (this.messageMap.has(data.uid)) {
this.upsertMessage(data);
}
});
app.ws.addEventListener("set_typing", (data) => {
this.triggerGlow(data.user_uid,data.color);
});
this.messageMap = new Map();
this.visibleSet = new Set();
this._observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
this.visibleSet.add(entry.target);
const messageElement = entry.target;
if (messageElement instanceof MessageElement) {
messageElement.updateUI();
if (entry.target instanceof MessageElement) {
entry.target.updateUI();
}
} else {
this.visibleSet.delete(entry.target);
@ -164,28 +154,42 @@ class MessageList extends HTMLElement {
}, {
root: this,
threshold: 0,
})
});
// End-of-messages marker
this.endOfMessages = document.createElement('div');
this.endOfMessages.classList.add('message-list-bottom');
this.prepend(this.endOfMessages);
for(const c of this.children) {
// Observe existing children and index by uid
for (const c of this.children) {
this._observer.observe(c);
if (c instanceof MessageElement) {
this.messageMap.set(c.dataset.uid, c);
this.messageMap.set(c.dataset.uid, c);
}
}
// Wire up socket events
app.ws.addEventListener("update_message_text", (data) => {
if (this.messageMap.has(data.uid)) {
this.upsertMessage(data);
}
});
app.ws.addEventListener("set_typing", (data) => {
this.triggerGlow(data.user_uid, data.color);
});
this.scrollToBottom(true);
}
connectedCallback() {
this.addEventListener('click', (e) => {
if (e.target.tagName !== 'IMG' || e.target.classList.contains('avatar-img')) return;
if (
e.target.tagName !== 'IMG' ||
e.target.classList.contains('avatar-img')
) return;
const img = e.target;
const overlay = document.createElement('div');
overlay.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.9);display:flex;justify-content:center;align-items:center;z-index:9999;cursor:pointer;';
@ -206,12 +210,11 @@ class MessageList extends HTMLElement {
overlay.appendChild(fullImg);
document.body.appendChild(overlay);
overlay.addEventListener('click', () => {
if (overlay.parentNode) {
overlay.parentNode.removeChild(overlay);
}
if (overlay.parentNode) overlay.parentNode.removeChild(overlay);
});
// Optional: ESC key closes overlay
// ESC to close
const escListener = (evt) => {
if (evt.key === 'Escape') {
if (overlay.parentNode) overlay.parentNode.removeChild(overlay);
@ -219,8 +222,9 @@ class MessageList extends HTMLElement {
}
};
document.addEventListener('keydown', escListener);
})
});
}
isElementVisible(element) {
if (!element) return false;
const rect = element.getBoundingClientRect();
@ -231,10 +235,12 @@ class MessageList extends HTMLElement {
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
isScrolledToBottom() {
return this.visibleSet.has(this.endOfMessages)
return this.visibleSet.has(this.endOfMessages);
}
scrollToBottom(force = false, behavior= 'instant') {
scrollToBottom(force = false, behavior = 'instant') {
if (force || !this.isScrolledToBottom()) {
this.endOfMessages.scrollIntoView({ behavior, block: 'end' });
setTimeout(() => {
@ -261,30 +267,29 @@ class MessageList extends HTMLElement {
}
}
updateTimes() {
this.visibleSet.forEach((messageElement) => {
if (messageElement instanceof MessageElement) {
messageElement.updateUI();
}
})
if (messageElement instanceof MessageElement) {
messageElement.updateUI();
}
});
}
upsertMessage(data) {
let message = this.messageMap.get(data.uid);
if (message) {
message.parentElement?.removeChild(message);
message.parentElement?.removeChild(message);
}
if (!data.message) return
if (!data.message) return;
const wrapper = document.createElement("div");
wrapper.innerHTML = data.html;
if (message) {
// If the old element is already custom, only update its message children
message.updateMessage(...(wrapper.firstElementChild._originalChildren || wrapper.firstElementChild.children));
} else {
// If not, insert the new one and observe
message = wrapper.firstElementChild;
this.messageMap.set(data.uid, message);
this._observer.observe(message);
@ -298,3 +303,4 @@ class MessageList extends HTMLElement {
customElements.define("chat-message", MessageElement);
customElements.define("message-list", MessageList);

View File

@ -188,6 +188,7 @@ class WebdavApplication(aiohttp.web.Application):
headers = {
"DAV": "1, 2",
"Allow": "OPTIONS, GET, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND, PROPPATCH, PROPGET, PROPSET, PROPDEL",
"MS-Author-Via": "DAV",
}
return aiohttp.web.Response(status=200, headers=headers)