From 3e377e7df6431ffb88dcd8377969f62dd8e3c7d5 Mon Sep 17 00:00:00 2001 From: Miles Frain Date: Mon, 7 Dec 2020 16:40:12 -0800 Subject: [PATCH] ComponentsHalogenHooks in style of React --- recipes/ComponentsHalogenHooks/src/Main.purs | 40 +++++++------------- 1 file changed, 14 insertions(+), 26 deletions(-) diff --git a/recipes/ComponentsHalogenHooks/src/Main.purs b/recipes/ComponentsHalogenHooks/src/Main.purs index 0142032c..b2c5c529 100644 --- a/recipes/ComponentsHalogenHooks/src/Main.purs +++ b/recipes/ComponentsHalogenHooks/src/Main.purs @@ -1,9 +1,8 @@ module ComponentsHalogenHooks.Main where -import Prelude hiding (top) +import Prelude import Data.Maybe (Maybe(..), maybe) -import Data.Symbol (SProxy(..)) import Data.Tuple.Nested ((/\)) import Effect (Effect) import Halogen as H @@ -20,21 +19,24 @@ main = body <- HA.awaitBody void $ runUI containerComponent unit body -_button :: SProxy "button" -_button = SProxy - containerComponent :: forall unusedQuery unusedInput unusedOutput anyMonad . H.Component HH.HTML unusedQuery unusedInput unusedOutput anyMonad containerComponent = Hooks.component \rec _ -> Hooks.do + enabled /\ enabledIdx <- Hooks.useState false toggleCount /\ toggleCountIdx <- Hooks.useState 0 buttonState /\ buttonStateIdx <- Hooks.useState (Nothing :: Maybe Boolean) + let + handleClick _ = + Just do + Hooks.modify_ toggleCountIdx (_ + 1) + Hooks.modify_ enabledIdx not + label = if enabled then "On" else "Off" Hooks.pure $ HH.div_ - [ HH.slot _button unit buttonComponent unit \_ -> Just do - Hooks.modify_ toggleCountIdx (_ + 1) + [ renderButton {enabled, handleClick} , HH.p_ - [ HH.text ("Button has been toggled " <> show toggleCount <> " time(s)") ] + [ HH.text ("the Button has been toggled " <> show toggleCount <> " time(s)") ] , HH.p_ [ HH.text $ "Last time I checked, the button was: " @@ -42,31 +44,17 @@ containerComponent = Hooks.component \rec _ -> Hooks.do <> ". " , HH.button [ HE.onClick \_ -> Just do - mbBtnState <- Hooks.query rec.slotToken _button unit $ H.request IsOn - Hooks.put buttonStateIdx mbBtnState + Hooks.put buttonStateIdx $ Just enabled ] [ HH.text "Check now" ] ] ] -data ButtonMessage = Toggled Boolean -data ButtonQuery a = IsOn (Boolean -> a) - -buttonComponent - :: forall unusedInput anyMonad - . H.Component HH.HTML ButtonQuery unusedInput ButtonMessage anyMonad -buttonComponent = Hooks.component \rec _ -> Hooks.do - enabled /\ enabledIdx <- Hooks.useState false - Hooks.useQuery rec.queryToken case _ of - IsOn reply -> do - isEnabled <- Hooks.get enabledIdx - pure $ Just $ reply isEnabled +renderButton {enabled, handleClick} = let label = if enabled then "On" else "Off" - Hooks.pure $ + in HH.button [ HP.title label - , HE.onClick \_ -> Just do - newState <- Hooks.modify enabledIdx not - Hooks.raise rec.outputToken $ Toggled newState + , HE.onClick handleClick ] [ HH.text label ]