构建一个即时消息应用(八):Home 页面

开发 后端
继续前端部分,让我们在本文中完成 home 页面的开发。 我们将添加一个开始对话的表单和一个包含最新对话的列表。

[[346742]]

本文是该系列的第八篇。

继续前端部分,让我们在本文中完成 home 页面的开发。 我们将添加一个开始对话的表单和一个包含最新对话的列表。

对话表单

转到 static/ages/home-page.js 文件,在 HTML 视图中添加一些标记。

 
  • 1.
<form id="conversation-form"
    <input type="search" placeholder="Start conversation with..." required> 
</form> 
  • 1.
  • 2.
  • 3.

将该表单添加到我们显示 “auth user” 和 “logout” 按钮部分的下方。

page.getElementById('conversation-form').onsubmit = onConversationSubmit 
  • 1.

现在我们可以监听 “submit” 事件来创建对话了。

import http from '../http.js' 
import { navigate } from '../router.js' 
 
async function onConversationSubmit(ev) { 
    ev.preventDefault() 
 
    const form = ev.currentTarget 
    const input = form.querySelector('input'
 
    input.disabled = true 
 
    try { 
        const conversation = await createConversation(input.value) 
        input.value = '' 
        navigate('/conversations/' + conversation.id) 
    } catch (err) { 
        if (err.statusCode === 422) { 
            input.setCustomValidity(err.body.errors.username) 
        } else { 
            alert(err.message) 
        } 
        setTimeout(() => { 
            input.focus() 
        }, 0) 
    } finally { 
        input.disabled = false 
    } 

 
function createConversation(username) { 
    return http.post('/api/conversations', { username }) 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.

在提交时,我们使用用户名对 /api/conversations 进行 POST 请求,并重定向到 conversation 页面(用于下一篇文章)。

对话列表

还是在这个文件中,我们将创建 homePage() 函数用来先异步加载对话。

export default async function homePage() { 
    const conversations = await getConversations().catch(err => { 
        console.error(err) 
        return [] 
    }) 
    /*...*/ 

 
function getConversations() { 
    return http.get('/api/conversations'

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

然后,在标记中添加一个列表来渲染对话。

<ol id="conversations"></ol> 
  • 1.

将其添加到当前标记的正下方。

const conversationsOList = page.getElementById('conversations'
for (const conversation of conversations) { 
    conversationsOList.appendChild(renderConversation(conversation)) 

  • 1.
  • 2.
  • 3.
  • 4.

因此,我们可以将每个对话添加到这个列表中。

import { avatar, escapeHTML } from '../shared.js' 
 
function renderConversation(conversation) { 
    const messageContent = escapeHTML(conversation.lastMessage.content) 
    const messageDate = new Date(conversation.lastMessage.createdAt).toLocaleString() 
 
    const li = document.createElement('li'
    li.dataset['id'] = conversation.id 
    if (conversation.hasUnreadMessages) { 
        li.classList.add('has-unread-messages'
    } 
    li.innerHTML = ` 
        <a href="/conversations/${conversation.id}"
            <div> 
                ${avatar(conversation.otherParticipant)} 
                <span>${conversation.otherParticipant.username}</span> 
            </div> 
            <div> 
                <p>${messageContent}</p> 
                <time>${messageDate}</time
            </div> 
        </a> 
    ` 
    return li 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.

每个对话条目都包含一个指向对话页面的链接,并显示其他参与者信息和最后一条消息的预览。另外,您可以使用 .hasUnreadMessages 向该条目添加一个类,并使用 CSS 进行一些样式设置。也许是粗体字体或强调颜色。

请注意,我们需要转义信息的内容。该函数来自于 static/shared.js 文件:

export function escapeHTML(str) { 
    return str 
        .replace(/&/g, '&amp;'
        .replace(/</g, '&lt;'
        .replace(/>/g, '&gt;'
        .replace(/"/g, '&quot;'
        .replace(/'/g, '&#039;') 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

这会阻止将用户编写的消息显示为 HTML。如果用户碰巧编写了类似以下内容的代码:

<script>alert('lololo')</script>
  • 1.

这将非常烦人,因为该脚本将被执行😅。所以,永远记住要转义来自不可信来源的内容。

消息订阅

最后但并非最不重要的一点,我想在这里订阅消息流。

const unsubscribe = subscribeToMessages(onMessageArrive) 
page.addEventListener('disconnect', unsubscribe) 
  • 1.
  • 2.

在 homePage() 函数中添加这一行。

function subscribeToMessages(cb) { 
    return http.subscribe('/api/messages', cb) 

  • 1.
  • 2.
  • 3.

函数 subscribe() 返回一个函数,该函数一旦调用就会关闭底层连接。这就是为什么我把它传递给 “断开连接”disconnect事件的原因;因此,当用户离开页面时,事件流将被关闭。

async function onMessageArrive(message) { 
    const conversationLI = document.querySelector(`li[data-id="${message.conversationID}"]`) 
    if (conversationLI !== null) { 
        conversationLI.classList.add('has-unread-messages'
        conversationLI.querySelector('a > div > p').textContent = message.content 
        conversationLI.querySelector('a > div > time').textContent = new Date(message.createdAt).toLocaleString() 
        return 
    } 
 
    let conversation 
    try { 
        conversation = await getConversation(message.conversationID) 
        conversation.lastMessage = message 
    } catch (err) { 
        console.error(err) 
        return 
    } 
 
    const conversationsOList = document.getElementById('conversations'
    if (conversationsOList === null) { 
        return 
    } 
 
    conversationsOList.insertAdjacentElement('afterbegin', renderConversation(conversation)) 

 
function getConversation(id) { 
    return http.get('/api/conversations/' + id) 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.

每次有新消息到达时,我们都会在 DOM 中查询会话条目。如果找到,我们会将 has-unread-messages 类添加到该条目中,并更新视图。如果未找到,则表示该消息来自刚刚创建的新对话。我们去做一个对 /api/conversations/{conversationID} 的 GET 请求,以获取在其中创建消息的对话,并将其放在对话列表的前面。


以上这些涵盖了主页的所有内容 😊。 在下一篇文章中,我们将对 conversation 页面进行编码。

 

 

责任编辑:庞桂玉 来源: Linux中国
相关推荐

2020-10-12 09:20:13

即时消息Access页面编程语言

2020-10-19 16:20:38

即时消息Conversatio编程语言

2020-10-09 12:45:19

创建消息即时消息编程语言

2019-09-29 15:25:13

CockroachDBGoJavaScript

2020-10-09 15:00:56

实时消息编程语言

2019-10-28 20:12:40

OAuthGuard中间件编程语言

2020-03-31 12:21:20

JSON即时消息编程语言

2020-10-10 20:51:10

即时消息编程语言

2021-03-25 08:29:33

SpringBootWebSocket即时消息

2023-08-14 08:01:12

websocket8g用户

2015-03-18 15:37:19

社交APP场景

2014-10-15 11:01:02

Web应用测试应用

2018-08-22 17:32:45

2022-02-10 07:03:32

流量应用架构数据交换

2023-09-21 08:00:00

ChatGPT编程工具

2021-07-14 17:39:46

ReactRails API前端组件

2021-12-03 00:02:01

通讯工具即时

2023-09-15 10:10:05

R 语言

2010-05-24 09:51:37

System Cent

2009-04-28 09:44:31

jQueryAjaxphp
点赞
收藏

51CTO技术栈公众号