Skip to content

Latest commit

 

History

History
769 lines (628 loc) · 27.2 KB

api.md

File metadata and controls

769 lines (628 loc) · 27.2 KB

Modules

fx
subs

fx

fx.exports.Console(...args)

Describes an effect that will call console.log with arguments. Useful for development and debugging. Not recommended for production.

Kind: static method of fx

Param Type Description
...args * arguments to log to the console

Example

import { Console } from "hyperapp-fx"

const ConsoleAction = state => [
  state,
  Console(
    "string arg",
    { object: "arg" },
    ["list", "of", "args"],
    someOtherArg
  )
]

fx.exports.ReadCookie(props)

Describes an effect that will read a cookie and then call an action with its value. If no prop is specified the action will receive the value of the cookie in the value prop. Extra properties may be added using by specifying props. If json is set to true the value will be converted from JSON.

Kind: static method of fx

Param Type Description
props object
props.name string Name of the cookie
props.action string Action to call when cookie is read
props.prop string Name of prop to which the cookie value is passed
props.props object Props to pass to action
props.json boolean Indicates whether cookie value should be converted from JSON
props.converter function Function used to convert cookie value
props.decoder function Function used to decode cookie value

Example

import { ReadCookie } from "hyperapp-fx"

const LoadPreferences = state => [
  state,
  ReadCookie({
    name: "preferences",
    action: function (state, { value }) {
      // this action will receive the cookie value
    },
    json: true
  })
]

fx.exports.WriteCookie(props)

Describes an effect that will write a cookie.

Kind: static method of fx

Param Type Description
props object
props.name string Name of the cookie
props.value string Value to save in cookie
props.domain string Domain of the cookie
props.path string Path of the cookie
props.expires date Expiry date of the cookie
props.ttl number Time to live of the cookie in seconds, this property has precedence over the expires property
props.json boolean Indicates whether the cookie value should be converted to JSON
props.nameEncoder function Function used to encode the cookie name
props.converter function Function used to convert cookie value
props.encoder function Function used to encode cookie value

Example

import { WriteCookie } from "hyperapp-fx"

const SavePreferences = state => [
  state,
  WriteCookie({
    name: "preferences",
    value: state.preferences
    json: true
  })
]

fx.exports.DeleteCookie(props)

Describes an effect that will delete a cookie.

Kind: static method of fx

Param Type Description
props object
props.name string Name of the cookie to delete

Example

import { DeleteCookie } from "hyperapp-fx"

 const ClearPreferences = state => [
  state,
  DeleteCookie({
    name: "preferences"
  })
]

fx.exports.Debounce(props)

Describes an effect that will call an action after waiting for a delay to pass. The delay will be reset each time the action is called.

Kind: static method of fx

Param Type Description
props object
props.wait number delay to wait before calling the action
props.action * action to debounce

Example

import { Debounce } from "hyperapp-fx"

const OriginalAction = state => {
  // This action will run after waiting for 500ms since the last call
}

const DebouncedAction = state => [
  state,
  Debounce({
    wait: 500,
    action: OriginalAction
  })
]

fx.exports.Dispatch(action)

Describes an effect that will dispatch whatever action is passed to it. Useful for batching actions and FX together.

Kind: static method of fx

Param Type Description
action * an action to dispatch

Example

import { Dispatch } from "hyperapp-fx"

const BatchedFxAndActions = state => [
  state,
  SomeFx,
  Dispatch(SomeAction)
]

fx.exports.GetCurrentPosition(props)

Describes an effect that will get the current user's location using the Geolocation API and then call an action with the coordinates.

Kind: static method of fx

Param Type Description
props object
props.action * Action to call with the position
props.error * Action to call if there is a problem getting the position
props.options object An optional PositionOptions object

Example

import { GetCurrentPosition } from "hyperapp-fx"

const WhereAmI = state => [
  state,
  GetCurrentPosition({
    action(state, position) {
      console.log(position);
    },
    error(state, error) {
      // please handle your errors...
    }
  })
]

