Вход Регистрация
Файл: upload/pages/messages/dialog.php
Строк: 187
<?php
require_once ($_SERVER['DOCUMENT_ROOT'] . '/core/core.php');

if (!isset(
$user['id'])) {
    
showAlert('Ошибка''fail''Сперва необходимо авторизоваться');
    
RedirectToPage('/');
    exit();
}

$id abs((int)($_GET['id'] ?? 0));
$ank FetchAssoc(dbquery("SELECT * FROM users WHERE id = ?", [$id]));

if (empty(
$ank['id'])) {
    
header("HTTP/1.0 404 Not Found");
    include (
$_SERVER['DOCUMENT_ROOT'] . '/pages/err_pages/404.php'); 
    exit();
}

$breadcrumbs generateBreadcrumbs([
    [
'/''Главная'],
    [
'/mes/''Сообщения'],
    [
'#''Диалог с ' $ank['login']]
]);

// Подключаем список диалогов через буфер
$GLOBALS['userId'] = $user['id'];
$GLOBALS['activePeer'] = $id;

require 
$_SERVER['DOCUMENT_ROOT'] . '/core/elements/dialog_list.php';

$dialog_list_html $messages_cmp;

$page_html $view->render('pages/messages/dialog.html', [
    
'breadcrumbs_html' => $breadcrumbs['html'],
    
'breadcrumbs_json' => $breadcrumbs['json_ld'],

    
'dialog_list' => $dialog_list_html,

    
'home' => homeLink(),

    
'avatar' => GetAvatar($ank['avatar']),
    
'nickname' => nick($ank['id']),
    
'rating_num' => rating_num_work($ank['id']),
    
'rating_stars' => rating_star_work($ank['id'])
]);

require_once (
$_SERVER['DOCUMENT_ROOT'] . '/layout.php');
?>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const msg = document.getElementById('msg');

    function autoResize() {
        msg.style.height = '35px'; // сброс к минимуму
        let newHeight = msg.scrollHeight;

        // ограничиваем диапазон: минимум 35px, максимум 55px
        newHeight = Math.max(35, Math.min(newHeight, 55));

        msg.style.height = newHeight + 'px';
    }

    msg.addEventListener('input', autoResize);
    autoResize(); // инициализация при загрузке
});
</script>

<script>
const userId = <?= $user['id'?>;
const peerId = <?= $id ?>;

let lastId = 0;
let selectedFiles = [];
let sending = false; // защита от двойной отправки

document.addEventListener('DOMContentLoaded', () => {

  // --- отправка по кнопке ---
  const btn = document.getElementById('sendBtn');
  if (btn) btn.addEventListener('click', sendMessage);

  // --- отправка по Enter ---
  const msgInput = document.getElementById('msg');
  if (msgInput) {
    msgInput.addEventListener('keydown', e => {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
      }
    });
  }

  // --- выбор файлов ---
  const fileInput = document.getElementById('file');
  if (fileInput) fileInput.addEventListener('change', handleFileSelection);

  // --- polling ---
  setInterval(pollMessages, 1500);
});

function handleFileSelection() {
  const input = document.getElementById('file');
  selectedFiles.push(...input.files);
  updateFileList();
}

function updateFileList() {
  const fileList = document.getElementById('fileList');
  fileList.innerHTML = '';

  selectedFiles.forEach((file, index) => {
    const li = document.createElement('li');
    li.textContent = file.name;

    const removeBtn = document.createElement('button');
    removeBtn.textContent = '✖';
    removeBtn.onclick = () => {
      selectedFiles.splice(index, 1);
      updateFileList();
    };

    li.appendChild(removeBtn);
    fileList.appendChild(li);
  });
}

function sendMessage() {

  // --- защита от двойной отправки ---
  if (sending) return;
  sending = true;

  const btn = document.getElementById('sendBtn');
  if (btn) btn.disabled = true;

  const form = new FormData();
  form.append('from', userId);
  form.append('to', peerId);
  form.append('text', document.getElementById('msg').value);

  selectedFiles.forEach(file => {
    form.append('file[]', file);
  });

  fetch('/core/ajax/messages/send_mes.php', { method: 'POST', body: form })
    .then(() => {
      document.getElementById('msg').value = '';
      document.getElementById('file').value = '';
      selectedFiles = [];
      updateFileList();
      pollMessages();
      updateUnread();
      moveDialogToTop(peerId);
    })
    .finally(() => {
      sending = false;
      if (btn) btn.disabled = false;
    });
}

function pollMessages() {
  fetch(`/core/ajax/messages/fetch_mes.php?user=${userId}&peer=${peerId}&after=${lastId}`)
    .then(res => res.text())
    .then(html => {
      if (html.trim()) {
        const chat = document.getElementById('chat');
        chat.insertAdjacentHTML('beforeend', html);
        chat.scrollTop = chat.scrollHeight;

        const parser = new DOMParser();
        const doc = parser.parseFromString(html, 'text/html');
        const lastMsg = doc.querySelector('[data-id]:last-child');
        if (lastMsg) {
          const newLastId = parseInt(lastMsg.getAttribute('data-id'), 10);
          if (newLastId > lastId) lastId = newLastId;
        }
      }
    });

  fetch('/core/ajax/messages/read_mes.php', {
    method: 'POST',
    body: new URLSearchParams({
      user: userId,
      peer: peerId
    })
  });
}
</script>
Онлайн: 0
Реклама