All files / app/assets/javascripts/ide sync_router_and_store.js

100% Statements 18/18
100% Branches 4/4
100% Functions 6/6
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 55                              10x 191x   191x     191x   260x   69x 14x     55x   55x           191x   33x 4x     29x 29x       191x 26x     191x    
/**
 * 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;
};