Skip to content

Commit

Permalink
fix(*): general cleanup, patch absinthe start issue (#90)
Browse files Browse the repository at this point in the history
* fix(*): general cleanup, patch absinthe start issue

* chore(*): base_path, use parentheses to remove the ambiguity

* chore(*): undo lock file change

* feat(*): hook up key combos

* feat(*): rewrite keyCombo sub in elm
  • Loading branch information
tbash authored Apr 5, 2019
1 parent 5179882 commit 673c338
Show file tree
Hide file tree
Showing 10 changed files with 89 additions and 210 deletions.
68 changes: 18 additions & 50 deletions assets/src/Effect/Program.elm
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
port module Effect.Program exposing (Config, Model(..), Msg(..), Program, State, debounceConfig, effectProgramKeyDowns, initialState, keyDownDecoder, maybeWithDebounce, maybeWithToken, program, runCmd, runSub, withCaching, wrapInit, wrapSubscriptions, wrapUpdate, wrapView)
module Effect.Program exposing (Config, Model(..), Msg(..), Program, State, debounceConfig, initialState, keyDownDecoder, maybeWithDebounce, maybeWithToken, program, runCmd, runSub, withCaching, wrapInit, wrapSubscriptions, wrapUpdate, wrapView)

import Browser
import Browser.Events
Expand Down Expand Up @@ -28,9 +28,6 @@ import Time
import Url exposing (Url)


port effectProgramKeyDowns : (Decode.Value -> a) -> Sub a


type alias Config flags route model msg =
{ init : flags -> route -> ( model, Command msg )
, url : Url -> route
Expand All @@ -56,7 +53,6 @@ debounceConfig debounceMsg =
type Msg msg
= UserMsg msg
| SetupSocket String { url : String, token : Maybe String } (SelectionSet msg RootSubscription)
| SubscriptionMsg String Absinthe.Msg
| KeyDown String
| KeyUp String
| Debounce String Debounce.Msg
Expand Down Expand Up @@ -133,33 +129,31 @@ runCmd config state cmd =
|> maybeWithToken token
|> withCaching cache
|> Graphql.Http.send identity
-- |> Cmd.map (Result.mapError Graphql.Http.ignoreParsedErrorData)
|> Cmd.map Graphql.Http.discardParsedErrorData
|> Cmd.map
(\result ->
case result of
Ok msg ->
UserMsg msg

Err str ->
-- UserMsg (onError str)
NoOp
UserMsg (onError str)
)
|> maybeWithDebounce state debounce

Command.GraphqlMutation { url, token, selection, onError, debounce } ->
Graphql.Http.mutationRequest url selection
|> maybeWithToken token
|> Graphql.Http.send identity
-- |> Cmd.map (Result.mapError Graphql.Http.ignoreParsedErrorData)
|> Cmd.map Graphql.Http.discardParsedErrorData
|> Cmd.map
(\result ->
case result of
Ok msg ->
UserMsg msg

Err str ->
-- UserMsg (onError str)
NoOp
UserMsg (onError str)
)
|> maybeWithDebounce state debounce

Expand Down Expand Up @@ -207,35 +201,29 @@ runCmd config state cmd =

keyDownDecoder : Bool -> Bool -> String -> msg -> Decoder (Msg msg)
keyDownDecoder needsShift needsMeta key msg =
Decode.map3
(\actualKey shift meta ->
Decode.andThen
(\( actualKey, shift, meta ) ->
if shift == needsShift && meta == needsMeta && key == actualKey then
UserMsg msg
Decode.succeed (UserMsg msg)

else
NoOp
Decode.fail ""
)
(Decode.field "key" Decode.string)
(Decode.field "shiftKey" Decode.bool)
(Decode.map2 (||)
(Decode.field "metaKey" Decode.bool)
(Decode.field "ctrlKey" Decode.bool)
(Decode.map3 (\actualKey shift meta -> ( actualKey, shift, meta ))
(Decode.field "key" Decode.string)
(Decode.field "shiftKey" Decode.bool)
(Decode.map2 (||)
(Decode.field "metaKey" Decode.bool)
(Decode.field "ctrlKey" Decode.bool)
)
)


runSub : Config flags route model msg -> State msg -> Subscription msg -> Sub (Msg msg)
runSub config state sub =
case sub of
Subscription.KeyCombo combo msg ->
effectProgramKeyDowns
(\value ->
case Decode.decodeValue (keyDownDecoder combo.shift combo.meta combo.key msg) value of
Ok wrappedMsg ->
wrappedMsg

Err _ ->
NoOp
)
Browser.Events.onKeyDown (keyDownDecoder combo.shift combo.meta combo.key msg)

Subscription.PortReceive channel callback ->
config.inbound <|
Expand Down Expand Up @@ -285,9 +273,6 @@ runSub config state sub =

Absinthe.Status bool ->
UserMsg (onStatus bool)

Absinthe.Control msg ->
SubscriptionMsg key msg
)

Nothing ->
Expand Down Expand Up @@ -364,7 +349,7 @@ wrapUpdate config msg model =
SetupSocket key socketConfig selection ->
let
( absinthe, absintheCmd ) =
Absinthe.init socketConfig always selection
Absinthe.init socketConfig selection
in
( Running
{ state | sockets = Dict.insert key absinthe state.sockets }
Expand All @@ -373,23 +358,6 @@ wrapUpdate config msg model =
, absintheCmd
)

SubscriptionMsg key socketMsg ->
case Dict.get key state.sockets of
Just socket ->
let
( newSocket, socketCmd ) =
Absinthe.update socketMsg socket
in
( Running
{ state | sockets = Dict.insert key newSocket state.sockets }
flags
m
, Cmd.map (SubscriptionMsg key) socketCmd
)

Nothing ->
( model, Cmd.none )


wrapView : Config flags route model msg -> Model flags model msg -> Browser.Document (Msg msg)
wrapView config model =
Expand Down
99 changes: 10 additions & 89 deletions assets/src/Network/Absinthe/Socket.elm
Original file line number Diff line number Diff line change
@@ -1,13 +1,4 @@
port module Network.Absinthe.Socket exposing
( Info(..)
, Logger
, Msg
, Socket
, emptyLogger
, init
, listen
, update
)
port module Network.Absinthe.Socket exposing (Info(..), Socket, init, listen)

import Extra.Json.Encode as Encode
import Graphql.Document as Document
Expand All @@ -23,46 +14,29 @@ port absintheSocketOutbound : Value -> Cmd msg
port absintheSocketInbound : (Value -> msg) -> Sub msg


socketListen : Socket -> Sub Info
socketListen state =
listen : Socket -> Sub Info
listen state =
absintheSocketInbound <|
\input ->
case Decode.decodeValue (infoDecoder state) input of
Ok info ->
info

Err _ ->
Control SocketClosed
Status False


type alias Socket =
{ connected : Bool
, url : String
{ url : String
, token : Maybe String
, logger : Logger
, document : String
}


type alias Logger =
String -> String -> String


emptyLogger : Logger
emptyLogger a b =
b


init :
{ url : String, token : Maybe String }
-> Logger
-> SelectionSet a RootSubscription
-> ( Socket, Cmd msg )
init { url, token } logger doc =
( { connected = False
, url = url
init : { url : String, token : Maybe String } -> SelectionSet a RootSubscription -> ( Socket, Cmd msg )
init { url, token } doc =
( { url = url
, token = token
, logger = logger
, document = Document.serializeSubscription doc
}
, absintheSocketOutbound <|
Expand All @@ -78,59 +52,6 @@ init { url, token } logger doc =
type Info
= Data Value
| Status Bool
| Control Msg


type Msg
= SocketOpened
| SocketClosed
| ProblemResponse String
| NoOp


update : Msg -> Socket -> ( Socket, Cmd Msg )
update msg state =
case msg of
SocketOpened ->
( { state | connected = True }
, Cmd.none
)

SocketClosed ->
( { state | connected = False }
, Cmd.none
)

ProblemResponse string ->
let
_ =
state.logger "Malformed response" string
in
( state, Cmd.none )

NoOp ->
( state, Cmd.none )


listen : Socket -> Sub Info
listen state =
Sub.batch
[ Sub.map toStatus (socketListen state)
, socketListen state
]


toStatus : Info -> Info
toStatus socketInfo =
case socketInfo of
Control SocketClosed ->
Status False

Control SocketOpened ->
Status True

_ ->
Control NoOp


infoDecoder : Socket -> Decoder Info
Expand All @@ -140,11 +61,11 @@ infoDecoder state =
(\tag ->
case tag of
"Open" ->
Decode.succeed <| Control SocketOpened
Decode.succeed <| Status True

"Data" ->
Decode.map Data <| Decode.field "data" Decode.value

_ ->
Decode.succeed <| Control SocketClosed
Decode.succeed <| Status False
)
59 changes: 29 additions & 30 deletions assets/src/Network/Absinthe/Socket.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,41 @@
import * as AbsintheSocket from "@absinthe/socket";
import { Socket as PhoenixSocket } from "phoenix";

const createPhoenixSocket = (address, params) =>
new PhoenixSocket(address, { params });

export default {
start(app) {
const onOpen = () => {
start: app => {
const initialize = ({ url, token, doc }) => {
return Promise.all([
import(/* webpackChunkName: "phoenix" */ "phoenix"),
import(/* webpackChunkName: "absinthe-socket" */ "@absinthe/socket")
]).then(([Phoenix, AbsintheSocket]) => {
const phoenixSocket = new Phoenix.Socket(url, { params: { token } });
const absintheSocket = AbsintheSocket.create(phoenixSocket);

const notifier = AbsintheSocket.send(absintheSocket, {
operation: doc,
variables: {}
});

AbsintheSocket.observe(absintheSocket, notifier, {
onStart,
onAbort,
onError,
onCancel,
onResult
});
});
};

const onStart = _data => {
app.ports.absintheSocketInbound.send({ tag: "Open" });
};

const onAbort = data => {
const onAbort = _data => {
app.ports.absintheSocketInbound.send({ tag: "Abort" });
};

const onCancel = data => {
const onCancel = _data => {
app.ports.absintheSocketInbound.send({ tag: "Cancel" });
};

const onError = data => {
const onError = _data => {
app.ports.absintheSocketInbound.send({ tag: "Error" });
};

Expand All @@ -29,25 +46,7 @@ export default {
app.ports.absintheSocketOutbound.subscribe(data => {
switch (data.tag) {
case "Initialize": {
const phoenixSocket = createPhoenixSocket(data.url, {
token: data.token
});
const absintheSocket = AbsintheSocket.create(phoenixSocket);

phoenixSocket.onOpen(onOpen);

const notifier = AbsintheSocket.send(absintheSocket, {
operation: data.doc,
variables: {}
});

AbsintheSocket.observe(absintheSocket, notifier, {
onAbort,
onError,
onCancel,
onResult
});

initialize(data);
break;
}

Expand Down
Loading

0 comments on commit 673c338

Please sign in to comment.