Learn HalogenGHC loads in the background

22. A view's logic as a pure step

This lesson builds search as you type. You type a word, and the view lists the words that start with it. A search starts after a short pause in typing, and an older answer must never replace a newer one. You write the view's rules as a pure function, and Halogen.Machine runs it.

This way of writing a view is optional. A view with one ask is simpler as a plain handler, as in lesson 7.

Try it first

Compile Start.hs and type "ab" quickly. The list ends on the words for "a", while the field says "ab".

The server in this lesson is the function search. It waits, then answers. A short query takes it longer: 0.9 seconds for one letter, 0.3 seconds for more. So the answer for "a" always comes after the answer for "ab".

The step

The top of the module is plain Haskell. Model is what the view knows. Event is what can happen to it. Effect is what it wants done. step takes an event and the model, and returns the new model and a list of effects:

step :: Event -> Model -> (Model, [Effect])

step is a pure function. A test can call it with any order of events, with no component and no browser.

Halogen.Machine makes one promise: the effects of one step do not mix with later events. It carries out a step's effects in the list's order, before it steps the next event.

Two kinds of effect

carry says how each effect is carried out. An effect is one of two kinds.

  • M.Now runs in place, before the next effect. FocusField uses it to put the cursor back in the field. Its code cannot wait, and the compiler checks that.
  • M.Ask starts work that takes time, such as M.run (liftIO (search text)). The work cannot change the view. Its answer comes back later as an event, here Found, and step handles it like any other event.

A pause is an ask too. M.AskUnder Pausing (M.delayCounted 0.3) waits 0.3 seconds under the key Pausing, then brings Paused. M.Cancel Pausing stops every ask under that key, and their answers never come. A test that waits for the program to be quiet waits for M.delayCounted, since a search follows it. Under a test's clock the test advances the clock by the pause instead, and the program is quiet while it sleeps.

The component

The component keeps the machine in its state, made with M.new. M.Spec names step, carry, and where the state keeps the machine. H.onAction (M.happen spec) brings each event to the machine. render reads the model with M.current.

Tickets

Halogen.Latest keeps the latest answer on the screen. Each search gets a ticket from newAsk, and its answer brings the ticket back. takes says whether to take an answer: it says no when an answer to a later search was taken already. supersede makes every search still out too old. cleared uses it, for Clear and for an empty field.

Start.hs takes a ticket for each search, but never looks at it.

Exercise

Change only step:

  1. In Typed, put StopPause before Pause text. Each key then cancels the pause still out, and typing "ab" quickly starts one search.
  2. In Found, take the answer only when takes ticket model.searches gives Just the new Asks. Put that value in the model's searches. On Nothing, change nothing.

Compile and type "ab" quickly. Then type "a", wait half a second, and type "b". The list ends on the words for "ab" both times. Without step 2, the second try still ends on "a".

When not to use it

Use a plain handler for a view with one ask and simple rules. Use a pure step when a view has several asks, pauses or pushes, and its rules are hard to keep right in handlers.

Lesson.hs
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE OverloadedStrings #-}

module Lesson (component) where

import Control.Concurrent (threadDelay)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.State (gets)
import Data.Foldable (traverse_)
import Data.Text (Text)
import Data.Text qualified as T
import Halogen qualified as H
import Halogen.HTML qualified as HH
import Halogen.HTML.Events qualified as HE
import Halogen.HTML.Properties qualified as HP
import Halogen.Latest (Ask, Asks, newAsk, noAsks, supersede)
import Halogen.Machine qualified as M
import Halogen.Sync qualified as Sync
import Web.HTML.HTMLElement qualified as HTMLElement

-- The view's logic. It is plain Haskell: no component and no effects.
data Model = Model {typed :: Text, shown :: Text, results :: [Text], searches :: Asks}

data Event = Typed Text | Paused Text | Found Ask Text [Text] | Cleared

data Effect = Pause Text | StopPause | Search Ask Text | FocusField

step :: Event -> Model -> (Model, [Effect])
step event model = case event of
  Typed text -> (model {typed = text}, [Pause text])
  Paused text
    | T.null text -> (cleared model, [])
    | otherwise ->
        let (ticket, later) = newAsk model.searches
         in (model {searches = later}, [Search ticket text])
  Found _ text found -> (model {shown = text, results = found}, [])
  Cleared -> ((cleared model) {typed = ""}, [StopPause, FocusField])

-- Show no words, and make every search still out too old.
cleared :: Model -> Model
cleared model = model {shown = "", results = [], searches = supersede model.searches}

-- The server. It answers a short query more slowly than a long one.
search :: Text -> IO [Text]
search text = do
  threadDelay (if T.length text < 2 then 900000 else 300000)
  pure (filter (T.isPrefixOf (T.toLower text)) dictionary)

dictionary :: [Text]
dictionary = ["abacus", "able", "about", "acorn", "actor", "after", "bacon", "cabin"]

-- The component keeps the machine, and the field's ref for the focus.
data State = State {machine :: M.Machine Pausing Event Model, field :: H.RefLabel}

data Pausing = Pausing
  deriving (Eq, Ord)

component :: forall q o m. (MonadIO m) => H.Component q () o m
component = H.component initialState render [H.onAction (M.happen spec)]
  where
    initialState _ = do
      label <- liftIO (H.newRefLabel "search")
      pure State {machine = M.new (Model "" "" [] noAsks), field = label}
    spec = M.Spec {M.step = step, M.carry = carry, M.get = (.machine), M.set = \m s -> s {machine = m}}
    carry = \case
      Pause text -> M.AskUnder Pausing (M.delayCounted 0.3) (const (Paused text))
      StopPause -> M.Cancel Pausing
      Search ticket text -> M.Ask (M.run (liftIO (search text))) (Found ticket text . either (const []) id)
      FocusField -> M.Now $ do
        found <- gets (.field) >>= Sync.getHTMLElementRef
        traverse_ (Sync.sync . liftIO . HTMLElement.focus) found
    render state =
      let model = M.current state.machine
       in HH.div_
            [ HH.input [HP.ref state.field, HP.value model.typed, HE.onValueInput Typed]
            , HH.button [HE.onClick (const Cleared)] [HH.text "Clear"]
            , HH.p_ [HH.text (if T.null model.shown then "Type a word." else "Words for \"" <> model.shown <> "\":")]
            , HH.ul_ [HH.li_ [HH.text word] | word <- model.results]
            ]

The compiler loads once the page has started.

Your component will appear here after compilation.