Skip to content

Commit b60d7e7

Browse files
author
Julien Dehos
committed
undo button
1 parent d3ed069 commit b60d7e7

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

src/Component.hs

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import Control.Concurrent (threadDelay)
77
import Control.Monad (forM_, when)
88
import Control.Monad.IO.Class (liftIO)
99
import Data.IntSet qualified as IS
10+
import Data.Maybe (isNothing)
1011
import Language.Javascript.JSaddle (liftJSM, FromJSVal(..), ToJSVal(..))
1112
import Miso
1213
import Miso.Canvas as Canvas
@@ -49,6 +50,7 @@ data Action
4950
| ActionAskTime
5051
| ActionSetTime Double
5152
| ActionPointer PointerEvent
53+
| ActionUndo
5254

5355
-------------------------------------------------------------------------------
5456
-- update
@@ -93,11 +95,19 @@ updateModel (ActionPointer event) = do
9395
(False, _, True) -> doPlayMove $ playMove MoveRight
9496
(False, _, False) -> doPlayMove $ playMove MoveLeft
9597

98+
updateModel ActionUndo = do
99+
previous <- use modelPrevious
100+
forM_ previous $ \g -> do
101+
modelPrevious .= Nothing
102+
modelGame .= g
103+
96104
doPlayMove :: (Game -> Maybe Game) -> Transition Model Action
97105
doPlayMove f = do
98-
mg <- f <$> use modelGame
99-
forM_ mg $ \g -> do
100-
modelGame .= g
106+
g0 <- use modelGame
107+
let mg1 = f g0
108+
forM_ mg1 $ \g1 -> do
109+
modelPrevious .= Just g0
110+
modelGame .= g1
101111
modelNbMoves += 1
102112

103113
-------------------------------------------------------------------------------
@@ -147,6 +157,7 @@ viewModel m@Model{..} =
147157
]
148158
, p_ []
149159
[ select_ [ onChange ActionAskLevel ] (map fmtOption [1 .. length allWorlds])
160+
, button_ (undoOpts ++ [ onClick ActionUndo ]) [ "undo" ]
150161
, button_ [ onClick (ActionSetLevel _modelLevel) ] [ "reset" ]
151162
, button_ [ onClick (ActionSetLevel (1 + _modelLevel)) ] [ "next level" ]
152163
]
@@ -162,6 +173,8 @@ viewModel m@Model{..} =
162173
]
163174

164175
where
176+
undoOpts = [ disabled_ | isNothing _modelPrevious ]
177+
165178
(w, h) = ij2xy $ getNiNj _modelGame
166179

167180
status = if computeRunning _modelGame then "" else ", done !!!"

src/Model.hs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,14 @@ data Model = Model
1111
, _modelNbMoves :: Int
1212
, _modelLevel :: Int -- 1-indexed world, in allWorlds
1313
, _modelTime :: Double
14+
, _modelPrevious :: Maybe Game
1415
} deriving (Eq)
1516

1617
makeLenses ''Model
1718

1819
initialModel :: Model
19-
initialModel = Model (mkGame 1) 0 1 0
20+
initialModel = Model (mkGame 1) 0 1 0 Nothing
2021

2122
mkModel :: Int -> Model
22-
mkModel n = Model (mkGame n) 0 n 0
23+
mkModel n = Model (mkGame n) 0 n 0 Nothing
2324

0 commit comments

Comments
 (0)