view src/chat.js @ 15:8b8905f63d80

add get_chats
author Franklin Schmidt <fschmidt@gmail.com>
date Sun, 03 Nov 2024 17:36:49 -0700
parents 0df3a63a895f
children 82b55186a4a0
line wrap: on
line source

'use strict';

let currentChatId = null;
let eventSource;

function setUserEventSource(userId) {
	let userEventSource = new EventSource(`${location.origin}/user/${userId}`);
	userEventSource.onmessage = function(event) {
		eval(event.data);
	};
}

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'});
}

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}"]`);
		current.setAttribute('selected','');
		current.scrollIntoViewIfNeeded(false);
	}
}