miso
Copyright(C) 2016-2026 David M. Johnson
LicenseBSD3-style (see the file LICENSE)
MaintainerDavid M. Johnson <code@dmj.io>
Stabilityexperimental
Portabilitynon-portable
Safe HaskellNone
LanguageHaskell2010

Miso.Types

Description

Overview

Miso.Types defines every core type that miso applications are built from. It is re-exported in its entirety by Miso, so most application code never needs to import it directly.

The Component record

Component context props model action is the central record type. It wires together the MVU loop and all supporting runtime configuration:

data Component context props model action = Component
  { model           :: model
  , hydrateModel    :: Maybe (IO model)
  , update          :: action -> Effect context props model action
  , view            :: context -> props -> model -> View context action
  , useContext      :: Bool
  , subs            :: [Sub action]
  , styles          :: [CSS]
  , scripts         :: [JS]
  , mountPoint      :: Maybe MountPoint
  , logLevel        :: LogLevel
  , mailbox         :: Value -> Maybe action
  , eventPropagation :: Bool
  , mount           :: Maybe action
  , unmount         :: Maybe action
  , onPropsChanged  :: Maybe (props -> props -> action)
  }

Use the component smart constructor to build one with sane defaults, then override only the fields you need:

myApp :: App Model Action
myApp = (component initialModel update view)
  { subs   = [ mySub ]
  , styles = [ Href "style.css" False ]
  }

The View type

View context action is miso's virtual DOM tree. Its four constructors map to the four node kinds the runtime handles:

  • VNode — a regular DOM element (<div>, <svg>, …)
  • VText — a text node
  • VComp — an embedded child Component
  • VFrag — a keyless group of siblings (no wrapper element)

Key types at a glance

Component
full MVU application/component record
App
alias for Component () () model action
View
virtual DOM node
Attribute
DOM property, class list, event handler, or style
Namespace
HTML | SVG | MATHML
Key
reconciliation hint for list diffing
CSS
stylesheet reference (Href, Style, Sheet)
JS
script reference (Src, Script, Module, …)
LogLevel
debug verbosity (Off, DebugHydrate, …)
URI
parsed URL (path + query string + fragment)

Text combinators

  • text — create a text node (HTML-escaped in SSR mode)
  • textRaw — create a text node without HTML escaping
  • text_ — concatenate a list of strings with a space separator
  • textKey / textKey_ — keyed variants for efficient list diffing
  • htmlEncode — manually escape & " '

Component mounting

Fragment and keyed combinators

Conditional view utilities

See also

Synopsis

Types

type App model action = Component () () model action Source #

A miso application is a top-level Component. Its app-global context defaults to () (see startAppWithContext to supply a non-trivial context), and its props are fixed to ().

data Component context props model action Source #

Application entry point

Constructors

Component 

Fields

  • model :: model

    Initial model

  • hydrateModel :: Maybe (IO model)

    Optional IO to load component model state, such as reading data from page. The resulting model is only used during initial hydration, not on remounts.

    Note: only synchronous IO should be used here (e.g. reading from localStorage via getLocalStorage).

  • update :: action -> Effect context props model action

    Updates model, optionally providing effects.

  • view :: context -> props -> model -> View context action

    Draws View. Receives the app-global context, the props passed by the parent, and the current model.

  • useContext :: Bool

    Whether this Component should be re-rendered when the app-global context changes (see modifyContext).

    This controls whether a component reacts to context changes, not whether it may change the context. A component may call modifyContext / putContext with useContext = False; it simply won't re-render in response. Enable it on the (usually nested) components whose view reads the context and must refresh when it changes.

    Defaults to False.

    Since: 1.9.0.0

  • subs :: [Sub action]

    Subscriptions to run during application lifetime

  • styles :: [CSS]

    CSS styles expressed as either a URL (Href) or as Style text. These styles are appended dynamically to the <head> section of your HTML page before the initial draw on <body> occurs.

    Note: This field should only be used in development mode.

    Since: 1.9.0.0

  • scripts :: [JS]

    JavaScript scripts expressed as either a URL (Src) or raw JS text. These scripts are appended dynamically to the <head> section of your HTML page before the initial draw on <body> occurs.

    Note: This field should only be used in development mode.

    Since: 1.9.0.0

  • mountPoint :: Maybe MountPoint

    ID of the root element for DOM diff. If Nothing is provided, the entire document body is used as a mount point.

  • logLevel :: LogLevel

    Debugging configuration for prerendering and event delegation

  • mailbox :: Value -> Maybe action

    Receives mail from other components

    Since: 1.9.0.0

  • eventPropagation :: Bool

    Should events bubble up past the Component barrier.

    Defaults to False

    Since: 1.9.0.0

  • mount :: Maybe action

    action to execute during Component mount phase.

    Since: 1.9.0.0

  • unmount :: Maybe action

    action to execute during Component unmount phase.

    Since: 1.9.0.0

  • onPropsChanged :: Maybe (props -> props -> action)

    action to execute when Component props have changed (a.k.a. props phase). Receives previous props and current props as arguments.

    Since: 1.11.0.0

