@@ -15,19 +15,43 @@ export const ReduxStoreContext = createContext(warningObject);
15
15
16
16
// patch store with batchedUpdates
17
17
const patchReduxStore = ( origStore ) => {
18
- if ( ! batchedUpdates ) return origStore ;
18
+ const safeBatchedUpdates = batchedUpdates || ( f => f ( ) ) ;
19
19
const listeners = [ ] ;
20
+ // proof of concept: heuristically reorder listeners to mimic top-down
21
+ const fingerprints = [ ] ;
22
+ const registerFingerprint = ( fingerprint ) => {
23
+ const index = fingerprints . indexOf ( fingerprint ) ;
24
+ if ( index < 0 ) fingerprints . push ( fingerprint ) ;
25
+ } ;
26
+ const unregisterFingerprint = ( fingerprint ) => {
27
+ const index = fingerprints . indexOf ( fingerprint ) ;
28
+ if ( index >= 0 ) fingerprints . splice ( index , 1 ) ;
29
+ } ;
30
+ const sortListeners = ( ) => {
31
+ listeners . sort ( ( a , b ) => {
32
+ const ia = fingerprints . indexOf ( a . fingerprint ) ;
33
+ const ib = fingerprints . indexOf ( b . fingerprint ) ;
34
+ return ia - ib ;
35
+ } ) ;
36
+ } ;
20
37
let unsubscribe ;
21
38
const subscribe = ( listener ) => {
22
39
listeners . push ( listener ) ;
23
40
if ( listeners . length === 1 ) {
24
41
unsubscribe = origStore . subscribe ( ( ) => {
25
- batchedUpdates ( ( ) => {
42
+ if ( fingerprints . length ) {
43
+ sortListeners ( ) ;
44
+ // we can't use batchedUpdates because we need to render each time
26
45
listeners . forEach ( l => l ( ) ) ;
27
- } ) ;
46
+ } else {
47
+ safeBatchedUpdates ( ( ) => {
48
+ listeners . forEach ( l => l ( ) ) ;
49
+ } ) ;
50
+ }
28
51
} ) ;
29
52
}
30
53
return ( ) => {
54
+ unregisterFingerprint ( listener . fingerprint ) ;
31
55
const index = listeners . indexOf ( listener ) ;
32
56
listeners . splice ( index , 1 ) ;
33
57
if ( listeners . length === 0 ) {
@@ -38,6 +62,7 @@ const patchReduxStore = (origStore) => {
38
62
return {
39
63
...origStore ,
40
64
subscribe,
65
+ registerFingerprint,
41
66
} ;
42
67
} ;
43
68
0 commit comments