Skip to content

Instantly share code, notes, and snippets.

@theadam
Created June 10, 2015 21:32
Show Gist options
  • Save theadam/a73d31e576f5d05d75d1 to your computer and use it in GitHub Desktop.
Save theadam/a73d31e576f5d05d75d1 to your computer and use it in GitHub Desktop.
A simple undo example
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 StartApp
import List exposing (head, tail)
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 = Modify Model Action | Undo ()
type alias HistoryModel = { current:Model, history:List Model }
state = { current = model, history = [] }
historyUpdate : HistoryAction -> HistoryModel -> HistoryModel
historyUpdate action model =
case action of
Modify current action -> { model | current <- update action model.current,
history <- model.current :: model.history }
Undo action -> { model | current <- case head model.history of
Just xs -> xs
Nothing -> model.current,
history <- case tail model.history of
Just xs -> xs
Nothing -> []}
historyView : Signal.Address HistoryAction -> HistoryModel -> Html
historyView address model =
view ({
actions = (Signal.forwardTo address (Modify model.current)),
undo = (Signal.forwardTo address Undo)
}) model.current
type alias Context = {
actions : Signal.Address Action,
undo : Signal.Address ()
}
main =
StartApp.start { model = state, view = historyView, update = historyUpdate }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment