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、WebSocket、Hono でチャットするの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

JavaScriptは1995年に発信され、Brandon Ikeによって作成され、言語をCに実現しました。 2。JavaScriptのメモリ管理とパフォーマンスの最適化は、C言語に依存しています。 3. C言語のクロスプラットフォーム機能は、さまざまなオペレーティングシステムでJavaScriptを効率的に実行するのに役立ちます。

JavaScriptはブラウザとnode.js環境で実行され、JavaScriptエンジンに依存してコードを解析および実行します。 1)解析段階で抽象的構文ツリー(AST)を生成します。 2)ASTをコンパイル段階のバイトコードまたはマシンコードに変換します。 3)実行段階でコンパイルされたコードを実行します。

PythonとJavaScriptの将来の傾向には、1。Pythonが科学コンピューティングの分野での位置を統合し、AI、2。JavaScriptはWebテクノロジーの開発を促進します。どちらもそれぞれのフィールドでアプリケーションシナリオを拡大し続け、パフォーマンスをより多くのブレークスルーを行います。

開発環境における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は、Webページのインタラクティブ性とダイナミズムを向上させるため、現代のWebサイトの中心にあります。 1)ページを更新せずにコンテンツを変更できます。2)Domapiを介してWebページを操作する、3)アニメーションやドラッグアンドドロップなどの複雑なインタラクティブ効果、4)ユーザーエクスペリエンスを改善するためのパフォーマンスとベストプラクティスを最適化します。

CおよびJavaScriptは、WebAssemblyを介して相互運用性を実現します。 1)CコードはWebAssemblyモジュールにコンパイルされ、JavaScript環境に導入され、コンピューティングパワーが強化されます。 2)ゲーム開発では、Cは物理エンジンとグラフィックスレンダリングを処理し、JavaScriptはゲームロジックとユーザーインターフェイスを担当します。

JavaScriptは、Webサイト、モバイルアプリケーション、デスクトップアプリケーション、サーバー側のプログラミングで広く使用されています。 1)Webサイト開発では、JavaScriptはHTMLおよびCSSと一緒にDOMを運用して、JQueryやReactなどのフレームワークをサポートします。 2)ReactNativeおよびIonicを通じて、JavaScriptはクロスプラットフォームモバイルアプリケーションを開発するために使用されます。 3)電子フレームワークにより、JavaScriptはデスクトップアプリケーションを構築できます。 4)node.jsを使用すると、JavaScriptがサーバー側で実行され、高い並行リクエストをサポートします。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

SublimeText3 Linux 新バージョン
SublimeText3 Linux 最新バージョン

SublimeText3 中国語版
中国語版、とても使いやすい

VSCode Windows 64 ビットのダウンロード
Microsoft によって発売された無料で強力な IDE エディター

Safe Exam Browser
Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

PhpStorm Mac バージョン
最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール

ホットトピック