fx.exports.HistoryPush(props)

Describes an effect that will add an entry to the browsers navigation history with the supplied location and state.

Kind: static method of fx

Param Type Description
props object
props.state * data to add to browser history
props.url string url to add to browser history
props.title string title to set document to

Example

import { HistoryPush } from "hyperapp-fx"

export const UpdateHistory = state => [
  state,
  HistoryPush({
    state,
    title: document.title,
    url: '#foo'
  })
]

fx.exports.HistoryReplace(props)

Describes an effect that will replace the browsers current history navigation entry with the supplied location and state.

Kind: static method of fx

Param Type Description
props object
props.state * data to add to browser history
props.url string url to add to browser history
props.title string title to set document to

Example

import { HistoryReplace } from "hyperapp-fx"

export const InitialiseHistory = state => [
  state,
  HistoryReplace({
    state,
    title: document.title,
    url: '#foo'
  })
]

fx.exports.Http(props)

Describes an effect that will send an HTTP request using fetch and then call an action with the response. If you are using a browser from the Proterozoic Eon like Internet Explorer you will want one of the available fetch polyfills.

Kind: static method of fx

Param Type Description
props object
props.url string URL for sending HTTP request
props.options object same options as fetch
props.response string Specify which method to use on the response body, defaults to "json", other supported methods include "text"
props.action * Action to call with the results of a successful HTTP response
props.error * Action to call if there is a problem making the request or a not-ok HTTP response, defaults to the same action defined for success

Example

import { Http } from "hyperapp-fx"

const Login = state => [
  state,
  Http({
    url: "/login",
    options: {
      method: "POST",
      body: form
    },
    action(state, loginResponse) {
      // loginResponse will have the JSON-decoded response from POSTing to /login
    },
    error(state, error) {
      // please handle your errors...
    }
  })
]

fx.exports.Merge(action)

Describes an effect that will shallow-merge the results from actions that return partial state.

Kind: static method of fx

Param Type Description
action function an action function that takes state and returns a partial new state which will be shallow-merged with the previous state

Example

import { Merge } from "hyperapp-fx"

const MergingAction = state => [
  state,
  Merge(ActionReturningPartialState)
]

fx.exports.Random(props)

Describes an effect that will call an action with one or more randomly generated value(s). If provided the range for random numeric values will be [min, max) or else the default range is [0, 1). Also booleans, integers, and arrays of values are supported. The random value will be provided as the action data.

Kind: static method of fx

Param Type Description
props object
props.action * action to call with the random number result
props.min number minimum random number to generate
props.max number maximum random number to generate
props.int boolean round number to nearest integer
props.bool boolean generate a boolean instead of a number (ignores numeric options)
props.values array(object) generate an array of values (ignores other options, each object accepts same props as the root)

Example

import { Random } from "hyperapp-fx"

const RollDie = state => [
  state,
  Random({
    min: 1,
    max: 6,
    int: true,
    action: (_, roll) => {
      // roll will be an int from 1-6

      // return new state using roll
    }
  })
]

fx.exports.WriteToStorage(props)

Describes an effect that will write a key value pair to Storage. By default the item is written to localStorage, to write to sessionStorage set the storage prop to session. Values are saved in JSON, unless a custom converter is provided.

Kind: static method of fx

Param Type Description
props object
props.key string Specify key to use
props.value * Value to write to storage
props.storage string Storage area to write to, can be either "session" or "local"
props.converter function Use a custom converter function to encode the value of the item

Example

import { WriteToStorage } from "hyperapp-fx"

const SavePreferences = (state, preferences) => [
  state,
  WriteToStorage({
    key: "preferences",
    value: preferences,
    storage: "local"
  })
]

fx.exports.ReadFromStorage(props)

Describes an effect that will read the value of a key from Storage. By default the item is read from localStorage, to read from sessionStorage set the storage prop to session. Values are converted from JSON, unless a custom converter is provided.

