htmx icon indicating copy to clipboard operation
htmx copied to clipboard

Web Socket Extension: Add events

Open benpate opened this issue 2 years ago • 3 comments

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

Something mirroring htmx:afterSettle was requested.

benpate avatar Dec 01 '21 21:12 benpate

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.

ajusa avatar Dec 02 '21 00:12 ajusa

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)

benpate avatar Dec 02 '21 15:12 benpate

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.

wodny avatar Dec 30 '21 21:12 wodny