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

Update store paths to require numbers for indices #666

Closed
wants to merge 2 commits into from
Closed
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
5 changes: 3 additions & 2 deletions src/core/middleware/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,13 @@ export const createStoreMiddleware = <S = any>(initial?: (store: Store<S>) => vo
};
return {
get<U = any>(path: Path<S, U>): U {
if (registeredPaths.indexOf(path.path) === -1) {
const stringPath = Array.isArray(path.path) ? path.path.join('/') : String(path.path);
if (registeredPaths.indexOf(stringPath) === -1) {
const handle = store.onChange(path, () => {
invalidator();
});
handles.push(() => handle.remove());
registeredPaths.push(path.path);
registeredPaths.push(stringPath);
}
return store.get(path);
},
Expand Down
26 changes: 16 additions & 10 deletions src/stores/Store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import Map from '../shim/Map';
*
*/
export interface Path<M, T> {
path: string;
path: string | number | (string | number)[];
state: M;
value: T;
}
Expand All @@ -24,7 +24,6 @@ export interface State<M> {
at<S extends Path<M, Array<any>>>(path: S, index: number): Path<M, S['value'][0]>;
path: StatePaths<M>;
}

export interface StatePaths<M> {
<T, P0 extends keyof Required<T>>(path: Path<M, T>, a: P0): Path<M, Required<T>[P0]>;
<T, P0 extends keyof T, P1 extends keyof Required<T>[P0]>(path: Path<M, T>, a: P0, b: P1): Path<
Expand Down Expand Up @@ -108,8 +107,9 @@ interface OnChangeValue {
previousValue: any;
}

function isString(segment?: string): segment is string {
return typeof segment === 'string';
function isStringOrNumber(segment?: string | number): segment is string | number {
const type = typeof segment;
return type === 'string' || type === 'number';
}

export interface MutableState<T = any> extends State<T> {
Expand Down Expand Up @@ -153,14 +153,17 @@ export class DefaultState<T = any> implements MutableState<T> {
};
};

public path: State<T>['path'] = (path: string | Path<T, any>, ...segments: (string | undefined)[]) => {
if (typeof path === 'string') {
public path: State<T>['path'] = (
path: string | number | Path<T, any>,
...segments: (string | number | undefined)[]
) => {
if (typeof path === 'string' || typeof path === 'number') {
segments = [path, ...segments];
} else {
segments = [...new Pointer(path.path).segments, ...segments];
}

const stringSegments = segments.filter<string>(isString);
const stringSegments = segments.filter(isStringOrNumber);
const hasMultipleSegments = stringSegments.length > 1;
const pointer = new Pointer(hasMultipleSegments ? stringSegments : stringSegments[0] || '');

Expand Down Expand Up @@ -224,7 +227,9 @@ export class Store<T = any> extends Evented implements MutableState<T> {
return {
remove: () => {
(paths as Path<T, U>[]).forEach((path) => {
const onChange = this._changePaths.get(path.path);
const onChange = this._changePaths.get(
Array.isArray(path.path) ? path.path.join('/') : String(path.path)
);
if (onChange) {
onChange.callbacks = onChange.callbacks.filter((callback) => {
return callback.callbackId !== callbackId;
Expand All @@ -236,12 +241,13 @@ export class Store<T = any> extends Evented implements MutableState<T> {
};

private _addOnChange = <U = any>(path: Path<T, U>, callback: () => void, callbackId: number): void => {
let changePaths = this._changePaths.get(path.path);
const stringPath = Array.isArray(path.path) ? path.path.join('/') : String(path.path);
let changePaths = this._changePaths.get(stringPath);
if (!changePaths) {
changePaths = { callbacks: [], previousValue: this.get(path) };
}
changePaths.callbacks.push({ callbackId, callback });
this._changePaths.set(path.path, changePaths);
this._changePaths.set(stringPath, changePaths);
};

private _runOnChanges() {
Expand Down
2 changes: 1 addition & 1 deletion src/stores/process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ export function processExecutor<T = any, P extends object = DefaultPayload>(
const createHandler = (partialPath?: Path<T, any>) => ({
get(obj: any, prop: string): any {
const fullPath = partialPath ? path(partialPath, prop) : path(prop as keyof T);
const stringPath = fullPath.path;
const stringPath = Array.isArray(fullPath.path) ? fullPath.path.join('/') : String(fullPath.path);

if (typeof prop === 'symbol' && prop === valueSymbol) {
return proxied.get(stringPath);
Expand Down
20 changes: 12 additions & 8 deletions src/stores/state/ImmutableState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ import { Map, List } from 'immutable';

import { getFriendlyDifferenceMessage, isEqual } from './compare';

function isString(segment?: string): segment is string {
return typeof segment === 'string';
function isStringOrNumber(segment?: string | number): segment is string | number {
const type = typeof segment;
return type === 'string' || type === 'number';
}

function isList(value?: any): value is List<any> {
Expand Down Expand Up @@ -88,14 +89,17 @@ export class ImmutableState<T = any> implements MutableState<T> {
};
};

public path: State<T>['path'] = (path: string | Path<T, any>, ...segments: (string | undefined)[]) => {
if (typeof path === 'string') {
public path: State<T>['path'] = (
path: string | number | Path<T, any>,
...segments: (string | number | undefined)[]
) => {
if (typeof path === 'string' || typeof path === 'number') {
segments = [path, ...segments];
} else {
segments = [...new Pointer(path.path).segments, ...segments];
}

const stringSegments = segments.filter<string>(isString);
const stringSegments = segments.filter(isStringOrNumber);
const hasMultipleSegments = stringSegments.length > 1;
const pointer = new Pointer(hasMultipleSegments ? stringSegments : stringSegments[0] || '');
let value = this._state.getIn(pointer.segments);
Expand Down Expand Up @@ -157,7 +161,7 @@ export class ImmutableState<T = any> implements MutableState<T> {
return undoOperations;
}

private setIn(segments: string[], value: any, state: Map<any, any>, add = false) {
private setIn(segments: (string | number)[], value: any, state: Map<any, any>, add = false) {
const updated = this.set(segments, value, state, add);
if (updated) {
return updated;
Expand All @@ -171,7 +175,7 @@ export class ImmutableState<T = any> implements MutableState<T> {
}
const value = state.getIn([...segments.slice(0, index), segment]);
if (!value || !(value instanceof List || value instanceof Map)) {
if (!isNaN(nextSegment) && !isNaN(parseInt(nextSegment, 0))) {
if (typeof nextSegment === 'number') {
map = map.setIn([...segments.slice(0, index), segment], List());
} else {
map = map.setIn([...segments.slice(0, index), segment], Map());
Expand All @@ -183,7 +187,7 @@ export class ImmutableState<T = any> implements MutableState<T> {
return this.set(segments, value, state, add) || state;
}

private set(segments: string[], value: any, state: Map<any, any>, add = false) {
private set(segments: (string | number)[], value: any, state: Map<any, any>, add = false) {
if (typeof value === 'object' && value != null) {
if (Array.isArray(value)) {
value = List(value);
Expand Down
14 changes: 6 additions & 8 deletions src/stores/state/Patch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,28 +44,26 @@ export interface PatchResult<T = any, U = any> {
}

function add(pointerTarget: PointerTarget, value: any): any {
let index = parseInt(pointerTarget.segment, 10);
if (Array.isArray(pointerTarget.target) && !isNaN(index)) {
pointerTarget.target.splice(index, 0, value);
if (Array.isArray(pointerTarget.target) && typeof pointerTarget.segment === 'number') {
pointerTarget.target.splice(pointerTarget.segment, 0, value);
} else {
pointerTarget.target[pointerTarget.segment] = value;
}
return pointerTarget.object;
}

function replace(pointerTarget: PointerTarget, value: any): any {
let index = parseInt(pointerTarget.segment, 10);
if (Array.isArray(pointerTarget.target) && !isNaN(index)) {
pointerTarget.target.splice(index, 1, value);
if (Array.isArray(pointerTarget.target) && typeof pointerTarget.segment === 'number') {
pointerTarget.target.splice(pointerTarget.segment, 1, value);
} else {
pointerTarget.target[pointerTarget.segment] = value;
}
return pointerTarget.object;
}

function remove(pointerTarget: PointerTarget): any {
if (Array.isArray(pointerTarget.target)) {
pointerTarget.target.splice(parseInt(pointerTarget.segment, 10), 1);
if (Array.isArray(pointerTarget.target) && typeof pointerTarget.segment === 'number') {
pointerTarget.target.splice(pointerTarget.segment, 1);
} else {
delete pointerTarget.target[pointerTarget.segment];
}
Expand Down
41 changes: 26 additions & 15 deletions src/stores/state/Pointer.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
export function decode(segment: string) {
return segment.replace(/~1/g, '/').replace(/~0/g, '~');
export function decode(segment: string | number) {
return typeof segment === 'number' ? segment : segment.replace(/~1/g, '/').replace(/~0/g, '~');
}

function encode(segment: string) {
return segment.replace(/~/g, '~0').replace(/\//g, '~1');
function encode(segment: string | number) {
return typeof segment === 'number' ? segment : segment.replace(/~/g, '~0').replace(/\//g, '~1');
}

export interface PointerTarget {
object: any;
target: any;
segment: string;
segment: string | number;
}

export function walk(segments: string[], object: any, clone = true, continueOnUndefined = true): PointerTarget {
export function walk(
segments: (string | number)[],
object: any,
clone = true,
continueOnUndefined = true
): PointerTarget {
if (clone) {
object = { ...object };
}
Expand All @@ -27,7 +32,7 @@ export function walk(segments: string[], object: any, clone = true, continueOnUn
return pointerTarget;
}
if (Array.isArray(pointerTarget.target) && segment === '-') {
segment = String(pointerTarget.target.length - 1);
segment = pointerTarget.target.length - 1;
}
if (index + 1 < segments.length) {
const nextSegment: any = segments[index + 1];
Expand All @@ -43,10 +48,10 @@ export function walk(segments: string[], object: any, clone = true, continueOnUn
target = [...target];
} else if (typeof target === 'object') {
target = { ...target };
} else if (isNaN(nextSegment) || isNaN(parseInt(nextSegment, 0))) {
target = {};
} else {
} else if (typeof nextSegment === 'number') {
target = [];
} else {
target = {};
}
pointerTarget.target[segment] = target;
pointerTarget.target = target;
Expand All @@ -61,22 +66,28 @@ export function walk(segments: string[], object: any, clone = true, continueOnUn
}

export class Pointer<T = any, U = any> {
private readonly _segments: string[];
private readonly _segments: (string | number)[];

constructor(segments: string | string[]) {
constructor(segments: number | string | (string | number)[]) {
if (Array.isArray(segments)) {
this._segments = segments;
} else {
this._segments = (segments[0] === '/' ? segments : `/${segments}`).split('/');
this._segments =
typeof segments === 'string'
? (segments[0] === '/' ? segments : `/${segments}`).split('/')
: [segments];
this._segments.shift();
}
if (segments.length === 0 || ((segments.length === 1 && segments[0] === '/') || segments[0] === '')) {
if (
typeof segments !== 'number' &&
(segments.length === 0 || ((segments.length === 1 && segments[0] === '/') || segments[0] === ''))
) {
throw new Error('Access to the root is not supported.');
}
this._segments = this._segments.map(decode);
}

public get segments(): string[] {
public get segments(): (string | number)[] {
return this._segments;
}

Expand Down
17 changes: 13 additions & 4 deletions tests/stores/unit/process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,15 @@ const tests = (stateType: string, state?: () => MutableState<any>) => {
assert.strictEqual(foobar, 'foo/bar');
});

it('handles array indices in `path`', () => {
const store = new Store<{ foo: { bar: string }[] }>();
store.apply([add(store.path('foo'), [{ bar: 'baz' }])]);
const foo = store.get(store.path('foo'));
const foobar = store.get(store.path('foo', 0, 'bar'));
assert.deepEqual(foo, [{ bar: 'baz' }]);
assert.strictEqual(foobar, 'baz');
});

it('should handle optional properties for updates', () => {
type StateType = { a?: { b?: string }; foo?: number; bar: string };
const createCommand = createCommandFactory<StateType>();
Expand Down Expand Up @@ -649,7 +658,7 @@ const tests = (stateType: string, state?: () => MutableState<any>) => {
const paths = result.operations.map((operation) => operation.path.path);
const logs = result.get(store.path('logs')) || [];

result.apply([{ op: OperationType.ADD, path: new Pointer(`/logs/${logs.length}`), value: paths }]);
result.apply([{ op: OperationType.ADD, path: new Pointer(['logs', logs.length]), value: paths }]);
}
});

Expand Down Expand Up @@ -682,7 +691,7 @@ const tests = (stateType: string, state?: () => MutableState<any>) => {
store.apply([
{
op: OperationType.ADD,
path: new Pointer(`/initLogs/${initLog.length}`),
path: new Pointer(['initLogs', initLog.length]),
value: 'initial value'
}
]);
Expand Down Expand Up @@ -712,7 +721,7 @@ const tests = (stateType: string, state?: () => MutableState<any>) => {
const paths = result.operations.map((operation) => operation.path.path);
const logs = result.get(store.path('logs')) || [];

result.apply([{ op: OperationType.ADD, path: new Pointer(`/logs/${logs.length}`), value: paths }]);
result.apply([{ op: OperationType.ADD, path: new Pointer(['logs', logs.length]), value: paths }]);
}
});

Expand Down Expand Up @@ -764,7 +773,7 @@ const tests = (stateType: string, state?: () => MutableState<any>) => {
const paths = result.operations.map((operation) => operation.path.path);
const logs = result.get(store.path('logs')) || [];

result.apply([{ op: OperationType.ADD, path: new Pointer(`/logs/${logs.length}`), value: paths }]);
result.apply([{ op: OperationType.ADD, path: new Pointer(['logs', logs.length]), value: paths }]);
};

const process = createProcess('test', [testCommandFactory('foo'), testCommandFactory('bar')], () => ({
Expand Down
10 changes: 5 additions & 5 deletions tests/stores/unit/state/ImmutableState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@ describe('state/ImmutableState', () => {

it('value to array index path', () => {
const state = new ImmutableState();
const result = state.apply([ops.add({ path: '/test/0', state: null, value: null }, 'test')]);
const result = state.apply([ops.add({ path: ['test', 0], state: null, value: null }, 'test')]);
assert.deepEqual(state.path('/test').value, ['test']);
assert.deepEqual(result, [
{ op: OperationType.TEST, path: new Pointer('/test/0'), value: 'test' },
{ op: OperationType.REMOVE, path: new Pointer('/test/0') }
{ op: OperationType.TEST, path: new Pointer(['test', 0]), value: 'test' },
{ op: OperationType.REMOVE, path: new Pointer(['test', 0]) }
]);
});
});
Expand Down Expand Up @@ -171,12 +171,12 @@ describe('state/ImmutableState', () => {
state.apply([ops.add({ path: '/foo/0/bar/baz/0/qux', state: null, value: null }, true)]);
const result = state.apply([ops.test({ path: '/foo/0/bar/baz/0/qux', state: null, value: null }, true)]);
assert.deepEqual(result, []);
assert.deepEqual(state.path('/foo').value, [{ bar: { baz: [{ qux: true }] } }]);
assert.deepEqual(state.path('/foo').value, { 0: { bar: { baz: { 0: { qux: true } } } } });
});

it('complex value', () => {
const state = new ImmutableState();
state.apply([ops.add({ path: '/foo/0/bar/baz/0/qux', state: null, value: null }, true)]);
state.apply([ops.add({ path: ['foo', 0, 'bar', 'baz', 0, 'qux'], state: null, value: null }, true)]);
const result = state.apply([
ops.test({ path: '/foo', state: null, value: null }, [
{
Expand Down
4 changes: 2 additions & 2 deletions tests/stores/unit/state/Patch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,13 +154,13 @@ describe('state/Patch', () => {
});

it('array index path', () => {
const patch = new Patch(ops.remove({ path: '/test/1', state: null, value: null }));
const patch = new Patch(ops.remove({ path: ['test', 1], state: null, value: null }));
const obj = { test: ['test', 'foo'] };
const result = patch.apply(obj);
assert.notStrictEqual(result.object, obj);
assert.deepEqual(result.object, { test: ['test'] });
assert.deepEqual(result.undoOperations, [
{ op: OperationType.ADD, path: new Pointer('/test/1'), value: 'foo' }
{ op: OperationType.ADD, path: new Pointer(['test', 1]), value: 'foo' }
]);
});
});
Expand Down