Last week, I wrote about tweaking htmx to display instant messages. A week into using HTMX, I needed more. I wanted a better way to stream HTML from the server, using JSX components instead of plain HTML strings for better code usability.
? Quick reminder: if you find this useful, please give it a thumbs up! Your support helps me create more content.
Tools I Used:
- HTMX
- HTMX Websockets Extension
- Hono for the backend
- Websockets - client-side
The idea is simple. My Conversation component is wrapped in a div with hx-ext="ws", which connects to my backend when rendered.
export const Conversation = (props: { messages: Message[] }) => ( <div hx-ext="ws" ws-connect="/chatroom-ws"> <div id="conversation"> {props.messages.reverse().map((message) => ( <div> <usermessage message="{message}"></usermessage> <assistantmessage message="{message}"></assistantmessage> </div> ))} </div> <inputmessageform></inputmessageform> </div> );
Next important thing is the InputMessageForm. Just add ws-send to the form, and it will send a message where the key is the textarea’s ID (messageInput) with its value.
export const InputMessageForm = () => ();
Websockets - Server
Here’s the full code block for the Hono server. Some console logs for opening and closing connection. onMessage is where the magic happens.
get( '/chatroom-ws', upgradeWebSocket((c) => { return { onOpen: () => { console.log('WS Connection open'); }, onClose: () => { console.log('WS Connection closed'); }, onMessage: async (event, ws) => { const { userMessage } = JSON.parse(event.data.toString()); console.log('Got user message', userMessage); const inputArea = await c.html( <div id="query-submit-form"> <inputmessageform></inputmessageform> </div>, ); ws.send(await inputArea.text()); const htmlUser = await c.html( <div id="conversation" hx-swap-oob="beforeend"> <usermessage message="{{" id: v4 some random ids used here for placeholder query: usermessage completion: conversationid: toolsresponse: null createdat: new date updatedat:></usermessage> </div>, ); ws.send(await htmlUser.text()); const response = await talk(userMessage); const htmlAgent = await c.html( <div id="conversation" hx-swap-oob="beforeend"> <assistantmessage message="{response}"></assistantmessage> </div>, ); ws.send(await htmlAgent.text()); }, }; }), );
So the flow is:
- Receive the query
- Send back empty just to make it clean. There is no hx-swap-oob specified so its True by default. That means that it will find the element with id=query-submit-form and swap it.
- Send back the component with the user message. Here hx-swap-oob is specified to beforeend which simply means that it will be added to existing messages.
- talk → here comes your logic. I’m talking to AI assistant so making some external API calls.
- Send back the component with assistant answer. The same as step 3 but the component is different.
Problems I found
Sending response back was a bit problematic since docs are hmm… not that easy to understand I think. There is even an issue created to fix this: Improve documentation for websocket extension. That helped me a lot!
So the most important thing is:
You need to send back string, that parses to html that has the same id as the thing you want to swap!
So the problem nr. 1
I accidentally sent back something like this:
JSON.stringify('<div id="someid">test 123</div>') // '"<div id='\\"someid\\"'>test 123</div>"'
This is wrong. Note the ID and escape characters! Don’t stringify the string here.
The problem nr. 2
You might think you can return something and it will get swapped where you want. Not exactly. The first div is just information for HTMX on what to do. At least I understand it this way ?.
I’m returning html like this:
<div id="conversation" hx-swap-oob="beforeend"> <assistantmessage message="{response}"></assistantmessage> </div>
Only is appended inside the existing
on the client side.End result
https://assets.super.so/c0fc84d8-fb32-4194-8758-4be657666aab/videos/c814dcd2-b9e9-4bb2-b8db-2ed9cd7819b7/lucy-chat-example.mov
? Does this post help you? Please spam the like button! Your support is awesome. Thanks!
Want to Know More?
Stay tuned for more insights and tutorials! Visit My Blog ?
以上是与 HTMX、WebSockets 和 Hono 聊天的详细内容。更多信息请关注PHP中文网其他相关文章!

Python和JavaScript在性能和效率方面的差异主要体现在:1)Python作为解释型语言,运行速度较慢,但开发效率高,适合快速原型开发;2)JavaScript在浏览器中受限于单线程,但在Node.js中可利用多线程和异步I/O提升性能,两者在实际项目中各有优势。

JavaScript起源于1995年,由布兰登·艾克创造,实现语言为C语言。1.C语言为JavaScript提供了高性能和系统级编程能力。2.JavaScript的内存管理和性能优化依赖于C语言。3.C语言的跨平台特性帮助JavaScript在不同操作系统上高效运行。

JavaScript在浏览器和Node.js环境中运行,依赖JavaScript引擎解析和执行代码。1)解析阶段生成抽象语法树(AST);2)编译阶段将AST转换为字节码或机器码;3)执行阶段执行编译后的代码。

Python和JavaScript的未来趋势包括:1.Python将巩固在科学计算和AI领域的地位,2.JavaScript将推动Web技术发展,3.跨平台开发将成为热门,4.性能优化将是重点。两者都将继续在各自领域扩展应用场景,并在性能上有更多突破。

Python和JavaScript在开发环境上的选择都很重要。1)Python的开发环境包括PyCharm、JupyterNotebook和Anaconda,适合数据科学和快速原型开发。2)JavaScript的开发环境包括Node.js、VSCode和Webpack,适用于前端和后端开发。根据项目需求选择合适的工具可以提高开发效率和项目成功率。

是的,JavaScript的引擎核心是用C语言编写的。1)C语言提供了高效性能和底层控制,适合JavaScript引擎的开发。2)以V8引擎为例,其核心用C 编写,结合了C的效率和面向对象特性。3)JavaScript引擎的工作原理包括解析、编译和执行,C语言在这些过程中发挥关键作用。

JavaScript是现代网站的核心,因为它增强了网页的交互性和动态性。1)它允许在不刷新页面的情况下改变内容,2)通过DOMAPI操作网页,3)支持复杂的交互效果如动画和拖放,4)优化性能和最佳实践提高用户体验。

C 和JavaScript通过WebAssembly实现互操作性。1)C 代码编译成WebAssembly模块,引入到JavaScript环境中,增强计算能力。2)在游戏开发中,C 处理物理引擎和图形渲染,JavaScript负责游戏逻辑和用户界面。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

WebStorm Mac版
好用的JavaScript开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

Dreamweaver CS6
视觉化网页开发工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。