andrejewski / raj

The Elm Architecture for JavaScript
https://jew.ski/raj
MIT License
196 stars 8 forks source link

Create routing package #5

Closed andrejewski closed 7 years ago

andrejewski commented 7 years ago

We need a routing solution for single-page apps. Below is the husk of a router implementation. The internal router is using the method names used in rove but does not matter from a user perspective. Describing the parser argument will also be a challenge, but if we use rove we can make an arbitrary, but deterministic, mapping between user-defined messages and name strings.

raj-url-router

export default class Router {
  constructor (parser) {
    this._router = this._createRouter(parser) // TODO: the hard part
    this._isSubscribed = false
  }

  href (routeMsg) {
    return this._router.getRouteUrl(routeMsg)
  }

  subscribe (setRouteMsg, cancelMsg) {
    // TODO: throw if _isSubscribed is true
    this._isSubscribed = true

    let isDispatched = false
    return dispatch => {
      // TODO: throw if called more than once
      isDispatched = true
      this._dispatch = dispatch

      const offNavigation = this._router.onNavigation(routeMsg => {
        dispatch(setRouteMsg(routeMsg))
      })

      let isCancelled = false
      function cancel () {
        // TODO: throw if called more than once
        isCancelled = true
        this._isSubscribed = false
        offNavigation()
      }

      dispatch(cancelMsg(cancel))
      dispatch(setRouteMsg(this._router.getCurrentRoute()))
    }
  }
}
andrejewski commented 7 years ago

Closing as I think this important but not really a Raj issue, more a Raj ecosystem issue. I plan to create a package just for SPAs in Raj so I will work on this problem there.