Skip to content

Instantly share code, notes, and snippets.

@davismj
Last active December 19, 2017 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save davismj/6d5306655aaa6152863bcc5f6f0efb1e to your computer and use it in GitHub Desktop.
Save davismj/6d5306655aaa6152863bcc5f6f0efb1e to your computer and use it in GitHub Desktop.

aurelia-store

CircleCI

Aurelia single state store based on RxJS

THIS IS WORK IN PROGRESS, DO NOT USE YET FOR PRODUCTION

Install

Install the npm dependency via

npm install aurelia-store rxjs

[Matt] shouldn't it declare an explicit dependency on rxjs so you don't have to install it separately?

Aurelia CLI Support

If your Aurelia CLI build is based on RequireJS or SystemJS you can setup the plugin using the following dependency declaration:

...
"dependencies": [
  {
    "name": "aurelia-store",
    "path": "../node_modules/aurelia-store/dist/amd",
    "main": "aurelia-store"
  },
  {
    "name": "rxjs",
    "path": "../node_modules/rxjs",
    "main": false
  }
]

Configuration

In your main.ts you'll have to register the Store using a custom entity as your State type:

import {Aurelia} from 'aurelia-framework'
import environment from './environment'; // [Matt] remove this I think

export interface State {
  frameworks: string[];
}

export function configure(aurelia: Aurelia) {
  aurelia.use
    .standardConfiguration()
    .feature('resources');

  ...

  // [Matt] In general, wouldn't you want to keep your state in a separate file? I would demonstrate that here.
  const initialState: State = {
    frameworks: ["Aurelia", "React", "Angular"]
  };

  aurelia.use.plugin("aurelia-store", initialState);  // <----- REGISTER THE PLUGIN

  aurelia.start().then(() => aurelia.setRoot());
}

Usage

Once the plugin is installed and configured you can use the Store by injecting it via constructor injection.

You register actions (reducers) by with methods which get the current state and have to return the modified next state.

An example VM and View can be seen below:

import { autoinject } from 'aurelia-dependency-injection';
import { State } from './state';
import { Store } from "aurelia-store";

const demoAction = (state: State) => {

  // [Matt] I feel like there's a lot of repeated code here? It would be nice if somehow the plugin would handle this for you. 
  // Perhaps instead of returning, you modify the state in place and the plugin makes the copies, etc. Or perhapas if there is
  // a valid use case for wanting to pass a completely new object, then if return is undefined it makes a copy of the current state.

  const newState = Object.assign({}, state);
  newState.frameworks.push("PustekuchenJS");

  return newState;
}

// [Matt] maybe it would be cool if you could do this instead
const demoAction = function demoAction(state: state) {
  state.frameworks.push("PustekuchenJS");
};
// [Matt] Or this
const demoAction = function demoAction(state: state) {
  return {
    frameworks: Object.freeze(['Aurelia'])
  }
}


@autoinject()
export class App {

  public state: State;

  constructor(private store: Store<State>) {
    this.store.registerAction("DemoAction", demoAction); // No idea what this does!

    // [Matt] Maybe this is a bit too contrived. Maybe make it an actual callback from an event delegated by the view?
    setTimeout(() => this.store.dispatch(demoAction), 2000);
  }
  
  // [Matt] It seems that all events need to be delegated by the store, so maybe an API like this would be nice.
  @dispatch
  demoAction(state: State) {
    state.frameworks.push("PustekuchenJS");
  }

  attached() {
    // this is the single point of data subscription, the state inside the component will be automatically updated
    // no need to take care of manually handling that. This will also update all subcomponents
    
    // [Matt] Is this something else that the plugin can handle? 
    this.store.state.subscribe(
      (state: State) => this.state = state
    );
    
    // [Matt] For example, is there a reason I wouldn't want to do this and have it "just work"
    this.state = this.store.state;
  }
}
<template>
  <h1>Frameworks</h1>

  <ul>
    <li repeat.for="framework of state.frameworks">${framework}</li>
  </ul>
