# Run with: python basic_app.py
from fasthtml.common import *
# TODO: this should happen automatically in the future
import jc.common
jc.common.patch_anyio()
from asyncio import sleep
from fasthtml.common import *
app = FastHTML(ws_hdr=True)
rt = app.route
def mk_inp(): return Input(id='msg')
nid = 'notifications'
@rt('/')
async def get():
cts = Div(
Div(id=nid),
Form(mk_inp(), id='form', ws_send=True),
# TODO: is there no other way than to prepend the ROOT_PATH?
hx_ext='ws', ws_connect=jc.asgi.ROOT_PATH+'/ws')
# TODO: this is not needed I think, but does not affect the ws_connect setting above
script = Script("""
document.body.addEventListener('htmx:configRequest', (event) => {
event.detail.path = `""" +jc.asgi.ROOT_PATH +"""${event.detail.path}`
})
""")
return Titled('Websocket Test', cts, script)
async def on_connect(send):
print("on connect")
await send(Div('Hello, you have connected', id=nid))
async def on_disconnect( ):
print('Disconnected!')
@app.ws('/ws', conn=on_connect, disconn=on_disconnect)
async def ws(msg:str, send):
print("ws", msg)
await send(Div('Hello ' + msg, id=nid))
await sleep(2)
return Div('Goodbye ' + msg, id=nid), mk_inp()
serve()