Kind: static method of fx

Param Type Description
props object
props.key string Specify key to use with which to write to storage
props.action * Action to call with the value of the item in storage
props.storage string Storage area to read from, can be either "session" or "local"
props.prop string Property of the action where the value is received, defaults to "value"
props.converter function Use a custom converter function to decode the value of the item

Example

import { ReadFromStorage } from "hyperapp-fx"

const LoadPreferences = state => [
 state,
 ReadFromStorage({
   key: "preferences",
   action: function (state, { value }) {
     // this action will receive the value of the item in storage
   }
 })
]

fx.exports.RemoveFromStorage(props)

Describes an effect that will remove a key value pair Storage. By default the item is deleted from localStorage, to delete from sessionStorage set the storage prop to session.

Kind: static method of fx

Param Type Description
props object
props.key string Specify key to delete from storage
props.storage string Storage area to delete from, can be either "session" or "local"

Example

import { RemoveFromStorage } from "hyperapp-fx"

const ClearPreferences = state => [
 state,
 RemoveFromStorage({
   key: "preferences",
   storage: "local"
 })
]

fx.exports.Throttle(props)

Describes an effect that will call an action at a maximum rate. Where rate is one call per rate milliseconds.

Kind: static method of fx

Param Type Description
props object
props.rate number minimum time between action calls
props.action * action to throttle

Example

import { Throttle } from "hyperapp-fx"

const OriginalAction = state => {
  // This action will only run once per 500ms
}

const ThrottledAction = state => [
  state,
  Throttle({
    rate: 500,
    action: OriginalAction
  })
]

fx.exports.Now(props)

Describes an effect that provides the current timestamp (using performance.now) or current date (using new Date()). The timestamp/date will be provided as the action data.

Kind: static method of fx

Param Type Description
props object
props.asDate boolean use a Date object instead of a timestamp
props.action * action to call with the timestamp/date

Example

import { Now } from "hyperapp-fx"

const NowAction = state => [
  state,
  Now({
    asDate: true,
    action(currentDate) {
    }
  })
]

fx.exports.Delay(props)

Describes an effect that provides a timestamp (using performance.now) or date (using new Date()) after a delay. The timestamp/date will be provided as the action data.

Kind: static method of fx

Param Type Description
props object
props.wait number delay to wait before calling action
props.asDate boolean use a Date object instead of a timestamp
props.action * action to call with the timestamp/date

Example

import { Delay } from "hyperapp-fx"

const DelayedAction = state => [
  state,
  Delay({
    wait: 500,
    action() {
      // This action will run after a 500ms delay
    }
  })
]

fx.exports.WebSocketSend(props)

Describes an effect that will open a WebSocket connection for a given URL (and optional protocols) and send a message reusing existing connections.

Kind: static method of fx

Param Type Description
props object
props.url string The URL to which to connect; this should be the URL to which the WebSocket server will respond
props.protocols string | Array.<string> Either a single protocol string or an array of protocol strings. These strings are used to indicate sub-protocols, so that a single server can implement multiple WebSocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified protocol). If you don't specify a protocol string, an empty string is assumed.
props.data * data to send once connected

Example

import { WebSocketSend } from "hyperapp-fx"

 const SendAction = state => [
  state,
  WebSocketSend({
    url: "wss://example.com",
    data: JSON.stringify({
      sendThisData: "on connecting"
    })
  })
]

subs

subs.exports.Animation(action)

Describes an effect that will call an action from inside a requestAnimationFrame loop, which is also where the render triggered by the action will run. A relative timestamp will be provided as the action data.

Kind: static method of subs

Param Type Description
action * action to call inside a requestAnimationFrame loop

Example

import { h, app } from "hyperapp"
import { Animation, Merge } from "hyperapp-fx"

