|
| 1 | +{-# LANGUAGE OverloadedLists #-} |
| 2 | +{-# LANGUAGE OverloadedStrings #-} |
| 3 | +{-# LANGUAGE RecursiveDo #-} |
| 4 | +{-# LANGUAGE ScopedTypeVariables #-} |
| 5 | + |
| 6 | +{- |
| 7 | + - Stripped version of todo list: just add new todo and delete an old one |
| 8 | + -} |
| 9 | + |
| 10 | +import Control.Lens |
| 11 | +import qualified Data.Map as M |
| 12 | +import qualified Data.Text as T |
| 13 | +import Reflex |
| 14 | +import Reflex.Dom hiding (mainWidget) |
| 15 | +import Reflex.Dom.Core (mainWidget) |
| 16 | + |
| 17 | + |
| 18 | +type MM a = M.Map Int a |
| 19 | + |
| 20 | +-- add a new value to a map, automatically choosing an unused key |
| 21 | +new :: a -> MM a -> MM a |
| 22 | +new v m = case M.maxViewWithKey m of |
| 23 | + Nothing -> [(0,v)] -- overloadedlists |
| 24 | + Just ((k, _), _) -> M.insert (succ k) v m |
| 25 | + |
| 26 | +-- output the ul of the elements of the given map and return the delete |
| 27 | +-- event for each key |
| 28 | +ulW :: MonadWidget t m => Dynamic t (MM T.Text) -> m (Dynamic t (MM (Event t Int))) |
| 29 | +ulW xs = elClass "ul" "list" $ listWithKey xs $ \k x -> elClass "li" "element" $ do |
| 30 | + dynText x -- output the text |
| 31 | + fmap (const k) <$> elClass "div" "delete" (button "x") |
| 32 | + -- tag the event of button press with the key of the text |
| 33 | + |
| 34 | +-- output an input text widget with auto clean on return and return an |
| 35 | +-- event firing on return containing the string before clean |
| 36 | +inputW :: MonadWidget t m => m (Event t T.Text) |
| 37 | +inputW = do |
| 38 | + rec let send = ffilter (==13) $ view textInput_keypress input |
| 39 | + -- send signal firing on *return* key press |
| 40 | + input <- textInput $ def & setValue .~ fmap (const "") send |
| 41 | + -- textInput with content reset on send |
| 42 | + return $ tag (current $ view textInput_value input) send |
| 43 | + -- tag the send signal with the inputText value BEFORE resetting |
| 44 | + |
| 45 | +-- circuit ulW with a MM String kept updated by new strings from the passed |
| 46 | +-- event and deletion of single element in the MM |
| 47 | +listW :: MonadWidget t m => Event t T.Text -> m () |
| 48 | +listW e = do |
| 49 | + rec xs <- foldDyn ($) M.empty $ mergeWith (.) |
| 50 | + -- live state, updated by two signals |
| 51 | + [ fmap new e -- insert a new text |
| 52 | + , switch . current $ zs -- delete text at specific keys |
| 53 | + ] |
| 54 | + bs <- ulW xs -- delete signals from outputted state |
| 55 | + let zs = fmap (mergeWith (.) . map (fmap M.delete) . M.elems) bs |
| 56 | + -- merge delete events |
| 57 | + return () |
| 58 | + |
| 59 | +app :: forall t m. MonadWidget t m => m () |
| 60 | +app = el "div" $ inputW >>= listW |
| 61 | + |
| 62 | +main :: IO () |
| 63 | +main = run $ mainWidget app |
| 64 | + |
0 commit comments