bigskysoftware / htmx

</> htmx - high power tools for HTML
https://htmx.org
Other
37.28k stars 1.26k forks source link

Web Socket Extension: Add events #699

Open benpate opened 2 years ago

benpate commented 2 years ago

As per this conversation on Discord, web sockets should trigger events similar to standard htmx requests.

Something mirroring htmx:afterSettle was requested.

ajusa commented 2 years ago

Additionally, it would be nice to have an additional event that is fired on connect, and potentially one on disconnect just for completeness. The actual websocket object should be included as the connect event.

That'll make it more doable to have hyperscript hook into an existing websocket with its socket feature. I haven't looked into the internals, but I'm sure that with the underlying socket being available from HTMX, hyperscript would just need to add a different socket constructor that works with an existing WebSocket.

benpate commented 2 years ago

Giving this a little more thought, each library has its own custom wrapper around websockets (and SSE) connections that is tailored to its own use cases. While they do need custom adapters for their separate feature sets, I think both htmx and hyperscript would benefit from using a shared core. So, when both libraries are present, web socket connections could be shared easily because they're effectively the same.

Currently, hyperscript's websocket function is our best candidate because it has a nicely abstracted proxy that can survive server disconnects. (Htmx has this feature, but it's not wrapped into a separate object)

I think the effort would look something like this:

  1. Build and test a WebSocket wrapper using hyperscript's existing code as a starter

  2. Replace htmx and hyperscript's existing implementations

  3. Add we wrappers into the events generated by htmx and hyperscript (from @ajusa 's suggestion above)

  4. Possibly allow htmx to expose its WS wrappers as JavaScript objects (like hyperscript does)

  5. Possibly allow htmx to connect to existing WS wrappers in the JavaScript scope (like hyperscript does)

wodny commented 2 years ago

It would be great to have a htmx:beforeOnLoad analog and a possibility to reject an update from a WebSocket. For now I've created a wrapper class that overrides addEventListener() and decides if the message event should be forwarded.