History and Location Proxies

This commit is contained in:
Timothy Farrell 2017-01-31 16:17:58 -06:00
parent 8bd0937988
commit f01c2fa2f3
2 changed files with 53 additions and 0 deletions

View File

@ -0,0 +1,19 @@
export function history(onChange) {
const methods = 'pushState replaceState go back forward'.split(' ');
return new Proxy(
{},
{
get(target, name) {
if (methods.includes(name)) {
return (...args) => onChange([6, 'history', name, args]);
}
// return undefined;
}
set(target, name, value) {
throw new Error(`Cannot set ${name} on history.`);
}
}
);
}

View File

@ -0,0 +1,34 @@
// Heavily modified from Preact Worker Demo - https://github.com/developit/preact-worker-demo
// Copyright (c) 2016 Jason Miller
// License: MIT
export function Location(onChange) {
const settables = 'href hash search pathname';
let url = '/';
return new Proxy(
{
_current: '/',
get href() {
return url;
},
get pathname() {
return url.replace(/^(([a-z0-9]+\:)?\/\/[^/]+|[?#].*$)/g, '');
},
get search() {
return (url.match(/\?([^#]*)(#.*)?$/) || [])[1];
},
get hash() {
return (url.match(/#(.*)$/) || [])[1];
}
},
{
set(target, name, value) {
if (settables.includes(name)) {
return (...args) => onChange([5, 'location', name, value]);
}
throw new Error(`Cannot set location.${name}.`);
}
}
);
}