data SomeComponent context Source #

Existential wrapper allowing nesting of Component in Component.

The context type parameter is shared with the enclosing View, so every nested Component participates in the same app-global context.

Constructors

(Eq context, Eq model, Eq props) => SomeComponent props (Component context props model action) 

data View context action Source #

Core type for constructing a virtual DOM in Haskell

Constructors

VNode Namespace Tag [Attribute action] [View context action] 
VText (Maybe Key) MisoString 
VComp (Maybe Key) (SomeComponent context) 
VFrag (Maybe Key) [View context action] 

Instances

Instances details
Functor (View context) Source # 
Instance details

Defined in Miso.Types

Methods

fmap :: (a -> b) -> View context a -> View context b #

(<$) :: a -> View context b -> View context a #

ToHtml [View m a] Source #

Render a [Miso.Types.View] to a L.ByteString

Instance details

Defined in Miso.Html.Render

Methods

toHtml :: [View m a] -> ByteString Source #

IsString (View context action) Source #

IsString instance

Instance details

Defined in Miso.Types

Methods

fromString :: String -> View context action #

ToHtml (View m a) Source #

Render a Miso.Types.View to a L.ByteString

Instance details

Defined in Miso.Html.Render

Methods

toHtml :: View m a -> ByteString Source #

newtype Key Source #

Unique key for a DOM node.

This key is only used to speed up diffing the children of a DOM node, the actual content is not important. The keys of the children of a given DOM node must be unique. Failure to satisfy this invariant gives undefined behavior at runtime.

Constructors

Key MisoString 

Instances

Instances details
IsString Key Source # 
Instance details

Defined in Miso.Types

Methods

fromString :: String -> Key #

Show Key Source # 
Instance details

Defined in Miso.Types

Methods

showsPrec :: Int -> Key -> ShowS #

show :: Key -> String #

showList :: [Key] -> ShowS #

Eq Key Source # 
Instance details

Defined in Miso.Types

Methods

(==) :: Key -> Key -> Bool #

(/=) :: Key -> Key -> Bool #

ToJSVal Key Source #

ToJSVal instance for Key

Instance details

Defined in Miso.Types

Methods

toJSVal :: Key -> IO JSVal Source #

ToJSON Key Source # 
Instance details

Defined in Miso.Types

Methods

toJSON :: Key -> Value Source #

toJSONList :: [Key] -> Value

ToMisoString Key Source # 
Instance details

Defined in Miso.Types

ToKey Key Source #

Identity instance

Instance details

Defined in Miso.Types

Methods

toKey :: Key -> Key Source #

data Attribute action Source #

Attribute of a vnode in a View.

Constructors

Property MisoString Value 
ClassList [MisoString] 
On (Sink action -> VTree -> LogLevel -> Events -> IO ())

The Sink callback can be used to dispatch actions which are fed back to the update function. This is especially useful for event handlers like the onclick attribute. The second argument represents the vnode the attribute is attached to.

Styles (Map MisoString MisoString) 

Instances

Instances details
Functor Attribute Source # 
Instance details

Defined in Miso.Types

Methods

