histore / historee / historey / histoire
by karlhorky
HTML
<script>
function histore() {
let get = key => history.state && history.state[key];
let set = (key, value) => {
let state = {};
state[key] = value;
history.replaceState(state);
};
let wrap = m => (state, title, url) => (
m.call(history, Object.assign({}, history.state, state || {}), title, url)
);
history.pushState = wrap(history.pushState);
history.replaceState = wrap(history.replaceState);
return { set, get };
}
function a(){
let histoire = histore()
histoire.set('foo', { bar: 1 });
histoire.set('bar', 'baz');
alert(histoire.get('foo')) alert(histoire.get('bar'));
history.pushState(null, null, '/');
alert(histoire.get('foo')) alert(histoire.get('bar'));
history.back();
alert(histoire.get('foo')) alert(histoire.get('bar'));
}
</script>
<button onclick="let histoire = histore()
histoire.set('foo', { bar: 1 });
histoire.set('bar', 'baz');
alert(histoire.get('foo')) alert(histoire.get('bar'));
history.pushState(null, null, '/');
alert(histoire.get('foo')) alert(histoire.get('bar'));
history.back();
alert(histoire.get('foo')) alert(histoire.get('bar'));">open your console 🌹</h4>
CSS
html, body {
height: 100%;
display: flex;
justify-content: center;
align-items: center;
font: 16px/1.3 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #333;
background: #eee;
}
h4 {
font-weight: 300;
font-size: 8vw;
text-shadow: 0 1px 0 #fff;
}
Babel + JSX
function histore() {
let get = key => history.state && history.state[key];
let set = (key, value) => {
let state = {};
state[key] = value;
history.replaceState(state);
};
let wrap = m => (state, title, url) => (
m.call(history, Object.assign({}, history.state, state || {}), title, url)
);
history.pushState = wrap(history.pushState);
history.replaceState = wrap(history.replaceState);
return { set, get };
}
let histoire = histore()
histoire.set('foo', { bar: 1 });
histoire.set('bar', 'baz');
alert(histoire.get('foo')) alert(histoire.get('bar'));
history.pushState(null, null, '/');
alert(histoire.get('foo')) alert(histoire.get('bar'));
history.back();
alert(histoire.get('foo')) alert(histoire.get('bar'));