Svelte store with a websocket backend
import websocketStore from "svelte-websocket-store";
const initialValue = { };
export const myStore = websocketStore("wss://mydomain.com/ws1", initialValue, ['option 1', 'option 2']);
// send JSON to websocket server
$myStore = { content: "to be saved", other_values: "all" };
// receive JSON from server (push)
let response = $myStore;- active
- Key
- BaseRouter
- BaseTransition
- DetailRoute
- Entitlement
- Guard
- redirectGuard
- sequenceGuard
- parallelGuard
- websocketStore
- login
- handleFailedResponse
- MasterRoute
- nullGuard
- RootRoute
- SkeletonRoute
- ValueStoreRoute
- SessionData
- msecsRequiredForRefresh
- supportedTokenTypes
- Session
- decode
- Transition
- findClosestAttribute
- dispatchNavigationEvent
- nameValueStore
- WaitingGuard
- See: {Router.updateActive}
Keeps the node active state in sync.
nodeElementrouterRouter
Keys also act as svelte stores and can be subscribed.
export const article = derived(
[articles, router.keys.article],
([$articles, $id], set) => {
set($articles.find(a => a.id === $id));
return () => {};
}
);Type: Object
Extends BaseTransition
key subscriptions:
const aKey = router.keys.aKey;
$aKey // fired if value of aKey changesroutesArray<Route> all managed routesbasestring url (optional, defaultnew URL("../",import.meta.url).pathname)
linkNodesSet<Node> nodes having their active state updatedroutesArray<Route>keysObject collected keys of all routesparamsObject value mapping from keys (from current route)routeRoute currentnestedTransition ongoing nested transitionbasestring url
Current component. Either from a nested transition or from the current route
Returns SvelteComponent
Value if the current route
Returns any
Returns string url path with fragment & query
Replace current route.
pathstring
Replace current route without updating the state.
pathstring
Returns Object former state
Leave current route and enter route for given path. The work is done by a Transition.
pathstring where to go
Returns Transition running transition
Called from a Transition to manifest the new destination. If path is undefined the Transition has been aborderd.
pathstring
Continue a transition to its original destination. Shortcut for this.transition.continue(). If there is no transition ongoing and a fallbackPath is present, it will be entered. Otherwise does nothing.
fallbackPathstring
Abort a transition. Shortcut for this.transition.abort() If there is no transition ongoing and a fallbackPath is present it will be entered. Otherwise does nothing.
fallbackPathstring
Router subscription. Changes in the current route will trigger a update
subscriptionFunction
Update the active state of a node. A node is considered active if it shared the path prefix with the current route.
nodeElement
Add a new Route.
routeRoute
Find Route for a given value.
valueany
Returns Route able to support given value
Find path for a given value.
valueanysuffixstring to be appended
Returns string path + suffix
Deliver url search params form the current location.
Returns URLSearchParams as extracted from the path
Replaces the search part of the path with the given searchParams.
searchParams(URLSearchParams | Object)
Add another transition nesting level. Starts a transition from the given factory.
pathstringfactoryTransition
Continue a nested route to its original destination. Does nothing if the transition has not been nested.
Abort the transition.
error
Returns Promise<boolean> truen in case there was a nesten transition
Extends ValueStoreRoute
Route to represent a slice of the masters list of values.
masterRoute route holding the master records
Route holding the list ov values
Returns Route our master
Returns Promise<any> 1st. entry
Returns any last entry
Returns any previous value
Returns Promise<any> next value
Enforces conditions of routes Like the presents of values in the context
Called while entering a route (current outlet is not yet set)
transitionTransition
Called before leaving a route
transitionTransition
Redirects to a given path if condition is met.
Execute guards in a sequence.
childrenIterable<Guard>
Execute guards in a parallel.
childrenIterable<Guard>
Create a writable store based on a web-socket. Data is transferred as JSON. Keeps socket open (reopens if closed) as long as there are subscriptions.
urlstring the WebSocket urlinitialValueany store value used before 1st. response from server is presentsocketOptionsArray<string> transparently passed to the WebSocket constructor
Returns Store
Bring session into the valid state by calling the authorization endpoint and asking for a access_token. Executes a POST on the endpoint url expecting username, and password as json
sessionSession to be openedendpointstring authorization urlusernamestring id of the userpasswordstring user credentialstokenmapObject token names in response to internal known values (optional, defaultdefaultTokenMap)
Returns Promise<(string | undefined)> error message in case of failure or undefined on success
Extract error description from response.
responseResponse
Extends SkeletonRoute
Route holding a ordered collection of values.
pathoptions
valueArray<any>
Default empty guard does nothing.
Route at the root of the tree. This route has no parent. All other routes are below of this one.
Are there parameters in the path.
Returns boolean true if route has parameters (:key)
Returns string empty as we are the root
Returns Object empty object
Returns Guard empty guard which does nothing
Extends RootRoute
Route Subscriptions on Routes fire when the route value changes.
pathoptions(optional, default{})
pathstring full path of the Route including all parentscomponentSvelteComponent target to showlinkComponentSvelteComponent content for ObjectLinkpropertyMappingObject Map properties to object attributes Keys are the property names and values are the keys in the resulting object.prioritynumberkeysArray<string> as found in the pathregexRegExvalueany
Enter the route from a former one. All parent routes up to the common ancestor are entered first.
transitionTransitionuntilRouteRoute the common ancestor with the former route
Leave the route to a new one. All parent routes up to the common ancestor are left.
transitionTransitionuntilRouteRoute the common ancestor with the future route
Check if value and properties are acceptable for the route.
valueany to be placed into routepropertiesObject as presented in the route
Returns boolean true if value can be accepted
Extract properties from a value. All property values must be strings.
valueany source of the properties
Returns (Object | undefined) properties extracted from given value
Find common ancestor with an other Route.
otherRoute
Returns (Route | undefined) common ancestor Route between receiver and other
Deliver value for a given set of properties of the transition. Default implemantation asks the parent route.
transitionTransition
Returns any for matching properties
Deliver route value. Default implemantation asks the parent route.
Returns any
Deliver property mapping. Default implemantation asks the parent route.
Returns Object for matching properties
Default implemantation asks the parent route.
Extends SkeletonRoute
Route holding a single value
Data as preserved in the backing store.
Type: Object
Time required to execute a refresh
Type: number
User session. To create as session backed by browser local storage.
let session = new Session(localStorage);or by browser session storage
let session = new Session(sessionStorage);storeSessionData (optional, defaultlocalStorage)
entitlementsSet<string>subscriptionsSet<Object> store subscriptionsexpirationDateDate when the access token expiresaccess_tokenstring token itselfrefresh_tokenstring refresh token
Consume auth response data and reflect internal state.
dataObject
Refresh with refresh_token.
Returns Promise<boolean> true if refresh was succcessfull false otherwise
Http header suitable for fetch.
Returns Object header The http header.
Returns string header.Authorization The Bearer access token.
As long as the expirationTimer is running we must be valid.
Returns boolean true if session is valid (not expired)
Remove all tokens from the session and the backing store.
Check presence of an entitlement.
namestring of the entitlement
Returns boolean true if the named entitlement is present
Fired when the session changes.
subscriptionFunction
Extract and decode the payload.
tokenstring
Returns Object payload object
Extends BaseTransition
Transition between routes.
routerRouterpathstring new destination
routerRouterpathstring new destination
Start the transition
- leave old route
- find matching target route @see matcher()
- enter new route
- set params
- set current route
- See: Router.finalizePush
Cleanup transition. Update Nodes active state
Halt current transition and go to another route. To proceed with the original route call continue() The original transition will keept in place and can be continued afterwards.
pathstring new route to enter temporary
Bring back the router into the state before the transition has started. All nested transitions also will be termniated.
e(Exception | undefined)
Walks up the dom tree parents unti a node with a given attribute is found or the root node is reached.
Dispatches a NAVIGATION_EVENT with pathname and hash
eventEvent
Create a named object which also acts as a store.
namestringvalueany initial value
valueany
Returns Store
Extends Guard
Shows a component during transition.
componentSvelteComponent to show up during th transitionrampUpTimenumber initial delay for the componnt to show up (optional, default300)
With npm do:
npm install svelte-websocket-storeWith yarn do:
yarn add svelte-websocket-storeexport BROWSER=safari|chrome|...
npm|yarn testBSD-2-Clause