Mercurial Hosting > chat
view src/chat.js @ 14:0df3a63a895f
minor
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Fri, 01 Nov 2024 11:22:01 -0600 |
parents | 9f45d32670ae |
children | 8b8905f63d80 |
line wrap: on
line source
'use strict'; let currentChatId = null; let eventSource; 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 = function(event) { eval(event.data); }; } 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'}); }