Mercurial Hosting > chat
view src/chat.js @ 17:7230c821c368
push fixes
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Mon, 04 Nov 2024 14:44:35 -0700 |
parents | 82b55186a4a0 |
children | 0721dcf222e1 |
line wrap: on
line source
'use strict'; let currentChatId = null; let eventSource; function evalEvent(event) { // console.log(event); eval(event.data); } function setUserEventSource(userId) { let userEventSource = new EventSource(`${location.origin}/user/${userId}`); userEventSource.onmessage = evalEvent; } function selectChat(div) { let chatId = div.getAttribute('chat'); if( chatId === currentChatId ) return; let selected = div.parentNode.querySelector('[selected]'); if( selected ) selected.removeAttribute('selected'); div.setAttribute('selected',''); ajax(`get_chat.js?chat=${chatId}`); currentChatId = chatId; if(eventSource) eventSource.close(); eventSource = new EventSource(`${location.origin}/chat/${chatId}`); eventSource.onmessage = evalEvent; } function gotChat(html) { document.querySelector('div[posts]').innerHTML = html; fixDates(); document.querySelector('div[input] textarea').focus(); document.querySelector('div[input]').scrollIntoView({block: 'end'}); } function fixTextarea(event) { let textarea = event.target; textarea.style.height = 'initial'; textarea.style.height = (textarea.scrollHeight+2) + 'px'; textarea.scrollIntoViewIfNeeded(false); } const isMobile = 'ontouchstart' in window || navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0; function addPost() { let textarea = document.querySelector('div[input] textarea'); let text = textarea.value; if( text.trim() === '' ) return; ajax(`add_post.js?chat=${currentChatId}&content=${encodeURIComponent(text)}`); textarea.value = ''; } function textareaKey(event) { if( event.keyCode===13 && !event.shiftKey && !event.ctrlKey && !isMobile ) { event.preventDefault(); addPost(); } } function fixDates() { let spans = document.querySelectorAll('span[when][fix]'); for( let span of spans ) { span.textContent = new Date(Number(span.textContent)).toLocaleString(); span.removeAttribute('fix'); } } function deleteChat() { ajax(`delete_chat.js?chat=${currentChatId}`); } function added(html) { let input = document.querySelector('div[input]'); input.insertAdjacentHTML('beforebegin',html); fixDates(); input.scrollIntoView({block: 'end'}); } function getChats(chatId) { let first = document.querySelector('div[chat]'); if( !first || first.getAttribute('chat') != chatId ) { // console.log('getChats'); ajax('get_chats.js'); } } function gotChats(html) { document.querySelector('div[chats]').innerHTML = html; if( currentChatId ) { let current = document.querySelector(`div[chat="${currentChatId}"]`); if( current ) { current.setAttribute('selected',''); current.scrollIntoViewIfNeeded(false); } else { currentChatId = null; document.querySelector('div[posts]').innerHTML = ''; } } }