respond to browser hash to show markdown/plaintext view

This commit is contained in:
Adam Brown 2017-02-05 13:36:10 -05:00
parent 368d19dd21
commit c633afa184
2 changed files with 46 additions and 1 deletions

View File

@ -12,6 +12,8 @@ import thunk from 'redux-thunk'
import * as reducers from '../common/reducers'
import routes from '../common/routes'
import {Format} from '../common/constants'
import * as Actions from '../common/actions'
import LocalStorage from './LocalStorage'
@ -29,6 +31,48 @@ const store = Redux.createStore(
)
)
render()
// read and init the hash after render:
// because this parameter is passed as a hash, it isn't available on the server,
// so the server initial render will be with plaintext, so we have to start with that.
// lame.
initFormatHash(store)
registerFormatListener(store)
// detect hash parameter for markdown/plaintext format and initialize store
function initFormatHash(store) {
// get the has from the window location
let hash = window.location.hash.toUpperCase()
// strip the hash sign
hash = hash.substring(1)
// dispatch the appropriate action
if (hash === Format.MARKDOWN)
store.dispatch(Actions.setMarkdownFormat())
else if (hash === Format.PLAINTEXT || hash === '')
store.dispatch(Actions.setPlaintextFormat())
}
// listen to changes in the redux store and update the url hash parameter when appropriate
function registerFormatListener(store) {
function handleChange() {
let nextFormat = store.getState().format;
if (nextFormat === Format.MARKDOWN)
window.history.replaceState("", document.title, window.location.pathname+"#"+nextFormat);
else if (nextFormat === Format.PLAINTEXT) {
window.history.replaceState("", document.title, window.location.pathname);
}
}
let unsubscribe = store.subscribe(handleChange);
return unsubscribe;
}
function render () {
ReactDOM.render(
<Provider store={store}>
@ -41,5 +85,4 @@ function render () {
, document.getElementById('root'))
}
render()

View File

@ -5,6 +5,8 @@ import {Segment, Grid} from 'semantic-ui-react'
import * as Selectors from '../selectors'
import {Format} from '../constants'
import Header from './Header'
import Footer from './Footer'
import CompareControls from './CompareControls'