summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/ide/sync_router_and_store.js
blob: b33bcbb94ea59e9bd4430fc8064810d93925191c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
 * This method adds listeners to the given router and store and syncs their state with eachother
 *
 * ### Why?
 *
 * Previously the IDE had a circular dependency between a singleton router and a singleton store.
 * This causes some integration testing headaches...
 *
 * At the time, the most effecient way to break this ciruclar dependency was to:
 *
 * - Replace the router with a factory function that receives a store reference
 * - Have the store write to a certain state that can be watched by the router
 *
 * Hence... This helper function...
 */
export const syncRouterAndStore = (router, store) => {
  const disposables = [];

  let currentPath = '';

  // sync store to router
  disposables.push(
    store.watch(
      state => state.router.fullPath,
      fullPath => {
        if (currentPath === fullPath) {
          return;
        }

        currentPath = fullPath;

        router.push(fullPath);
      },
    ),
  );

  // sync router to store
  disposables.push(
    router.afterEach(to => {
      if (currentPath === to.fullPath) {
        return;
      }

      currentPath = to.fullPath;
      store.dispatch('router/push', currentPath, { root: true });
    }),
  );

  const unsync = () => {
    disposables.forEach(fn => fn());
  };

  return unsync;
};