diff --git a/README.md b/README.md index da89fa0..719dc02 100644 --- a/README.md +++ b/README.md @@ -655,6 +655,10 @@ following values: - __opts.href:__ default: `true`. Handle all relative `` clicks and update internal `state.location` accordingly. +- __opts.hash:__ default: `false`. Enable a `subscription` to the hash change + event, updating the internal `state.location` state whenever the URL hash + changes (eg `localhost/#posts/123`). Enabling this option automatically + disables `opts.history` and `opts.href`. ## Errors ### Could not find DOM node (#id) to update diff --git a/index.js b/index.js index c19c0bd..473f81e 100644 --- a/index.js +++ b/index.js @@ -2,6 +2,8 @@ const history = require('sheet-router/history') const sheetRouter = require('sheet-router') const document = require('global/document') const href = require('sheet-router/href') +const hash = require('sheet-router/hash') +const hashMatch = require('hash-match') const sendAction = require('send-action') const mutate = require('xtend/mutable') const assert = require('assert') @@ -190,9 +192,13 @@ function choo () { // initial application state model // obj -> obj function appInit (opts) { + const initialLocation = (opts.hash === true) + ? hashMatch(document.location.hash) + : document.location.href + const model = { namespace: 'app', - state: { location: document.location.href }, + state: { location: initialLocation }, subscriptions: [], reducers: { // handle href links @@ -204,10 +210,19 @@ function appInit (opts) { } } - // enable catching links - // enable HTML5 history API - if (opts.href !== false) pushLocationSub(href) - if (opts.history !== false) pushLocationSub(history) + // if hash routing explicitly enabled, subscribe to it + if (opts.hash === true) { + pushLocationSub(function (navigate) { + hash(function (fragment) { + navigate(hashMatch(fragment)) + }) + }) + // otherwise, subscribe to HTML5 history API + } else { + if (opts.history !== false) pushLocationSub(history) + // enable catching links + if (opts.href !== false) pushLocationSub(href) + } return model diff --git a/package.json b/package.json index cf7f1cb..45e6579 100644 --- a/package.json +++ b/package.json @@ -20,8 +20,9 @@ "license": "MIT", "dependencies": { "global": "^4.3.0", + "hash-match": "^1.0.2", "send-action": "^1.1.0", - "sheet-router": "^3.0.0", + "sheet-router": "^3.1.0", "xhr": "^2.2.0", "xtend": "^4.0.1", "yo-yo": "^1.2.0"