</template>

Passing parameters to actions

You can provide parameters to your actions by adding them after the initial state parameter. When dispatching provide your values which will be spread to the actual reducer.

// additional parameter
const greetingAction = (state: State, greetingTarget: string) => {
  const newState = Object.assign({}, state);
  newState.target = greetingTarget;

  return newState;
}

...

// dispatching with the value for greetingTarget
this.store.dispatch(greetingAction, "zewa666");

Undo / Redo support

If you need to keep track of the history of states you can pass a third parameter to the Store initialization with the value of true to setup the store to work on a StateHistory vs State model.

export function configure(aurelia: Aurelia) {
  aurelia.use
    .standardConfiguration()
    .feature('resources');

  ...

  const initialState: State = {
    frameworks: ["Aurelia", "React", "Angular"]
  };

  aurelia.use.plugin("aurelia-store", initialState, true);  // <----- REGISTER THE PLUGIN WITH HISTORY SUPPORT

  aurelia.start().then(() => aurelia.setRoot());
}

Now when you subscribe to new state changes instead of a simple State you'll get a StateHistory object returned:

attached() {
  this.store.state.subscribe(
    (state: StateHistory<State>) => this.state = state
  );
}

A state history is an interface defining all past and future states as arrays of these plus a currently present one.

// aurelia-store -> history.ts
export interface StateHistory<T> {
  past: T[];
  present: T;
  future: T[];
}

Now keep in mind that every action will receive a StateHistory<T> as input and should return a new StateHistory<T>:

// [Matt] That escalated quickly. Looks pretty painful. I might skip this example in the docs cause it's scary.
const greetingAction = (currentState: StateHistory<State>, greetingTarget: string) => {
  return Object.assign(
    {},
    currentState,
    { 
      past: [...currentState.past, currentState.present],
      present: { target: greetingTarget },
      future: [] 
    }
  );
}

Next StateHistory creation helper

Looking back at how you have to create the next StateHistory, you can reduce the work by using the nextStateHistory helper function. This will simply move the currently present state to the past, place you new one and remove the future states.

import { nextStateHistory } from "aurelia-store";

const greetingAction = (currentState: StateHistory<State>, greetingTarget: string) => {
  return nextStateHistory(currentState, { target: greetingTarget });
}

Navigating through history

In order to do state time-travelling you can import the pre-registered action jump and pass it either a positive number for traveling into the future or a negative for travelling to past states.

import { jump } from "aurelia-store";

...
// Go back one step in time
store.dispatch(jump, -1);

// Move forward one step to future
store.dispatch(jump, 1);

// [Matt] Why not store.jump?

Async actions

You may also register actions which resolve the newly created state with a promise. Same applies for history enhanced Stores. Just make sure the all past/present/future states by themselves are synchronous values.

Middleware

A middleware is similar to an action, with the difference that it may return void as well. Middlewares can be executed before the dispatched action, thus potentially manipulating the current state which will be passed to the action, or afterwards, thus modifying the returned value from the action. Either way the middleware reducer can be sync as well as async.

You register a middleware by it as the first parameter to store.registerMiddleware and the placement before or after as second.

const customLogMiddleware = (currentState) => console.log(currentState);
// In TypeScript you can use the exported MiddlewarePlacement string enum
store.registerMiddleware(customLogMiddleware, MiddlewarePlacement.After);

// in JavaScript just provide the string "before" or "after"
store.registerMiddleware(customLogMiddleware, "after");

// [Matt] Maybe a demo of how this works. Does this work for all state things? Is there any way to scope it to a state or a property on a state?

Acknowledgement

Thanks goes to Dwayne Charrington for his Aurelia-TypeScript starter package https://github.com/Vheissu/aurelia-typescript-plugin

Further info

If you want to learn more about state containers in Aurelia take a look at this article from Pragmatic Coder

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment