Allows to synchronize shareable key-value state to the window.location.hash
in a format as human-readable as possible.
It serializes and parses the following very simple form of state (TypeScript notation):
{ [key: string]: string[] }
For example the following state:
{
foo: [ 'bar' ],
baz: [ 'qux', 'gorge' ]
}
would be serialized as #!foo:bar/baz:qux,gorge
and vice versa.
Start by creating a HashStateManager
instance:
const hsm = new HashStateManager
If you, for whatever reason, want to create a manager for a different window, you can pass that to the constructor:
const hsm = new HashStateManager({ global: window.parent })
By default, the manager reacts to hashes of the form #!...
. However, you can change the !
prefix to anything you want:
const hsm = new HashStateManager({ prefix: '+' })
If you stop using the hash state manager, you can destroy
it to revert side effects it caused:
hsm.destroy()
Check if any state is available:
hsm.has()
// #!foo:bar -> true
// #foo -> false
Check if a certain key is set:
hsm.has('baz')
// #!foo:bar/baz:qux -> true
// #!foo:bar -> false
Check if a key contains a certain value:
hsm.has('foo', 'bar')
// #!foo:bar -> true
// #!foo:bar,baz -> true
// #!foo:qux -> false
Get the value of a key:
hsm.get('foo')
// #!foo:bar -> [ 'bar' ]
Get the state as a whole:
hsm.get()
// #!foo:bar/baz:qux,gorge -> { foo: [ 'bar' ], baz: [ 'qux', 'gorge' ] }
// #! -> {}
Set the state as a whole:
hsm.set({ bar: [ 'baz' ] })
// #!bar:baz
Set one property:
hsm.set({ foo: [ 'grault' ] })
// #!foo:bar/baz:qux -> #!foo:grault/baz:qux
hsm.set({ foo: [] })
// #!foo:bar/baz:qux -> #!baz:qux
Add value to a property:
hsm.add('foo', 'baz')
// #! -> #!foo:baz
// #!foo:bar -> #!foo:bar,baz
// #!foo:bar,baz -> #!foo:bar,baz
Remove value from a property:
hsm.remove('foo', 'baz')
// #!foo:bar,baz -> #!foo:bar
// #!foo:baz -> #!
// #!foo:bar -> #!foo:bar
Remove a whole property:
hsm.remove('foo')
// #!foo:bar,baz -> #!
Be notified when the state changes:
hsm.onChange((newState, oldState) => { ... })
Stop listening to changes:
const unwatch = hsm.onChange((newState, oldState) => { ... })
unwatch()