fmap :: (a -> b) -> Attribute a -> Attribute b #

(<$) :: a -> Attribute b -> Attribute a #

Show (Attribute action) Source # 
Instance details

Defined in Miso.Types

Methods

showsPrec :: Int -> Attribute action -> ShowS #

show :: Attribute action -> String #

showList :: [Attribute action] -> ShowS #

Eq (Attribute action) Source # 
Instance details

Defined in Miso.Types

Methods

(==) :: Attribute action -> Attribute action -> Bool #

(/=) :: Attribute action -> Attribute action -> Bool #

data Namespace Source #

DOM element namespace.

Constructors

HTML

HTML Namespace

SVG

SVG Namespace

MATHML

MATHML Namespace

Instances

Instances details
Show Namespace Source # 
Instance details

Defined in Miso.Types

Eq Namespace Source # 
Instance details

Defined in Miso.Types

ToJSVal Namespace Source # 
Instance details

Defined in Miso.Types

data CSS Source #

Allow users to express CSS and append it to <head> before the first draw

'Href' "http://domain.com/style.css" ('True' :: 'CacheBust')
'Style' "body { background-color: red; }"

Constructors

Href MisoString CacheBust

URL linking to hosted CSS

Style MisoString

Raw CSS content in a style_ tag

Sheet StyleSheet

CSS built with Miso.CSS

Instances

Instances details
Show CSS Source # 
Instance details

Defined in Miso.Types

Methods

showsPrec :: Int -> CSS -> ShowS #

show :: CSS -> String #

showList :: [CSS] -> ShowS #

Eq CSS Source # 
Instance details

Defined in Miso.Types

Methods

(==) :: CSS -> CSS -> Bool #

(/=) :: CSS -> CSS -> Bool #

data JS Source #

Allow users to express JS and append it to <head> before the first draw

This is meant to be useful in development only.

Src "http://example.com/script.js" (False :: CacheBust)
Script "alert("hi");"
ImportMap [ "key" =: "value" ]
Module "console.log("hi");"

Since: 1.9.0.0

Constructors

Src MisoString CacheBust

URL linking to hosted JS

Script MisoString

Raw JS content that you would enter in a <script> tag

Module MisoString

Raw JS module content that you would enter in a <script type="module"> tag. See script type

ImportMap [(MisoString, MisoString)]

Import map content in a <script type="importmap"> tag. See importmap

Instances

Instances details
Show JS Source # 
Instance details

Defined in Miso.Types

Methods

showsPrec :: Int -> JS -> ShowS #

show :: JS -> String #

showList :: [JS] -> ShowS #

Eq JS Source # 
Instance details

Defined in Miso.Types

Methods

(==) :: JS -> JS -> Bool #

(/=) :: JS -> JS -> Bool #

data LogLevel Source #

Logging configuration for debugging Miso internals (useful to see if prerendering is successful)

Constructors

Off

No debug logging, the default value used in component

DebugHydrate

Will warn if the structure or properties of the DOM vs. Virtual DOM differ during prerendering.

DebugEvents

Will warn if an event cannot be routed to the Haskell event handler that raised it. Also will warn if an event handler is being used, yet it's not being listened for by the event delegator mount point.

DebugAll

Logs on all of the above

Instances

Instances details
Show LogLevel Source # 
Instance details

Defined in Miso.Types

Eq LogLevel Source # 
Instance details

Defined in Miso.Types

newtype VTree Source #

Virtual DOM implemented as a JavaScript Object. Used for diffing, patching and event delegation. Not meant to be constructed directly, see View instead.

Constructors

VTree 

Fields

  • getTree :: Object

    Underlying JavaScript object representing the virtual DOM tree

Instances

Instances details
ToJSVal VTree Source # 
Instance details

Defined in Miso.Types

Methods

toJSVal :: VTree -> IO JSVal Source #

ToObject VTree Source # 
Instance details

Defined in Miso.Types

data VTreeType Source #

VTreeType ADT for matching TypeScript enum

Instances

Instances details
Show VTreeType Source # 
Instance details

Defined in Miso.Types

Eq VTreeType Source # 
Instance details

Defined in Miso.Types

ToJSVal VTreeType Source # 
Instance details

Defined in Miso.Types

type Tag = MisoString Source #

Tag type, (e.g. div_, p_)

Meant to indicate the type of element being created. Used as the first argument to document.createElement for the web backend.

type CacheBust = Bool Source #

Parameter used to indicate cache busting logic should be used. If True this will append a timestamp to the query. This will force cache invalidation on the browser, causing a fetch of the resources.

type MountPoint = MisoString Source #

mountPoint for Component, e.g "body"

type DOMRef = JSVal Source #

Type to represent a DOM reference

type Events = Map MisoString Phase Source #

Convenience type for Events

data Phase Source #

Phase during which event listener is invoked.

Since: 1.9.0.0

Constructors

CAPTURE 
BUBBLE 

Instances

Instances details
Show Phase Source # 
Instance details

Defined in Miso.Event.Types

Methods

showsPrec :: Int -> Phase -> ShowS #

show :: Phase -> String #

showList :: [Phase] -> ShowS #

Eq Phase Source # 
Instance details

Defined in Miso.Event.Types

Methods

(==) :: Phase -> Phase -> Bool #

(/=) :: Phase -> Phase -> Bool #

ToJSVal Phase Source # 
Instance details

Defined in Miso.Event.Types

Methods

toJSVal :: Phase -> IO JSVal Source #

data URI Source #

URI type. See the official specification

Constructors

URI 

Fields

Instances

Instances details
Generic URI Source # 
Instance details

Defined in Miso.Types

Associated Types

type Rep URI 
Instance details

Defined in Miso.Types

Methods

from :: URI -> Rep URI x #

to :: Rep URI x -> URI #

Show URI Source # 
Instance details

Defined in Miso.Types

Methods

showsPrec :: Int -> URI -> ShowS #

show :: URI -> String #

showList :: [URI] -> ShowS #

Eq URI Source # 
Instance details

Defined in Miso.Types

Methods

(==) :: URI -> URI -> Bool #

(/=) :: URI -> URI -> Bool #

ToJSVal URI Source # 
Instance details

Defined in Miso.Types

Methods

toJSVal :: URI -> IO JSVal Source #

ToObject URI Source # 
Instance details

Defined in Miso.Types

Methods

toObject :: URI -> IO Object Source #

FromJSON URI Source # 
Instance details

Defined in Miso.Router

ToJSON URI Source # 
Instance details

Defined in Miso.Types

Methods

toJSON :: URI -> Value Source #

toJSONList :: [URI] -> Value

FromMisoString URI Source # 
Instance details

Defined in Miso.Router

ToMisoString URI Source # 
Instance details

Defined in Miso.Types

type Rep URI Source # 
Instance details

Defined in Miso.Types

Classes

class ToKey key where Source #

Convert custom key types to Key.

Instances of this class do not have to guarantee uniqueness of the generated keys, it is up to the user to do so. toKey must be an injective function (different inputs must map to different outputs).

Methods

toKey :: key -> Key Source #

Converts any key into Key

Instances

Instances details
ToKey Key Source #

Identity instance

Instance details

Defined in Miso.Types

Methods

toKey :: Key -> Key Source #

ToKey Text Source #

Convert Text to Key

Instance details

Defined in Miso.Types

Methods

toKey :: Text -> Key Source #

ToKey String Source #

Convert String to Key

Instance details

Defined in Miso.Types

Methods

toKey :: String -> Key Source #

ToKey Double Source #

Convert Double to Key

Instance details

Defined in Miso.Types

Methods

toKey :: Double -> Key Source #

ToKey Float Source #

Convert Float to Key

Instance details

Defined in Miso.Types

Methods

toKey :: Float -> Key Source #

ToKey Int Source #

Convert Int to Key

Instance details

Defined in Miso.Types

Methods

toKey :: Int -> Key Source #

ToKey Word Source #

Convert Word to Key

Instance details

Defined in Miso.Types

Methods

toKey :: Word -> Key Source #

Smart Constructors

component Source #

Arguments

:: model

model

-> (action -> Effect context props model action)

update

-> (context -> props -> model -> View context action)

view

-> Component context props model action 

Smart constructor for Component with sane defaults.

vcomp Source #

Arguments

:: model

model

-> (action -> Effect context props model action)

update

-> (context -> props -> model -> View context action)

view

-> Component context props model action 

Synonym for component

Component mounting

(+>) infixr 0 Source #

Arguments

:: (Eq context, Eq model) 
=> MisoString

VComp key_

-> Component context () model action

Component

-> View context a 

Component mounting combinator

Used in the view function to mount a Component on any VNode.

"component-id" +> component model noop $ \m ->
  div_ [ id_ "foo" ] [ text (ms m) ]

Since: 1.9.0.0

mount_ Source #

Arguments

:: (Eq context, Eq model) 
=> Component context () model action

Component to mount

-> View context a 

Component mounting combinator.

Note: only use this if you're certain you won't be diffing two Component against each other. Otherwise, you will need a key to distinguish between the two Component, to ensure unmounting and mounting occurs.

mount_ $ component model noop $ \m ->
 div_ [ id_ "foo" ] [ text (ms m) ]

Since: 1.9.0.0

mountUseContext Source #

Arguments

:: (Eq context, Eq model) 
=> Component context () model action

Component to mount

-> View context a 

Component mounting combinator that opts the child into app-global React-style context updates.

Equivalent to mount_, but sets useContext = True on the mounted Component so it re-renders whenever the context changes (see modifyContext). Like mount_, this is unkeyed and so unsafe when diffing two Component against each other.

mountUseContext $ component model noop $ \ctx m ->
 div_ [ id_ "foo" ] [ text (ms m) ]

Since: 1.9.0.0

mountWithProps_ Source #

Arguments

:: (Eq context, Eq model, Eq props) 
=> MisoString

key to use

-> props

props to use

-> Component context props model action

Component to mount

-> View context a 

Component mounting combinator.

mountWithProps_ "key" someProps $ component model noop $ \m ->
 div_ [ id_ "foo" ] [ text (ms m) ]

Since: 1.11.0.0

mountWithProps Source #

Arguments

:: (Eq context, Eq model, Eq props) 
=> props

props to use

-> Component context props model action

Component to mount

-> View context a 

Component mounting combinator.

Note: only use this if you're certain you won't be diffing two Component against each other. Otherwise, you will need a key to distinguish between the two Component, to ensure unmounting and mounting occurs.

mountWithProps someProps $ component model noop $ \m ->
 div_ [ id_ "foo" ] [ text (ms m) ]

Since: 1.11.0.0

Key combinators

keyed :: MisoString -> View context action -> View context action Source #

Like +> but operates on any View, not just Component.

This appends a Key to any View.

keyed "key" ("some text" :: View context action)
keyed "key" $ div_ [ id_ "container" ] [ "content" ]
keyed "key" (mount_ calendarComponent)

Since: 1.10.0.0

Fragment combinators

fragment :: [View context action] -> View context action Source #

Create a fragment (keyless).

A fragment groups multiple sibling View nodes without introducing an extra DOM element.

Since: 1.10.0.0

fragment_ :: MisoString -> [View context action] -> View context action Source #

Like fragment, but keyed for efficient diffing.

Since: 1.10.0.0

vfrag :: [View context action] -> View context action Source #

Create a fragment (keyless).

A fragment groups multiple sibling View nodes without introducing an extra DOM element.

Synonym for fragment

Since: 1.10.0.0

vfrag_ :: MisoString -> [View context action] -> View context action Source #

Like fragment, but keyed for efficient diffing.

Since: 1.10.0.0

Utils

getMountPoint :: Maybe MisoString -> MisoString Source #

Convenience for extracting mount point

optionalAttrs Source #

Arguments

:: ([Attribute action] -> [View context action] -> View context action) 
-> [Attribute action]

Attributes to be added unconditionally

-> Bool

A condition

-> [Attribute action]

Additional attributes to add if the condition is True

-> [View context action]

Children

-> View context action 

Utility function to make it easy to specify conditional attributes

view :: Bool -> View context action
view danger = optionalAttrs div_ [ id_ "some-div" ] danger [ class_ "danger" ] ["child"]

Since: 1.9.0.0

optionalVoidAttrs Source #

Arguments

:: ([Attribute action] -> View context action) 
-> [Attribute action]

Attributes to be added unconditionally

-> Bool

A condition

-> [Attribute action]

Additional attributes to add if the condition is True

-> View context action 

Utility function to make it easy to specify conditional attributes for void elements.

view :: Bool -> View context action
view shouldClear = optionalVoidAttrs textarea_ [ value_ "" ] shouldClear [ id_ "text-area-id" ]

Since: 1.9.0.0

optionalChildren Source #

Arguments

:: ([Attribute action] -> [View context action] -> View context action) 
-> [Attribute action]

Attributes to be added unconditionally

-> [View context action]

Children to be added unconditionally

-> Bool

A condition

-> [View context action]

Additional children to add if the condition is True

-> View context action 

Conditionally adds children.

view :: Bool -> View context action
view withChild = optionalChildren div_ [ id_ "txt" ] [] withChild [ "foo" ]

Since: 1.9.0.0

prettyURI :: URI -> MisoString Source #

Pretty-prints a URI.

prettyQueryString :: URI -> MisoString Source #

Pretty-prints a URI query string.

Combinators

node Source #

Arguments

:: Namespace

Element namespace (HTML, SVG, or MATHML)

-> MisoString

Tag name (e.g. "div", "circle")

-> [Attribute action]

Attributes, properties, and event handlers

-> [View context action]

Child nodes

-> View context action 

Create a new VNode.

node ns tag attrs children creates a new node with tag tag in the namespace ns. All attrs are called when the node is created and its children are initialized to children.

vnode Source #

Arguments

:: Namespace

Element namespace (HTML, SVG, or MATHML)

-> MisoString

Tag name (e.g. "div", "circle")

-> [Attribute action]

Attributes, properties, and event handlers

-> [View context action]

Child nodes

-> View context action 

Create a new VNode.

Synonym for node

text :: MisoString -> View context action Source #

Create a new VText with the given content.

vtext :: MisoString -> View context action Source #

Synonym for text

text_ :: [MisoString] -> View context action Source #

Create a new VText containing concatenation of the given strings.

  view :: View context action
  view = div_
    [ className "container" ]
    [ text_
      [ "foo"
      , "bar"
      ]
    ]

Renders as class="container"foo bar/div

A single additional space is added between elements.

textRaw :: MisoString -> View context action Source #

Create a new VText, not subject to HTML escaping.

Like text, except will not escape HTML when used on the server.

textKey :: ToKey key => key -> MisoString -> View context action Source #

Like text, but allow the node to be keyed for efficient diffing.

view :: model -> View context action
view = x -> div_ [] [ textKey (1 :: Int) "text here" ]

Since: 1.9.0.0

textKey_ :: ToKey key => key -> [MisoString] -> View context action Source #

Like text_, but allow the node to be keyed for efficient diffing.

view :: model -> View context action
view = x -> div_ [] [ textKey_ (1 :: Int) [ "text", "goes", "here" ] ]

Since: 1.9.0.0

htmlEncode :: MisoString -> MisoString Source #

HTML-encodes text.

Useful for escaping HTML when delivering on the server. Naive usage of text will ensure this as well.

>>> Data.Text.IO.putStrLn $ text "<a href=\"\">"
&lt;a href=&quot;&quot;&gt;

MisoString

type MisoString = Text Source #

The primary string type in Miso applications.

  • 1 (server/SSR build): alias for Text
  • WASM / GHC JS backend: alias for JSString — a zero-copy wrapper around a native JavaScript string, giving optimal interop with the DOM and JSON APIs

toMisoString :: ToMisoString str => str -> MisoString Source #

Convert a value to MisoString.

fromMisoString :: FromMisoString a => MisoString -> a Source #

Parse a MisoString, throwing an error on failure. Use fromMisoStringEither as a safe alternative.

ms :: ToMisoString str => str -> MisoString Source #

Short alias for toMisoString. The idiomatic way to construct a MisoString.