Skip to content

Commit 5d0c555

Browse files
committed
feat(hatch): allow to create hatch with config of events
1 parent c94bf9b commit 5d0c555

1 file changed

Lines changed: 26 additions & 6 deletions

File tree

src/hatch.ts

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import * as React from 'react';
2-
import { Domain, Event, Store, combine } from 'effector';
2+
import { Domain, Event, Store, combine, is } from 'effector';
33
import { MatchedRoute } from 'react-router-config';
44

55
import { defaultDomain } from './default-domain';
@@ -27,20 +27,40 @@ export interface Hatch {
2727
$props: Store<HatchParams>;
2828
}
2929

30+
interface Config {
31+
enter: Event<HatchParams>;
32+
update: Event<HatchParams>;
33+
exit: Event<void>;
34+
domain?: Domain;
35+
}
36+
3037
/**
3138
* Events here is an input signal, history should call them when route enters, updates, and exits.
3239
* Stores is derived from this events and holds specific parameters
3340
* `$opened` holds current state of page, if user visited page but not left, it is `true`
3441
*/
35-
export function createHatch(domain: Domain = defaultDomain): Hatch {
42+
export function createHatch(config_: Config | Domain = defaultDomain): Hatch {
43+
let domain;
44+
let config: Partial<Config>;
45+
if (is.domain(config_)) {
46+
domain = config_;
47+
config = {};
48+
} else if (is.domain(config_.domain)) {
49+
domain = config_.domain;
50+
config = config_;
51+
} else {
52+
domain = defaultDomain;
53+
config = {};
54+
}
55+
3656
const $opened = domain.createStore(Boolean(false));
3757
const $params = domain.createStore<Record<string, string>>({});
3858
const $query = domain.createStore<Record<string, string>>({});
3959

4060
const hatch = {
41-
enter: domain.createEvent<HatchParams>(),
42-
update: domain.createEvent<HatchParams>(),
43-
exit: domain.createEvent<void>(),
61+
enter: config.enter ?? domain.createEvent<HatchParams>(),
62+
update: config.update ?? domain.createEvent<HatchParams>(),
63+
exit: config.exit ?? domain.createEvent<void>(),
4464
$opened,
4565
$params,
4666
$query,
@@ -50,7 +70,7 @@ export function createHatch(domain: Domain = defaultDomain): Hatch {
5070
$params.on([hatch.enter, hatch.update], (_, { params }) => params);
5171
$query.on([hatch.enter, hatch.update], (_, { query }) => query);
5272

53-
hatch.$opened.on(hatch.enter, () => Boolean(true)).on(hatch.exit, () => Boolean(false));
73+
hatch.$opened.on(hatch.enter, () => Boolean(true)).reset(hatch.exit);
5474
// Developer may want to read props when user leaves the page
5575
// if $opened store will reset on hatch.exit, data will be deleted
5676

0 commit comments

Comments
 (0)