Home

Awesome

Introduction

This driver help you manage browser history and receive Location.

Concepts

Location represents a url with related state.

interface Location {
  host: string,
  protocol: string,
  path: string,
  canonicalPath: string, // path without baseName
  hash?: string,
  baseName?: string,
  state?: any,
  queryString?: {
    [name: string]: string
  }
}

Action represents a history operation:

enum Action {
  push,
  replace,
  forward,
  back
}

User uses Directive to controls history behavior.
location is optional,
because not all action needs it.
such as back action.

interface Directive {
  location?: Location,
  action: Action
}

Driver sends a Context to your data component when history changed.

interface Context {
  name?: string,
  location: Location,
  args?: {
    [name: string]: string
  }
}

Finally, driver accepts an optional Option to initialization.

interface Option {
  hash?: boolean,
  baseName?: string,
  click?: boolean,
  patterns?: {
    [name: string]: string
  }
}

Detail of option:

Driver exports

Main function

function makePageDriver(option : Option) : (directive$ : Stream<Directive>) => Stream<Context>

and Action constant...

const action = {
  push: "PUSH",
  replace: "REPLACE",
  forward: "FORWARD",
  back: "BACK"
}

Work with path arguments.

please see path-to-regexp#parameters !

Examples

Send initial Directive.

import {run} from "@cycle/xstream-run"
import {makePageDriver, Action} from "cycle-page"
import xstream from "xstream"

function main() {
  return {
    page: xstream.of({
      action: Action.push,
      location: {
        path: "/"
      }
    })
  }
}

run(main, {
  page: makePageDriver({
    hash: true
  })
})

Show component by url.

import {run} from "@cycle/xstream-run"
import {makePageDriver, Action} from "cycle-page"
import xstream from "xstream"
import {makeDOMDriver, div} from "@cycle/dom"

function main({ dom, page }) {
  return {
    dom: page.map(context => {
      // name will be matched pattern's name defined in option.
      switch (context.name) {
        case "index": return div("index")
        case "userDetail": return div(`Hello ${context.args.id}`)
        default: return div("404")
      }
    }),
    page: xstream.of({
      action: Action.push,
      location: {
        path: "/"
      }
    })
  }
}

run(main, {
  dom: makeDOMDriver(document.body),
  page: makePageDriver({
    patterns: {
      userDetail: "/users/:id",
      index: "/"
    }
  })
})

Redirection

import {run} from "@cycle/xstream-run"
import {makePageDriver, Action} from "cycle-page"
import xstream from "xstream"

function main() {
  return {
    page: xstream.of({
      action: Action.push,
      location: {
        protocol: 'https',
        host: 'www.google.com',
        queryString: {
          q: 'cycle.js'
        }
      }
    })
  }
}

run(main, {
  page: makePageDriver()
})