Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Memory-ish protocol #44

Merged
merged 5 commits into from
Dec 22, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,20 @@ The examples here assume the use of a `new BrowserProtocol()`.
const protocol = new ServerProtocol(req.url);
```

#### `MemoryProtocol`

`MemoryProtocol` tracks the current location and the location history in memory. It is intended for use in tests exercising navigation, and in cases where actual browser navigation is not possible or not desired, such as in browser plugins and in Electron apps. `MemoryProtocol` requires an initial location.

```js
const protocol = new MemoryProtocol(initialLocation);
```

`MemoryProtocol` also supports persisting the location history state to session storage, which allows for use cases like preserving navigation state when refreshing in an Electron app.

```js
const protocol = new MemoryProtocol(initialLocation, { persistent: true });
```

### Middlewares

#### `queryMiddleware` and `createQueryMiddleware`
Expand Down
126 changes: 126 additions & 0 deletions src/MemoryProtocol.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import invariant from 'invariant';

import createPath from './utils/createPath';
import ensureLocation from './utils/ensureLocation';

const STATE_KEY = '@@farce/state';

export default class MemoryProtocol {
constructor(initialLocation, { persistent = false } = {}) {
this._persistent = persistent;

const initialState = persistent ? this._loadState() : null;
if (initialState) {
this._stack = initialState.stack;
this._index = initialState.index;
} else {
this._stack = [ensureLocation(initialLocation)];
this._index = 0;
}

this._keyPrefix = Math.random()
.toString(36)
.slice(2, 8);
this._keyIndex = 0;

this._listener = null;
}

_loadState() {
try {
const { stack, index } = JSON.parse(
window.sessionStorage.getItem(STATE_KEY),
);

// Check that the stack and index at least seem reasonable before using
// them as state. This isn't foolproof, but it might prevent mistakes.
if (Array.isArray(stack) && typeof index === 'number' && stack[index]) {
return { stack, index };
}
} catch (e) {} // eslint-disable-line no-empty

return null;
}

init(delta = 0) {
return {
...this._stack[this._index],
action: 'POP',
index: this._index,
delta,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So I originally did this sticking index and delta on location, but what's the value in doing so?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in principle for consistency with browser protocol... e.g. if you want to animate differently based on whether delta is positive or negative

not sure if index has any purpose... really just from remix-run/history#36 and remix-run/history#334

};
}

transition(location) {
// Match BrowserProtocol here in only saving these fields.
const { action, pathname, search, hash, state } = location;

const push = action === 'PUSH';
invariant(
push || action === 'REPLACE',
`Unrecognized memory protocol action ${action}.`,
);

const delta = push ? 1 : 0;
this._index += delta;

const keyIndex = this._keyIndex++;
const key = `${this._keyPrefix}:${keyIndex.toString(36)}`;

this._stack[this._index] = { pathname, search, hash, state, key };
if (push) {
this._stack.length = this._index + 1;
}

if (this._persistent) {
this._saveState();
}

return { ...location, key, index: this._index, delta };
}

go(delta) {
const prevIndex = this._index;

this._index = Math.min(
Math.max(this._index + delta, 0),
this._stack.length - 1,
);

if (this._index === prevIndex) {
return;
}

if (this._persistent) {
this._saveState();
}

if (this._listener) {
this._listener(this.init(this._index - prevIndex));
}
}

_saveState() {
try {
window.sessionStorage.setItem(
STATE_KEY,
JSON.stringify({
stack: this._stack,
index: this._index,
}),
);
} catch (e) {} // eslint-disable-line no-empty
}

createHref(location) {
return createPath(location);
}

subscribe(listener) {
this._listener = listener;

return () => {
this._listener = null;
};
}
}
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export createStoreHistory from './createStoreHistory';
export createTransitionHookMiddleware from './createTransitionHookMiddleware';
export ensureLocationMiddleware from './ensureLocationMiddleware';
export locationReducer from './locationReducer';
export MemoryProtocol from './MemoryProtocol';
export queryMiddleware from './queryMiddleware';
export ServerProtocol from './ServerProtocol';
export StateStorage from './StateStorage';
200 changes: 200 additions & 0 deletions test/MemoryProcotol.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
import MemoryProtocol from '../src/MemoryProtocol';

describe.only('MemoryProtocol', () => {
it('should parse the initial loocation', () => {
const protocol = new MemoryProtocol('/foo?bar=baz#qux');

expect(protocol.init()).to.eql({
action: 'POP',
pathname: '/foo',
search: '?bar=baz',
hash: '#qux',
index: 0,
delta: 0,
});
});

it('should support basic navigation', () => {
const protocol = new MemoryProtocol('/foo');

const listener = sinon.spy();
protocol.subscribe(listener);

const barLocation = protocol.transition({
action: 'PUSH',
pathname: '/bar',
state: { the: 'state' },
});
expect(barLocation).to.deep.include({
action: 'PUSH',
pathname: '/bar',
index: 1,
delta: 1,
state: { the: 'state' },
});
expect(barLocation.key).not.to.be.empty();

expect(
protocol.transition({ action: 'PUSH', pathname: '/baz' }),
).to.include({
action: 'PUSH',
pathname: '/baz',
index: 2,
delta: 1,
});

expect(
protocol.transition({ action: 'REPLACE', pathname: '/qux' }),
).to.include({
action: 'REPLACE',
pathname: '/qux',
index: 2,
delta: 0,
});

expect(listener).not.to.have.been.called();

protocol.go(-1);

expect(listener).to.have.been.calledOnce();
expect(listener.firstCall.args[0]).to.deep.include({
action: 'POP',
pathname: '/bar',
key: barLocation.key,
index: 1,
delta: -1,
state: { the: 'state' },
});
});

it('should support subscribing and unsubscribing', () => {
const protocol = new MemoryProtocol('/foo');
protocol.transition({ action: 'PUSH', pathname: '/bar' });
protocol.transition({ action: 'PUSH', pathname: '/baz' });

const listener = sinon.spy();
const unsubscribe = protocol.subscribe(listener);

protocol.go(-1);

expect(listener).to.have.been.calledOnce();
expect(listener.firstCall.args[0]).to.include({
action: 'POP',
pathname: '/bar',
});
listener.reset();

unsubscribe();

protocol.go(-1);

expect(listener).not.to.have.been.called();
});

it('should respect stack bounds', () => {
const protocol = new MemoryProtocol('/foo');
protocol.transition({ action: 'PUSH', pathname: '/bar' });
protocol.transition({ action: 'PUSH', pathname: '/baz' });

const listener = sinon.spy();
protocol.subscribe(listener);

protocol.go(-390);

expect(listener).to.have.been.calledOnce();
expect(listener.firstCall.args[0]).to.include({
action: 'POP',
pathname: '/foo',
delta: -2,
});
listener.reset();

protocol.go(-1);

expect(listener).not.to.have.been.called();

protocol.go(+22);

expect(listener).to.have.been.calledOnce();
expect(listener.firstCall.args[0]).to.include({
action: 'POP',
pathname: '/baz',
delta: 2,
});
listener.reset();

protocol.go(+1);

expect(listener).not.to.have.been.called();
});

it('should reset forward entries on push', () => {
const protocol = new MemoryProtocol('/foo');
protocol.transition({ action: 'PUSH', pathname: '/bar' });
protocol.transition({ action: 'PUSH', pathname: '/baz' });
protocol.go(-2);
protocol.transition({ action: 'REPLACE', pathname: '/qux' });

const listener = sinon.spy();
protocol.subscribe(listener);

protocol.go(+1);

expect(listener).to.have.been.calledOnce();
expect(listener.firstCall.args[0]).to.include({
action: 'POP',
pathname: '/bar',
delta: 1,
});
});

it('should not reset forward entries on replace', () => {
const protocol = new MemoryProtocol('/foo');
protocol.transition({ action: 'PUSH', pathname: '/bar' });
protocol.transition({ action: 'PUSH', pathname: '/baz' });
protocol.go(-2);
protocol.transition({ action: 'PUSH', pathname: '/qux' });

const listener = sinon.spy();
protocol.subscribe(listener);

protocol.go(+1);

expect(listener).not.to.have.been.called();
});

it('should support createHref', () => {
const protocol = new MemoryProtocol('/foo');

expect(
protocol.createHref({
pathname: '/foo',
search: '?bar=baz',
hash: '#qux',
}),
).to.equal('/foo?bar=baz#qux');
});

it('should support persistence', () => {
window.sessionStorage.clear();

const protocol1 = new MemoryProtocol('/foo', { persistent: true });
expect(protocol1.init()).to.include({
pathname: '/foo',
});

protocol1.transition({ action: 'PUSH', pathname: '/bar' });
protocol1.transition({ action: 'PUSH', pathname: '/baz' });
protocol1.go(-1);

const protocol2 = new MemoryProtocol('/foo', { persistent: true });
expect(protocol2.init()).to.include({
pathname: '/bar',
});

protocol2.go(+1);
expect(protocol2.init()).to.include({
pathname: '/baz',
});
});
});