Skip to content
This repository has been archived by the owner on Jan 24, 2020. It is now read-only.

Commit

Permalink
Wrote readme, added some minor improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
duskpoet committed Feb 16, 2019
1 parent 25c634c commit 8eef820
Show file tree
Hide file tree
Showing 8 changed files with 795 additions and 1,246 deletions.
65 changes: 63 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,64 @@
Hello

# redux-href
[![Build Status](https://travis-ci.com/duskpoet/redux-href.svg?branch=master)](https://travis-ci.com/duskpoet/redux-href)

## Simple routing management in library written in typescript for redux.

```ts
import { createStore } from 'redux';
import rehref from 'redux-href';

import reducer from './reducer';

interface State {
name: string;
userId: string;
page: number;
}

const initialState: State = {
name: '',
userId: '',
page: 0,
};

const rehrefEnhancer = rehref<State>(
(url, state) => ({
...state,
page: Number(url.searchParams.get('page')),
}),
(state) => ({
params: {
page: String(state.page),
},
})
);

const store = createStore(reducer, {}, rehrefEnhancer);
```

## API

### rehref(locationToState: LocationToState, stateToLocation: StateToLocation) => StoreEnhancer

`type LocationToState<S> = (href: URL, state: S) => S`
Function that takes current href as [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) object, current state and returns actual state. It will be called on every popstate event.

```ts
interface LocationParams {
path?: string; // path part of url, like "full/path" in example.com/full/path
params?: { [name: string]: string }; // query params in url
}

type StateToLocation<S> = (state: S) => LocationParams
```
Function that takes current state and returns object, that will be used to update current location.
It will be called on every dispatch to calculate location params. If returned object equals to previous result, no update will be performed.
If you need to replace history instead of creating a new record, then include `replaceHistory: true` as a part of action object.
```ts
dispatch({
type: "some_action",
payload: "some_data",
meta: { replaceHistory: true },
})
```
6 changes: 3 additions & 3 deletions lib/actions.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
export const Types = {
replaceUrl: '@@re-href/replace-url',
replaceUrl: "@@re-href/replace-url"
};

export const replaceUrl = (href: string) => ({
type: Types.replaceUrl,
payload: {
href,
},
href
}
});
40 changes: 20 additions & 20 deletions lib/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createStore, AnyAction } from 'redux';
import rehrefFactory from '.';
import { createStore, AnyAction } from "redux";
import rehrefFactory from ".";

interface State {
name: string;
Expand All @@ -8,66 +8,66 @@ interface State {
}

const initialState: State = {
name: '',
userId: '',
page: 0,
name: "",
userId: "",
page: 0
};

const enhancerSimple = rehrefFactory<State>(
(url, state) => ({
...state,
page: Number(url.searchParams.get('page')),
page: Number(url.searchParams.get("page"))
}),
state => ({
params: {
page: String(state.page),
},
page: String(state.page)
}
})
);

const SET_PAGE = 'SET_PAGE';
const SET_PAGE = "SET_PAGE";

const reducer = (state: State = initialState, action: AnyAction): State => {
switch (action.type) {
case SET_PAGE:
return {
...state,
page: action.payload,
page: action.payload
};
default:
return state;
}
};

describe('re-href', () => {
describe("re-href", () => {
beforeEach(() => {
window.history.replaceState({}, '', '/');
Object.defineProperty(window.history, 'pushState', {
window.history.replaceState({}, "", "/");
Object.defineProperty(window.history, "pushState", {
writable: true,
value: jasmine.createSpy('pushState'),
value: jasmine.createSpy("pushState")
});
});

it('works with no specific info in location', () => {
it("works with no specific info in location", () => {
const store = createStore(reducer, {}, enhancerSimple);
const state = store.getState();
expect(state.page).toEqual(0);
});

it('works with set up location', () => {
window.history.replaceState({}, '', '/?page=2');
it("works with set up location", () => {
window.history.replaceState({}, "", "/?page=2");
const store = createStore(reducer, {}, enhancerSimple);
const state = store.getState();
expect(state.page).toEqual(2);
});

it('propagates changes to location', () => {
it("propagates changes to location", () => {
const store = createStore(reducer, {}, enhancerSimple);
const prevHref = window.location.href;
store.dispatch({ type: SET_PAGE, payload: 5 });
expect(window.history.pushState).toHaveBeenCalled();
window.history.replaceState({}, '', prevHref);
window.dispatchEvent(new Event('popstate'));
window.history.replaceState({}, "", prevHref);
window.dispatchEvent(new Event("popstate"));
expect(store.getState().page).toEqual(0);
});
});
23 changes: 14 additions & 9 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,24 @@ import {
AnyAction,
Reducer,
DeepPartial,
StoreEnhancerStoreCreator,
} from 'redux';
StoreEnhancerStoreCreator
} from "redux";

import locationReducer from './reducer';
import { LocationToState, StateToLocation } from './typings';
import { replaceUrl } from './actions';
import locationReducer from "./reducer";
import { LocationToState, StateToLocation, LocationParams } from "./typings";
import { replaceUrl } from "./actions";

const factory = <S>(
locationToState: LocationToState<S>,
stateToLocation: StateToLocation<S>
) => {
let currentUrlData: LocationParams = {};
const updateLocation = (state: S, replaceHistory: boolean) => {
const urlData = stateToLocation(state);
if (urlData === currentUrlData) {
return;
}
currentUrlData = urlData;
const currentUrl = new URL(window.location.href);
const { params = {}, path } = urlData;
for (let key in params) {
Expand All @@ -24,9 +29,9 @@ const factory = <S>(
currentUrl.pathname = path;
}
if (replaceHistory) {
window.history.replaceState(state, '', currentUrl.href);
window.history.replaceState(state, "", currentUrl.href);
} else {
window.history.pushState(state, '', currentUrl.href);
window.history.pushState(state, "", currentUrl.href);
}
};

Expand All @@ -49,13 +54,13 @@ const factory = <S>(
updateLocation(store.getState(), meta.replaceHistory);
};

window.addEventListener('popstate', () => {
window.addEventListener("popstate", () => {
store.dispatch(replaceUrl(window.location.href));
});

return {
...store,
dispatch,
dispatch
};
}) as StoreEnhancerStoreCreator;
};
Expand Down
6 changes: 3 additions & 3 deletions lib/reducer.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { AnyAction } from 'redux';
import { AnyAction } from "redux";

import { LocationToState, StateToLocation } from './typings';
import { Types } from './actions';
import { LocationToState, StateToLocation } from "./typings";
import { Types } from "./actions";

const reducer = <S>(
locationToState: LocationToState<S>,
Expand Down
10 changes: 4 additions & 6 deletions lib/typings.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
export type LocationToState<S> = (href: URL, state: S) => S;
export type StateToLocation<S> = (
state: S
) => {
export interface LocationParams {
path?: string;
params?: { [name: string]: string };
replaceHistory?: boolean;
};
}
export type LocationToState<S> = (href: URL, state: S) => S;
export type StateToLocation<S> = (state: S) => LocationParams;
Loading

0 comments on commit 8eef820

Please sign in to comment.