Skip to content

Instantly share code, notes, and snippets.

@tfc
Last active March 27, 2021 11:44
Show Gist options
  • Save tfc/2028faf25cb8fd8c301a2e6f4f4773f0 to your computer and use it in GitHub Desktop.
Save tfc/2028faf25cb8fd8c301a2e6f4f4773f0 to your computer and use it in GitHub Desktop.
module Main where
import Control.Monad.Fix (MonadFix)
import Data.Text (Text)
import Reflex.Dom
data Tool = Tool { toolName :: Text } deriving (Eq, Show)
main :: IO ()
main = mainWidget bodyWidget
bodyWidget :: ( DomBuilder t m, MonadFix m, MonadHold t m, PostBuild t m)
=> m ()
bodyWidget = do
-- simulate a dyn that might come from some internet request
let existingTools = constDyn [ Tool "Hammer"
, Tool "Saw"
, Tool "Screwdriver"
]
eeToolSelected :: Event t (Event t Tool) <- dyn $ ffor existingTools toolSelectWidget
eToolSelected :: Event t Tool <- switchHold never eeToolSelected
selectedTool :: Dynamic t (Maybe Tool) <- holdDyn Nothing (Just <$> eToolSelected)
selectedToolWidget selectedTool
return ()
toolSelectWidget :: DomBuilder t m
=> [Tool]
-> m (Event t Tool)
toolSelectWidget tools = el "ul" $ do
events <- mapM (el "li" . toolSelectButton) tools
return $ leftmost events
toolSelectButton :: DomBuilder t m
=> Tool
-> m (Event t Tool)
toolSelectButton tool = do
eClick <- button $ "Select: " <> toolName tool
return $ tool <$ eClick
selectedToolWidget :: (DomBuilder t m, PostBuild t m)
=> Dynamic t (Maybe Tool)
-> m ()
selectedToolWidget dMaybeTool = el "p" $ dyn_ $ ffor dMaybeTool $ \case
Nothing -> text "No tool selected"
Just m -> text $ "Selected tool: " <> toolName m
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment