Skip to content

Instantly share code, notes, and snippets.

@mfeineis
Last active March 6, 2018 01:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfeineis/b5dea2ecf8c93085079f8876c6cb75c2 to your computer and use it in GitHub Desktop.
Save mfeineis/b5dea2ecf8c93085079f8876c6cb75c2 to your computer and use it in GitHub Desktop.
This is a "minimal" example for integrating Elm with Flux-Standard-Actions of ReactJS fame (https://ellie-app.com/d6C53Vf3Pa1/0).
port module ElmFsaPorts exposing (main)
import Html exposing (Html, text)
import Json.Decode as Decode exposing (Decoder, Value)
import Json.Encode as Encode
port fromElm : Value -> Cmd msg
port toElm : (Value -> msg) -> Sub msg
type alias SayHelloData =
{ who : String
}
type Msg
= Incoming Value
| SayHello SayHelloData
| Unknown String
type alias Model =
{ greeting : Maybe String
}
main : Program Never Model Msg
main =
Html.program
{ init = ( { greeting = Nothing }, Cmd.none )
, subscriptions = subscriptions
, update = update
, view = view
}
subscriptions : Model -> Sub Msg
subscriptions model =
-- (A.2), (B.2), (C.2) Flowing the subscription data into `update`
Sub.batch
[ toElm Incoming
]
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Incoming json ->
-- Note that recursively calling `update` is probably
-- not something you would do normally but I think here
-- its use is justified because we can keep all pattern
-- matches for `Msg` on the same level. Otherwise we would
-- either need to nest the `update` further or resort to
-- the "create a Cmd out of a Msg" anti-pattern.
-- Just keep in mind that doing this might result in infinite
-- recursion, so either *never* return an `Incoming` from your
-- decoder or take a different approach, if you're not
-- confident that this convention will hold in a team setting
-- (A.3), (B.3), (C.3) Mapping incoming JSON to `Msg`
update (decodeAction json) model
SayHello { who } ->
-- (A.9) Decoded `SayHello` can be processed!
let
answer =
createAction
"ANSWER"
(Encode.string ("Good to see you too " ++ who ++ "!"))
in
-- (A.10) `fromElm` port will channel the answer to the JS subscription
( { model | greeting = Just who }, fromElm answer )
Unknown reason ->
-- (B.8), (C.8) The `Unknown` `Msg` carries a reason that we channel back to JS
let
answer =
createAction
"BLOWUP"
(Encode.string ("Something went wrong: " ++ reason))
in
-- (B.9), (C.9) `fromElm` port will channel the answer to the JS subscription
( model, fromElm answer )
view : Model -> Html msg
view { greeting } =
text ("Hello, " ++ Maybe.withDefault "Stranger" greeting ++ "!")
-- # JSON Decoding stuff
-- Don't worry if the JSON decoder stuff doesn't click right away
-- it is something that takes some getting used to.
-- Note that we're using the Flux-Standard-Action nomenclature
-- of calling the JSON being handled an `action`, which is kind
-- of a silly name for data if you think about it :-)
decodeAction : Value -> Msg
decodeAction json =
-- (A.4), (B.4), (C.4)
case Decode.decodeValue incomingActionDecoder json of
Ok value ->
-- (A.8) Returning the decoded result
Debug.log "Action decoded successfully!"
value
Err reason ->
-- (B.7), (C.7) Returning the default `Unknown` `Msg` on decoder failures
Debug.log ("Failed to decode incoming " ++ reason)
(Unknown reason)
incomingActionDecoder : Decoder Msg
incomingActionDecoder =
let
decideWhichAction type_ =
case type_ of
"HELLO" ->
-- (A.6) `type` matches "HELLO" so try to decode payload
Decode.map SayHello
(Decode.field "payload" helloPayloadDecoder)
_ ->
-- (C.6) The structure matches but we don't know about that message type
Decode.fail ("Unknown action " ++ type_)
in
-- (A.5), (B.5), (C.5) Decoding `type` and deciding what to do next
Decode.field "type" Decode.string
-- (B.6) The structure doesn't match, so decoding fails here
|> Decode.andThen decideWhichAction
helloPayloadDecoder : Decoder SayHelloData
helloPayloadDecoder =
-- (A.7) Decoding the payload of the "HELLO" FSA
Decode.map SayHelloData
(Decode.field "who" Decode.string)
createAction : String -> Value -> Value
createAction type_ payload =
Encode.object
[ ( "type", Encode.string type_ )
, ( "payload", payload )
]
<html>
<head>
<style>
/* you can style your program here */
</style>
</head>
<body>
<script>
const app = Elm.ElmFsaPorts.fullscreen();
// This is not exactly the simplest form of integration
// but it's kind of what you would do to integrate
// with a non-trivial outside app.
// Using i.e. Flux-Standard-Actions, you can use
// whatever you want, it's just data after all
// but FSAs are pretty common with Redux et al.
app.ports.fromElm.subscribe(value => {
switch (value.type) {
case "ANSWER":
console.log(`fromElm -> ${value.type}`, value);
break;
default:
console.warn(`fromElm -> ${value.type} unknown!`, value);
break;
}
});
// Sending a valid message into Elm (A.1)
app.ports.toElm.send({
type: "HELLO",
payload: { who: "Elm" },
});
// Sending invalid data into Elm (B.1)
app.ports.toElm.send("Invalid FSA data");
// Sending a valid but unknown message into Elm (C.1)
app.ports.toElm.send({
type: "GOTCHA",
payload: { will: "not be decoded..." },
});
</script>
</body>
</html>

MIT License

Copyright (c) 2018 Martin Feineis

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment