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

splitMap - added targets field #336

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
49 changes: 45 additions & 4 deletions src/split-map/index.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,77 @@
import { Event, is, Store, Unit } from 'effector';
import { Event, Tuple, Unit, UnitTargetable, is, sample } from 'effector';

type TargetUnits<T> =
| UnitTargetable<T | void>
| Tuple<UnitTargetable<T | void>>
| ReadonlyArray<UnitTargetable<T | void>>;

const hasPropBase = {}.hasOwnProperty;
const hasOwnProp = <O extends { [k: string]: unknown }>(object: O, key: string) =>
hasPropBase.call(object, key);

export function splitMap<
S,
Cases extends Record<string, (payload: S) => any | undefined>,
Targets extends {
[K in keyof Cases]?: Cases[K] extends (s: S) => infer R
? Targets[K] extends TargetUnits<infer TargetType>
? Exclude<R, undefined> extends TargetType
? TargetUnits<TargetType>
: TargetUnits<Exclude<R, undefined>>
: TargetUnits<Exclude<R, undefined>>
: never;
} & { __?: TargetUnits<S> },
>({
source,
cases,
targets,
}: {
source: Unit<S>;
cases: Cases;
targets?: Targets;
}): {
[K in keyof Cases]: Cases[K] extends (p: S) => infer R
? Event<Exclude<R, undefined>>
: never;
} & { __: Event<S> } {
const result: Record<string, Event<any> | Store<any>> = {};
const result: Record<string, Event<any>> = {};

let current = is.store(source) ? source.updates : (source as Event<S>);

for (const key in cases) {
if (key in cases) {
if (hasOwnProp(cases, key)) {
const fn = cases[key];

result[key] = current.filterMap(fn);
const caseEvent = current.filterMap(fn);

result[key] = caseEvent;

current = current.filter({
fn: (data) => !fn(data),
});

if (targets && hasOwnProp(targets, key)) {
const currentTarget = targets[key];

sample({
clock: caseEvent,
target: currentTarget as UnitTargetable<any>,
});
}
}
}

// eslint-disable-next-line no-underscore-dangle
result.__ = current;

if (targets && '__' in targets) {
const defaultCaseTarget = targets.__;

sample({
clock: current,
target: defaultCaseTarget as UnitTargetable<any>,
});
}

return result as any;
}
115 changes: 115 additions & 0 deletions src/split-map/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,118 @@ websocketEventReceived({ type: 'increment', name: 'demo', count: 5 });
websocketEventReceived({ type: 'bang', random: 'unknown' });
// => Unknown type: 'bang'
```

## `splitMap({ source, cases, targets? })`

### Motivation

Often we need the same behavior as in split — react to derived events received from `cases` and trigger the corresponding units. In `targets` field we can pass object with the same keys as in `cases` and values with `units` to trigger on the corresponding event.

### Formulae

```ts
splitMap({ source, cases, targets });
```

- On each `source` trigger, call each function in `cases` object one after another until function returns non undefined, and call event in `shape` with the same name as function in `cases` object.
- Trigger the corresponding `unit`(s) from `targets` object
- If no function returned value, event `__` in `shape` should be triggered, same for `targets` field — trigger `unit`(s) provided in `__` key

### Arguments

1. `source` ([_`Event`_] | [_`Store`_] | [_`Effect`_]) — Source unit, data from this unit passed to each function in `cases` object and `__` event in `shape` as is
2. `cases` (`{ [key: string]: (payload: T) => any | void }`) — Object of functions. Function receives one argument is a payload from `source`, should return any value or `undefined`
3. `targets` (`{ [key: string]?: Unit<any> | Unit<any>[]; __?: Unit<any> | Unit<any>[] }`) — Object of units to trigger on corresponding event from `cases` object

### Returns

- `shape` (`{ [key: string]: Event<any>; __: Event<T> }`) — Object of events, with the same structure as `cases`, but with the _default_ event `__`, that triggered when each other function returns `undefined`

[_`event`_]: https://effector.dev/docs/api/effector/event
[_`effect`_]: https://effector.dev/docs/api/effector/effect
[_`store`_]: https://effector.dev/docs/api/effector/store

### Examples

#### Split WebSocket events to effector events with targets

```ts
import { createEvent } from 'effector';
import { splitMap } from 'patronum/split-map';
import { spread } from 'patronum/spread';

type WSEvent =
| { type: 'init'; key: string }
| { type: 'increment'; count: number }
| { type: 'reset' };

export const websocketEventReceived = createEvent<WSEvent>();

const $isInitialized = createStore(false);
const $count = createStore<number | null>(null);

const getInitialDataFx = createEffect<string, void>();

splitMap({
source: websocketEventReceived,
cases: {
init: (event) => {
if (event.type === 'init') return { init: true, dataId: event.key };
},
increment: (payload) => {
if (payload.type === 'increment') return payload.count;
},
reset: ({ type }) => {
if (type === 'reset') return null;
},
},
targets: {
// EventCallable<{ init?: boolean; dataId?: string }>
init: spread({ init: $isInitialized, dataId: getInitialDataFx }),
increment: $count,
reset: [$count.reinit, $isInitialized.reinit],
},
});

websocketEventReceived({ type: 'init', key: 'key' });
// => $isInitialized: true, getInitialDataFx: 'key'

websocketEventReceived({ type: 'increment', count: 2 });
// => $count: 2

websocketEventReceived({ type: 'reset' });
// => $count: null, $isInitialized: false
```

#### We can still use returned events to do some other logic

```ts
const { init } = splitMap({
source: websocketEventReceived,
cases: {
init: (event) => {
if (event.type === 'init') return { init: true, dataId: event.key };
},
increment: (payload) => {
if (payload.type === 'increment') return payload.count;
},
reset: ({ type }) => {
if (type === 'reset') return null;
},
},
targets: {
// EventCallable<{ init?: boolean; dataId?: string }>
init: spread({ init: $isInitialized, dataId: getInitialDataFx }),
increment: $count,
reset: [$count.reinit, $isInitialized.reinit],
},
});

sample({
clock: init,
// some other logic
source: ...,
filter: ...,
target: ...,
})
```
68 changes: 39 additions & 29 deletions src/split-map/split-map.fork.test.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
import 'regenerator-runtime/runtime';
import { createDomain, fork, serialize, allSettled } from 'effector';
import {
createDomain,
fork,
allSettled,
createEvent,
createStore,
createApi,
} from 'effector';

import { splitMap } from './index';

test('works in forked scope', async () => {
const app = createDomain();
const source = app.createEvent<{ first?: number; another?: boolean }>();
const $target = createStore(0);

const source = createEvent<{ first?: number; another?: boolean }>();
const out = splitMap({
source,
cases: {
first: (payload) => payload.first,
},
targets: {
earthspacon marked this conversation as resolved.
Show resolved Hide resolved
first: $target,
__: createApi($target, { another: (state) => -state }).another,
},
});

const $data = app.createStore(0);
const $data = createStore(0);

$data
.on(out.first, (state, payload) => state + payload)
Expand All @@ -25,31 +37,30 @@ test('works in forked scope', async () => {
scope,
params: { first: 15 },
});
expect(serialize(scope)).toMatchInlineSnapshot(`
{
"xwy4bm": 15,
}
`);
expect(scope.getState($data)).toBe(15);
expect(scope.getState($target)).toBe(15);

await allSettled(source, {
scope,
params: { another: true },
});
expect(serialize(scope)).toMatchInlineSnapshot(`
{
"xwy4bm": -15,
}
`);
expect(scope.getState($data)).toBe(-15);
expect(scope.getState($target)).toBe(-15);
});

test('do not affect another fork', async () => {
const $target = createStore(0);

const app = createDomain();
const source = app.createEvent<{ first?: number; another?: boolean }>();
const out = splitMap({
source,
cases: {
first: (payload) => payload.first,
},
targets: {
first: $target,
},
});

const $data = app.createStore(0);
Expand All @@ -65,31 +76,30 @@ test('do not affect another fork', async () => {
scope: scopeA,
params: { first: 200 },
});
expect(serialize(scopeA)).toMatchInlineSnapshot(`
{
"l4dkuf": 200,
}
`);
expect(scopeA.getState($data)).toBe(200);
expect(scopeA.getState($target)).toBe(200);

await allSettled(source, {
scope: scopeB,
params: { first: -5 },
});
expect(serialize(scopeB)).toMatchInlineSnapshot(`
{
"l4dkuf": -5,
}
`);
expect(scopeB.getState($data)).toBe(-5);
expect(scopeB.getState($target)).toBe(-5);
});

test('do not affect original store value', async () => {
const $target = createStore(0);

const app = createDomain();
const source = app.createEvent<{ first?: number; another?: boolean }>();
const out = splitMap({
source,
cases: {
first: (payload) => payload.first,
},
targets: {
first: $target,
},
});

const $data = app.createStore(0);
Expand All @@ -104,10 +114,10 @@ test('do not affect original store value', async () => {
scope,
params: { first: 15 },
});
expect(serialize(scope)).toMatchInlineSnapshot(`
{
"8sunrf": 15,
}
`);

expect(scope.getState($data)).toBe(15);
expect($data.getState()).toBe($data.defaultState);

expect(scope.getState($target)).toBe(15);
expect($target.getState()).toBe($target.defaultState);
});
Loading