Ejemplo n.º 1
2
// use channel to make sure every create/remove run one by one
function* watchCreateAndRemoveLastPosition(): SagaIterator {
  try {
    const createLastPositionChan: TakeableChannel<{}> = yield actionChannel(
      getType(lastPositionsCreator.createLastPosition)
    )
    const removeLastPositionChan: TakeableChannel<{}> = yield actionChannel(
      getType(lastPositionsCreator.removeLastPosition)
    )
    while (true) {
      const [createLastPositionAction, removeLastPositionAction]: [
        ReturnType<typeof lastPositionsCreator.createLastPosition> | void,
        ReturnType<typeof lastPositionsCreator.removeLastPosition> | void
      ] = yield race([take(createLastPositionChan), take(removeLastPositionChan)])

      if (createLastPositionAction) {
        yield call(createLastPosition, createLastPositionAction)
      }

      if (removeLastPositionAction) {
        yield call(removeLastPosition, removeLastPositionAction)
      }
    }
  } catch (err) {
    console.error(err)
  }
}
Ejemplo n.º 2
1
function* testTake(): SagaIterator {
  yield take();
  yield take('my-action');
  yield take((action: Action) => action.type === 'my-action');
  yield take(isMyAction);

  // typings:expect-error
  yield take(() => {});

  yield take(stringableActionCreator);

  yield take([
    'my-action',
    (action: Action) => action.type === 'my-action',
    stringableActionCreator,
    isMyAction,
  ]);

  // typings:expect-error
  yield take([() => {}]);

  yield takeMaybe([
    'my-action',
    (action: Action) => action.type === 'my-action',
    stringableActionCreator,
    isMyAction,
  ]);

  yield take(channel);

  yield takeMaybe(channel);
}
Ejemplo n.º 3
0
function* handleOpenTandem() {
  yield take(OPEN_TANDEM_EXECUTED);

  let state: ExtensionState = yield select();
  var textDocumentContentProvider = {
    provideTextDocumentContent(uri) {
      return `
        <html>
          <head>
            <title>Tandem</title>
          </head>
          <body>
            <iframe src="${getIndexUrl(state)}" style="position:absolute;left:0;top:0;width:100vw; height: 100%; border: none;"></iframe>
          </body>
        </html>
      `;
    },
  };

  state.context.subscriptions.push(
    vscode.workspace.registerTextDocumentContentProvider(
      PREVIEW_NAME,
      textDocumentContentProvider)
  );

  while(true) {
    yield call(vscode.commands.executeCommand,
      "vscode.previewHtml",
      PREVIEW_URI,
      vscode.ViewColumn.Two,
      "Tandem"
    );
    yield take(OPEN_TANDEM_EXECUTED);
  }
}
Ejemplo n.º 4
0
function* watchDelete() {
  while (true) {
    const { id, formId } = yield take(DELETE_SUBMISSION);
    const { auth: { api } } = yield select();

    try {
      const [{ payload: { prevRowId } }] = yield [
        take(action => action.query === 'SUBMISSIONS' && action.type === ROW_REMOVED && action.payload.row.id === id),
        api.deleteSubmission(id),
      ];

      const { submissions } = yield select();

      if (prevRowId) {
        const nextRow = submissions.rows.get(submissions.rows.findIndex(row => row.id === prevRowId) + 1);

        var redirectTo = nextRow ? nextRow.id : prevRowId;
      } else {
        var redirectTo = submissions.rows.isEmpty() ? '' : submissions.rows.first().id;
      }

      yield put(routeActions.push(`forms/${formId}/submissions/${redirectTo}`));
    } catch(error) {
      console.log(error);
    }
  }
}
Ejemplo n.º 5
0
export default function* botSaga(tankId: TankId) {
  const ctx = new Bot(tankId)
  try {
    yield takeEvery(hitPredicate, hitHandler)
    const result = yield race({
      service: all([
        generateBulletCompleteNote(),
        directionController(tankId, ctx.directionControllerCallback),
        fireController(tankId, ctx.fireControllerCallback),
        AIWorkerSaga(ctx),
      ]),
      killed: take(killedPredicate),
      endGame: take(A.EndGame),
    })
    const tank: TankRecord = yield select(selectors.tank, tankId)
    yield put(actions.setTankToDead(tankId))
    if (result.killed) {
      yield explosionFromTank(tank)
      if (result.killed.method === 'bullet') {
        yield scoreFromKillTank(tank)
      }
    }
    yield put(actions.reqAddBot())
  } finally {
    const tank: TankRecord = yield select(selectors.tank, tankId)
    if (tank && tank.alive) {
      yield put(actions.setTankToDead(tankId))
    }
  }

  function hitPredicate(action: actions.Action) {
    return action.type === actions.A.Hit && action.targetTank.tankId === tankId
  }

  function* hitHandler(action: actions.Hit) {
    const tank: TankRecord = yield select(selectors.tank, tankId)
    DEV.ASSERT && console.assert(tank != null)
    if (tank.hp > 1) {
      yield put(actions.hurt(tank))
    } else {
      const { sourceTank, targetTank } = action
      yield put(actions.kill(targetTank, sourceTank, 'bullet'))
    }
  }

  function killedPredicate(action: actions.Action) {
    return action.type === actions.A.Kill && action.targetTank.tankId === tankId
  }

  function* generateBulletCompleteNote() {
    while (true) {
      const { bulletId }: actions.BeforeRemoveBullet = yield take(actions.A.BeforeRemoveBullet)
      const { bullets }: State = yield select()
      const bullet = bullets.get(bulletId)
      if (bullet.tankId === tankId) {
        ctx.noteChannel.put({ type: 'bullet-complete', bullet })
      }
    }
  }
}
Ejemplo n.º 6
0
export function* authFlow() {
  yield fork(watchStorage);
  yield fork(redirectOnAuth);

  while (true) {
    const token = auth.retrieveToken();

    if (token) {
      const state = yield select(state => state.auth);

      if (!state || state.token.toString() !== token.toString()) {
        yield put(signinSuccess(token, false));
      }

      yield call(watchExpiration, token.expiresIn);
    } else {
      yield call(purgeToken, false);
    }

    const { signin, signup } = yield race({ signin: take(SIGNIN), signup: take(SIGNUP), overwise: take(SIGNIN_SUCCESS) });

    if (signin) {
      yield fork(submitSigninForm, signin.resolve, signin.reject);
      yield call(createToken, signin);
      continue;
    }

    if (signup) {
      yield fork(submitSignupForm, signup.resolve, signup.reject);
      yield call(createUser, signup);
      continue;
    }
  }
}
Ejemplo n.º 7
0
  yield fork(function* () {
    const { success } = yield race({ success: take(SIGNUP_SUCCESS), otherwise: take(SIGNUP_FAILURE) });

    if (success) {
      yield call(createToken, { email, password });
    }
  });
