Skip to content

Instantly share code, notes, and snippets.

@dlants
Created August 24, 2017 04:01
Show Gist options
  • Save dlants/f211c7bea2eeab22d1f4770bd4d5e533 to your computer and use it in GitHub Desktop.
Save dlants/f211c7bea2eeab22d1f4770bd4d5e533 to your computer and use it in GitHub Desktop.
Adding a Window Resize signal to a purescript pux webapp

One of those things that's incredibly useful, but not built in... I figure others may be googling for this one day.

I found the source for https://pursuit.purescript.org/packages/purescript-pux/11.0.0/docs/Pux.DOM.History very useful!

Here is a commit adding it to my app: https://github.com/dlants/doodleometry/commit/43d38a3d6d4c8c755cdbe63b690837bdd2085a93

module SampleWindow (sampleWindowSize) where

import Control.Alternative (pure)
import Control.Bind (bind)
import Control.Monad.Eff (Eff)
import DOM (DOM)
import DOM.Event.EventTarget (addEventListener, eventListener)
import DOM.HTML.Event.EventTypes (resize)
import DOM.HTML.Types (Window, windowToEventTarget)
import DOM.HTML.Window (innerHeight, innerWidth)
import Prelude (discard, ($))
import Signal (Signal)
import Signal.Channel (CHANNEL, channel, send, subscribe)

-- | Returns a signal containing the current window size
-- | which is updated on every "resize" event.
sampleWindowSize :: forall eff. Window -> Eff (channel :: CHANNEL, dom :: DOM | eff) (Signal {width:: Int, height:: Int})
sampleWindowSize win = do
  width <- innerWidth win
  height <- innerHeight win
  chan <- channel {width, height}

  let listener = eventListener \ev -> do
        w <- innerWidth win
        h <- innerHeight win
        send chan {width: w, height: h}

  addEventListener resize listener false (windowToEventTarget win)

  pure $ subscribe chan
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment