miso-1.13.0.0: A tasty Haskell front-end web framework
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.Runtime.Internal

Description

Overview

Miso.Runtime.Internal is a testing-only facade that re-exports the miso runtime's global mutable state from the internal runtime module.

Do not import this module in application code. Mutating any of the exported IORef values will corrupt the component lifecycle and produce undefined behaviour. The module exists solely to give the miso-tests integration-test package direct access to component state for assertions.

Exported names

See also

  • Miso.Reload — uses these internals to kill and restart the scheduler on :r
Synopsis

Documentation

components :: IORef (IntMap (ComponentState context props model action)) Source #

componentMap

This is a global Component Map that holds the state of all currently mounted Components

componentIds :: IORef Int Source #

The global store of ComponentId, for internal-use only.

Used internally freshComponentId to allocate new ComponentId on mount.

rootComponentId :: ComponentId Source #

This is used to demarcate the ROOT of a page. This ID will *never* exist in the components map.

data ComponentState context props model action Source #

Component state, data associated with the lifetime of a Component

Constructors

ComponentState 

Fields

type ComponentIds = IntSet Source #

The set of child ComponentIds a component currently has mounted (the _componentChildren field of ComponentState).

schedulerThread :: IORef ThreadId Source #

Placeholder passed to a Props constructor when only the resulting SomeComponent's types (model / props / action) are needed, not a real props value — e.g. to recover the action type for decoding. Safe because every Props built by mount_ / mountWithProps / (+>) is lazy in its props argument, so applying it never forces this.

Used for unidirectional BTS -> MTS communication

dmj: This only runs on the MTS.

Dispatch a main-thread (MTS) event on the Haskell layer.

Invoked synchronously by the MTS delegator (see ts/miso/native/mts/context.ts) with a { componentId, staticKey, event, target } object. Recovers the event handler by its StaticKey, runs it against the owning component's Sink to install its decode+dispatch closure on a scratch node, then invokes that closure with the live event and target DOMRef. No BTS round-trip — the handler runs entirely on the main thread, and its update/effects run there (the scheduler suppresses the redraw; see scheduler).

N.B. unsafeLookupStaticPtr recovers the handler at the component's action type. This is sound because the (componentId, staticKey) pair is emitted together from the same component's setAttrs; the handler's action unifies with the sink's via the quantified components CAF (no unsafeCoerce).

Dispatches a COMPONENT lifecycle message (BTS → MTS) on the "Miso.components" channel. No-op for components without a StaticKey (e.g. the root), since the MTS locates the component via unsafeLookupStaticPtr.

Dispatches an EFFECT message carrying a serialized action across the Lynx thread boundary on the "Miso.effects" channel:

  • MTS → BTS when called on the main thread (mts).
  • BTS → MTS when called on the background thread (bts).

A no-op on plain web builds (neither mts nor bts).

Global variable to hold the scheduler thread

N.B. undefined is safe here, it will always get populated. Also, we use this in cleanup when interactive mode (GHCi) is detected in that circumstance schedulerThread will always be populated. It's an invariant.

unmountComponent :: Eq context => ComponentState context props model action -> IO () Source #

Helper function for cleanly destroying a Component

freeLifecycleHooks :: ComponentState context props model action -> IO () Source #

Helper to drop all lifecycle and mounting hooks if defined.

inline :: (FromJSVal return, ToObject object) => MisoString -> object -> IO return Source #

Convenience function to write inline javascript.

Prefer this function over the use of eval.

This function takes as arguments a JavaScript object and makes the keys available in the function body.

data Person = Person { name :: MisoString, age :: Int }
  deriving stock (Generic)
  deriving anyclass (ToJSVal, ToObject)

logNameGetAge :: Person -> IO Int
logNameGetAge = inline
  """
  console.log(name, name);
  return age;
  """

newtype Event Source #

Constructors

Event JSVal 

Instances

Instances details
Eq Event Source # 
Instance details

Defined in Miso.FFI.Internal

Methods

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

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

FromJSVal Event Source # 
Instance details

Defined in Miso.FFI.Internal

ToJSVal Event Source # 
Instance details

Defined in Miso.FFI.Internal

Methods

toJSVal :: Event -> IO JSVal Source #

diff Source #

Arguments

:: Object

current object

-> Object

new object

-> JSVal

parent node

-> IO () 

Diff two virtual DOMs

flush :: IO () Source #

Flush is used to force a draw of the render tree. This is currently only used when targeting platforms other than the browser (like mobile).

select :: MisoString -> IO () Source #

Fails silently if the element is not found.

Analogous to document.querySelector(# + id).select().

set Source #

Arguments

:: ToJSVal v 
=> MisoString

Property name to set

-> v

Value to assign

-> Object

JavaScript object to mutate

-> IO () 

Set property on object

newtype Image Source #

Type that holds an Image.

Constructors

Image JSVal 

Instances

Instances details
FromJSVal Image Source # 
Instance details

Defined in Miso.FFI.Internal

ToJSVal Image Source # 
Instance details

Defined in Miso.FFI.Internal

Methods

toJSVal :: Image -> IO JSVal Source #

ToObject Image Source # 
Instance details

Defined in Miso.FFI.Internal

cookieGet Source #

Arguments

:: MisoString

Cookie name

-> (JSVal -> IO ())

Successful callback

-> (MisoString -> IO ())

Errorful callback

-> IO () 

Retrieve a single cookie by name from the CookieStore API.

The successful callback receives a null JSVal when no cookie with that name exists. The errorful callback receives the error message string.

See https://developer.mozilla.org/en-US/docs/Web/API/CookieStore/get

Since: 1.13.0.0

cookieGetAll Source #

Arguments

:: (JSVal -> IO ())

Successful callback (receives a JS array of cookie objects)

-> (MisoString -> IO ())

Errorful callback

-> IO () 

cookieSet Source #

Arguments

:: JSVal

Cookie options object (serialised Cookie)

-> IO ()

Successful callback

-> (MisoString -> IO ())

Errorful callback

-> IO () 

cookieDelete Source #

Arguments

:: MisoString

Cookie name

-> IO ()

Successful callback

-> (MisoString -> IO ())

Errorful callback

-> IO () 

cookieDeleteWith Source #

Arguments

:: JSVal

Cookie options object (name, path, domain, partitioned)

-> IO ()

Successful callback

-> (MisoString -> IO ())

Errorful callback

-> IO () 

Delete a cookie by options object via the CookieStore API.

See https://developer.mozilla.org/en-US/docs/Web/API/CookieStore/delete

Since: 1.13.0.0

newtype Date Source #

The Date type

Constructors

Date JSVal 

Instances

Instances details
Eq Date Source # 
Instance details

Defined in Miso.FFI.Internal

Methods

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

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

ToJSVal Date Source # 
Instance details

Defined in Miso.FFI.Internal

Methods

toJSVal :: Date -> IO JSVal Source #

ToObject Date Source # 
Instance details

Defined in Miso.FFI.Internal

Methods

toObject :: Date -> IO Object Source #

toLocaleString :: Date -> IO MisoString Source #

Date conversion function to produce a locale

getMilliseconds :: Date -> IO Double Source #

Retrieves current milliseconds from Date

getSeconds :: Date -> IO Double Source #

Retrieves current seconds from Date

callFunction :: ToArgs args => JSVal -> MisoString -> args -> IO JSVal Source #

Calls a function on a JSVal

Example usage:

callFunction domRef "focus" ()
callFunction domRef "setSelectionRange" (0, 3, "none")

syncCallback :: IO () -> IO JSVal Source #

A synchronous callback

syncCallback1 :: (JSVal -> IO ()) -> IO JSVal Source #

A synchronous callback with a single argument

syncCallback2 :: (JSVal -> JSVal -> IO ()) -> IO JSVal Source #

A synchronous callback with two arguments

asyncCallback :: IO () -> IO JSVal Source #

A asynchronous callback

asyncCallback1 :: (JSVal -> IO ()) -> IO JSVal Source #

A asynchronous callback with one argument

asyncCallback2 :: (JSVal -> JSVal -> IO ()) -> IO JSVal Source #

A asynchronous callback with two arguments

data CONTENT_TYPE Source #

List of possible content types that are available for use with the fetch API

Instances

Instances details
Show CONTENT_TYPE Source # 
Instance details

Defined in Miso.FFI.Internal

Eq CONTENT_TYPE Source # 
Instance details

Defined in Miso.FFI.Internal

ToJSVal CONTENT_TYPE Source # 
Instance details

Defined in Miso.FFI.Internal

data Response body Source #

Type returned from a fetch request

Constructors

Response 

Fields

Instances

Instances details
Functor Response Source # 
Instance details

Defined in Miso.FFI.Internal

Methods

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

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

FromJSVal body => FromJSVal (Response body) Source # 
Instance details

Defined in Miso.FFI.Internal

fetch Source #

Arguments

:: (FromJSVal success, FromJSVal error) 
=> MisoString

url

-> MisoString

method

-> Maybe JSVal

body

-> [(MisoString, MisoString)]

headers

-> (Response success -> IO ())

successful callback

-> (Response error -> IO ())

errorful callback

-> CONTENT_TYPE

content type

-> IO () 

Retrieve JSON via Fetch API

Basic GET of JSON using Fetch API, will be expanded upon.

See https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

newtype Blob Source #

Constructors

Blob JSVal 

Instances

Instances details
Eq Blob Source # 
Instance details

Defined in Miso.FFI.Internal

Methods

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

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

FromJSVal Blob Source # 
Instance details

Defined in Miso.FFI.Internal

ToJSVal Blob Source # 
Instance details

Defined in Miso.FFI.Internal

Methods

toJSVal :: Blob -> IO JSVal Source #

newtype FormData Source #

Constructors

FormData JSVal 

Instances

Instances details
Eq FormData Source # 
Instance details

Defined in Miso.FFI.Internal

FromJSVal FormData Source # 
Instance details

Defined in Miso.FFI.Internal

ToJSVal FormData Source # 
Instance details

Defined in Miso.FFI.Internal

newtype ArrayBuffer Source #

Constructors

ArrayBuffer JSVal 

Instances

Instances details
Eq ArrayBuffer Source # 
Instance details

Defined in Miso.FFI.Internal

FromJSVal ArrayBuffer Source # 
Instance details

Defined in Miso.FFI.Internal

ToJSVal ArrayBuffer Source # 
Instance details

Defined in Miso.FFI.Internal

newtype Uint8Array Source #

Constructors

Uint8Array JSVal 

Instances

Instances details
FromJSVal Uint8Array Source # 
Instance details

Defined in Miso.FFI.Internal

ToJSVal Uint8Array Source # 
Instance details

Defined in Miso.FFI.Internal

now :: IO Double Source #

Retrieve high resolution time stamp

See https://developer.mozilla.org/en-US/docs/Web/API/Performance/now Lynx's *background* thread realm has no performance global at all - only the main thread does - so the obvious performance.now() throws cannot read property now of undefined there. Everything that timestamps from the BTS goes through here, including gesture handling like double-tap detection, so that throw took real features down rather than merely losing precision. Falls back to Date.now(), which every realm has.

consoleLog :: MisoString -> IO () Source #

Outputs a message to the web console

See https://developer.mozilla.org/en-US/docs/Web/API/Console/log

Console logging of JavaScript strings.

consoleLog' :: ToArgs a => a -> IO () Source #

Console-logging of JSVal

consoleError :: MisoString -> IO () Source #

Outputs an error message to the web console

See https://developer.mozilla.org/en-US/docs/Web/API/Console/error

Console logging of JavaScript strings.

consoleWarn :: MisoString -> IO () Source #

Outputs a warning message to the web console

See https://developer.mozilla.org/en-US/docs/Web/API/Console/warn

Console logging of JavaScript strings.

getElementById :: MisoString -> IO JSVal Source #

Returns an Element object representing the element whose id property matches the specified string.

See https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

focus :: MisoString -> IO () Source #

Fails silently if the element is not found.

Analogous to document.getElementById(id).focus().

blur :: MisoString -> IO () Source #

Fails silently if the element is not found.

Analogous to document.getElementById(id).blur()

setSelectionRange Source #

Arguments

:: MisoString

DOM element id (without the # prefix) to call setSelectionRange on

-> Int

Selection start index (inclusive)

-> Int

Selection end index (exclusive)

-> IO () 

Fails silently if the element is not found.

Analogous to document.querySelector(# + id).setSelectionRange(start, end, 'none').

alert :: MisoString -> IO () Source #

Calls the alert() function.

getProperty Source #

Arguments

:: JSVal

JavaScript object to read from

-> MisoString

Property name to retrieve

-> IO JSVal 

Get a property of a JSVal

Example usage:

Just (value :: String) <- fromJSVal =<< getProperty domRef "value"

castJSVal :: FromJSVal a => JSVal -> IO (Maybe a) Source #

Marshalling of JSVal, useful for getProperty

removeChild :: JSVal -> JSVal -> IO () Source #

Removes a child node from a parent node.

Calls miso.drawingContext.removeChild(parent, child).

Since: 1.9.0.0

addStyle :: MisoString -> IO JSVal Source #

Appends a style_ element containing CSS to head_

addStyle "body { background-color: green; }"
<head><style>body { background-color: green; }</style></head>

addStyleSheet :: MisoString -> Bool -> IO JSVal Source #

Appends a StyleSheet link_ element to head_ The link_ tag will contain a URL to a CSS file.

addStyleSheet "https://cdn.jsdelivr.net/npm/todomvc-common@1.0.5/base.min.css"
<head><link href="https://cdn.jsdelivr.net/npm/todomvc-common@1.0.5/base.min.css" ref="stylesheet"></head>

addSrc :: MisoString -> Bool -> IO JSVal Source #

Appends a <script> element to head_

addSrc "https://example.com/script.js"

addScript :: Bool -> MisoString -> IO JSVal Source #

Appends a script_ element containing JS to head_

addScript False "function () { alert('hi'); }"

addScriptImportMap :: MisoString -> IO JSVal Source #

Appends a script_ element containing a JS import map.

addScript "{ \"import\" : { \"three\" : \"url\" } }"

setDrawingContext :: MisoString -> IO () Source #

Used to select a drawing context. Users can override the default DOM renderer by implementing their own Context, and exporting it to the global scope. This opens the door to different rendering engines, ala miso-lynx.

windowInnerWidth :: IO Int Source #

Retrieves the width (in pixels) of the browser window viewport including if rendered, the vertical scrollbar.

See https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth

windowInnerHeight :: IO Int Source #

Retrieves the height (in pixels) of the browser window viewport including, if rendered, the horizontal scrollbar.

See https://developer.mozilla.org/en-US/docs/Web/API/Window/innerHeight

locationReload :: IO () Source #

Calls the location.reload() function.

newImage :: MisoString -> IO Image Source #

Smart constructor for building a Image w/ src_ Attribute.

newDate :: IO Date Source #

Smart constructor for a Date

nextSibling :: JSVal -> IO JSVal Source #

Fetch next sibling DOM node

Since: 1.9.0.0

previousSibling :: JSVal -> IO JSVal Source #

Fetch previous sibling DOM node

Since: 1.9.0.0

click :: () -> JSVal -> IO () Source #

Simulates a click event

button & click ()

Since: 1.9.0.0

setValue :: JSVal -> MisoString -> IO () Source #

Sets the .value property on a DOMRef.

Useful for resetting the value property on an input element.

  setValue domRef ("" :: MisoString)

files :: JSVal -> IO [JSVal] Source #

When working with <input type="file">, this is useful for extracting out the selected files.

  update (InputClicked inputElement) = withSink $ \sink -> do
     files_ <- files inputElement
     forM_ files_ $ \file -> sink (Upload file)
  update (Upload file) = do
     fetch "https://localhost:8080/upload" "POST" (Just file) []
       Successful Errorful

Since: 1.9.0.0

isOnLine :: IO Bool Source #

Navigator function to query the current online status of the user's computer

See navigator.onLine

onBTS :: IO Bool Source #

Returns True when executing on the Lynx background thread (BTS), False on the main thread or in a web build.

Backed by miso.onBTS(), which uses the BACKGROUND compile-time define injected by rspeedy. In web builds where BACKGROUND is undefined the function safely returns false.

Since: 1.13.0.0

onMTS :: IO Bool Source #

Returns True when executing on the Lynx main thread (MTS), False on the background thread and in web builds.

Since: 1.13.0.0

getThreads :: IO (Bool, Bool, Bool) Source #

Returns (mts, bts, web): whether the current execution context is the Lynx main thread, Lynx background thread, or a plain web build.

Since: 1.13.0.0

newtype File Source #

Constructors

File JSVal 

Instances

Instances details
Eq File Source # 
Instance details

Defined in Miso.FFI.Internal

Methods

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

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

FromJSVal File Source # 
Instance details

Defined in Miso.FFI.Internal

ToJSVal File Source # 
Instance details

Defined in Miso.FFI.Internal

Methods

toJSVal :: File -> IO JSVal Source #

ToObject File Source # 
Instance details

Defined in Miso.FFI.Internal

Methods

toObject :: File -> IO Object Source #

newtype FileReader Source #

Constructors

FileReader JSVal 

Instances

Instances details
Eq FileReader Source # 
Instance details

Defined in Miso.FFI.Internal

FromJSVal FileReader Source # 
Instance details

Defined in Miso.FFI.Internal

ToJSVal FileReader Source # 
Instance details

Defined in Miso.FFI.Internal

ToObject FileReader Source # 
Instance details

Defined in Miso.FFI.Internal

newFileReader :: IO FileReader Source #

Smart constructor for building a FileReader

addEventListener Source #

Arguments

:: JSVal

Event target on which we want to register event listener

-> MisoString

Type of event to listen to (e.g. "click")

-> (JSVal -> IO ())

Callback which will be called when the event occurs, the event will be passed to it as a parameter.

-> IO Function 

Register an event listener on given target.

removeEventListener Source #

Arguments

:: JSVal

Event target from which we want to remove event listener

-> MisoString

Type of event to listen to (e.g. "click")

-> Function

Callback which will be called when the event occurs, the event will be passed to it as a parameter.

-> IO () 

Removes an event listener from given target.

dispatchEvent :: Event -> IO () Source #

Invokes document.dispatchEvent

  update ChangeTheme = io_ $ do
    themeEvent <- newEvent "basecoat:theme"
    dispatchEvent themeEvent

newEvent :: ToArgs args => args -> IO Event Source #

Creates a new Event

  update ChangeTheme = io_ $ do
    themeEvent <- newEvent "basecoat:theme"
    dispatchEvent themeEvent

newCustomEvent :: ToArgs args => args -> IO Event Source #

Creates a new Event

  update ToggleSidebar = io_ $ do
    themeEvent <- newCustomEvent "basecoat:sidebar"
    dispatchEvent themeEvent

eventPreventDefault :: JSVal -> IO () Source #

Prevent default event behavior

eventStopPropagation :: JSVal -> IO () Source #

Stop propagation of events

scrollIntoView :: MisoString -> IO () Source #

Calls document.getElementById(id).scrollIntoView()

requestFullscreen :: IO () Source #

Calls document.documentElement.requestFullscreen(), falling back to webkitRequestFullscreen for Safari.

splitmix32 :: Double -> IO JSVal Source #

Uses the splitmix function to generate a PRNG.

mathRandom :: IO Double Source #

Uses the 'Math.random()' function.

getUserMedia Source #

Arguments

:: Bool

video

-> Bool

audio

-> (JSVal -> IO ())

successful

-> (JSVal -> IO ())

errorful

-> IO () 

copyClipboard Source #

Arguments

:: MisoString

Text to copy

-> IO ()

successful

-> (JSVal -> IO ())

errorful

-> IO () 

geolocation :: (JSVal -> IO ()) -> (JSVal -> IO ()) -> IO () Source #

Reads the device position via navigator.geolocation.getCurrentPosition.

Since: 1.13.0.0

delegator :: JSVal -> JSVal -> Bool -> IO JSVal -> IO () Source #

Initialize event delegation from a mount point.

hydrate :: Bool -> JSVal -> JSVal -> IO JSVal Source #

Copies DOM pointers into virtual dom entry point into isomorphic javascript

See hydration)

windowAddEventListener Source #

Arguments

:: MisoString

Type of event to listen to (e.g. "click")

-> (JSVal -> IO ())

Callback which will be called when the event occurs, the event will be passed to it as a parameter.

-> IO Function 

Registers an event listener on window

windowRemoveEventListener Source #

Arguments

:: MisoString

Type of event to listen to (e.g. "click")

-> Function

Callback which will be called when the event occurs, the event will be passed to it as a parameter.

-> IO () 

Removes an event listener from window

eventJSON Source #

Arguments

:: JSVal

decodeAt :: [JSString]

-> JSVal

object with impure references to the DOM

-> IO JSVal 

Convert a JavaScript object to JSON JSONified representation of events

getDrawingContext :: IO JSVal Source #

Retrieves a reference to the drawing context.

This is a miso specific construct used to provide an identical interface for both native (iOS / Android, etc.) and browser environments.

getHydrationContext :: IO JSVal Source #

Retrieves a reference to the hydration context.

This is a miso specific construct used to provide an identical interface for both native (iOS / Android, etc.) and browser environments.

getEventContext :: IO JSVal Source #

Retrieves a reference to the event context.

This is a miso specific construct used to provide an identical interface for both native (iOS / Android, etc.) and browser environments.

getHead :: IO JSVal Source #

Retrieves a reference to the renderer's "head" mount.

Calls miso.drawingContext.getHead().

Note: custom renderers should implement this method.

Since: 1.9.0.0

websocketConnect :: MisoString -> IO () -> (JSVal -> IO ()) -> Maybe (JSVal -> IO ()) -> Maybe (JSVal -> IO ()) -> Maybe (JSVal -> IO ()) -> Maybe (JSVal -> IO ()) -> (JSVal -> IO ()) -> Bool -> IO JSVal Source #

Establishes a WebSocket connection

websocketClose :: JSVal -> IO () Source #

Closes an open WebSocket.

Since: 1.13.0.0

websocketSend :: JSVal -> JSVal -> IO () Source #

Sends a payload over an open WebSocket.

Since: 1.13.0.0

eventSourceConnect :: MisoString -> IO () -> Maybe (JSVal -> IO ()) -> Maybe (JSVal -> IO ()) -> (JSVal -> IO ()) -> Bool -> IO JSVal Source #

Opens a Server-Sent Events connection and wires up its callbacks.

Since: 1.13.0.0

eventSourceClose :: JSVal -> IO () Source #

Closes an open Server-Sent Events connection.

Since: 1.13.0.0

cookieStoreAddEventListener :: (JSVal -> IO ()) -> IO Function Source #

Register a listener for cookieStore change events. Returns the Function handle needed to remove the listener later.

When the CookieStore API is unavailable (e.g. Firefox, insecure contexts) no listener is registered and an inert Function handle is returned.

cookieStoreRemoveEventListener :: Function -> IO () Source #

Remove a previously registered cookieStore change listener.

When the CookieStore API is unavailable this is a no-op.

populateClass Source #

Arguments

:: JSVal

Node

-> [MisoString]

classes

-> IO () 

Populate the classList Set on the virtual DOM.

updateRef :: ToJSVal val => val -> val -> IO () Source #

Used to update the JavaScript reference post-diff.

getRandomValue :: IO Double Source #

Uses the first element of 'crypto.getRandomValues()'.