OvermindDL1

OvermindDL1 OP

Due to not being able to use elm-phoenix-socket for a few reasons including that it owns the websocket (can only have one, meaning legacy javascript cannot touch it, which does not work for me), heartbeat is not setup properly (I think that is now fixed, but it was a large issue at the time), and reconnection does not really work at all (elm-websocket’s fault I hear), I made my own library that lets Elm use Phoenix channels via the javascript interface, thus other javascript libraries that use the websocket can still work, it will have no heartbeat or reconnection issues, and I think I made a decent interface (although could probably still use some more helpers to ease some of the large connection structs and such). I am still very much in the phase of learning Elm so the code may not be Elm’ish, but it works well in my work-test-project.

The Github URL is at: GitHub - OvermindDL1/elm-jsphoenix: Elm Port wrapper around Phoenix Socket/Presence javascript library to allow compatibility with existing javascript websocket usage · GitHub

And the initial README.md of the project is the remainder of this post:

elm-jsphoenix

Elm Port wrapper around Phoenix Socket/Presence javascript library to allow compatibility with existing javascript websocket usage

Installation

Include the JSPhoenix.elm module however you wish.

Add the javascript file to your Phoenix brunch (or whatever you’ve replaced it with) build system to include in your Phoenix project.

In the javascript for your Phoenix project any Elm app that you instance just call the setup_phoenix_socket_ports from the setup_phoenix_socket_ports javascript module, such as by:

import socket from './socket'
import Elm from './elm' // Assuming your Elm mains compile to a ./elm.js in the same directory as your app.js
import setup_phoenix_socket_ports from 'setup_phoenix_socket_ports' // Or from where-ever


let socket_setup_once = false
socket.onOpen(() => {
  $(document).ready(function(){
    if(socket_setup_once) return
    socket_setup_once = true

    // Here setup all your usual javascript that also needs to use the websocket

    let app = Elm.Main.embed(document.querySelector('#my-elm-container'))
    setup_phoenix_socket_ports(app, socket)
  }
}

Even if you do not have any other javascript code using the socket this still ensures full compatibility of your Elm app with the Phoenix socket interface, heartbeats, recovery, and all.

Usage

The bindings are not absolutely complete to the javascript code, but rather a useful interface is exposed to Elm within its type system.

This is a brand new project and the documentation is not entirely complete, however the code is short and should be readable.

General usage is as follows

Connect to a channel, specify presence sync ports and some message ports and how to use:

import JSPhoenix exposing (ChannelEventMsg, ChanExitCB)

-- Currently this next line does not work due to Elm bugs...
--type alias RoomSyncState = List (JSPhoenix.PresenceObject {} {online_at : JSPhoenix.TimexDateTime, nick : String})
-- So instead you have to do this mess for each of your presence sync object types because of Elm port bugs:
type alias RoomSyncMeta =
  { phx_ref : String -- Until Elm bug is fixed, phx_ref should 'generally' always be here
  , loc : String
  , online_at : JSPhoenix.TimexDateTime
  , nick : String
  }

type alias RoomSyncState =
  List ( String, { metas : List RoomSyncMeta } ) -- Until Elm bug is fixed 'metas' must *always* be here with a List of records


-- Same bug issue as above, you should be able to do:
--type alias RoomSyncEvent = JSPhoenix.PresenceObject {} {online_at : JSPhoenix.TimexDateTime, nick : String}
-- Instead you have to do this mess for each presence sync event type
type alias RoomSyncEvent =
  { id : String
  , old : Maybe { String, List RoomSyncMeta }
  , new : List ( String, List RoomSyncMeta )
  }

-- Custom messages, whatever fits your Phoenix app:
type alias RoomMessage =
  { room_id : Int
  , uid : Int
  , inserted_at : JSPhoenix.TimexDateTime
  , updated_at : JSPhoenix.TimexDateTime
  , nick : String
  , msg : String
  }

type alias RoomMessages =
  { msgs : List RoomMessage }

port onRoomConnect : (ChannelEventMsg {} Int -> msg) -> Sub msg
port onRoomInfo : (ChannelEventMsg {} Int -> msg) -> Sub msg
port onRoomMsgsInit : (ChannelEventMsg RoomMessages Int -> msg) -> Sub msg
port onRoomMsgsAdd : (ChannelEventMsg RoomMessages Int -> msg) -> Sub msg
port onRoomSyncState : (ChannelEventMsg RoomSyncState Int -> msg) -> Sub msg
port onRoomSyncJoin : (ChannelEventMsg RoomSyncEvent Int -> msg) -> Sub msg
port onRoomSyncLeave : (ChannelEventMsg RoomSyncEvent Int -> msg) -> Sub msg

connect_room rid =
  JSPhoenix.connect
      { topic = room_id_to_topic rid
      , timeout_ms = Nothing -- Just 10000 -- Default value is 10000 if Nothing is used
      , chanCloseCB = Nothing
      , chanErrorCB = Nothing
      , syncState = Just { portName = "onRoomSyncState", cb_data = (int rid) }
      , syncJoin = Just { portName = "onRoomSyncJoin", cb_data = (int rid) }
      , syncLeave = Just { portName = "onRoomSyncLeave", cb_data = (int rid) }
      , joinData = null
      , joinEvents =
          [ { portName = "onRoomConnect", msgID = "ok", cb_data = (int rid) }
          ]
      , onPorts =
          [ { portName = "onRoomInfo", msgID = "room:info", cb_data = (int rid) }
          , { portName = "onRoomMsgsInit", msgID = "msgs:init", cb_data = (int rid) }
          , { portName = "onRoomMsgsAdd", msgID = "msgs:add", cb_data = (int rid) }
          ]
      }

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
  case msg of
    -- ... other messages

    MyConnectMessage rid ->
      ( model
      , connect_room rid -- You can use the JSPhoenix.connect like any normal command
      )

subscriptions : Model -> Sub Msg
subscriptions model =
  Sub.batch -- Subscribe to your port events to get their messages
    [ onRoomConnect (\{ msg, cb_data } -> MyRoomConnectMsg msg cb_data) -- Example to show you the structure of the data
    , onRoomInfo MyRoomInfoMsg
    , onRoomMsgsInit MyRoomMsgsInitMsg
    , onRoomMsgsAdd MyRoomMsgsAddMsg
    , onRoomSyncState MyRoomSyncStateMsg
    , onRoomSyncJoin MyRoomSyncJoinMsg
    , onRoomSyncLeave MyRoomSyncLeaveMsg
    ]

Where Next? Top

Trending in Discussions Top

AstonJ
As the title says, please share what you’ve been up to with Elixir. Whether that’s been learning it, looking into it, making stuff with i...
2977 91898 914
New
byu
@chrismccord : I just saw the Extract AGENTS.md from Phoenix.new into phx.new generator commit to the phoenix project. My initial shotgu...
New
arcanemachine
I was working on an Ecto migration and I needed a timestamp. So, for the nth time, I looked up the different data types for timestamps, a...
New
AstonJ
Just a general thread to post chat/news/info relating to AI/ML stuff that may be relevant for Nx now or in the future. Got anything to sh...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
alexslade
Fly’s CEO posted this recently - Turn And Face The Strange · The Fly Blog It says that Fly is going all-in on sprites, which is a worry ...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
mudasobwa
While I am working on the Language Agnostic Code Audit SaaS, which uses MetaAST (spoiler: I am expecting it to be in a good shape for ann...
New

We're in Beta

About us Mission Statement