Skip to content

Instantly share code, notes, and snippets.

@Apanatshka
Forked from theadam/Simple Undo Example
Last active August 29, 2015 14:22
Show Gist options
  • Save Apanatshka/049f66131f5a1a7a3801 to your computer and use it in GitHub Desktop.
Save Apanatshka/049f66131f5a1a7a3801 to your computer and use it in GitHub Desktop.
Added debouncing. Had to change update/undo logic too!
import Html exposing (Html, div, text, input, button)
import Html.Attributes exposing (value, placeholder)
import Html.Events exposing (on, targetValue, onClick)
import Signal as Signal
import List exposing (head, tail)
import Maybe
import Debug
isUpdate ha = case ha of
Just (Update _ _) -> True
_ -> False
toSave = Maybe.map (\ha -> case ha of
Update m _ -> Save m
_ -> Debug.crash "toModify: called on non-Ignore")
start model view update =
let
actions =
Signal.mailbox Nothing
debouncedUpdateText =
actions.signal
|> Signal.filter isUpdate Nothing
|> settledAfter (500 * Time.millisecond)
|> Signal.map toSave
address =
Signal.forwardTo actions.address Just
modelSig =
Signal.foldp
(\(Just action) model -> update action model)
model
(Signal.merge actions.signal debouncedUpdateText)
in
Signal.map (view address) modelSig
type alias Model = { text:String }
type Action = UpdateText String
update : Action -> Model -> Model
update action model =
case action of
UpdateText text -> { model | text <- text }
model = { text = "" }
view : Context -> Model -> Html
view context model =
div [] [
input [ on "input" targetValue (Signal.message context.actions << UpdateText ), value model.text, placeholder "Type Something Here!" ] [ ],
div [] [text model.text],
button [ onClick context.undo ()] [text "click" ]
]
type HistoryAction = Save Model | Update Model Action | Undo
type alias HistoryModel = { current:Model, history:List Model }
state = { current = model, history = [model] }
historyUpdate : HistoryAction -> HistoryModel -> HistoryModel
historyUpdate action model =
case action of
Update current action -> { model | current <- update action model.current }
Save current -> { model | history <- model.current :: model.history }
Undo -> { model | current <- Maybe.withDefault model.current
(Maybe.andThen (tail model.history) head)
, history <- case tail model.history of
Just (h::t) -> h::t
_ -> model.history }
historyView : Signal.Address HistoryAction -> HistoryModel -> Html
historyView address model =
view ({
actions = (Signal.forwardTo address (Update model.current)),
undo = (Signal.forwardTo address (always Undo))
}) model.current
type alias Context = {
actions : Signal.Address Action,
undo : Signal.Address ()
}
main =
start state historyView historyUpdate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment