├── .babelrc ├── .editorconfig ├── .gitignore ├── .prettierrc ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── rollup.config.js ├── src ├── mobx-location.js └── mobx-location.spec.js └── test ├── e2e.js ├── index.html └── spec-bundle.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["@babel/preset-env"] 3 | } 4 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 2 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # nyc test coverage 18 | .nyc_output 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # node-waf configuration 24 | .lock-wscript 25 | 26 | # Compiled binary addons (http://nodejs.org/api/addons.html) 27 | build/Release 28 | 29 | # Dependency directories 30 | node_modules 31 | jspm_packages 32 | .cache 33 | 34 | # Optional npm cache directory 35 | .npm 36 | 37 | # Optional REPL history 38 | .node_repl_history 39 | dist -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": false, 3 | "singleQuote": true, 4 | "arrowParens": "always" 5 | } 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Jiri Spac 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mobx-location 2 | 3 | a browser location as a mobx observable. Minimal wrapper around browser history utilizing popstate event and HTML5 history api. Package [history-events](https://github.com/xpepermint/history-events) is used for monkeypatching. 4 | 5 | Prime usage is in your mobx observers. You can directly access the location and your app will rerender itself without the need for react-router or similar solution. 6 | 7 | ```javascript 8 | import makeMobxLocation from './mobx-location' 9 | import { autorun, toJS } from 'mobx' 10 | 11 | const mobxLocation = makeMobxLocation({ hashHistory: false }) // default 12 | const mobxLocation = makeMobxLocation({ hashHistory: true }) // when you use hash history instead of html5 history APIs 13 | 14 | const mobxLocation = makeMobxLocation({ arrayFormat: 'bracket' }) // default 15 | const mobxLocation = makeMobxLocation({ arrayFormat: 'index' }) // will index array params in the url, refer to https://www.npmjs.com/package/query-string#arrayformat 16 | 17 | autorun(() => { 18 | toJS(mobxLocation) // runs every time browser location changes 19 | }) 20 | ``` 21 | 22 | location has all the standard properties: 23 | 24 | ``` 25 | hash 26 | host 27 | hostname 28 | href 29 | origin 30 | pathname 31 | port 32 | protocol 33 | search 34 | ``` 35 | 36 | plus one extra- `query`. Query is just parsed `location.search`. Query is always there even if no search params are in your location. 37 | 38 | If you modify the query object, it will propagate back to the window location so you don't have to construct the search params yourself when modifying. 39 | Keep in mind that any newly added property in `query` won't be picked up-you must use `set` from `import {set} from 'mobx'` to set new props. 40 | 41 | ## Browser support 42 | 43 | same as html5 history api-so with that shim even IE9 44 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mobx-location", 3 | "version": "0.6.5", 4 | "description": "minimal observable wrapper around browser location utilizing popstate event of HTML5 history api", 5 | "module": "dist/mobx-location.es.js", 6 | "main": "dist/mobx-location.cjs.js", 7 | "scripts": { 8 | "build": "rollup -c", 9 | "test": "node test/e2e.js", 10 | "e2e": "cd test && parcel index.html", 11 | "prepare": "npm run build" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "git+https://github.com/capaj/mobx-location.git" 16 | }, 17 | "keywords": [ 18 | "html5", 19 | "location", 20 | "history" 21 | ], 22 | "author": "capajj@gmail.com", 23 | "license": "MIT", 24 | "bugs": { 25 | "url": "https://github.com/capaj/mobx-location/issues" 26 | }, 27 | "homepage": "https://github.com/capaj/mobx-location#readme", 28 | "peerDependencies": { 29 | "mobx": "^4" 30 | }, 31 | "devDependencies": { 32 | "@babel/cli": "^7.1.2", 33 | "@babel/core": "^7.1.2", 34 | "@babel/preset-env": "^7.1.0", 35 | "mobx": "^4.5.0", 36 | "parcel-bundler": "^1.10.1", 37 | "puppeteer": "^1.8.0", 38 | "rollup": "^0.66.2", 39 | "rollup-plugin-babel": "^4.0.3" 40 | }, 41 | "dependencies": { 42 | "history-events": "^1.0.4", 43 | "query-string": "^6.2.0" 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import babel from 'rollup-plugin-babel' 2 | 3 | export default { 4 | input: 'src/mobx-location.js', 5 | plugins: [babel()], 6 | output: [ 7 | { file: 'dist/mobx-location.cjs.js', format: 'cjs' }, 8 | { file: 'dist/mobx-location.es.js', format: 'es' } 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /src/mobx-location.js: -------------------------------------------------------------------------------- 1 | import { set, observable, action, autorun, toJS, observe } from 'mobx' 2 | import queryString from 'query-string' 3 | import 'history-events' 4 | 5 | const propsToMirror = [ 6 | 'hash', 7 | 'host', 8 | 'hostname', 9 | 'href', 10 | 'origin', 11 | 'pathname', 12 | 'port', 13 | 'protocol', 14 | 'search' 15 | ] 16 | const { location } = window 17 | 18 | export default ({ hashHistory, arrayFormat = 'bracket' }) => { 19 | const createSnapshot = (previousQuery) => { 20 | const snapshot = propsToMirror.reduce((snapshot, prop) => { 21 | snapshot[prop] = location[prop] 22 | return snapshot 23 | }, {}) 24 | let q 25 | 26 | if (hashHistory) { 27 | q = queryString.parse(snapshot.hash.split('?')[1], { arrayFormat }) 28 | } else { 29 | q = queryString.parse(snapshot.search, { arrayFormat }) 30 | } 31 | 32 | snapshot.query = q || {} 33 | 34 | return snapshot 35 | } 36 | 37 | const firstSnapshot = createSnapshot() 38 | const locationObservable = observable(firstSnapshot) 39 | 40 | /** 41 | * executes each time a mobxLocation.query is mutated 42 | */ 43 | const propagateQueryToLocationSearch = () => { 44 | const queryInObservable = queryString.stringify( 45 | toJS(locationObservable.query), 46 | { encode: false, arrayFormat } 47 | ) 48 | // console.log('currentlyInObservable: ', currentlyInObservable) 49 | const { search, protocol, host, pathname, hash } = location 50 | let qs = search 51 | 52 | const hashParts = hash.split('?') 53 | if (hashHistory && hash.includes('?')) { 54 | qs = hashParts[1] 55 | } 56 | if (!qs && !queryInObservable) { 57 | return 58 | } 59 | if (decodeURI(qs) === queryInObservable) { 60 | return 61 | } 62 | if (qs !== queryInObservable) { 63 | let newUrl = protocol + '//' + host + pathname 64 | if (hashHistory) { 65 | const newHash = hashParts[0] + '?' + queryInObservable 66 | 67 | locationObservable.hash = newHash 68 | newUrl += newHash 69 | } else { 70 | const newSearch = '?' + queryInObservable + hash 71 | 72 | locationObservable.search = newSearch 73 | newUrl += newSearch 74 | } 75 | locationObservable.href = newUrl 76 | 77 | window.removeEventListener('changestate', snapshotAndSet) 78 | // console.log('newUrl: ', newUrl) 79 | history.replaceState(null, '', newUrl) 80 | window.addEventListener('changestate', snapshotAndSet) 81 | } 82 | } 83 | 84 | let unsubscribe = autorun(propagateQueryToLocationSearch) 85 | 86 | const snapshotAndSet = action('changestateHandler', (ev) => { 87 | const snapshot = createSnapshot(toJS(locationObservable.query)) 88 | const currentlyInObservable = toJS(locationObservable) 89 | //unfortunately we need to check that the new snapshot is different-for example when integrating with angularjs it happens that angular router is setting a URL again after we changed it via interacting with observable 90 | 91 | if ( 92 | snapshot.href !== currentlyInObservable && 93 | decodeURI(snapshot.href) !== locationObservable.href 94 | ) { 95 | set(locationObservable, snapshot) 96 | } 97 | }) 98 | 99 | observe(locationObservable, (change) => { 100 | const { name } = change 101 | if (name === 'query') { 102 | return // we ignore these 103 | } 104 | if (location[change.name] !== change.newValue) { 105 | const { search, protocol, host, pathname, hash } = locationObservable 106 | const newUrl = protocol + '//' + host + pathname + search + hash 107 | window.removeEventListener('changestate', snapshotAndSet) 108 | if (change.name === 'search') { 109 | unsubscribe() 110 | 111 | locationObservable.query = queryString.parse(change.newValue, { 112 | arrayFormat 113 | }) 114 | unsubscribe = autorun(propagateQueryToLocationSearch) 115 | } 116 | history.pushState(null, '', newUrl) 117 | window.addEventListener('changestate', snapshotAndSet) 118 | } 119 | }) 120 | 121 | window.addEventListener('changestate', snapshotAndSet) 122 | 123 | return locationObservable 124 | } 125 | -------------------------------------------------------------------------------- /src/mobx-location.spec.js: -------------------------------------------------------------------------------- 1 | import test from 'ava' 2 | import location from './mobx-location' 3 | import { autorun, toJS } from 'mobx' 4 | // import jsdom from 'jsdom' 5 | 6 | test('it reacts to popstate', t => { 7 | let c = 0 8 | autorun(() => { 9 | toJS(location) 10 | c++ 11 | }) 12 | window.location.hash = '#somehash' 13 | // window.location.href = 14 | // jsdom.changeURL(window, 'https://example.com/#someHash') 15 | window.eventHandlers.forEach(cb => cb()) // jsdom is lame, it doesn't trigger popstate event 16 | 17 | t.is(c, 2) 18 | }) 19 | 20 | test('it has query object', t => { 21 | // jsdom.changeURL(window, 'http://localhost:3003/?redirect=no') 22 | console.log('window.location.search: ', window.location.search) 23 | window.location.search = `?redirect=no` 24 | console.log('window.location.search: ', window.location.search) 25 | window.eventHandlers.forEach(cb => cb()) 26 | t.is(location.query.redirect, 'no') 27 | 28 | // jsdom.changeURL(window, 'http://localhost:3003/?other=1') 29 | window.location.search = `?other=1` 30 | 31 | window.eventHandlers.forEach(cb => cb()) 32 | 33 | t.is(location.query.redirect, undefined) 34 | t.is(location.query.other, '1') 35 | }) 36 | 37 | test('it changes query when we change the observable', t => {}) 38 | -------------------------------------------------------------------------------- /test/e2e.js: -------------------------------------------------------------------------------- 1 | const puppeteer = require('puppeteer') 2 | const Bundler = require('parcel-bundler') 3 | const bundler = new Bundler('test/index.html') 4 | ;(async () => { 5 | const server = await bundler.serve(4051) 6 | const browser = await puppeteer.launch() 7 | const page = await browser.newPage() 8 | 9 | page.on('console', msg => { 10 | console.log(msg._text) 11 | }) 12 | 13 | const exit = async code => { 14 | bundler.stop() 15 | await browser.close() 16 | process.exit(code) 17 | } 18 | await page.goto('http://localhost:4051/?someQuery=1') 19 | 20 | // Get the "viewport" of the page, as reported by the page. 21 | const tests = await page.evaluate(() => { 22 | const { query } = mobxLocation 23 | const initial = query.someQuery === '1' 24 | 25 | history.pushState(null, null, '?someQuery=2') 26 | const secondAssert = query.someQuery === '2' 27 | console.log('bb', JSON.stringify(query), location.search) 28 | 29 | query.someQuery = 3 30 | console.log('aaa', JSON.stringify(query)) 31 | const thirdAssert = query.someQuery === 3 32 | 33 | return [initial, secondAssert, thirdAssert] 34 | }) 35 | await Promise.all( 36 | tests.map(async (testResult, index) => { 37 | if (!testResult) { 38 | console.error(`a test ${index + 1} failed`) 39 | await exit(1) 40 | } 41 | }) 42 | ) 43 | 44 | console.log('test passed') 45 | await exit() 46 | })() 47 | -------------------------------------------------------------------------------- /test/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | mobx-location 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /test/spec-bundle.js: -------------------------------------------------------------------------------- 1 | import makeMobxLocation from '../src/mobx-location' 2 | import { set, autorun, toJS } from 'mobx' 3 | 4 | window.mobxLocation = makeMobxLocation({ hashHistory: false }) 5 | // mobxLocation.hash = '#/aagg' 6 | // set(mobxLocation.query, { foo: new Date().toISOString() }) 7 | 8 | // autorun(() => { 9 | // console.log('autorun', toJS(mobxLocation)) 10 | // }) 11 | --------------------------------------------------------------------------------