const UpdateTime = time => ({ time: lastTime, delta: lastDelta }) => ({
  time,
  delta: time && lastTime ? time - lastTime : lastDelta
})

const AnimationFrame = (state, time) => [
  state,
  Merge(UpdateTime(time)),
  Merge(UpdateStateForDelta),
  Merge(UpdateMoreStateForDelta),
  // ...
]

app({
  init: {
    time: 0,
    delta: 0,
    running: true
  }
  // ...
  subscriptions: ({ running }) => (running ? [Animation(AnimationFrame)] : [])
})

subs.exports.WatchPosition(props)

Describes an effect that can monitor geolocation using the Geolocation API, sending updates each time the location is updated

Kind: static method of subs

Param Type Description
props object
props.action * required action to call each time the location changes
props.error * optional action to call on error
props.options object An optional PositionOptions object

Example

import { WatchPosition } from "hyperapp-fx"

const GeoSub = WatchPosition({
  action: (state, position) => {
    state.user_location = position.coords,
  }
})

subs.exports.HistoryPop(action)

Describes an effect that will call an action whenever a user navigates through their browser history. The action will receive the state at that point in the browsers history.

Kind: static method of subs

Param Type Description
action * Action to call

Example

import { h, app } from "hyperapp"
import { HistoryPop } from "hyperapp-fx"

app({
  init: { page: 1 },
  view: state => <App page={state.page} />,
  container: document.body,
  subscriptions: state => [
    HistoryPop({ action: (state, event) => event.state || state })
  ]
})

subs.exports.Keyboard(props)

Describes an effect that can capture keydown, keyup, and keypress events for your entire document. The KeyboardEvent will be provided as the action data.

Kind: static method of subs

Param Type Description
props object
props.downs boolean listen for keydown events
props.ups boolean listen for keyup events
props.presses boolean listen for keypress events
props.action * action to call when keyboard events are fired

Example

import { Keyboard } from "hyperapp-fx"

const KeySub = Keyboard({
  downs: true,
  ups: true,
  action: (_, keyEvent) => {
    // keyEvent has the props of the KeyboardEvent
    // action will be called for keydown and keyup
  }
})

subs.exports.Interval(props)

Describes an effect that provides a timestamp (using performance.now) or date (using new Date()) at a regular interval. The timestamp/date will be provided as the action data.

Kind: static method of subs

Param Type Description
props object
props.asDate boolean use a Date object instead of a timestamp
props.every number get the time repeatedly after waiting a set interval
props.action * action to call with the timestamp/date

Example

import { h, app } from "hyperapp"
import { Now, Interval } from "hyperapp-fx"

const UpdateDate = (_, date) =>
  date.toLocaleString("uk", {
    hour: "numeric",
    minute: "numeric",
    second: "numeric"
  })

const InitialTime = Now({
  asDate: true,
  action: UpdateDate
})

const TimeSub = Interval({
  every: 100,
  asDate: true,
  action: UpdateDate
})

app({
  init: ["", InitialTime],
  view: time => <h1>{time}</h1>,
  container: document.body,
  subscriptions: () => [TimeSub]
})

subs.exports.WebSocketListen(props)

Describes an effect that will open a WebSocket connection for a given URL and optional protocols. Connections will remain open until the last subscription for that URL are cancelled.

Kind: static method of subs

Param Type Description
props object
props.url string The URL to which to connect; this should be the URL to which the WebSocket server will respond
props.protocols string | Array.<string> Either a single protocol string or an array of protocol strings. These strings are used to indicate sub-protocols, so that a single server can implement multiple WebSocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified protocol). If you don't specify a protocol string, an empty string is assumed.
props.action * action to call with new incoming messages
props.error * action to call if an error occurs
props.open * action to call when the socket is opened
props.close * action to call when the socket is closed

Example

import { WebSocketListen } from "hyperapp-fx"

const WebSocketSub = WebSocketListen({
  url: "wss://example.com",
  action: ReceivedMessageAction
})