add server- and client-side store management (#178)

This commit is contained in:
Rich Harris
2018-03-17 13:45:59 -04:00
parent 67a81a3cac
commit 9812cbd71c
8 changed files with 67 additions and 15 deletions

View File

@@ -1,10 +1,11 @@
import { detach, findAnchor, scroll_state, which } from './utils';
import { Component, ComponentConstructor, Params, Query, Route, RouteData, ScrollPosition, Target } from './interfaces';
import { Component, ComponentConstructor, Params, Query, Route, RouteData, ScrollPosition, Store, Target } from './interfaces';
const manifest = typeof window !== 'undefined' && window.__SAPPER__;
export let component: Component;
let target: Node;
let store: Store;
let routes: Route[];
let errors: { '4xx': Route, '5xx': Route };
@@ -69,6 +70,7 @@ function render(Component: ComponentConstructor, data: any, scroll: ScrollPositi
component = new Component({
target,
data,
store,
hydrate: !component
});
@@ -227,7 +229,7 @@ function handle_touchstart_mouseover(event: MouseEvent | TouchEvent) {
let inited: boolean;
export function init(_target: Node, _routes: Route[]) {
export function init(_target: Node, _routes: Route[], opts?: { store?: (data: any) => Store }) {
target = _target;
routes = _routes.filter(r => !r.error);
errors = {
@@ -235,6 +237,10 @@ export function init(_target: Node, _routes: Route[]) {
'5xx': _routes.find(r => r.error === '5xx')
};
if (opts && opts.store) {
store = opts.store(manifest.store);
}
if (!inited) { // this check makes HMR possible
window.addEventListener('click', handle_click);
window.addEventListener('popstate', handle_popstate);

View File

@@ -1,9 +1,12 @@
import { Store } from '../interfaces';
export { Store };
export type Params = Record<string, string>;
export type Query = Record<string, string | true>;
export type RouteData = { params: Params, query: Query };
export interface ComponentConstructor {
new (options: { target: Node, data: any, hydrate: boolean }): Component;
new (options: { target: Node, data: any, store: Store, hydrate: boolean }): Component;
preload: (data: { params: Params, query: Query }) => Promise<any>;
};