Skip to content

Commit f5547d1

Browse files
authored
Listen for URI hash changes (#27)
1 parent 11426cd commit f5547d1

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

src/Docs/Search/App.purs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import Control.Coroutine as Coroutine
1212
import Data.Maybe (Maybe(..))
1313
import Data.Newtype (wrap)
1414
import Effect (Effect)
15+
import Effect.Aff (launchAff_)
1516
import Halogen as H
1617
import Halogen.Aff as HA
1718
import Halogen.VDom.Driver (runUI)
@@ -21,10 +22,12 @@ import Web.DOM.Element as Element
2122
import Web.DOM.Node as Node
2223
import Web.DOM.ParentNode as ParentNode
2324
import Web.DOM.Text as Text
25+
import Web.Event.EventTarget (addEventListener, eventListener)
2426
import Web.HTML as HTML
2527
import Web.HTML.HTMLDocument as HTMLDocument
2628
import Web.HTML.HTMLElement (fromElement)
2729
import Web.HTML.Window as Window
30+
import Web.HTML.Event.HashChangeEvent.EventTypes (hashchange)
2831

2932
main :: Effect Unit
3033
main = do
@@ -57,7 +60,18 @@ main = do
5760

5861
-- We need to read the URI hash only when both components are initialized and
5962
-- the search field is subscribed to the main component.
60-
sfio.query (SearchField.ReadURIHash unit)
63+
void $ sfio.query $ H.tell SearchField.ReadURIHash
64+
65+
-- Subscribe to URI hash updates
66+
H.liftEffect do
67+
68+
listener <-
69+
eventListener \event ->
70+
launchAff_ do
71+
sfio.query $ H.tell SearchField.ReadURIHash
72+
73+
addEventListener hashchange listener true (Window.toEventTarget win)
74+
6175

6276
insertStyle :: Document.Document -> Effect Unit
6377
insertStyle doc = do

src/Docs/Search/App/SearchField.purs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,11 @@ handleQuery
6363
. Query a
6464
-> H.HalogenM State Action () SearchFieldMessage Aff (Maybe a)
6565
handleQuery (ReadURIHash next) = do
66-
state <- H.get
67-
H.raise (InputUpdated state.input)
66+
oldInput <- H.get <#> _.input
67+
newInput <- H.liftEffect URIHash.getInput
68+
when (oldInput /= newInput) do
69+
H.modify_ (_ { input = newInput })
70+
H.raise (InputUpdated newInput)
6871
pure Nothing
6972

7073
initialState :: forall i. i -> State
@@ -75,9 +78,6 @@ handleAction = case _ of
7578

7679
InitKeyboardListener -> do
7780

78-
input <- H.liftEffect URIHash.getInput
79-
H.modify_ (_ { input = input })
80-
8181
document <- H.liftEffect $ Web.document =<< Web.window
8282
H.subscribe' \sid ->
8383
ES.eventListenerEventSource

0 commit comments

Comments
 (0)