From 864638520a9af4695e4ea46fed2b1113ea2c1fb6 Mon Sep 17 00:00:00 2001 From: Steven Vandevelde Date: Sat, 20 Apr 2019 15:29:06 +0200 Subject: [PATCH] Refactor Return types and handling of nested state --- elm.json | 3 +- src/Applications/Brain.elm | 133 ++--- src/Applications/Brain/Authentication.elm | 156 +++-- src/Applications/Brain/Sources/Processing.elm | 84 ++- .../Brain/Sources/Processing/Steps.elm | 11 +- src/Applications/Brain/Tracks.elm | 10 +- src/Applications/UI.elm | 546 ++++++++---------- src/Applications/UI/Authentication.elm | 80 ++- src/Applications/UI/Backdrop.elm | 18 +- src/Applications/UI/Core.elm | 18 - src/Applications/UI/Equalizer.elm | 38 +- src/Applications/UI/Notifications.elm | 15 +- src/Applications/UI/Queue.elm | 129 ++--- src/Applications/UI/Reply.elm | 41 +- src/Applications/UI/Sources.elm | 45 +- src/Applications/UI/Sources/Form.elm | 13 +- src/Applications/UI/Tracks.elm | 80 ++- src/Applications/UI/UserData.elm | 59 +- src/Library/Replying.elm | 128 ---- src/Library/Return2.elm | 59 ++ src/Library/Return3.elm | 175 ++++++ src/Library/Task/Extra.elm | 12 + 22 files changed, 909 insertions(+), 944 deletions(-) delete mode 100644 src/Library/Replying.elm create mode 100644 src/Library/Return2.elm create mode 100644 src/Library/Return3.elm create mode 100644 src/Library/Task/Extra.elm diff --git a/elm.json b/elm.json index 4bb29c01..a8e7287c 100644 --- a/elm.json +++ b/elm.json @@ -7,7 +7,6 @@ "elm-version": "0.19.0", "dependencies": { "direct": { - "Chadtech/return": "1.0.2", "FabienHenon/elm-infinite-list-view": "3.0.0", "Gizra/elm-debouncer": "2.0.0", "NoRedInk/elm-json-decode-pipeline": "1.0.0", @@ -51,4 +50,4 @@ "direct": {}, "indirect": {} } -} \ No newline at end of file +} diff --git a/src/Applications/Brain.elm b/src/Applications/Brain.elm index e78ce82f..7da42d9e 100644 --- a/src/Applications/Brain.elm +++ b/src/Applications/Brain.elm @@ -13,7 +13,8 @@ import Debouncer.Basic as Debouncer import Json.Decode as Json import Json.Decode.Pipeline exposing (optional) import Json.Encode -import Replying exposing (andThen2, return) +import Return2 exposing (..) +import Return3 import Sources.Encoding as Sources import Sources.Processing.Encoding as Processing import Tracks.Encoding as Tracks @@ -71,50 +72,38 @@ update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of Bypass -> - ( model - , Cmd.none - ) + return model NotifyUI alienEvent -> - ( model - , Cmd.batch - [ Brain.Ports.toUI alienEvent + [ Brain.Ports.toUI alienEvent - -- Sometimes the loading screen is still showing, - -- so we hide it here just in case. - , case alienEvent.error of - Just _ -> - Brain.Ports.toUI (Alien.trigger Alien.HideLoadingScreen) + -- Sometimes the loading screen is still showing, + -- so we hide it here just in case. + , case alienEvent.error of + Just _ -> + Brain.Ports.toUI (Alien.trigger Alien.HideLoadingScreen) - Nothing -> - Cmd.none - ] - ) + Nothing -> + Cmd.none + ] + |> Cmd.batch + |> returnWithModel model NotSoFast debouncerMsg -> - let - ( subModel, subCmd, emittedMsg ) = - Debouncer.update debouncerMsg model.notSoFast - - mappedCmd = - Cmd.map NotSoFast subCmd - - updatedModel = - { model | notSoFast = subModel } - in - case emittedMsg of - Just emitted -> - updatedModel - |> update emitted - |> Tuple.mapSecond (\cmd -> Cmd.batch [ cmd, mappedCmd ]) - - Nothing -> - ( updatedModel, mappedCmd ) + Return3.wieldNested + update + { mapCmd = NotSoFast + , mapModel = \child -> { model | notSoFast = child } + , update = \m -> Debouncer.update m >> Return3.fromDebouncer + } + { model = model.notSoFast + , msg = debouncerMsg + } ToCache alienEvent -> - ( model - , Brain.Ports.toCache alienEvent - ) + alienEvent + |> Brain.Ports.toCache + |> returnWithModel model ----------------------------------------- -- Children @@ -156,18 +145,18 @@ update msg model = encodedTracks = Json.Encode.list Tracks.encodeTrack decodedData.tracks in - andThen2 - (updateSearchIndex encodedTracks) - ( { model | hypaethralUserData = decodedData } - , Brain.Ports.toUI (Alien.broadcast Alien.LoadHypaethralUserData value) - ) + value + |> Alien.broadcast Alien.LoadHypaethralUserData + |> Brain.Ports.toUI + |> returnWithModel { model | hypaethralUserData = decodedData } + |> andThen (updateSearchIndex encodedTracks) SaveHypaethralData -> model.hypaethralUserData |> Authentication.encodeHypaethral |> Authentication.SaveHypaethralData |> AuthenticationMsg - |> (\m -> update m model) + |> updateWithModel model SaveFavourites value -> value @@ -196,44 +185,49 @@ update msg model = |> Result.withDefault model.hypaethralUserData.tracks |> hypaethralLenses.setTracks model |> updateSearchIndex value - |> andThen2 saveHypaethralData + |> andThen saveHypaethralData + + +updateWithModel : Model -> Msg -> ( Model, Cmd Msg ) +updateWithModel model msg = + update msg model updateSearchIndex : Json.Value -> Model -> ( Model, Cmd Msg ) updateSearchIndex value model = - update - (value - |> Tracks.UpdateSearchIndex - |> TracksMsg - ) - model + value + |> Tracks.UpdateSearchIndex + |> TracksMsg + |> updateWithModel model -- 📣 ░░ REPLIES -translateReply : Reply -> Msg -translateReply reply = +translateReply : Reply -> Model -> ( Model, Cmd Msg ) +translateReply reply model = case reply of FabricatedNewSecretKey -> - SaveHypaethralData + update SaveHypaethralData model ----------------------------------------- -- To UI ----------------------------------------- GiveUI Alien.LoadHypaethralUserData data -> - LoadHypaethralUserData data + update (LoadHypaethralUserData data) model GiveUI tag data -> - NotifyUI (Alien.broadcast tag data) + data + |> Alien.broadcast tag + |> NotifyUI + |> updateWithModel model NudgeUI tag -> - NotifyUI (Alien.trigger tag) - - -updateChild = - Replying.updateChild update translateReply + tag + |> Alien.trigger + |> NotifyUI + |> updateWithModel model @@ -242,7 +236,8 @@ updateChild = updateAuthentication : Model -> Authentication.Msg -> ( Model, Cmd Msg ) updateAuthentication model sub = - updateChild + Return3.wieldNested + translateReply { mapCmd = AuthenticationMsg , mapModel = \child -> { model | authentication = child } , update = Authentication.update @@ -254,7 +249,8 @@ updateAuthentication model sub = updateProcessing : Model -> Processing.Msg -> ( Model, Cmd Msg ) updateProcessing model sub = - updateChild + Return3.wieldNested + translateReply { mapCmd = ProcessingMsg , mapModel = \child -> { model | processing = child } , update = Processing.update @@ -266,7 +262,8 @@ updateProcessing model sub = updateTracks : Model -> Tracks.Msg -> ( Model, Cmd Msg ) updateTracks model sub = - updateChild + Return3.wieldNested + translateReply { mapCmd = TracksMsg , mapModel = \child -> { model | tracks = child } , update = Tracks.update @@ -295,12 +292,10 @@ makeHypaethralLens setter model value = saveHypaethralData : Model -> ( Model, Cmd Msg ) saveHypaethralData model = - update - (SaveHypaethralData - |> Debouncer.provideInput - |> NotSoFast - ) - model + SaveHypaethralData + |> Debouncer.provideInput + |> NotSoFast + |> updateWithModel model diff --git a/src/Applications/Brain/Authentication.elm b/src/Applications/Brain/Authentication.elm index c61aba7c..886eb801 100644 --- a/src/Applications/Brain/Authentication.elm +++ b/src/Applications/Brain/Authentication.elm @@ -26,7 +26,8 @@ import Brain.Reply exposing (Reply(..)) import Conditional exposing (..) import Json.Decode as Decode import Json.Encode as Json -import Replying exposing (R3D3, do) +import Return3 as Return exposing (..) +import Task.Extra exposing (do) @@ -77,7 +78,7 @@ type Msg | SaveHypaethralData Json.Value -update : Msg -> Model -> R3D3 Model Msg Reply +update : Msg -> Model -> Return Model Msg Reply update msg model = case msg of -- 🐤 @@ -87,100 +88,90 @@ update msg model = let decoder = Decode.map2 - (\a b -> { maybeMethod = a, maybePassphrase = b }) + Tuple.pair (Decode.field "method" <| Decode.map methodFromString Decode.string) (Decode.field "passphrase" <| Decode.maybe Decode.string) in case Decode.decodeValue decoder json of - Ok { maybeMethod, maybePassphrase } -> - case maybePassphrase of - Just passphrase -> - ( { model | method = maybeMethod, performingSignIn = True } - , do (FabricateSecretKey passphrase) - , Nothing - ) - - Nothing -> - ( { model | method = maybeMethod, performingSignIn = True } - , do RetrieveHypaethralData - , Nothing - ) + Ok ( maybeMethod, Just passphrase ) -> + update + (FabricateSecretKey passphrase) + { model | method = maybeMethod, performingSignIn = True } + + Ok ( maybeMethod, Nothing ) -> + update + RetrieveHypaethralData + { model | method = maybeMethod, performingSignIn = True } _ -> - ( model - , Cmd.none - , Nothing - ) + return model -- 💀 -- Unset & remove stored method. PerformSignOut -> - ( { model | method = Nothing } - , Cmd.batch - [ Ports.removeCache (Alien.trigger Alien.AuthMethod) - , Ports.removeCache (Alien.trigger Alien.AuthSecretKey) - ] - , Nothing - ) + [ Ports.removeCache (Alien.trigger Alien.AuthMethod) + , Ports.removeCache (Alien.trigger Alien.AuthSecretKey) + ] + |> Cmd.batch + |> Return.commandWithModel { model | method = Nothing } ----------------------------------------- -- # 0 ----------------------------------------- FabricateSecretKey passphrase -> - ( model - , passphrase + passphrase |> Json.string |> Alien.broadcast Alien.FabricateSecretKey |> Ports.fabricateSecretKey - , Nothing - ) + |> Return.commandWithModel model SecretKeyFabricated -> if model.performingSignIn then - ( model, do RetrieveHypaethralData, Nothing ) + update RetrieveHypaethralData model else - ( model, Cmd.none, Just [ FabricatedNewSecretKey ] ) + returnReplyWithModel model FabricatedNewSecretKey ----------------------------------------- -- # 1 ----------------------------------------- RetrieveMethod -> - ( model - , Alien.AuthMethod + Alien.AuthMethod |> Alien.trigger |> Ports.requestCache - , Nothing - ) + |> Return.commandWithModel model MethodRetrieved json -> case decodeMethod json of -- 🚀 Just method -> - ( { model | method = Just method } - , do RetrieveHypaethralData - , Nothing - ) + update + RetrieveHypaethralData + { model | method = Just method } -- ✋ _ -> - ( model - , Cmd.none - , terminate NotAuthenticated - ) + addReplies + (terminate NotAuthenticated) + (return model) ----------------------------------------- -- # 2 ----------------------------------------- RetrieveHypaethralData -> - ( model - , case model.method of + case model.method of -- 🚀 Just Ipfs -> - Ports.requestIpfs (Alien.trigger Alien.AuthIpfs) + Alien.AuthIpfs + |> Alien.trigger + |> Ports.requestIpfs + |> Return.commandWithModel model Just Local -> - Ports.requestCache (Alien.trigger Alien.AuthAnonymous) + Alien.AuthAnonymous + |> Alien.trigger + |> Ports.requestCache + |> Return.commandWithModel model Just (RemoteStorage { userAddress, token }) -> [ ( "token", Json.string token ) @@ -189,12 +180,11 @@ update msg model = |> Json.object |> Alien.broadcast Alien.AuthRemoteStorage |> Ports.requestRemoteStorage + |> Return.commandWithModel model -- ✋ Nothing -> - Cmd.none - , Nothing - ) + return model HypaethralDataRetrieved json -> ( { model | performingSignIn = False } @@ -209,43 +199,46 @@ update msg model = _ -> Cmd.none -- - , Maybe.andThen - (\method -> terminate <| Authenticated method json) - model.method + , model.method + |> Maybe.map (\method -> Authenticated method json) + |> Maybe.map terminate + |> Maybe.withDefault [] ) ----------------------------------------- -- Data ----------------------------------------- RetrieveEnclosedData -> - ( model - , Ports.requestCache (Alien.trigger Alien.AuthEnclosedData) - , Nothing - ) + Alien.AuthEnclosedData + |> Alien.trigger + |> Ports.requestCache + |> Return.commandWithModel model EnclosedDataRetrieved json -> - ( model - , Cmd.none - , Just [ GiveUI Alien.LoadEnclosedUserData json ] - ) + json + |> GiveUI Alien.LoadEnclosedUserData + |> Return.replyWithModel model SaveEnclosedData json -> - ( model - , json + json |> Alien.broadcast Alien.AuthEnclosedData |> Ports.toCache - , Nothing - ) + |> Return.commandWithModel model SaveHypaethralData json -> - ( model - , case model.method of + case model.method of -- 🚀 Just Ipfs -> - Ports.toIpfs (Alien.broadcast Alien.AuthIpfs json) + json + |> Alien.broadcast Alien.AuthIpfs + |> Ports.toIpfs + |> Return.commandWithModel model Just Local -> - Ports.toCache (Alien.broadcast Alien.AuthAnonymous json) + json + |> Alien.broadcast Alien.AuthAnonymous + |> Ports.toCache + |> Return.commandWithModel model Just (RemoteStorage { userAddress, token }) -> [ ( "data", json ) @@ -255,12 +248,11 @@ update msg model = |> Json.object |> Alien.broadcast Alien.AuthRemoteStorage |> Ports.toRemoteStorage + |> Return.commandWithModel model -- ✋ Nothing -> - Cmd.none - , Nothing - ) + return model @@ -272,17 +264,15 @@ type Termination | NotAuthenticated -terminate : Termination -> Maybe (List Reply) +terminate : Termination -> List Reply terminate t = case t of Authenticated method hypData -> - Just - [ GiveUI Alien.LoadHypaethralUserData hypData - , GiveUI Alien.AuthMethod (Authentication.encodeMethod method) - ] + [ GiveUI Alien.LoadHypaethralUserData hypData + , GiveUI Alien.AuthMethod (Authentication.encodeMethod method) + ] NotAuthenticated -> - Just - [ NudgeUI Alien.NotAuthenticated - , NudgeUI Alien.HideLoadingScreen - ] + [ NudgeUI Alien.NotAuthenticated + , NudgeUI Alien.HideLoadingScreen + ] diff --git a/src/Applications/Brain/Sources/Processing.elm b/src/Applications/Brain/Sources/Processing.elm index a965bc92..0b338c34 100644 --- a/src/Applications/Brain/Sources/Processing.elm +++ b/src/Applications/Brain/Sources/Processing.elm @@ -9,10 +9,10 @@ import Http import Json.Encode as Encode import List.Extra as List import Maybe.Extra as Maybe -import Replying exposing (R3D3, do) -import Return3 +import Return3 as Return exposing (..) import Sources.Processing exposing (..) import Task +import Task.Extra exposing (do) import Time import Tracks.Encoding @@ -38,7 +38,7 @@ initialCommand = -- 📣 -update : Msg -> Model -> R3D3 Model Msg Reply +update : Msg -> Model -> Return Model Msg Reply update msg model = case msg of {- If already processing, do nothing. @@ -46,26 +46,25 @@ update msg model = If there are sources, start processing the first source. -} Process { origin, sources, tracks } -> - if isProcessing model.status || List.isEmpty sources then - Return3.withNothing model - - else - let - filter s = - List.filter (.sourceId >> (==) s.id) tracks - - all = - List.map (\s -> ( s, filter s )) sources - in - case List.uncons all of - Just ( ( s, t ), future ) -> - ( { model | origin = origin, status = Processing ( s, t ) future } - , Steps.takeFirstStep origin model.currentTime s - , Nothing - ) - - Nothing -> - Return3.withNothing model + let + filter s = + List.filter (.sourceId >> (==) s.id) tracks + + all = + List.map (\s -> ( s, filter s )) sources + in + case + ( isProcessing model.status || List.isEmpty sources + , List.uncons all + ) + of + ( False, Just ( ( s, t ), future ) ) -> + Return.commandWithModel + { model | origin = origin, status = Processing ( s, t ) future } + (Steps.takeFirstStep origin model.currentTime s) + + _ -> + return model {- If not processing, do nothing. If there are no sources left, do nothing. @@ -74,16 +73,14 @@ update msg model = NextInLine -> case model.status of Processing _ (( source, tracks ) :: rest) -> - ( { model | status = Processing ( source, tracks ) rest } - , Steps.takeFirstStep model.origin model.currentTime source - , Nothing - ) + Return.commandWithModel + { model | status = Processing ( source, tracks ) rest } + (Steps.takeFirstStep model.origin model.currentTime source) _ -> - ( { model | status = NotProcessing } - , Cmd.none - , Just [ NudgeUI Alien.FinishedProcessingSources ] - ) + Return.repliesWithModel + { model | status = NotProcessing } + [ NudgeUI Alien.FinishedProcessingSources ] ----------------------------------------- -- Phase 1 @@ -91,18 +88,18 @@ update msg model = ----------------------------------------- PrepareStep context (Ok response) -> let - ( cmd, maybeReplies ) = + ( cmd, replies ) = Steps.takePrepareStep context response model.currentTime in ( model , cmd - , maybeReplies + , replies ) PrepareStep context (Err err) -> ( model , do NextInLine - , Just [ reportHttpError context.source err ] + , [ reportHttpError context.source err ] ) ----------------------------------------- @@ -114,19 +111,16 @@ update msg model = Processing ( source, tracks ) rest -> ( { model | status = Processing ( context.source, tracks ) rest } , Steps.takeTreeStep context response tracks model.currentTime - , Nothing + , [] ) NotProcessing -> - ( model - , Cmd.none - , Nothing - ) + return model TreeStep context (Err err) -> ( model , do NextInLine - , Just [ reportHttpError context.source err ] + , [ reportHttpError context.source err ] ) TreeStepRemoveTracks sourceId filePaths -> @@ -139,7 +133,7 @@ update msg model = in ( model , Cmd.none - , Just [ GiveUI Alien.RemoveTracksByPath encodedData ] + , [ GiveUI Alien.RemoveTracksByPath encodedData ] ) ----------------------------------------- @@ -164,7 +158,7 @@ update msg model = -------- , case List.isEmpty (List.filter Maybe.isJust tagsContext.receivedTags) of True -> - Nothing + [] False -> tagsContext @@ -172,17 +166,13 @@ update msg model = |> Encode.list Tracks.Encoding.encodeTrack |> GiveUI Alien.AddTracks |> List.singleton - |> Just ) ----------------------------------------- -- Bits & Pieces ----------------------------------------- SetCurrentTime time -> - ( { model | currentTime = time } - , Cmd.none - , Nothing - ) + return { model | currentTime = time } diff --git a/src/Applications/Brain/Sources/Processing/Steps.elm b/src/Applications/Brain/Sources/Processing/Steps.elm index d1faa9cf..a00ffaec 100644 --- a/src/Applications/Brain/Sources/Processing/Steps.elm +++ b/src/Applications/Brain/Sources/Processing/Steps.elm @@ -26,12 +26,12 @@ import Brain.Ports as Ports import Brain.Reply exposing (Reply(..)) import Brain.Sources.Processing.Common exposing (..) import List.Extra as List -import Replying exposing (do) import Set import Sources exposing (Source) import Sources.Encoding import Sources.Processing exposing (..) import Sources.Services as Services +import Task.Extra exposing (do) import Time import Tracks exposing (Track) @@ -74,7 +74,7 @@ takeFirstStep origin currentTime source = -- 2nd STEP -takePrepareStep : Context -> String -> Time.Posix -> ( Cmd Msg, Maybe (List Reply) ) +takePrepareStep : Context -> String -> Time.Posix -> ( Cmd Msg, List Reply ) takePrepareStep context response currentTime = context |> handlePreparationResponse response @@ -164,12 +164,12 @@ handlePreparationResponse response context = } -intoPreparationCommands : Time.Posix -> Context -> ( Cmd Msg, Maybe (List Reply) ) +intoPreparationCommands : Time.Posix -> Context -> ( Cmd Msg, List Reply ) intoPreparationCommands currentTime context = case context.preparationMarker of TheBeginning -> ( Cmd.none - , Nothing + , [] ) -- Still preparing, @@ -177,7 +177,7 @@ intoPreparationCommands currentTime context = -- InProgress _ -> ( prepare context currentTime - , Nothing + , [] ) -- The preparation is completed, @@ -196,7 +196,6 @@ intoPreparationCommands currentTime context = |> Sources.Encoding.encode |> GiveUI Alien.UpdateSourceData |> List.singleton - |> Just ) diff --git a/src/Applications/Brain/Tracks.elm b/src/Applications/Brain/Tracks.elm index 615b2eae..30220196 100644 --- a/src/Applications/Brain/Tracks.elm +++ b/src/Applications/Brain/Tracks.elm @@ -4,7 +4,7 @@ import Alien import Brain.Ports as Ports import Brain.Reply exposing (Reply(..)) import Json.Encode as Json -import Replying exposing (R3D3) +import Return3 as Return exposing (..) import Tracks exposing (Track) @@ -31,25 +31,25 @@ type Msg | UpdateSearchIndex Json.Value -update : Msg -> Model -> R3D3 Model Msg Reply +update : Msg -> Model -> Return Model Msg Reply update msg model = case msg of Search term -> ( model , Ports.requestSearch term - , Nothing + , [] ) Searched results -> ( model , Cmd.none - , Just [ GiveUI Alien.SearchTracks <| Json.list Json.string results ] + , [ GiveUI Alien.SearchTracks (Json.list Json.string results) ] ) UpdateSearchIndex tracksJson -> ( model , Ports.updateSearchIndex tracksJson - , Nothing + , [] ) diff --git a/src/Applications/UI.elm b/src/Applications/UI.elm index 625e07a7..24f2249e 100644 --- a/src/Applications/UI.elm +++ b/src/Applications/UI.elm @@ -28,8 +28,8 @@ import Json.Encode import Maybe.Extra as Maybe import Notifications import Process -import Replying as N5 exposing (do, return) -import Return2 as R2 +import Return2 exposing (..) +import Return3 import Sources import Sources.Encoding import Tachyons.Classes as T @@ -37,7 +37,7 @@ import Task import Time import Tracks.Encoding import UI.Authentication as Authentication -import UI.Authentication.ContextMenu +import UI.Authentication.ContextMenu as Authentication import UI.Backdrop as Backdrop import UI.Console import UI.ContextMenu @@ -134,17 +134,17 @@ update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of Bypass -> - R2.withNoCmd model + return model LoadEnclosedUserData json -> model |> UserData.importEnclosed json - |> N5.reducto update translateReply + |> Return3.wield translateReply LoadHypaethralUserData json -> model |> UserData.importHypaethral json - |> N5.reducto update translateReply + |> Return3.wield translateReply SetCurrentTime time -> let @@ -159,170 +159,57 @@ update msg model = ) Core.ToggleLoadingScreen On -> - R2.withNoCmd { model | isLoading = True } + return { model | isLoading = True } Core.ToggleLoadingScreen Off -> - R2.withNoCmd { model | isLoading = False } + return { model | isLoading = False } ----------------------------------------- -- Audio ----------------------------------------- Pause -> - R2.withCmd (Ports.pause ()) model + returnWithModel model (Ports.pause ()) Play -> - R2.withCmd (Ports.play ()) model + returnWithModel model (Ports.play ()) Seek percentage -> - R2.withCmd (Ports.seek percentage) model + returnWithModel model (Ports.seek percentage) SetAudioDuration duration -> - R2.withNoCmd { model | audioDuration = duration } + return { model | audioDuration = duration } SetAudioHasStalled hasStalled -> - R2.withNoCmd { model | audioHasStalled = hasStalled } + return { model | audioHasStalled = hasStalled } SetAudioIsLoading isLoading -> - R2.withNoCmd { model | audioIsLoading = isLoading } + return { model | audioIsLoading = isLoading } SetAudioIsPlaying isPlayinh -> - R2.withNoCmd { model | audioIsPlaying = isPlayinh } + return { model | audioIsPlaying = isPlayinh } Unstall -> - R2.withCmd (Ports.unstall ()) model - - ----------------------------------------- - -- Authentication - ----------------------------------------- - Core.ExternalAuth (Authentication.RemoteStorage _) input -> - -- TODO: - -- 1. Make request to RemoteStorage.webfingerAddress - -- 2. If proper response -> Valid RemoteStorage - -- If not -> Not a RemoteStorage -> Show notification - -- 3. Extract oauth address from webfinger response - let - origin = - Common.urlOrigin model.url - in - input - |> Authentication.RemoteStorage.parseUserAddress - |> Maybe.map (Authentication.RemoteStorage.oauthAddress { origin = origin }) - |> Maybe.map Nav.load - |> Maybe.withDefault Cmd.none - |> Tuple.pair model - - Core.ExternalAuth _ _ -> - R2.withNoCmd model - - Core.ShowMoreAuthenticationOptions coordinates -> - coordinates - |> UI.Authentication.ContextMenu.moreOptionsMenu - |> Just - |> (\c -> { model | contextMenu = c }) - |> R2.withNoCmd + returnWithModel model (Ports.unstall ()) ----------------------------------------- -- Brain ----------------------------------------- - Core.ProcessSources -> - let - notification = - Notifications.warning "Processing sources …" - - notificationId = - Notifications.id notification - - sources = - model.sources - - newSources = - { sources | processingNotificationId = Just notificationId } - in - [ ( "origin" - , Json.Encode.string (Common.urlOrigin model.url) - ) - , ( "sources" - , Json.Encode.list Sources.Encoding.encode model.sources.collection - ) - , ( "tracks" - , Json.Encode.list Tracks.Encoding.encodeTrack model.tracks.collection.untouched - ) - ] - |> Json.Encode.object - |> Alien.broadcast Alien.ProcessSources - |> Ports.toBrain - |> R2.withModel { model | sources = newSources } - |> N5.andThen2 (update <| ShowNotification notification) - - Core.SaveEnclosedUserData -> - model - |> UserData.exportEnclosed - |> Alien.broadcast Alien.SaveEnclosedUserData - |> Ports.toBrain - |> R2.withModel model - - Core.SaveFavourites -> - model - |> UserData.encodedFavourites - |> Alien.broadcast Alien.SaveFavourites - |> Ports.toBrain - |> R2.withModel model - - Core.SaveSettings -> - model - |> UserData.gatherSettings - |> Authentication.encodeSettings - |> Alien.broadcast Alien.SaveSettings - |> Ports.toBrain - |> R2.withModel model - - Core.SaveSources -> - let - updateEnabledSourceIdsOnTracks = - model.sources.collection - |> Sources.enabledSourceIds - |> Tracks.SetEnabledSourceIds - |> TracksMsg - |> update - - ( updatedModel, updatedCmd ) = - updateEnabledSourceIdsOnTracks model - in - updatedModel - |> UserData.encodedSources - |> Alien.broadcast Alien.SaveSources - |> Ports.toBrain - |> R2.withModel updatedModel - |> R2.addCmd updatedCmd - - Core.SaveTracks -> - model - |> UserData.encodedTracks - |> Alien.broadcast Alien.SaveTracks - |> Ports.toBrain - |> R2.withModel model - - Core.SignOut -> - let - alienSigningOut = - Alien.SignOut - |> Alien.trigger - |> Ports.toBrain - in + SignOut -> { model | authentication = Authentication.initialModel model.url , sources = Sources.initialModel , tracks = Tracks.initialModel } |> update (BackdropMsg Backdrop.Default) - |> R2.addCmd alienSigningOut - |> R2.addCmd (Nav.pushUrl model.navKey "/") + |> addCommand (Ports.toBrain <| Alien.trigger Alien.SignOut) + |> addCommand (Nav.pushUrl model.navKey "/") ----------------------------------------- -- Children ----------------------------------------- AuthenticationMsg sub -> - updateChild + Return3.wieldNested + translateReply { mapCmd = AuthenticationMsg , mapModel = \child -> { model | authentication = child } , update = Authentication.update @@ -332,7 +219,8 @@ update msg model = } BackdropMsg sub -> - updateChild + Return3.wieldNested + translateReply { mapCmd = BackdropMsg , mapModel = \child -> { model | backdrop = child } , update = Backdrop.update @@ -342,7 +230,8 @@ update msg model = } EqualizerMsg sub -> - updateChild + Return3.wieldNested + translateReply { mapCmd = EqualizerMsg , mapModel = \child -> { model | equalizer = child } , update = Equalizer.update @@ -352,7 +241,8 @@ update msg model = } QueueMsg sub -> - updateChild + Return3.wieldNested + translateReply { mapCmd = QueueMsg , mapModel = \child -> { model | queue = child } , update = Queue.update @@ -362,7 +252,8 @@ update msg model = } SourcesMsg sub -> - updateChild + Return3.wieldNested + translateReply { mapCmd = SourcesMsg , mapModel = \child -> { model | sources = child } , update = Sources.update @@ -372,7 +263,8 @@ update msg model = } TracksMsg sub -> - updateChild + Return3.wieldNested + translateReply { mapCmd = TracksMsg , mapModel = \child -> { model | tracks = child } , update = Tracks.update @@ -381,76 +273,34 @@ update msg model = , msg = sub } - ----------------------------------------- - -- Children, Pt. 2 - ----------------------------------------- - Core.ActiveQueueItemChanged maybeQueueItem -> - let - nowPlaying = - Maybe.map .identifiedTrack maybeQueueItem - - portCmd = - maybeQueueItem - |> Maybe.map .identifiedTrack - |> Maybe.map - (UI.Queue.Common.makeEngineItem - model.currentTime - model.sources.collection - ) - |> Ports.activeQueueItemChanged - in - model - |> update (TracksMsg <| Tracks.SetNowPlaying nowPlaying) - |> R2.addCmd portCmd - - Core.FillQueue -> - update - (model.tracks.collection.harvested - |> Queue.Fill model.currentTime - |> QueueMsg - ) - model - ----------------------------------------- -- Context Menu ----------------------------------------- - Core.HideContextMenu -> - ( { model | contextMenu = Nothing } - , Cmd.none - ) - - Core.ShowTracksContextMenu coordinates tracks -> - ( { model | contextMenu = Just (Tracks.trackMenu tracks coordinates) } - , Cmd.none - ) + HideContextMenu -> + return { model | contextMenu = Nothing } ----------------------------------------- -- Import / Export ----------------------------------------- - Core.Export -> - ( model - , File.Download.string - "diffuse.json" - "application/json" - ({ favourites = model.tracks.favourites - , settings = Just (UserData.gatherSettings model) - , sources = model.sources.collection - , tracks = model.tracks.collection.untouched - } - |> Authentication.encodeHypaethral - |> Json.Encode.encode 2 - ) - ) + Export -> + { favourites = model.tracks.favourites + , settings = Just (UserData.gatherSettings model) + , sources = model.sources.collection + , tracks = model.tracks.collection.untouched + } + |> Authentication.encodeHypaethral + |> Json.Encode.encode 2 + |> File.Download.string "diffuse.json" "application/json" + |> returnWithModel model - Core.Import file -> - ( { model | isLoading = True } - , 250 + Import file -> + 250 |> Process.sleep |> Task.andThen (\_ -> File.toString file) |> Task.perform ImportJson - ) + |> returnWithModel { model | isLoading = True } - Core.ImportJson json -> + ImportJson json -> let notification = Notifications.success "Imported data successfully!" @@ -462,158 +312,266 @@ update msg model = |> Result.withDefault Json.Encode.null |> LoadHypaethralUserData ) - |> N5.andThen2 (update Core.SaveFavourites) - |> N5.andThen2 (update Core.SaveSources) - |> N5.andThen2 (update Core.SaveTracks) - |> N5.andThen2 (update <| ShowNotification notification) - |> R2.addCmd (do <| ChangeUrlUsingPage Page.Index) + |> andThen (translateReply SaveFavourites) + |> andThen (translateReply SaveSources) + |> andThen (translateReply SaveTracks) + |> andThen (update <| ShowNotification notification) + |> andThen (update <| ChangeUrlUsingPage Page.Index) - Core.InsertDemo -> - model - |> update (LoadHypaethralUserData UserData.demo) - |> N5.andThen2 (update Core.SaveFavourites) - |> N5.andThen2 (update Core.SaveSources) - |> N5.andThen2 (update Core.SaveTracks) - - Core.RequestImport -> - ( model - , File.Select.file [ "application/json" ] Import - ) + RequestImport -> + Import + |> File.Select.file [ "application/json" ] + |> returnWithModel model ----------------------------------------- -- Notifications ----------------------------------------- Core.DismissNotification args -> - UI.Notifications.dismissNotification model args + UI.Notifications.dismiss model args RemoveNotification { id } -> - ( { model - | notifications = - List.filter - (Notifications.id >> (/=) id) - model.notifications - } - , Cmd.none - ) + model.notifications + |> List.filter (Notifications.id >> (/=) id) + |> (\notifications -> { model | notifications = notifications }) + |> return ShowNotification notification -> - UI.Notifications.showNotification model notification + UI.Notifications.show notification model ----------------------------------------- -- URL ----------------------------------------- ChangeUrlUsingPage page -> - ( model - , Nav.pushUrl model.navKey (Page.toString page) - ) + page + |> Page.toString + |> Nav.pushUrl model.navKey + |> returnWithModel model - LinkClicked urlRequest -> - case urlRequest of - Browser.Internal url -> - if url.path == "/about" then - return model (Nav.load "/about") + LinkClicked (Browser.Internal url) -> + if url.path == "/about" then + returnWithModel model (Nav.load "/about") - else - return model (Nav.pushUrl model.navKey <| Url.toString url) + else + returnWithModel model (Nav.pushUrl model.navKey <| Url.toString url) - Browser.External href -> - return model (Nav.load href) + LinkClicked (Browser.External href) -> + returnWithModel model (Nav.load href) UrlChanged url -> case Page.fromUrl url of Just page -> - ( { model - | page = page - , url = url - } - , Cmd.none - ) + return { model | page = page, url = url } Nothing -> - ( model - , Nav.replaceUrl model.navKey "/" - ) + returnWithModel model (Nav.replaceUrl model.navKey "/") + + +updateWithModel : Model -> Msg -> ( Model, Cmd Msg ) +updateWithModel model msg = + update msg model -- 📣 ░░ CHILDREN & REPLIES -translateReply : Reply -> Msg -translateReply reply = +translateReply : Reply -> Model -> ( Model, Cmd Msg ) +translateReply reply model = case reply of - Reply.ActiveQueueItemChanged m -> - Core.ActiveQueueItemChanged m + ExternalAuth (Authentication.RemoteStorage _) input -> + -- TODO: + -- 1. Make request to RemoteStorage.webfingerAddress + -- 2. If proper response -> Valid RemoteStorage + -- If not -> Not a RemoteStorage -> Show notification + -- 3. Extract oauth address from webfinger response + let + origin = + Common.urlOrigin model.url + in + input + |> Authentication.RemoteStorage.parseUserAddress + |> Maybe.map (Authentication.RemoteStorage.oauthAddress { origin = origin }) + |> Maybe.map Nav.load + |> Maybe.withDefault Cmd.none + |> returnWithModel model - Reply.AddSourceToCollection source -> - SourcesMsg (Sources.AddToCollection source) + ExternalAuth _ _ -> + return model - Reply.DismissNotification opts -> - Core.DismissNotification opts + GoToPage page -> + page + |> ChangeUrlUsingPage + |> updateWithModel model - Reply.ExternalAuth a b -> - Core.ExternalAuth a b + Reply.ToggleLoadingScreen state -> + update (Core.ToggleLoadingScreen state) model - Reply.FillQueue -> - Core.FillQueue + ----------------------------------------- + -- Context Menu + ----------------------------------------- + ShowMoreAuthenticationOptions coordinates -> + return { model | contextMenu = Just (Authentication.moreOptionsMenu coordinates) } - Reply.GoToPage page -> - ChangeUrlUsingPage page + ShowTracksContextMenu coordinates tracks -> + return { model | contextMenu = Just (Tracks.trackMenu tracks coordinates) } - Reply.InsertDemo -> - Core.InsertDemo + ----------------------------------------- + -- Notifications + ----------------------------------------- + Reply.DismissNotification options -> + UI.Notifications.dismiss model options + + ShowErrorNotification string -> + UI.Notifications.show (Notifications.stickyError string) model + + ShowSuccessNotification string -> + UI.Notifications.show (Notifications.success string) model + + ShowWarningNotification string -> + UI.Notifications.show (Notifications.stickyWarning string) model + + ----------------------------------------- + -- Queue + ----------------------------------------- + ActiveQueueItemChanged maybeQueueItem -> + let + nowPlaying = + Maybe.map .identifiedTrack maybeQueueItem - Reply.PlayTrack identifiedTrack -> - QueueMsg (Queue.InjectFirstAndPlay identifiedTrack) + portCmd = + maybeQueueItem + |> Maybe.map .identifiedTrack + |> Maybe.map + (UI.Queue.Common.makeEngineItem + model.currentTime + model.sources.collection + ) + |> Ports.activeQueueItemChanged + in + model + |> update (TracksMsg <| Tracks.SetNowPlaying nowPlaying) + |> addCommand portCmd - Reply.ProcessSources -> - Core.ProcessSources + FillQueue -> + model.tracks.collection.harvested + |> Queue.Fill model.currentTime + |> QueueMsg + |> updateWithModel model - Reply.RemoveTracksWithSourceId sourceId -> - TracksMsg (Tracks.RemoveBySourceId sourceId) + PlayTrack identifiedTrack -> + identifiedTrack + |> Queue.InjectFirstAndPlay + |> QueueMsg + |> updateWithModel model - Reply.ResetQueue -> - QueueMsg Queue.Reset + ResetQueue -> + update (QueueMsg Queue.Reset) model - Reply.ShiftQueue -> - QueueMsg Queue.Shift + ShiftQueue -> + update (QueueMsg Queue.Shift) model - Reply.SaveEnclosedUserData -> - Core.SaveEnclosedUserData + ----------------------------------------- + -- Sources & Tracks + ----------------------------------------- + AddSourceToCollection source -> + source + |> Sources.AddToCollection + |> SourcesMsg + |> updateWithModel model - Reply.SaveFavourites -> - Core.SaveFavourites + ProcessSources -> + let + notification = + Notifications.warning "Processing sources …" - Reply.SaveSettings -> - Core.SaveSettings + notificationId = + Notifications.id notification - Reply.SaveSources -> - Core.SaveSources + sources = + model.sources - Reply.SaveTracks -> - Core.SaveTracks + newSources = + { sources | processingNotificationId = Just notificationId } + in + [ ( "origin" + , Json.Encode.string (Common.urlOrigin model.url) + ) + , ( "sources" + , Json.Encode.list Sources.Encoding.encode model.sources.collection + ) + , ( "tracks" + , Json.Encode.list Tracks.Encoding.encodeTrack model.tracks.collection.untouched + ) + ] + |> Json.Encode.object + |> Alien.broadcast Alien.ProcessSources + |> Ports.toBrain + |> returnWithModel { model | sources = newSources } + |> andThen (UI.Notifications.show notification) - Reply.ShowErrorNotification string -> - ShowNotification (Notifications.stickyError string) + RemoveTracksWithSourceId sourceId -> + sourceId + |> Tracks.RemoveBySourceId + |> TracksMsg + |> updateWithModel model - Reply.ShowMoreAuthenticationOptions coordinates -> - Core.ShowMoreAuthenticationOptions coordinates + ----------------------------------------- + -- User Data + ----------------------------------------- + InsertDemo -> + model + |> update (LoadHypaethralUserData UserData.demo) + |> andThen (translateReply SaveFavourites) + |> andThen (translateReply SaveSources) + |> andThen (translateReply SaveTracks) - Reply.ShowSuccessNotification string -> - ShowNotification (Notifications.success string) + SaveEnclosedUserData -> + model + |> UserData.exportEnclosed + |> Alien.broadcast Alien.SaveEnclosedUserData + |> Ports.toBrain + |> returnWithModel model - Reply.ShowWarningNotification string -> - ShowNotification (Notifications.stickyWarning string) + SaveFavourites -> + model + |> UserData.encodedFavourites + |> Alien.broadcast Alien.SaveFavourites + |> Ports.toBrain + |> returnWithModel model - Reply.ShowTracksContextMenu coordinates tracks -> - Core.ShowTracksContextMenu coordinates tracks + SaveSettings -> + model + |> UserData.gatherSettings + |> Authentication.encodeSettings + |> Alien.broadcast Alien.SaveSettings + |> Ports.toBrain + |> returnWithModel model - Reply.ToggleLoadingScreen state -> - Core.ToggleLoadingScreen state + SaveSources -> + let + updateEnabledSourceIdsOnTracks = + model.sources.collection + |> Sources.enabledSourceIds + |> Tracks.SetEnabledSourceIds + |> TracksMsg + |> update + ( updatedModel, updatedCmd ) = + updateEnabledSourceIdsOnTracks model + in + updatedModel + |> UserData.encodedSources + |> Alien.broadcast Alien.SaveSources + |> Ports.toBrain + |> returnWithModel updatedModel + |> addCommand updatedCmd -updateChild = - N5.updateChild update translateReply + SaveTracks -> + model + |> UserData.encodedTracks + |> Alien.broadcast Alien.SaveTracks + |> Ports.toBrain + |> returnWithModel model diff --git a/src/Applications/UI/Authentication.elm b/src/Applications/UI/Authentication.elm index 4b501ecf..85838014 100644 --- a/src/Applications/UI/Authentication.elm +++ b/src/Applications/UI/Authentication.elm @@ -20,9 +20,7 @@ import Json.Decode as Json import Json.Encode import Material.Icons.Av as Icons import Material.Icons.Navigation as Icons -import Replying exposing (R3D3, andThen3) -import Return2 as R2 -import Return3 as R3 +import Return3 as Return exposing (..) import Svg exposing (Svg) import Tachyons.Classes as T import UI.Kit @@ -128,28 +126,28 @@ type Msg | ConfirmInput -update : Msg -> Model -> R3D3 Model Msg Reply +update : Msg -> Model -> Return Model Msg Reply update msg model = case msg of Bypass -> - R3.withNothing model + return model Cancel -> case model of Authenticated method -> - R3.withNothing (Authenticated method) + return (Authenticated method) InputScreen _ _ -> - R3.withNothing Unauthenticated + return Unauthenticated NewEncryptionKeyScreen _ _ -> - R3.withNothing Unauthenticated + return Unauthenticated UpdateEncryptionKeyScreen method _ -> - R3.withNothing (Authenticated method) + return (Authenticated method) Unauthenticated -> - R3.withNothing Unauthenticated + return Unauthenticated ShowMoreOptions mouseEvent -> ( model @@ -164,7 +162,6 @@ update msg model = ) |> ShowMoreAuthenticationOptions |> List.singleton - |> Just ) SignIn method -> @@ -177,15 +174,14 @@ update msg model = |> Alien.broadcast Alien.SignIn |> Ports.toBrain -- - , Just [ ToggleLoadingScreen On ] + , [ ToggleLoadingScreen On ] ) SignInWithPassphrase method passphrase -> if String.length passphrase < minimumPassphraseLength then - ( model - , Cmd.none - , Just [ ShowErrorNotification passphraseLengthErrorMessage ] - ) + addReply + (ShowErrorNotification passphraseLengthErrorMessage) + (return model) else ( Unauthenticated @@ -197,11 +193,11 @@ update msg model = |> Alien.broadcast Alien.SignIn |> Ports.toBrain -- - , Just [ ToggleLoadingScreen On ] + , [ ToggleLoadingScreen On ] ) SignedIn method -> - R3.withNothing (Authenticated method) + return (Authenticated method) ----------------------------------------- -- Encryption @@ -209,36 +205,35 @@ update msg model = KeepPassphraseInMemory passphrase -> case model of NewEncryptionKeyScreen method _ -> - R3.withNothing (NewEncryptionKeyScreen method <| Just passphrase) + return (NewEncryptionKeyScreen method <| Just passphrase) UpdateEncryptionKeyScreen method _ -> - R3.withNothing (UpdateEncryptionKeyScreen method <| Just passphrase) + return (UpdateEncryptionKeyScreen method <| Just passphrase) _ -> - R3.withNothing model + return model ShowNewEncryptionKeyScreen method -> - R3.withNothing (NewEncryptionKeyScreen method Nothing) + return (NewEncryptionKeyScreen method Nothing) ShowUpdateEncryptionKeyScreen method -> - R3.withNothing (UpdateEncryptionKeyScreen method Nothing) + return (UpdateEncryptionKeyScreen method Nothing) UpdateEncryptionKey method passphrase -> if String.length passphrase < minimumPassphraseLength then - ( model - , Cmd.none - , Just [ ShowErrorNotification passphraseLengthErrorMessage ] - ) + addReply + (ShowErrorNotification passphraseLengthErrorMessage) + (return model) else - ( Authenticated method - , passphrase - |> Crypto.Hash.sha256 - |> Json.Encode.string - |> Alien.broadcast Alien.UpdateEncryptionKey - |> Ports.toBrain - , Nothing - ) + returnCommandWithModel + (Authenticated method) + (passphrase + |> Crypto.Hash.sha256 + |> Json.Encode.string + |> Alien.broadcast Alien.UpdateEncryptionKey + |> Ports.toBrain + ) ----------------------------------------- -- More Input @@ -249,26 +244,25 @@ update msg model = , question = opts.question } |> InputScreen method - |> R3.withNothing + |> return Input string -> case model of InputScreen method opts -> - R3.withNothing (InputScreen method { opts | input = string }) + return (InputScreen method { opts | input = string }) m -> - R3.withNothing m + return m ConfirmInput -> case model of InputScreen method { input } -> - ( model - , Cmd.none - , Just [ ExternalAuth method input ] - ) + addReply + (ExternalAuth method input) + (return model) _ -> - R3.withNothing model + return model diff --git a/src/Applications/UI/Backdrop.elm b/src/Applications/UI/Backdrop.elm index c5f344b9..54f84f11 100644 --- a/src/Applications/UI/Backdrop.elm +++ b/src/Applications/UI/Backdrop.elm @@ -8,9 +8,7 @@ import Html.Styled.Attributes exposing (class, css, src, style) import Html.Styled.Events exposing (on) import Html.Styled.Lazy as Lazy import Json.Decode -import Replying exposing (R3D3) -import Return2 as R2 -import Return3 as R3 +import Return3 as Return exposing (..) import Tachyons.Classes as T import UI.Animations import UI.Reply as Reply exposing (Reply) @@ -71,23 +69,17 @@ type Msg | Load String -update : Msg -> Model -> R3D3 Model Msg Reply +update : Msg -> Model -> Return Model Msg Reply update msg model = case msg of Choose backdrop -> - { model | chosen = Just backdrop } - |> R2.withNoCmd - |> R3.withReply [ Reply.SaveSettings ] + return { model | chosen = Just backdrop } |> addReply Reply.SaveSettings Default -> - { model | chosen = Just default } - |> R3.withNothing + return { model | chosen = Just default } Load backdrop -> - [ backdrop ] - |> List.append model.loaded - |> (\list -> { model | loaded = list }) - |> R3.withNothing + return { model | loaded = model.loaded ++ [ backdrop ] } diff --git a/src/Applications/UI/Core.elm b/src/Applications/UI/Core.elm index fdb50f8d..05f96e7c 100644 --- a/src/Applications/UI/Core.elm +++ b/src/Applications/UI/Core.elm @@ -94,20 +94,9 @@ type Msg | SetAudioIsLoading Bool | SetAudioIsPlaying Bool | Unstall - ----------------------------------------- - -- Authentication - ----------------------------------------- - | ExternalAuth Authentication.Method String - | ShowMoreAuthenticationOptions Coordinates ----------------------------------------- -- Brain ----------------------------------------- - | ProcessSources - | SaveEnclosedUserData - | SaveFavourites - | SaveSettings - | SaveSources - | SaveTracks | SignOut ----------------------------------------- -- Children @@ -118,23 +107,16 @@ type Msg | QueueMsg Queue.Msg | SourcesMsg Sources.Msg | TracksMsg Tracks.Msg - ----------------------------------------- - -- Children, Pt. 2 - ----------------------------------------- - | ActiveQueueItemChanged (Maybe Queue.Item) - | FillQueue ----------------------------------------- -- Context Menu ----------------------------------------- | HideContextMenu - | ShowTracksContextMenu Coordinates (List IdentifiedTrack) ----------------------------------------- -- Import / Export ----------------------------------------- | Export | Import File | ImportJson String - | InsertDemo | RequestImport ----------------------------------------- -- Notifications diff --git a/src/Applications/UI/Equalizer.elm b/src/Applications/UI/Equalizer.elm index f325278c..90e19d37 100644 --- a/src/Applications/UI/Equalizer.elm +++ b/src/Applications/UI/Equalizer.elm @@ -11,7 +11,7 @@ import Html.Styled exposing (Html, text) import Html.Styled.Attributes exposing (css, style) import Html.Styled.Events import Material.Icons.Navigation as Icons -import Replying exposing (R3D3) +import Return3 as Return exposing (..) import Svg.Styled exposing (Svg, polygon, svg) import Svg.Styled.Attributes import Tachyons.Classes as T @@ -70,21 +70,18 @@ type Msg | ResetKnob Knob -update : Msg -> Model -> R3D3 Model Msg Reply +update : Msg -> Model -> Return Model Msg Reply update msg model = case msg of ----------------------------------------- -- Activate ----------------------------------------- ActivateKnob theKnob { pointer } -> - let - ( x, y ) = - pointer.clientPos - in - ( { model | activeKnob = Just theKnob, startCoordinates = { x = x, y = y } } - , Cmd.none - , Nothing - ) + { model + | activeKnob = Just theKnob + , startCoordinates = Coordinates.fromTuple pointer.clientPos + } + |> return ----------------------------------------- -- Adjust @@ -143,25 +140,18 @@ update msg model = in case value of Just ( knobType, v ) -> - ( newModel - , adjustKnob knobType v - , Nothing - ) + returnCommandWithModel newModel (adjustKnob knobType v) Nothing -> - ( newModel - , Cmd.none - , Nothing - ) + return newModel ----------------------------------------- -- Deactivate ----------------------------------------- DeactivateKnob _ -> - ( { model | activeKnob = Nothing } - , Cmd.none - , Just [ UI.Reply.SaveEnclosedUserData ] - ) + Return.replyWithModel + { model | activeKnob = Nothing } + UI.Reply.SaveEnclosedUserData ----------------------------------------- -- Reset @@ -213,11 +203,11 @@ adjustAllKnobs model = ] -reset : Model -> Knob -> Float -> R3D3 Model Msg Reply +reset : Model -> Knob -> Float -> Return Model Msg Reply reset newModel knobType value = ( newModel , adjustKnob knobType value - , Just [ UI.Reply.SaveEnclosedUserData ] + , [ UI.Reply.SaveEnclosedUserData ] ) diff --git a/src/Applications/UI/Notifications.elm b/src/Applications/UI/Notifications.elm index 11ac7e18..7fe79087 100644 --- a/src/Applications/UI/Notifications.elm +++ b/src/Applications/UI/Notifications.elm @@ -1,4 +1,4 @@ -module UI.Notifications exposing (dismissNotification, showNotification, view) +module UI.Notifications exposing (dismiss, show, showWithModel, view) import Chunky exposing (..) import Color.Ext as Color @@ -21,8 +21,8 @@ import UI.Kit -- 📣 -dismissNotification : Model -> { id : Int } -> ( Model, Cmd Msg ) -dismissNotification model { id } = +dismiss : Model -> { id : Int } -> ( Model, Cmd Msg ) +dismiss model { id } = ( { model | notifications = List.map @@ -41,8 +41,8 @@ dismissNotification model { id } = ) -showNotification : Model -> Notification Msg -> ( Model, Cmd Msg ) -showNotification model notification = +show : Notification Msg -> Model -> ( Model, Cmd Msg ) +show notification model = ( { model | notifications = notification :: model.notifications } -- Hide notification after a certain amount of time, -- unless it's a sticky notification. @@ -56,6 +56,11 @@ showNotification model notification = ) +showWithModel : Model -> Notification Msg -> ( Model, Cmd Msg ) +showWithModel model notification = + show notification model + + -- 🗺 diff --git a/src/Applications/UI/Queue.elm b/src/Applications/UI/Queue.elm index 4e7493b7..65df7ae1 100644 --- a/src/Applications/UI/Queue.elm +++ b/src/Applications/UI/Queue.elm @@ -1,9 +1,9 @@ module UI.Queue exposing (initialModel, update) +import Conditional exposing (..) import List.Extra as List import Queue exposing (..) -import Replying exposing (R3D3) -import Return3 as R3 +import Return3 as Return exposing (..) import Time import Tracks exposing (IdentifiedTrack) import UI.Ports as Ports @@ -34,21 +34,17 @@ initialModel = -- 📣 -update : Msg -> Model -> R3D3 Model Msg Reply +update : Msg -> Model -> Return Model Msg Reply update msg model = case msg of ------------------------------------ -- Combos ------------------------------------ InjectFirstAndPlay identifiedTrack -> - let - ( a, b, _ ) = - update (InjectFirst { showNotification = False } [ identifiedTrack ]) model - - ( x, y, z ) = - update Shift a - in - ( x, Cmd.batch [ b, y ], z ) + [ identifiedTrack ] + |> InjectFirst { showNotification = False } + |> updateWithModel model + |> andThen (update Shift) ------------------------------------ -- Future @@ -71,29 +67,21 @@ update msg model = model.future tracks in - ( { model | future = items ++ cleanedFuture } - , Cmd.none - -- Show notification - -------------------- - , (if showNotification then - [ case tracks of - [ t ] -> - ShowSuccessNotification ("__" ++ t.tags.title ++ "__ will be played next") - - list -> - list - |> List.length - |> String.fromInt - |> (\s -> "__" ++ s ++ " tracks__ will be played next") - |> ShowSuccessNotification - ] - - else - [] - ) - |> List.append [ FillQueue ] - |> Just - ) + [ case tracks of + [ t ] -> + ("__" ++ t.tags.title ++ "__ will be played next") + |> ShowSuccessNotification + + list -> + list + |> List.length + |> String.fromInt + |> (\s -> "__" ++ s ++ " tracks__ will be played next") + |> ShowSuccessNotification + ] + |> (\list -> ifThenElse showNotification list []) + |> returnRepliesWithModel { model | future = items ++ cleanedFuture } + |> addReply FillQueue -- # InjectLast -- > Add an item after the last manual entry @@ -118,36 +106,28 @@ update msg model = cleanedFuture |> List.filter (.manualEntry >> (==) True) |> List.length - in - ( { model - | future = + + newFuture = [] ++ List.take manualItems cleanedFuture ++ items ++ List.drop manualItems cleanedFuture - } - , Cmd.none - -- Show notification - -------------------- - , (if showNotification then - [ case tracks of - [ t ] -> - ShowSuccessNotification ("__" ++ t.tags.title ++ "__ was added to the queue") - - list -> - list - |> List.length - |> String.fromInt - |> (\s -> "__" ++ s ++ " tracks__ were added to the queue") - |> ShowSuccessNotification - ] - - else - [] - ) - |> List.append [ FillQueue ] - |> Just - ) + in + [ case tracks of + [ t ] -> + ("__" ++ t.tags.title ++ "__ was added to the queue") + |> ShowSuccessNotification + + list -> + list + |> List.length + |> String.fromInt + |> (\s -> "__" ++ s ++ " tracks__ were added to the queue") + |> ShowSuccessNotification + ] + |> (\list -> ifThenElse showNotification list []) + |> returnRepliesWithModel { model | future = newFuture } + |> addReply FillQueue ----------------------------------------- -- Position @@ -193,7 +173,7 @@ update msg model = -- > Fill the queue with items. -- Fill timestamp tracks -> - ( fillQueue timestamp tracks model, Cmd.none, Nothing ) + return (fillQueue timestamp tracks model) -- # Reset -- > Renew the queue, meaning that the auto-generated items in the queue @@ -204,10 +184,9 @@ update msg model = newFuture = List.filter (.manualEntry >> (==) True) model.future in - ( { model | future = newFuture, ignored = [] } - , Cmd.none - , Just [ FillQueue ] - ) + returnRepliesWithModel + { model | future = newFuture, ignored = [] } + [ FillQueue ] ------------------------------------ -- Settings @@ -215,25 +194,31 @@ update msg model = ToggleRepeat -> ( { model | repeat = not model.repeat } , Ports.setRepeat (not model.repeat) - , Just [ SaveEnclosedUserData ] + , [ SaveEnclosedUserData ] ) ToggleShuffle -> { model | shuffle = not model.shuffle } |> update Reset - |> Replying.addReply SaveEnclosedUserData + |> addReply SaveEnclosedUserData + + +updateWithModel : Model -> Msg -> Return Model Msg Reply +updateWithModel model msg = + update msg model -- 📣 ░░ COMMON -changeActiveItem : Maybe Item -> Model -> R3D3 Model Msg Reply +changeActiveItem : Maybe Item -> Model -> Return Model Msg Reply changeActiveItem maybeItem model = - ( { model | activeItem = maybeItem } - , Cmd.none - , Just [ ActiveQueueItemChanged maybeItem, FillQueue ] - ) + returnRepliesWithModel + { model | activeItem = maybeItem } + [ ActiveQueueItemChanged maybeItem + , FillQueue + ] fillQueue : Time.Posix -> List IdentifiedTrack -> Model -> Model diff --git a/src/Applications/UI/Reply.elm b/src/Applications/UI/Reply.elm index e8d107a3..49c0aeaa 100644 --- a/src/Applications/UI/Reply.elm +++ b/src/Applications/UI/Reply.elm @@ -17,26 +17,41 @@ import UI.Page exposing (Page) type Reply - = ActiveQueueItemChanged (Maybe Queue.Item) - | AddSourceToCollection Source + = ExternalAuth Authentication.Method String + | GoToPage Page + | ToggleLoadingScreen Switch + ----------------------------------------- + -- Context Menu + ----------------------------------------- + | ShowMoreAuthenticationOptions Coordinates + | ShowTracksContextMenu Coordinates (List IdentifiedTrack) + ----------------------------------------- + -- Notifications + ----------------------------------------- | DismissNotification { id : Int } - | ExternalAuth Authentication.Method String + | ShowErrorNotification String + | ShowSuccessNotification String + | ShowWarningNotification String + ----------------------------------------- + -- Queue + ----------------------------------------- + | ActiveQueueItemChanged (Maybe Queue.Item) | FillQueue - | GoToPage Page - | InsertDemo | PlayTrack IdentifiedTrack - | ProcessSources - | RemoveTracksWithSourceId String | ResetQueue | ShiftQueue + ----------------------------------------- + -- Sources & Tracks + ----------------------------------------- + | AddSourceToCollection Source + | ProcessSources + | RemoveTracksWithSourceId String + ----------------------------------------- + -- User Data + ----------------------------------------- + | InsertDemo | SaveEnclosedUserData | SaveFavourites | SaveSettings | SaveSources | SaveTracks - | ShowErrorNotification String - | ShowMoreAuthenticationOptions Coordinates - | ShowSuccessNotification String - | ShowWarningNotification String - | ShowTracksContextMenu Coordinates (List IdentifiedTrack) - | ToggleLoadingScreen Switch diff --git a/src/Applications/UI/Sources.elm b/src/Applications/UI/Sources.elm index dc52ee1e..cc20f083 100644 --- a/src/Applications/UI/Sources.elm +++ b/src/Applications/UI/Sources.elm @@ -9,9 +9,7 @@ import Material.Icons.Content as Icons import Material.Icons.Navigation as Icons import Material.Icons.Notification as Icons import Notifications exposing (Notification) -import Replying exposing (R3D3, return) -import Return2 -import Return3 +import Return3 as Return exposing (..) import Sources exposing (..) import Sources.Encoding import Sources.Services as Services @@ -21,7 +19,7 @@ import UI.Kit exposing (ButtonType(..), select) import UI.List import UI.Navigation exposing (..) import UI.Page -import UI.Reply exposing (Reply) +import UI.Reply exposing (Reply(..)) import UI.Sources.Form as Form import UI.Sources.Page as Sources exposing (..) @@ -69,29 +67,24 @@ type Msg | UpdateSourceData Json.Value -update : Msg -> Model -> R3D3 Model Msg Reply +update : Msg -> Model -> Return Model Msg Reply update msg model = case msg of Bypass -> - Return3.withNothing model + return model FinishedProcessing -> - ( { model | isProcessing = False } - , Cmd.none - , Maybe.map - (\id -> [ UI.Reply.DismissNotification { id = id } ]) - model.processingNotificationId - ) + model.processingNotificationId + |> Maybe.map (\id -> [ DismissNotification { id = id } ]) + |> Maybe.withDefault [] + |> Return.repliesWithModel { model | isProcessing = False } Process -> if List.isEmpty model.collection then - Return3.withNothing model + return model else - ( { model | isProcessing = True } - , Cmd.none - , Just [ UI.Reply.ProcessSources ] - ) + returnReplyWithModel { model | isProcessing = True } ProcessSources ----------------------------------------- -- Children @@ -99,8 +92,8 @@ update msg model = FormMsg sub -> model.form |> Form.update sub - |> Return3.mapModel (\f -> { model | form = f }) - |> Return3.mapCmd FormMsg + |> mapModel (\f -> { model | form = f }) + |> mapCmd FormMsg ----------------------------------------- -- Collection @@ -111,8 +104,8 @@ update msg model = |> List.singleton |> List.append model.collection |> (\c -> { model | collection = c, isProcessing = True }) - |> Return2.withNoCmd - |> Return3.withReply + |> return + |> addReplies [ UI.Reply.SaveSources , UI.Reply.ProcessSources ] @@ -121,8 +114,8 @@ update msg model = model.collection |> List.filter (.id >> (/=) sourceId) |> (\c -> { model | collection = c }) - |> Return2.withNoCmd - |> Return3.withReply + |> return + |> addReplies [ UI.Reply.SaveSources , UI.Reply.RemoveTracksWithSourceId sourceId ] @@ -144,8 +137,8 @@ update msg model = ) |> Maybe.map (\col -> { model | collection = col }) |> Maybe.withDefault model - |> Return2.withNoCmd - |> Return3.withReply [ UI.Reply.SaveSources ] + |> return + |> addReply UI.Reply.SaveSources @@ -176,7 +169,7 @@ index model = UI.Navigation.local [ ( Icon Icons.add , Label "Add a new source" Shown - , GoToPage (UI.Page.Sources New) + , UI.Navigation.GoToPage (UI.Page.Sources New) ) -- Process diff --git a/src/Applications/UI/Sources/Form.elm b/src/Applications/UI/Sources/Form.elm index 5d436195..0c2361ef 100644 --- a/src/Applications/UI/Sources/Form.elm +++ b/src/Applications/UI/Sources/Form.elm @@ -11,7 +11,7 @@ import Html.Styled.Events exposing (onInput, onSubmit) import List.Extra as List import Material.Icons.Alert as Icons import Material.Icons.Navigation as Icons -import Replying exposing (R3D3) +import Return3 as Return exposing (..) import Sources exposing (..) import Sources.Services as Services import Sources.Services.Common @@ -71,7 +71,7 @@ type Msg | TakeStepBackwards -update : Msg -> Model -> R3D3 Model Msg Reply +update : Msg -> Model -> Return Model Msg Reply update msg model = ( ----------------------------------------- -- Model @@ -124,13 +124,12 @@ update msg model = ----------------------------------------- , case msg of AddSource -> - Just - [ UI.Reply.GoToPage (UI.Page.Sources UI.Sources.Page.Index) - , UI.Reply.AddSourceToCollection model.context - ] + [ UI.Reply.GoToPage (UI.Page.Sources UI.Sources.Page.Index) + , UI.Reply.AddSourceToCollection model.context + ] _ -> - Nothing + [] ) diff --git a/src/Applications/UI/Tracks.elm b/src/Applications/UI/Tracks.elm index f618ad8b..8594aa33 100644 --- a/src/Applications/UI/Tracks.elm +++ b/src/Applications/UI/Tracks.elm @@ -5,6 +5,7 @@ import Chunky exposing (..) import Color import Color.Ext as Color import Common exposing (Switch(..)) +import Coordinates import Css import Html.Styled as Html exposing (Html, text) import Html.Styled.Attributes exposing (css, placeholder, tabindex, title, value) @@ -21,9 +22,7 @@ import Material.Icons.Content as Icons import Material.Icons.Editor as Icons import Material.Icons.Image as Icons import Maybe.Extra as Maybe -import Replying as N5 exposing (R3D3) -import Return2 as R2 -import Return3 as R3 +import Return3 as Return exposing (..) import Tachyons.Classes as T import Tracks exposing (..) import Tracks.Collection as Collection exposing (..) @@ -64,33 +63,22 @@ initialModel = -- 📣 -update : Msg -> Model -> R3D3 Model Msg Reply +update : Msg -> Model -> Return Model Msg Reply update msg model = case msg of Bypass -> - R3.withNothing model + return model InfiniteListMsg infiniteList -> - R3.withNothing { model | infiniteList = infiniteList } + return { model | infiniteList = infiniteList } Reply replies -> - ( model - , Cmd.none - , Just replies - ) + returnRepliesWithModel model replies ShowContextMenu track mouseEvent -> - let - ( x, y ) = - mouseEvent.clientPos - - tracks = - [ track ] - in - ( model - , Cmd.none - , Just [ ShowTracksContextMenu { x = x, y = y } tracks ] - ) + [ track ] + |> ShowTracksContextMenu (Coordinates.fromTuple mouseEvent.clientPos) + |> returnReplyWithModel model ScrollToNowPlaying -> let @@ -112,14 +100,13 @@ update msg model = List -> identifiedTrack |> UI.Tracks.Scene.List.scrollToNowPlaying - |> R2.withModel model - |> R3.withNoReply + |> Return.commandWithModel model Nothing -> - R3.withNothing model + return model SetEnabledSourceIds sourceIds -> - R3.withNothing { model | enabledSourceIds = sourceIds } + return { model | enabledSourceIds = sourceIds } SetNowPlaying maybeIdentifiedTrack -> let @@ -149,12 +136,12 @@ update msg model = in { model | sortBy = property, sortDirection = sortDir } |> reviseCollection arrange - |> N5.addReply SaveEnclosedUserData + |> addReply SaveEnclosedUserData ToggleHideDuplicates -> { model | hideDuplicates = not model.hideDuplicates } |> reviseCollection arrange - |> N5.addReply SaveSettings + |> addReply SaveSettings ----------------------------------------- -- Collection @@ -204,13 +191,13 @@ update msg model = model.collection.harvested |> List.getAt index |> Maybe.map (toggleFavourite model) - |> Maybe.withDefault (R3.withNothing model) + |> Maybe.withDefault (return model) -- > Filter collection by favourites only {toggle} ToggleFavouritesOnly -> { model | favouritesOnly = not model.favouritesOnly } |> reviseCollection harvest - |> N5.addReply SaveEnclosedUserData + |> addReply SaveEnclosedUserData ----------------------------------------- -- Search @@ -218,21 +205,22 @@ update msg model = ClearSearch -> { model | searchResults = Nothing, searchTerm = Nothing } |> reviseCollection harvest - |> N5.addReply SaveEnclosedUserData + |> addReply SaveEnclosedUserData Search -> case ( model.searchTerm, model.searchResults ) of ( Just term, _ ) -> - ( model - , UI.Ports.giveBrain Alien.SearchTracks (Json.Encode.string <| String.trim term) - , Nothing - ) + term + |> String.trim + |> Json.Encode.string + |> UI.Ports.giveBrain Alien.SearchTracks + |> Return.commandWithModel model ( Nothing, Just _ ) -> reviseCollection harvest { model | searchResults = Nothing } ( Nothing, Nothing ) -> - R3.withNothing model + return model SetSearchResults json -> case model.searchTerm of @@ -242,20 +230,20 @@ update msg model = |> Result.withDefault [] |> (\results -> { model | searchResults = Just results }) |> reviseCollection harvest - |> N5.addReply (ToggleLoadingScreen Off) + |> addReply (ToggleLoadingScreen Off) Nothing -> - R3.withNothing model + return model SetSearchTerm term -> - R3.withReply + addReplies [ SaveEnclosedUserData ] (case String.trim term of "" -> - R2.withNoCmd { model | searchTerm = Nothing } + return { model | searchTerm = Nothing } _ -> - R2.withNoCmd { model | searchTerm = Just term } + return { model | searchTerm = Just term } ) @@ -278,7 +266,7 @@ makeParcel model = ) -resolveParcel : Model -> Parcel -> R3D3 Model Msg Reply +resolveParcel : Model -> Parcel -> Return Model Msg Reply resolveParcel model ( _, newCollection ) = let modelWithNewCollection = @@ -291,6 +279,7 @@ resolveParcel model ( _, newCollection ) = List.map (Tuple.second >> .id) newCollection.harvested in ( modelWithNewCollection + ---------- -- Command ---------- , if oldHarvest /= newHarvest then @@ -300,9 +289,10 @@ resolveParcel model ( _, newCollection ) = else Cmd.none + -------- -- Reply -------- - , (Just << Maybe.values) + , Maybe.values [ if model.collection.untouched /= newCollection.untouched then Just SaveTracks @@ -319,7 +309,7 @@ resolveParcel model ( _, newCollection ) = ) -reviseCollection : (Parcel -> Parcel) -> Model -> R3D3 Model Msg Reply +reviseCollection : (Parcel -> Parcel) -> Model -> Return Model Msg Reply reviseCollection collector model = model |> makeParcel @@ -331,7 +321,7 @@ reviseCollection collector model = -- 📣 ░░ FAVOURITES -toggleFavourite : Model -> IdentifiedTrack -> R3D3 Model Msg Reply +toggleFavourite : Model -> IdentifiedTrack -> Return Model Msg Reply toggleFavourite model ( i, t ) = let newFavourites = @@ -346,7 +336,7 @@ toggleFavourite model ( i, t ) = in { model | favourites = newFavourites } |> reviseCollection effect - |> N5.addReply SaveFavourites + |> addReply SaveFavourites diff --git a/src/Applications/UI/UserData.elm b/src/Applications/UI/UserData.elm index bf3445aa..0ba3e7eb 100644 --- a/src/Applications/UI/UserData.elm +++ b/src/Applications/UI/UserData.elm @@ -8,8 +8,7 @@ import Json.Decode.Pipeline exposing (..) import Json.Encode import Maybe.Extra as Maybe import Notifications -import Replying as N5 exposing (R3D3) -import Return3 as R3 +import Return3 exposing (..) import Sources import Sources.Encoding as Sources import Tracks exposing (emptyCollection) @@ -52,7 +51,7 @@ gatherSettings { backdrop, tracks } = } -importHypaethral : Json.Value -> UI.Core.Model -> R3D3 UI.Core.Model UI.Core.Msg UI.Reply +importHypaethral : Json.Value -> UI.Core.Model -> Return UI.Core.Model UI.Core.Msg UI.Reply importHypaethral value model = case decodeHypaethral value of Ok data -> @@ -67,10 +66,10 @@ importHypaethral value model = |> Just |> (\c -> { backdrop | chosen = c }) - ( sourcesModel, sourcesCmd, sourcesReply ) = + ( sourcesModel, sourcesCmd, sourcesReplies ) = importSources model.sources data - ( tracksModel, tracksCmd, tracksReply ) = + ( tracksModel, tracksCmd, tracksReplies ) = importTracks model.tracks data in ( { model @@ -82,35 +81,27 @@ importHypaethral value model = [ Cmd.map UI.Core.SourcesMsg sourcesCmd , Cmd.map UI.Core.TracksMsg tracksCmd ] - , mergeReplies - [ sourcesReply - , tracksReply - ] + , sourcesReplies ++ tracksReplies ) Err err -> err |> Json.errorToString |> Notifications.error - |> UI.Notifications.showNotification model - |> R3.withNoReply + |> UI.Notifications.showWithModel model + |> Return3.from2 -- ㊙️ -importSources : Sources.Model -> HypaethralUserData -> R3D3 Sources.Model Sources.Msg UI.Reply +importSources : Sources.Model -> HypaethralUserData -> Return Sources.Model Sources.Msg UI.Reply importSources model data = - ( { model - | collection = data.sources - } - , Cmd.none - , Nothing - ) + return { model | collection = data.sources } -importTracks : Tracks.Model -> HypaethralUserData -> R3D3 Tracks.Model Tracks.Msg UI.Reply +importTracks : Tracks.Model -> HypaethralUserData -> Return Tracks.Model Tracks.Msg UI.Reply importTracks model data = let adjustedModel = @@ -127,13 +118,13 @@ importTracks model data = identity Nothing -> - N5.addReply (UI.ToggleLoadingScreen Off) + addReply (UI.ToggleLoadingScreen Off) in adjustedModel |> Tracks.makeParcel |> Tracks.identify |> Tracks.resolveParcel adjustedModel - |> N5.andThen3 (Tracks.update Tracks.Search) + |> andThen (Tracks.update Tracks.Search) |> addReplyIfNecessary @@ -162,7 +153,7 @@ exportEnclosed model = } -importEnclosed : Json.Value -> UI.Core.Model -> R3D3 UI.Core.Model UI.Core.Msg UI.Reply +importEnclosed : Json.Value -> UI.Core.Model -> Return UI.Core.Model UI.Core.Msg UI.Reply importEnclosed value model = let { equalizer, queue, tracks } = @@ -202,31 +193,11 @@ importEnclosed value model = [ Cmd.map UI.Core.EqualizerMsg (Equalizer.adjustAllKnobs newEqualizer) , Ports.setRepeat data.repeat ] - , Nothing + , [] ) Err err -> - R3.withNothing model - - - --- ㊙️ - - -mergeReplies : List (Maybe (List UI.Reply)) -> Maybe (List UI.Reply) -mergeReplies list = - list - |> List.foldl - (\maybeReply replies -> - case maybeReply of - Just r -> - replies ++ r - - Nothing -> - replies - ) - [] - |> Just + return model diff --git a/src/Library/Replying.elm b/src/Library/Replying.elm deleted file mode 100644 index 7c69a1fd..00000000 --- a/src/Library/Replying.elm +++ /dev/null @@ -1,128 +0,0 @@ -module Replying exposing (R3D3, Updator, addReply, andThen2, andThen3, do, reducto, return, updateChild) - -import Return2 -import Return3 -import Task - - - --- 🌳 - - -type alias R3D3 model msg reply = - ( model, Cmd msg, Maybe (List reply) ) - - -type alias Updator msg model = - msg -> model -> ( model, Cmd msg ) - - - --- 🔱 - - -{-| Add a reply. --} -addReply : reply -> R3D3 model msg reply -> R3D3 model msg reply -addReply reply ( model, cmd, maybeReplies ) = - ( model - , cmd - , maybeReplies - |> Maybe.map (\l -> l ++ [ reply ]) - |> Maybe.withDefault [ reply ] - |> Just - ) - - -{-| Add a list of replies in front of the existing replies. --} -addRepliesInFront : List reply -> R3D3 model msg reply -> R3D3 model msg reply -addRepliesInFront replies ( model, cmd, maybeReplies ) = - ( model - , cmd - , maybeReplies - |> Maybe.map (\l -> replies ++ l) - |> Maybe.withDefault replies - |> Just - ) - - -{-| Chain R2D2 `update` calls. --} -andThen2 : (model -> ( model, Cmd msg )) -> ( model, Cmd msg ) -> ( model, Cmd msg ) -andThen2 fn ( model, cmd ) = - Return2.addCmd cmd (fn model) - - -{-| Chain R3D3 `update` calls. --} -andThen3 : (model -> R3D3 model msg reply) -> R3D3 model msg reply -> R3D3 model msg reply -andThen3 fn ( model, cmd, maybeReplies ) = - case maybeReplies of - Just replies -> - Return3.addCmd cmd (fn model) |> addRepliesInFront replies - - Nothing -> - Return3.addCmd cmd (fn model) - - -{-| Reduce a `R3D3` to a `R2D2`. --} -reducto : Updator msg model -> (reply -> msg) -> R3D3 model msg reply -> ( model, Cmd msg ) -reducto updator translator ( model, cmd, maybeReplies ) = - maybeReplies - |> Maybe.withDefault [] - |> List.map translator - |> List.foldl (andThenUpdate updator) ( model, cmd ) - - -{-| Convenience function for returning the standard ( model, Cmd msg ) tuple. --} -return : model -> Cmd msg -> ( model, Cmd msg ) -return = - Tuple.pair - - -{-| Handle the state of a child. - - NOTE: Replies are performed from left to right. - --} -updateChild : - (msg -> model -> ( model, Cmd msg )) - -> (reply -> msg) - -> - { mapCmd : childMsg -> msg - , mapModel : childModel -> model - , update : childMsg -> childModel -> R3D3 childModel childMsg reply - } - -> { model : childModel, msg : childMsg } - -> ( model, Cmd msg ) -updateChild update translateReply context data = - data.model - |> context.update data.msg - |> Return3.mapCmd context.mapCmd - |> Return3.mapModel context.mapModel - |> reducto update translateReply - - - --- 🔱 ░░ TASKS - - -do : msg -> Cmd msg -do msg = - Task.perform identity (Task.succeed msg) - - - ------------------------------------------ --- ㊙️ ------------------------------------------ - - -andThenUpdate : Updator msg model -> msg -> ( model, Cmd msg ) -> ( model, Cmd msg ) -andThenUpdate updator msg ( model, cmd ) = - model - |> updator msg - |> Tuple.mapSecond (\c -> Cmd.batch [ cmd, c ]) diff --git a/src/Library/Return2.elm b/src/Library/Return2.elm new file mode 100644 index 00000000..c42e0895 --- /dev/null +++ b/src/Library/Return2.elm @@ -0,0 +1,59 @@ +module Return2 exposing (Return, addCommand, andThen, mapCommand, mapModel, return, returnWithModel, withModel) + +-- 🌳 + + +type alias Return model msg = + ( model, Cmd msg ) + + + +-- 🔱 + + +andThen : (model -> Return model msg) -> Return model msg -> Return model msg +andThen update ( model, cmd ) = + let + ( newModel, newCmd ) = + update model + in + ( newModel + , Cmd.batch [ cmd, newCmd ] + ) + + +return : model -> Return model msg +return model = + ( model, Cmd.none ) + + +returnWithModel : model -> Cmd msg -> Return model msg +returnWithModel = + Tuple.pair + + + +-- 🔱 ░░░ ALIASES + + +withModel = + returnWithModel + + + +-- 🔱 ░░░ MODIFICATIONS + + +addCommand : Cmd msg -> Return model msg -> Return model msg +addCommand cmd ( model, earlierCmd ) = + ( model + , Cmd.batch [ earlierCmd, cmd ] + ) + + +mapCommand = + Tuple.mapSecond + + +mapModel = + Tuple.mapFirst diff --git a/src/Library/Return3.elm b/src/Library/Return3.elm new file mode 100644 index 00000000..36685a19 --- /dev/null +++ b/src/Library/Return3.elm @@ -0,0 +1,175 @@ +module Return3 exposing (Return, addCommand, addReplies, addReply, andThen, commandWithModel, from2, fromDebouncer, mapCmd, mapModel, mapReplies, repliesWithModel, replyWithModel, return, returnCommandWithModel, returnRepliesWithModel, returnReplyWithModel, three, wield, wieldNested) + +import Maybe.Extra as Maybe +import Return2 + + + +-- 🌳 + + +type alias Return model msg reply = + ( model, Cmd msg, List reply ) + + + +-- 🔱 + + +andThen : (model -> Return model msg reply) -> Return model msg reply -> Return model msg reply +andThen update ( model, cmd, replies ) = + let + ( newModel, newCmd, newReplies ) = + update model + in + ( newModel + , Cmd.batch [ cmd, newCmd ] + , replies ++ newReplies + ) + + +from2 : Return2.Return model msg -> Return model msg reply +from2 ( model, cmd ) = + ( model, cmd, [] ) + + +return : model -> Return model msg reply +return model = + ( model, Cmd.none, [] ) + + +returnCommandWithModel : model -> Cmd msg -> Return model msg reply +returnCommandWithModel model cmd = + ( model, cmd, [] ) + + +returnRepliesWithModel : model -> List reply -> Return model msg reply +returnRepliesWithModel model replies = + ( model, Cmd.none, replies ) + + +returnReplyWithModel : model -> reply -> Return model msg reply +returnReplyWithModel model reply = + ( model, Cmd.none, [ reply ] ) + + +three : model -> Cmd msg -> List reply -> Return model msg reply +three model cmd replies = + ( model, cmd, replies ) + + + +-- 🔱 ░░░ ALIASES + + +commandWithModel = + returnCommandWithModel + + +repliesWithModel = + returnRepliesWithModel + + +replyWithModel = + returnReplyWithModel + + + +-- 🔱 ░░░ MODIFICATIONS + + +addCommand : Cmd msg -> Return model msg reply -> Return model msg reply +addCommand cmd ( model, earlierCmd, replies ) = + ( model + , Cmd.batch [ earlierCmd, cmd ] + , replies + ) + + +addReply : reply -> Return model msg reply -> Return model msg reply +addReply reply = + addReplies [ reply ] + + +addReplies : List reply -> Return model msg reply -> Return model msg reply +addReplies replies ( model, cmd, earlierReplies ) = + ( model + , cmd + , earlierReplies ++ replies + ) + + +mapCmd : (msg -> newMsg) -> Return model msg reply -> Return model newMsg reply +mapCmd fn ( model, cmd, replies ) = + ( model, Cmd.map fn cmd, replies ) + + +mapModel : (model -> newModel) -> Return model msg reply -> Return newModel msg reply +mapModel fn ( model, cmd, replies ) = + ( fn model, cmd, replies ) + + +mapReplies : (reply -> newReply) -> Return model msg reply -> Return model msg newReply +mapReplies fn ( model, cmd, replies ) = + ( model, cmd, List.map fn replies ) + + + +-- 🔱 ░░░ WIELDING + + +wield : + (reply -> model -> Return2.Return model msg) + -> Return model msg reply + -> Return2.Return model msg +wield replyTransformer ( model, cmd, replies ) = + List.foldl + (\reply ( accModel, accCmd ) -> + Tuple.mapSecond + (\c -> Cmd.batch [ accCmd, c ]) + (replyTransformer reply accModel) + ) + ( model + , cmd + ) + replies + + +wieldNested : + (reply -> model -> Return2.Return model msg) + -> + { mapCmd : subMsg -> msg + , mapModel : subModel -> model + , update : subMsg -> subModel -> ( subModel, Cmd subMsg, List reply ) + } + -> + { model : subModel + , msg : subMsg + } + -> Return2.Return model msg +wieldNested replyTransformer a b = + let + cmdTransformer = + a.mapCmd + + modelTransformer = + a.mapModel + + ( subModel, subCmd, replies ) = + a.update b.msg b.model + in + wield + replyTransformer + ( modelTransformer subModel + , Cmd.map cmdTransformer subCmd + , replies + ) + + + +-- 🔱 ░░░ DEBOUNCER + + +fromDebouncer : ( model, Cmd msg, Maybe reply ) -> Return model msg reply +fromDebouncer ( a, b, c ) = + ( a, b, Maybe.unwrap [] List.singleton c ) diff --git a/src/Library/Task/Extra.elm b/src/Library/Task/Extra.elm new file mode 100644 index 00000000..cae083d1 --- /dev/null +++ b/src/Library/Task/Extra.elm @@ -0,0 +1,12 @@ +module Task.Extra exposing (do) + +import Task + + + +-- 🔱 + + +do : msg -> Cmd msg +do msg = + Task.perform identity (Task.succeed msg) -- knotmirror 0.0.1