Ejemplo n.º 8
0
 it('should add recommendations page if recommendations were returned', () => {
     return expectSaga(recommendationsSaga(mockStoreApi))
         .withState({
             currentUser: {
                 status: 'LOGGED_IN',
                 token: '',
             },
             ignored: [],
             owned: [],
         })
         .provide([
             [call(mockStoreApi.getRecommendations, ''), { data: mockRecommendations }],
             [call(createScrollChannel), mockScrollChannel],
             [take(mockScrollChannel), mockScrollInfo299px],
             [matchers.call.fn(getRecommendationsPage), mockPage],
             [take(mockScrollChannel), mockScrollInfo299px],
             [matchers.call.fn(getRecommendationsPage), mockPage],
         ])
         .put(productActions.add(mockPage.products))
         .put(recommendationsActions.addPage(mockPage.items))
         .delay(100)
         .put(productActions.add(mockPage.products))
         .put(recommendationsActions.addPage(mockPage.items))
         .silentRun(150)
 })
Ejemplo n.º 9
0
  yield fork(function*() {

    let prevState: ApplicationState;
    yield take(TRIED_LOADING_APP_STATE);

    while(true) {
      yield take();
      yield call(delay, PERSIST_DELAY_TIMEOUT);
      const state: ApplicationState = yield select();
      if (prevState === state) {
        continue;
      }

      prevState = state;

      // convert to a POJO object in case there are non serializable
      // object somehow in the application store. For the most part -- everything should be
      // a POJO with very few exceptions. For cases where data cannot be converted into a plain object, the application will need to re-hydrate the non-serializable data on startup. 
      const pojoState = serializeApplicationState(state);
      const { apiHost }: ApplicationState = state;

      yield call(fetch, apiHost + "/storage/" + state.storageNamespace + SAVE_KEY, {
        method: "POST",
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        } as any,
        body: JSON.stringify(pojoState)
      });
    }
  });  
Ejemplo n.º 10
0
export function* loginFlow() {
  window.beforeLogin = '******';
  let previousSession = null;
  yield take(LOCATION_CHANGE);
  while (true) { // eslint-disable-line no-constant-condition
    console.log('while true ', new Date());
    const session = authAgent.getSession();
    let location = yield select(makeSelectLocation());
    location = location.pathname;

    if (session !== null)
    {
      if (session !== previousSession) {
        yield put({type: AUTHENTICATED});
      }
      if (previousSession === null) {
        console.log('writing new session');
        previousSession = session;
      }
      console.log('Session:', session);
      if (location === '/login')
      {
        if (window.beforeLogin === '/login' || window.beforeLogin === '/logout')
          window.beforeLogin = '******';
        yield put(push(window.beforeLogin))
      }
      else
      {
        window.beforeLogin = location;
      }
      yield take(LOGOUT);
      try {
        yield call([authAgent,authAgent.logout]);
        yield put({type : LOGGED_OUT});
      }
      catch (e)
      {
        console.log('logout error!', e);
      }
    }
    else
    {
      if (location !== '/login') {
        window.beforeLogin = location;
        yield put(push('/login'));
      }
      const { login, password} = yield take(AUTH);

      try { //context call
        yield call([authAgent,authAgent.auth], login, password);
      }
      catch(e)
      {
        console.log('login error!',e);
      }

    }
  }
}