966 lines
24 KiB
JavaScript
966 lines
24 KiB
JavaScript
// chat.js
|
|
|
|
document.addEventListener(
|
|
'DOMContentLoaded',
|
|
() => {
|
|
const messagesContainer =
|
|
document.getElementById(
|
|
'chat-messages'
|
|
);
|
|
|
|
const messageInput =
|
|
document.getElementById(
|
|
'messageInput'
|
|
);
|
|
|
|
const sendBtn =
|
|
document.getElementById(
|
|
'sendBtn'
|
|
);
|
|
|
|
const gifBtn =
|
|
document.getElementById(
|
|
'gifBtn'
|
|
);
|
|
|
|
const fileBtn =
|
|
document.getElementById(
|
|
'fileBtn'
|
|
);
|
|
|
|
const fileInput =
|
|
document.getElementById(
|
|
'fileInput'
|
|
);
|
|
|
|
const chatStatus =
|
|
document.getElementById(
|
|
'chatStatus'
|
|
);
|
|
|
|
const renderedMessages =
|
|
new Set();
|
|
|
|
bindEvents();
|
|
setChatStatus('Room messages');
|
|
requestChatHistory();
|
|
|
|
|
|
function bindEvents() {
|
|
messageInput.addEventListener(
|
|
'keydown',
|
|
event => {
|
|
if (
|
|
event.key === 'Enter'
|
|
&& !event.shiftKey
|
|
) {
|
|
event.preventDefault();
|
|
handleOutboundMessage();
|
|
}
|
|
}
|
|
);
|
|
|
|
sendBtn.addEventListener(
|
|
'click',
|
|
handleOutboundMessage
|
|
);
|
|
|
|
gifBtn.addEventListener(
|
|
'click',
|
|
() => {
|
|
window.parent.postMessage(
|
|
{
|
|
type:
|
|
'KRONICK_CHAT_GIF_PICK'
|
|
},
|
|
window.location.origin
|
|
);
|
|
}
|
|
);
|
|
|
|
if (fileBtn && fileInput) {
|
|
fileBtn.addEventListener(
|
|
'click',
|
|
() => {
|
|
fileInput.click();
|
|
}
|
|
);
|
|
|
|
fileInput.addEventListener(
|
|
'change',
|
|
handleFileSelection
|
|
);
|
|
}
|
|
|
|
window.addEventListener(
|
|
'message',
|
|
handleParentMessage
|
|
);
|
|
}
|
|
|
|
|
|
function requestChatHistory() {
|
|
window.parent.postMessage(
|
|
{
|
|
type:
|
|
'KRONICK_CHAT_HISTORY_REQUEST'
|
|
},
|
|
window.location.origin
|
|
);
|
|
}
|
|
|
|
|
|
function handleParentMessage(event) {
|
|
if (
|
|
event.origin
|
|
!== window.location.origin
|
|
) {
|
|
return;
|
|
}
|
|
|
|
const data =
|
|
event.data;
|
|
|
|
if (
|
|
!data
|
|
|| typeof data !== 'object'
|
|
) {
|
|
return;
|
|
}
|
|
|
|
|
|
if (
|
|
data.type === 'CHAT_HISTORY'
|
|
|| data.type === 'KRONICK_CHAT_HISTORY'
|
|
) {
|
|
handleChatHistory(
|
|
data.messages
|
|
|| data.payload
|
|
);
|
|
|
|
return;
|
|
}
|
|
|
|
|
|
if (
|
|
data.type === 'CHAT_MESSAGE'
|
|
|| data.type === 'CHAT_RECEIVE'
|
|
|| data.type === 'KRONICK_CHAT_MESSAGE'
|
|
|| data.type === 'KRONICK_CHAT_RECEIVE'
|
|
) {
|
|
const message =
|
|
data.message
|
|
|| data.payload;
|
|
|
|
if (message) {
|
|
removeEmptyMessage();
|
|
displayMessage(message);
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
|
|
if (
|
|
data.type
|
|
=== 'CHAT_INSERT_AND_SEND_URL'
|
|
) {
|
|
messageInput.value =
|
|
data.url || '';
|
|
|
|
handleOutboundMessage();
|
|
|
|
return;
|
|
}
|
|
}
|
|
|
|
|
|
function handleChatHistory(history) {
|
|
clearMessages();
|
|
|
|
const messages =
|
|
Array.isArray(history)
|
|
? history
|
|
: [];
|
|
|
|
if (!messages.length) {
|
|
renderEmptyMessage();
|
|
return;
|
|
}
|
|
|
|
messages.forEach(
|
|
message => {
|
|
displayMessage(
|
|
message,
|
|
false
|
|
);
|
|
}
|
|
);
|
|
|
|
scrollToBottom();
|
|
}
|
|
|
|
|
|
function handleOutboundMessage() {
|
|
const rawText =
|
|
messageInput.value.trim();
|
|
|
|
if (!rawText) {
|
|
return;
|
|
}
|
|
|
|
const mediaInfo =
|
|
detectMedia(rawText);
|
|
|
|
const chatPayload = {
|
|
id:
|
|
createMessageId(),
|
|
|
|
sender:
|
|
'You',
|
|
|
|
text:
|
|
mediaInfo
|
|
? ''
|
|
: rawText,
|
|
|
|
gifUrl:
|
|
mediaInfo?.type
|
|
=== 'gif'
|
|
? mediaInfo.url
|
|
: null,
|
|
|
|
imageUrl:
|
|
mediaInfo?.type
|
|
=== 'image'
|
|
? mediaInfo.url
|
|
: null,
|
|
|
|
createdAt:
|
|
Date.now()
|
|
};
|
|
|
|
|
|
/*
|
|
* Render locally right away.
|
|
*
|
|
* If the parent sends the same message back,
|
|
* renderedMessages prevents a duplicate.
|
|
*/
|
|
removeEmptyMessage();
|
|
displayMessage(chatPayload);
|
|
|
|
|
|
window.parent.postMessage(
|
|
{
|
|
type:
|
|
'KRONICK_CHAT_SEND',
|
|
|
|
payload:
|
|
chatPayload
|
|
},
|
|
window.location.origin
|
|
);
|
|
|
|
|
|
messageInput.value = '';
|
|
messageInput.focus();
|
|
|
|
setChatStatus(
|
|
'Message sent'
|
|
);
|
|
|
|
setTimeout(
|
|
() => {
|
|
setChatStatus(
|
|
'Room messages'
|
|
);
|
|
},
|
|
1000
|
|
);
|
|
}
|
|
|
|
|
|
async function handleFileSelection(event) {
|
|
const file = event.target.files?.[0];
|
|
if (!file) {
|
|
return;
|
|
}
|
|
|
|
// Clear input so selecting the same file consecutively works properly
|
|
fileInput.value = '';
|
|
|
|
const formData = new FormData();
|
|
formData.append('file', file);
|
|
|
|
|
|
// Attempt to infer room name from the active context, window globals, or URL search params
|
|
const urlParams = new URLSearchParams(window.location.search);
|
|
const activeRoom =
|
|
urlParams.get('room')
|
|
|| window.parent?.Kronick?.state?.room?.name
|
|
|| window.Kronick?.state?.room?.name
|
|
|| window.parent?.Kronick?.state?.roomID
|
|
|| window.Kronick?.state?.roomID
|
|
|| 'kronic';
|
|
|
|
formData.append('room', activeRoom);
|
|
|
|
// Add the sender field required by your FastAPI backend
|
|
const senderName =
|
|
window.parent?.Kronick?.state?.room?.localParticipant?.identity
|
|
|| window.Kronick?.state?.room?.localParticipant?.identity
|
|
|| localStorage.getItem('kronick_username')
|
|
|| 'You';
|
|
formData.append('sender', senderName);
|
|
|
|
setChatStatus('Uploading file...');
|
|
|
|
try {
|
|
const response = await fetch('/api/chat/files', {
|
|
method: 'POST',
|
|
body: formData
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorData = await response.json().catch(() => ({}));
|
|
|
|
// Safely extract string message whether detail is a string or object
|
|
let errorMessage = 'File upload failed.';
|
|
if (typeof errorData.detail === 'string') {
|
|
errorMessage = errorData.detail;
|
|
} else if (errorData.detail && typeof errorData.detail === 'object') {
|
|
errorMessage = JSON.stringify(errorData.detail);
|
|
} else if (errorData.message) {
|
|
errorMessage = errorData.message;
|
|
}
|
|
|
|
throw new Error(errorMessage);
|
|
}
|
|
|
|
const fileMeta = await response.json();
|
|
|
|
const chatPayload = {
|
|
id: fileMeta.id || createMessageId(),
|
|
sender: 'You',
|
|
text: fileMeta.text || `Shared a file: ${fileMeta.filename}`,
|
|
fileId: fileMeta.id,
|
|
filename: fileMeta.filename,
|
|
fileSize: fileMeta.fileSize,
|
|
fileUrl: fileMeta.fileUrl,
|
|
createdAt: Date.now()
|
|
};
|
|
|
|
removeEmptyMessage();
|
|
displayMessage(chatPayload);
|
|
|
|
window.parent.postMessage(
|
|
{
|
|
type: 'KRONICK_CHAT_SEND',
|
|
payload: chatPayload
|
|
},
|
|
window.location.origin
|
|
);
|
|
|
|
setChatStatus('File sent');
|
|
} catch (error) {
|
|
console.error('File upload error:', error);
|
|
setChatStatus(`Upload failed: ${error.message}`);
|
|
} finally {
|
|
setTimeout(() => {
|
|
setChatStatus('Room messages');
|
|
}, 2000);
|
|
}
|
|
}
|
|
|
|
|
|
function detectMedia(text) {
|
|
const clean =
|
|
text.trim();
|
|
|
|
if (!clean) {
|
|
return null;
|
|
}
|
|
|
|
if (
|
|
/\.(gif)(\?.*)?$/i
|
|
.test(clean)
|
|
|| clean.includes(
|
|
'giphy.com'
|
|
)
|
|
|| clean.includes(
|
|
'media.giphy.com'
|
|
)
|
|
) {
|
|
return {
|
|
type: 'gif',
|
|
url: clean
|
|
};
|
|
}
|
|
|
|
if (
|
|
/\.(jpeg|jpg|png|webp)(\?.*)?$/i
|
|
.test(clean)
|
|
) {
|
|
return {
|
|
type: 'image',
|
|
url: clean
|
|
};
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
|
|
function displayMessage(
|
|
message,
|
|
shouldScroll = true
|
|
) {
|
|
if (
|
|
!message
|
|
|| typeof message !== 'object'
|
|
) {
|
|
return;
|
|
}
|
|
|
|
const normalizedMessage =
|
|
normalizeMessage(message);
|
|
|
|
const messageId =
|
|
getMessageId(
|
|
normalizedMessage
|
|
);
|
|
|
|
if (
|
|
renderedMessages.has(
|
|
messageId
|
|
)
|
|
) {
|
|
return;
|
|
}
|
|
|
|
renderedMessages.add(
|
|
messageId
|
|
);
|
|
|
|
removeEmptyMessage();
|
|
|
|
|
|
const messageDiv =
|
|
document.createElement(
|
|
'article'
|
|
);
|
|
|
|
messageDiv.className =
|
|
'chat-message';
|
|
|
|
messageDiv.dataset.messageId =
|
|
messageId;
|
|
|
|
|
|
const avatar =
|
|
createAvatar(
|
|
normalizedMessage.sender
|
|
);
|
|
|
|
|
|
const messageBody =
|
|
document.createElement(
|
|
'div'
|
|
);
|
|
|
|
messageBody.className =
|
|
'chat-message-body';
|
|
|
|
|
|
const headerDiv =
|
|
document.createElement(
|
|
'div'
|
|
);
|
|
|
|
headerDiv.className =
|
|
'chat-message-header';
|
|
|
|
|
|
const senderSpan =
|
|
document.createElement(
|
|
'span'
|
|
);
|
|
|
|
senderSpan.className =
|
|
'chat-username';
|
|
|
|
senderSpan.textContent =
|
|
normalizedMessage.sender;
|
|
|
|
|
|
const timeSpan =
|
|
document.createElement(
|
|
'time'
|
|
);
|
|
|
|
timeSpan.className =
|
|
'chat-timestamp';
|
|
|
|
const timestampDate =
|
|
new Date(
|
|
normalizedMessage.createdAt
|
|
);
|
|
|
|
if (
|
|
!Number.isNaN(
|
|
timestampDate.getTime()
|
|
)
|
|
) {
|
|
timeSpan.dateTime =
|
|
timestampDate.toISOString();
|
|
}
|
|
|
|
timeSpan.textContent =
|
|
formatTime(
|
|
normalizedMessage.createdAt
|
|
);
|
|
|
|
|
|
headerDiv.append(
|
|
senderSpan,
|
|
timeSpan
|
|
);
|
|
|
|
messageBody.appendChild(
|
|
headerDiv
|
|
);
|
|
|
|
|
|
if (normalizedMessage.text) {
|
|
const bodyDiv =
|
|
document.createElement(
|
|
'div'
|
|
);
|
|
|
|
bodyDiv.className =
|
|
'chat-message-text';
|
|
|
|
bodyDiv.textContent =
|
|
normalizedMessage.text;
|
|
|
|
messageBody.appendChild(
|
|
bodyDiv
|
|
);
|
|
}
|
|
|
|
|
|
const mediaUrl =
|
|
normalizedMessage.gifUrl
|
|
|| normalizedMessage.imageUrl;
|
|
|
|
if (mediaUrl) {
|
|
appendMedia(
|
|
messageBody,
|
|
mediaUrl,
|
|
Boolean(
|
|
normalizedMessage.gifUrl
|
|
)
|
|
);
|
|
}
|
|
|
|
// Handle file attachments if present
|
|
if (normalizedMessage.fileUrl || normalizedMessage.fileId) {
|
|
appendFileAttachment(messageBody, normalizedMessage);
|
|
}
|
|
|
|
|
|
messageDiv.append(
|
|
avatar,
|
|
messageBody
|
|
);
|
|
|
|
messagesContainer.appendChild(
|
|
messageDiv
|
|
);
|
|
|
|
|
|
if (shouldScroll) {
|
|
scrollToBottom();
|
|
}
|
|
}
|
|
|
|
|
|
function normalizeMessage(message) {
|
|
const sender =
|
|
message.sender
|
|
|| message.username
|
|
|| message.participantName
|
|
|| message.identity
|
|
|| 'Unknown';
|
|
|
|
const text =
|
|
message.text
|
|
|| message.message
|
|
|| '';
|
|
|
|
const gifUrl =
|
|
message.gifUrl
|
|
|| message.gif_url
|
|
|| null;
|
|
|
|
const imageUrl =
|
|
message.imageUrl
|
|
|| message.image_url
|
|
|| null;
|
|
|
|
const fileUrl =
|
|
message.fileUrl
|
|
|| message.file_url
|
|
|| (message.fileId ? `/api/chat/files/${message.fileId}` : null);
|
|
|
|
const filename =
|
|
message.filename
|
|
|| message.file_name
|
|
|| null;
|
|
|
|
const fileSize =
|
|
message.fileSize
|
|
|| message.file_size
|
|
|| null;
|
|
|
|
const createdAt =
|
|
message.createdAt
|
|
|| message.created_at
|
|
|| message.timestamp
|
|
|| Date.now();
|
|
|
|
return {
|
|
id:
|
|
message.id
|
|
|| message.messageId
|
|
|| message.message_id
|
|
|| null,
|
|
|
|
sender:
|
|
String(sender),
|
|
|
|
text:
|
|
String(text),
|
|
|
|
gifUrl:
|
|
gifUrl
|
|
? String(gifUrl)
|
|
: null,
|
|
|
|
imageUrl:
|
|
imageUrl
|
|
? String(imageUrl)
|
|
: null,
|
|
|
|
fileUrl:
|
|
fileUrl
|
|
? String(fileUrl)
|
|
: null,
|
|
|
|
filename:
|
|
filename
|
|
? String(filename)
|
|
: null,
|
|
|
|
fileSize:
|
|
fileSize,
|
|
|
|
createdAt:
|
|
normalizeTimestamp(
|
|
createdAt
|
|
)
|
|
};
|
|
}
|
|
|
|
|
|
function normalizeTimestamp(timestamp) {
|
|
if (
|
|
typeof timestamp === 'number'
|
|
) {
|
|
/*
|
|
* Convert Unix seconds to milliseconds.
|
|
*/
|
|
if (
|
|
timestamp > 0
|
|
&& timestamp < 100000000000
|
|
) {
|
|
return timestamp * 1000;
|
|
}
|
|
|
|
return timestamp;
|
|
}
|
|
|
|
const parsed =
|
|
new Date(timestamp).getTime();
|
|
|
|
if (
|
|
Number.isNaN(parsed)
|
|
) {
|
|
return Date.now();
|
|
}
|
|
|
|
return parsed;
|
|
}
|
|
|
|
|
|
function appendMedia(
|
|
messageBody,
|
|
mediaUrl,
|
|
isGif
|
|
) {
|
|
const image =
|
|
document.createElement(
|
|
'img'
|
|
);
|
|
|
|
image.className =
|
|
isGif
|
|
? 'chat-gif'
|
|
: 'chat-message-image';
|
|
|
|
image.src =
|
|
mediaUrl;
|
|
|
|
image.alt =
|
|
isGif
|
|
? 'Shared GIF'
|
|
: 'Shared image';
|
|
|
|
image.loading =
|
|
'lazy';
|
|
|
|
image.referrerPolicy =
|
|
'no-referrer';
|
|
|
|
image.addEventListener(
|
|
'load',
|
|
scrollToBottom
|
|
);
|
|
|
|
image.addEventListener(
|
|
'error',
|
|
() => {
|
|
image.remove();
|
|
|
|
const error =
|
|
document.createElement(
|
|
'div'
|
|
);
|
|
|
|
error.className =
|
|
'message-error';
|
|
|
|
error.textContent =
|
|
'Image failed to load.';
|
|
|
|
messageBody.appendChild(
|
|
error
|
|
);
|
|
|
|
scrollToBottom();
|
|
}
|
|
);
|
|
|
|
messageBody.appendChild(
|
|
image
|
|
);
|
|
}
|
|
|
|
|
|
function appendFileAttachment(messageBody, message) {
|
|
const fileCard = document.createElement('div');
|
|
fileCard.className = 'chat-file-card';
|
|
|
|
const iconSpan = document.createElement('span');
|
|
iconSpan.className = 'chat-file-icon';
|
|
iconSpan.textContent = '📄';
|
|
|
|
const infoDiv = document.createElement('div');
|
|
infoDiv.className = 'chat-file-info';
|
|
|
|
const link = document.createElement('a');
|
|
link.className = 'chat-file-link';
|
|
const rawUrl = String(message.fileUrl || (message.fileId ? `/api/chat/files/${encodeURIComponent(message.fileId)}` : ''));
|
|
const url = new URL(rawUrl, window.location.href);
|
|
if (!['https:', 'http:'].includes(url.protocol) || url.origin !== window.location.origin || !url.pathname.includes('/api/chat/files/')) {
|
|
link.textContent = 'Attachment unavailable';
|
|
infoDiv.appendChild(link);
|
|
fileCard.append(iconSpan, infoDiv);
|
|
messageBody.appendChild(fileCard);
|
|
return;
|
|
}
|
|
link.href = url.href;
|
|
link.textContent = message.filename || 'Download Attachment';
|
|
link.target = '_blank';
|
|
link.rel = 'noopener noreferrer';
|
|
|
|
infoDiv.appendChild(link);
|
|
|
|
if (message.fileSize) {
|
|
const sizeSpan = document.createElement('span');
|
|
sizeSpan.className = 'chat-file-size';
|
|
sizeSpan.textContent = formatFileSize(message.fileSize);
|
|
infoDiv.appendChild(sizeSpan);
|
|
}
|
|
|
|
fileCard.append(iconSpan, infoDiv);
|
|
messageBody.appendChild(fileCard);
|
|
}
|
|
|
|
|
|
function formatFileSize(bytes) {
|
|
if (!bytes || isNaN(bytes)) return '';
|
|
if (bytes < 1024) return bytes + ' B';
|
|
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
|
|
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
|
|
}
|
|
|
|
|
|
function createAvatar(sender) {
|
|
const avatar =
|
|
document.createElement(
|
|
'div'
|
|
);
|
|
|
|
avatar.className =
|
|
'chat-avatar';
|
|
|
|
const initial =
|
|
String(sender)
|
|
.trim()
|
|
.charAt(0)
|
|
.toUpperCase();
|
|
|
|
avatar.textContent =
|
|
initial || '?';
|
|
|
|
return avatar;
|
|
}
|
|
|
|
|
|
function createMessageId() {
|
|
if (
|
|
window.crypto
|
|
&& typeof crypto.randomUUID
|
|
=== 'function'
|
|
) {
|
|
return crypto.randomUUID();
|
|
}
|
|
|
|
return [
|
|
Date.now(),
|
|
Math.random()
|
|
.toString(36)
|
|
.slice(2)
|
|
].join('-');
|
|
}
|
|
|
|
|
|
function getMessageId(message) {
|
|
if (message.id) {
|
|
return String(
|
|
message.id
|
|
);
|
|
}
|
|
|
|
return [
|
|
message.sender
|
|
|| 'unknown',
|
|
|
|
message.createdAt
|
|
|| Date.now(),
|
|
|
|
message.text
|
|
|| message.gifUrl
|
|
|| message.imageUrl
|
|
|| message.fileUrl
|
|
|| ''
|
|
].join('-');
|
|
}
|
|
|
|
|
|
function clearMessages() {
|
|
renderedMessages.clear();
|
|
|
|
messagesContainer.innerHTML =
|
|
'';
|
|
}
|
|
|
|
|
|
function renderEmptyMessage() {
|
|
messagesContainer.innerHTML =
|
|
'';
|
|
|
|
const emptyMessage =
|
|
document.createElement(
|
|
'div'
|
|
);
|
|
|
|
emptyMessage.className =
|
|
'chat-empty';
|
|
|
|
emptyMessage.textContent =
|
|
'No messages yet.';
|
|
|
|
messagesContainer.appendChild(
|
|
emptyMessage
|
|
);
|
|
}
|
|
|
|
|
|
function removeEmptyMessage() {
|
|
const emptyMessage =
|
|
messagesContainer
|
|
.querySelector(
|
|
'.chat-empty'
|
|
);
|
|
|
|
emptyMessage?.remove();
|
|
}
|
|
|
|
|
|
function scrollToBottom() {
|
|
requestAnimationFrame(
|
|
() => {
|
|
messagesContainer.scrollTop =
|
|
messagesContainer.scrollHeight;
|
|
}
|
|
);
|
|
}
|
|
|
|
|
|
function setChatStatus(text) {
|
|
if (chatStatus) {
|
|
chatStatus.textContent =
|
|
text;
|
|
}
|
|
}
|
|
|
|
|
|
function formatTime(timestamp) {
|
|
const date =
|
|
new Date(timestamp);
|
|
|
|
if (
|
|
Number.isNaN(
|
|
date.getTime()
|
|
)
|
|
) {
|
|
return '';
|
|
}
|
|
|
|
return date.toLocaleTimeString(
|
|
[],
|
|
{
|
|
hour:
|
|
'2-digit',
|
|
|
|
minute:
|
|
'2-digit'
|
|
}
|
|
);
|
|
}
|
|
}
|
|
);
|