ramda#pathOr JavaScript Examples

The following examples show how to use ramda#pathOr. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CharacterDialog.jsx    From archeage-tools with The Unlicense 6 votes vote down vote up
componentDidUpdate(prevProps) {
    const { characterId, characters, open } = this.props;

    if (prevProps.characterId !== characterId || (!prevProps.open && open)) {
      let name = '';
      if (characterId !== null) {
        name = pathOr('', [characterId])(characters);
      }
      this.setState({ name, error: null });
    }
  }
Example #2
Source File: gameData.js    From archeage-tools with The Unlicense 6 votes vote down vote up
updateBonds = (bonds) => (dispatch) => {
  xhr.post(config.endpoints.service.bluesaltBonds, bonds)
  .then(() => {
    dispatch(fetchBonds());
  })
  .catch((e) => {
    dispatch(setNotification(pathOr('Failed to update bonds.', ['data', 'errorMessage'])(e), NOTIFICATION_TYPE.ERROR));
  });
}
Example #3
Source File: QuestTooltip.jsx    From archeage-tools with The Unlicense 6 votes vote down vote up
mapStateToProps2 = ({ gameData: { rewardTypes, questCriteriaTypes, titles, vocations, questCategories, quests }, dailies: { region } }, { id }) => {
  const quest = pathOr({}, [id])(quests);
  if (quest.categoryId) {
    quest.category = (quest && questCategories[quest.categoryId]) || {};
  }
  return {
    rewardTypes,
    criteriaTypes: questCriteriaTypes,
    titles,
    vocations,
    quest,
    region: region || 'NA',
  };
}
Example #4
Source File: DailyCategory.jsx    From archeage-tools with The Unlicense 6 votes vote down vote up
mapStateToProps = ({ dailies: { collapsedCategories, hiddenCategories, hideComplete, quests: completedQuests, showHidden, hiddenQuests, region, rewards }, gameData: { quests: questData, rewardTypes }, myGame: { castles, residence } }, { id, quests, instance }) => {
  if (instance) {
    quests = quests.map(q => q.id);
  }

  return ({
    collapsed: pathOr(false, [id])(collapsedCategories || {}) === true,
    hidden: pathOr(false, [id])(hiddenCategories || {}) === true && !showHidden,
    isHidden: pathOr(false, [id])(hiddenCategories || {}) === true,
    hideComplete,
    showHidden,
    completedQuests: Object.keys(completedQuests || {}).filter(key => quests.includes(Number.parseInt(key))).reduce((obj, key) => {
      obj[key] = completedQuests[key];
      return obj;
    }, {}),
    hiddenQuests: Object.keys(hiddenQuests || {}).filter(key => quests.includes(Number.parseInt(key))).reduce((obj, key) => {
      obj[key] = hiddenQuests[key];
      return obj;
    }, {}),
    // completedQuests,
    // hiddenQuests,
    region: region || 'NA',
    rewardTypes: Object.values(rewardTypes),
    questData,
    castles,
    residence,
    rewards,
  });
}
Example #5
Source File: EditComment.jsx    From archeage-tools with The Unlicense 6 votes vote down vote up
componentDidMount() {
    const { id, setNotification, onCancel } = this.props;
    if (id) {
      this.setState({ loading: true });
      xhr.get(substitute(config.endpoints.service.comment, { commentId: id }))
      .then(({ data }) => {
        if (data.deleted) {
          setNotification('This comment has been deleted and cannot be edited.', NOTIFICATION_TYPE.WARNING);
          onCancel();
          return;
        }
        this.setState({
          ...data,
          loading: false,
        });
      })
      .catch(error => {
        const message = pathOr('Failed to find comment.', ['data', 'errorMessage'])(error);

        setNotification(message, NOTIFICATION_TYPE.ERROR);
        onCancel();
      });
    }
  }
Example #6
Source File: CharacterDialog.jsx    From archeage-tools with The Unlicense 6 votes vote down vote up
render() {
    const { characters, characterId, open, onClose } = this.props;
    const { name, error } = this.state;
    const characterName = pathOr(null, [characterId])(characters);
    const validChar = !(characterId === null || characterName === null);

    return (
      <Dialog open={open} onClose={onClose}>
        <DialogTitle>
          {!validChar
            ? 'Add Character'
            : `Edit [${characterName}]`}
        </DialogTitle>
        <DialogContent>
          <form onSubmit={this.handleSave}>
            <TextField
              label="Character Name"
              value={name}
              onChange={this.handleChange}
              inputProps={{
                maxLength: 20,
              }}
              autoFocus
              error={Boolean(error)}
              helperText={error}
            />
          </form>
        </DialogContent>
        <DialogActions>
          {validChar &&
          <Button onClick={this.handleDelete} classes={{ label: 'text-red' }}>Delete</Button>}
          <Button onClick={onClose}>Cancel</Button>
          <Button color="primary" onClick={this.handleSave}>Confirm</Button>
        </DialogActions>
      </Dialog>
    );
  }
Example #7
Source File: Avatar.jsx    From archeage-tools with The Unlicense 6 votes vote down vote up
render() {
    const { size: em, avatar } = this.props;
    const size = `${em}em`;

    return (
      <MuiAvatar
        src={pathOr(null, ['src'])(avatar)}
        style={{ width: size, height: size }}
        className={cn('avatar', { [pathOr(null, ['platform'])(avatar)]: true })}
      >
        {!pathOr(null, ['src'])(avatar) && <PersonIcon />}
      </MuiAvatar>
    );
  }
Example #8
Source File: session.js    From archeage-tools with The Unlicense 6 votes vote down vote up
hasPermission = (permission) => (dispatch, getState) => {
  const permissions = Cookies.get('access_token') ? pathOr([], ['session', 'permissions'])(getState()) : [];

  if (permissions.includes(permission.toLowerCase())) {
    return true;
  }

  // find wildcard permissions
  return permission.split('.').some((_, i, permWhole) => {
    const wildcard = permWhole.slice(0, i).join('.');
    return permissions.includes(wildcard ? wildcard : '*');
  });
}
Example #9
Source File: session.js    From archeage-tools with The Unlicense 6 votes vote down vote up
refreshSession = () => (dispatch, getStorage) => new Promise((resolve) => {
  const { session } = getStorage();
  xhr.post(config.endpoints.session.authenticate, {
    grant_type: 'refresh_token',
    refresh_token: session.refresh_token,
  })
  .then(({ data }) => {
    dispatch({ type: SESSION_USER, ...data });
    resolve(data);
  })
  .catch(error => {
    const status = pathOr('', ['status'])(error);
    if (status === 400) {
      dispatch(setNotification('Your session has expired. Please log in again.', NOTIFICATION_TYPE.ERROR));
    } else {
      dispatch(setNotification('An unknown error occurred. Please log in again.', NOTIFICATION_TYPE.ERROR));
    }
    dispatch(logout());
  });
})
Example #10
Source File: session.js    From archeage-tools with The Unlicense 6 votes vote down vote up
createAccount = (data) => (dispatch) => new Promise((resolve, reject) => {
  xhr.post(config.endpoints.session.createAccount, data, { withCredentials: true })
  .then(({ data }) => {
    resolve(data);
  })
  .catch(error => {
    const status = pathOr(500, ['status'])(error);
    const errors = pathOr([], ['data', 'errors'])(error);
    if (status === 500) {
      dispatch(setNotification('Error attempting create account. Please try later.', NOTIFICATION_TYPE.ERROR));
    }
    reject(errors);
  });
})
Example #11
Source File: session.js    From archeage-tools with The Unlicense 6 votes vote down vote up
attemptLogin = (data) => (dispatch) => new Promise((resolve, reject) => {
  xhr.post(config.endpoints.session.authenticate, { grant_type: 'password', ...data }, { withCredentials: true })
  .then(({ data }) => {
    dispatch({ type: SESSION_USER, ...data });
    resolve();
  })
  .catch(error => {
    const status = pathOr(500, ['status'])(error);
    if (status === 400) {
      dispatch(setNotification('Invalid username or password.', NOTIFICATION_TYPE.ERROR));
    } else {
      dispatch(setNotification('Error attempting login. Please try later.', NOTIFICATION_TYPE.ERROR));
    }
    reject(error);
  });
})
Example #12
Source File: schedule.js    From archeage-tools with The Unlicense 6 votes vote down vote up
speak = (text) => (_, getState) => {
  if (!CAN_SPEAK) return;

  const volume = pathOr(VOLUME_DEFAULT, ['calendar', 'volume'])(getState());
  const message = new SpeechSynthesisUtterance();
  Object.entries(SPEECH_PRONUNCIATIONS).forEach(([key, value]) => {
    text = text.replace(key, value);
  });
  message.text = text;
  message.volume = maxDecimals(volume / 150, 2);
  if (preferredVoice) {
    message.voice = preferredVoice;
  }

  window.speechSynthesis.speak(message);
}
Example #13
Source File: CargoShip.jsx    From archeage-tools with The Unlicense 6 votes vote down vote up
mapStateToProps = ({
                           calendar: { alerts, speak },
                           display: { mobile },
                           gameData: { cargoTimers, servers },
                           myGame: { server },
                         }) => ({
  cargoTimers,
  servers,
  server,
  alerts: pathOr([], [CARGO_ID])(alerts),
  speak: pathOr(false, [CARGO_ID])(speak),
  mobile,
})
Example #14
Source File: EditNewsPost.jsx    From archeage-tools with The Unlicense 6 votes vote down vote up
componentDidMount() {
    const { match: { params: { postId, action } } } = this.props;
    if (action === 'edit' && postId) {
      this.setState({ loading: true });
      xhr.get(substitute(config.endpoints.service.newsPost, { postId }))
      .then(({ data }) => {
        this.setState({
          formData: {
            ...data,
          },
          createDate: data.createDate,
          editDate: data.editDate,
          loading: false,
        });
      })
      .catch(error => {
        const message = pathOr('Failed to get existing news post.', ['data', 'errorMessage'])(error);

        this.props.setNotification(message, NOTIFICATION_TYPE.ERROR);
        replace('/news');
      });
    }
  }
Example #15
Source File: gameData.js    From archeage-tools with The Unlicense 6 votes vote down vote up
updateCargoTimer = (cargoTimer) => (dispatch) => {
  xhr.post(config.endpoints.service.cargoTimer, cargoTimer)
  .then(() => {
    dispatch(fetchCargoTimer());
  })
  .catch((e) => {
    dispatch(setNotification(pathOr('Failed to cargo ship timer.', ['data',
      'errorMessage'])(e), NOTIFICATION_TYPE.ERROR));
  });
}
Example #16
Source File: NpcLink.jsx    From archeage-tools with The Unlicense 5 votes vote down vote up
mapStateToProps = ({ gameData: { npcs } }, { id }) => ({
  ...pathOr({}, [id])(npcs),
})
Example #17
Source File: DailyQuest.jsx    From archeage-tools with The Unlicense 5 votes vote down vote up
render() {
    const { id, name, completed, hidden, rewards, region, rewardTypes, instance } = this.props;
    const { setQuestStatus, setQuestHide } = this.props;

    const typeItem = pathOr(null, ['id'])(rewardTypes.find(t => t.name === REWARD_ITEM));
    const typeXp = pathOr(null, ['id'])(rewardTypes.find(t => t.name === REWARD_XP));
    const typeCoin = pathOr(null, ['id'])(rewardTypes.find(t => t.name === REWARD_COINS));
    const typeProf = pathOr(null, ['id'])(rewardTypes.find(t => t.name === REWARD_PROFICIENCY));

    const itemRewards = rewards
      ? rewards.filter(r => r.typeId === typeItem && (r.region === region || !r.region) && !r.optional) : [];
    const currencyRewards = rewards
      ? rewards.filter(r => ![typeItem, typeXp, typeCoin, typeProf].includes(r.typeId) &&
        (r.region === region || !r.region))
      : [];

    const maxRewards = instance ? 3 : 2;

    return (
      <Paper className="quest">
        <Checkbox
          color="primary"
          checked={completed}
          onChange={(_, checked) => setQuestStatus(id, checked)}
        />
        <QuestTooltip questId={id} disabled={instance}>
          <Typography variant="body2">
            {name}
          </Typography>
        </QuestTooltip>
        <div className="rewards">
          {itemRewards.slice(0, maxRewards).map(item => (
            <Item
              id={item.refId}
              count={item.quantity}
              showCount
              inline
              key={`qr-${id}-${item.refId}`}
            />))}
          {currencyRewards.slice(0, 2).map(currency => (
            <Currency
              key={`qr-${id}-${currency.typeId}`}
              type={rewardTypes.find(r => r.id === currency.typeId).name}
              count={currency.quantity}
              inline
              tooltip
            />))}
          <Tooltip title={`${hidden ? 'Show' : 'Hide'} ${instance ? 'Instance' : 'Quest'}`}>
            <IconButton onClick={() => setQuestHide(id, !hidden)} size="small" color="inherit">
              {hidden
                ? <VisibilityIcon />
                : <VisibilityOffIcon />}
            </IconButton>
          </Tooltip>
        </div>
      </Paper>
    );
  }
Example #18
Source File: PackViewer.jsx    From archeage-tools with The Unlicense 5 votes vote down vote up
// eslint-disable-next-line class-methods-use-this
  UNSAFE_componentWillReceiveProps(nextProps) {
    const packRecipe = pathOr(null, ['pack', 'recipeId'])(nextProps);
    if (packRecipe) {
      fetchRecipe(packRecipe);
    }
  }
Example #19
Source File: PackViewer.jsx    From archeage-tools with The Unlicense 5 votes vote down vote up
mapStateToProps = ({
                           tradepacks,
                           display: { mobile },
                           gameData: {
                             recipes,
                             tradePacks: { types, freshness: freshnessData = {} },
                             continents,
                             zones,
                           },
                         }, { pack, sellZoneId }) => {
  const tradePack = pack || {};
  let freshness;
  if (tradePack.packTypeId === PACK_TYPE.CARGO) {
    freshness = freshnessData[FRESHNESS.CARGO];
  } else if (tradePack.packTypeId === PACK_TYPE.DISGUISED) {
    freshness = freshnessData[FRESHNESS.DISGUISED];
  } else {
    freshness = Object.values(freshnessData).find(f => f.zoneIds.includes(tradePack.originZoneId));
  }
  return {
    region: tradepacks.region,
    craftLarder: tradepacks.craftLarder,
    degradeDemand: tradepacks.degradeDemand,
    showInterest: tradepacks.showInterest,
    ahCut: tradepacks.ahCut,
    packType: pathOr({}, [tradePack.packTypeId])(types),
    freshness,
    profitLevelName: pathOr('High', ['profitLevel', tradePack.id, sellZoneId])(tradepacks),
    percentage: pathOr(tradepacks.percentage, ['percentages', tradePack.id, sellZoneId])(tradepacks),
    quantity: pathOr(1, ['quantities', tradePack.id])(tradepacks),
    supplyLevelName: pathOr('Limited', ['supply', tradePack.id])(tradepacks),
    transportationQty: pathOr({}, ['transportationQty', tradePack.originZoneId, sellZoneId])(tradepacks),
    war: pathOr(false, ['war', sellZoneId])(tradepacks),
    mobile,
    recipe: recipes[tradePack.recipeId] || {},
    continents,
    zoneName: pathOr('', [tradePack.originZoneId, 'name'])(zones),
    zones,
  };
}
Example #20
Source File: calendar.js    From archeage-tools with The Unlicense 5 votes vote down vote up
calendar = (state = getItem('calendar', initialState), action) => {
  switch (action.type) {
    case SET_REGION:
      return {
        ...state,
        region: action.region,
      };
    case SET_ALERT: {
      const alerts = pathOr([], ['alerts', action.eventId])(state);
      if (action.value !== '') {
        toggleValue(alerts, action.value);
      } else {
        alerts.splice(0);
      }

      return {
        ...state,
        alerts: {
          ...state.alerts,
          [action.eventId]: alerts,
        },
      };
    }
    case CLEAR_ALERTS:
      return {
        ...state,
        alerts: {},
      };
    case SET_VOLUME:
      return {
        ...state,
        volume: action.volume,
      };
    case SET_SPEAK:
      return {
        ...state,
        speak: {
          ...state.speak,
          [action.eventId]: action.value,
        },
      };
    default:
      return state;
  }
}
Example #21
Source File: SkillTooltip.jsx    From archeage-tools with The Unlicense 5 votes vote down vote up
mapStateToProps = ({ gameData: { skills, skillsets } }, { skillId }) => {
  const skill = pathOr({}, [skillId])(skills);
  return {
    ...skill,
    skillset: pathOr({ id: 0, name: 'Basic' }, [skill.skillsetId])(skillsets),
  };
}
Example #22
Source File: Skill.jsx    From archeage-tools with The Unlicense 5 votes vote down vote up
mapStateToProps = ({ gameData: { skills } }, { id }) => ({
  ...pathOr({}, [id])(skills),
})
Example #23
Source File: QuestTooltip.jsx    From archeage-tools with The Unlicense 5 votes vote down vote up
mapStateToProps = ({ gameData: { quests } }, { questId }) => ({
  quest: pathOr({}, [questId])(quests),
})
Example #24
Source File: NpcTooltip.jsx    From archeage-tools with The Unlicense 5 votes vote down vote up
mapStateToProps = ({ gameData: { npcs } }, { npcId }) => ({
  npc: pathOr({}, [npcId])(npcs),
})
Example #25
Source File: NpcTooltip.jsx    From archeage-tools with The Unlicense 5 votes vote down vote up
mapStateToProps2 = ({ gameData: { npcs } }, { id }) => ({
  npc: pathOr({}, [id])(npcs),
})
Example #26
Source File: QuestLink.jsx    From archeage-tools with The Unlicense 5 votes vote down vote up
mapStateToProps = ({ gameData: { quests, questCategories }, dailies: { region } }, { id }) => {
  const quest = pathOr({}, [id])(quests);
  return {
    ...quest,
    region: region || 'NA',
    category: (quest && questCategories[quest.categoryId]) || {},
  };
}
Example #27
Source File: Navigation.jsx    From archeage-tools with The Unlicense 5 votes vote down vote up
render() {
    const { session, mobile } = this.props;
    const { userEl } = this.state;

    const menuItems = [];

    session.isAuthenticated = Boolean(session.access_token);
    if (session.isAuthenticated) {
      menuItems.push(
        <Link href={myAccountUrl} color="inherit" underline="none" key="my-acc"><MenuItem>My Account</MenuItem></Link>,
      );
      menuItems.push(<MenuItem onClick={this.handleNavigate('logout')} key="logout">Logout</MenuItem>);
    } else {
      menuItems.push(<MenuItem onClick={this.handleNavigate('login')} key="login">Login</MenuItem>);
      menuItems.push(<MenuItem onClick={this.handleNavigate('register')} key="create">Create Account</MenuItem>);
      session.avatar = null;
      session.discord = null;
    }

    const discordAvatar = pathOr(null, ['discord', 'avatar'])(session);
    const defaultAvatar = discordAvatar;
    switch (session.avatar) {
      case 0:
        session.avatarSrc = discordAvatar;
        break;
      default:
        session.avatarSrc = defaultAvatar;
    }
    if (!session.avatarSrc) {
      session.avatarSrc = defaultAvatar;
    }
    switch (session.avatarSrc) {
      case null:
        session.avatarPlatform = null;
        break;
      case discordAvatar:
        session.avatarPlatform = 'discord';
        break;
      default:
        session.avatarPlatform = null;
    }

    return (
      <>
        {!mobile &&
        <DesktopNavigation
          menuItems={menuItems}
          session={session}
          myAccountUrl={myAccountUrl}
          userMenu={userEl}
        />}
        <MobileNavigation
          menuItems={menuItems}
          session={session}
          myAccountUrl={myAccountUrl}
          open={Boolean(userEl)}
          handleOpen={this.handleOpen}
          handleClose={this.handleClose}
        />

        {!session.isAuthenticated &&
        <>
          <Login />
          <Register />
        </>}
      </>
    );
  }
Example #28
Source File: Residence.jsx    From archeage-tools with The Unlicense 5 votes vote down vote up
render() {
    const { residence, castles, continents, zones, setResidence, setCastles } = this.props;

    const zoneOptions = Object.values(zones).filter(z => z.housing)
    .map(z => ({
      ...z,
      group: continents[z.continentId].name,
    }))
    .sort(sortBy('group', true, sortBy('name')));

    const castleOptions = Object.values(zones).filter(z => z.claimable)
    .sort(sortBy('name'));

    return (
      <div className="residence-wrapper">
        <Autocomplete
          multiple
          options={zoneOptions}
          getOptionLabel={(option) => {
            if (typeof option === 'number') {
              return pathOr('', [option, 'name'])(zones);
            } else {
              return option.name;
            }
          }}
          getOptionSelected={(option, value) => option.id === value}
          groupBy={option => option.group}
          onChange={setResidence}
          value={residence}
          renderInput={(params) => (
            <TextField
              {...params}
              variant="standard"
              label="Your Residential Zones"
              placeholder="Select zone"
            />
          )}
        />
        <Autocomplete
          multiple
          options={castleOptions}
          getOptionLabel={(option) => {
            if (typeof option === 'number') {
              return pathOr('', [option, 'name'])(zones);
            } else {
              return option.name;
            }
          }}
          getOptionSelected={(option, value) => option.id === value}
          groupBy={option => option.group}
          onChange={setCastles}
          value={castles}
          renderInput={(params) => (
            <TextField
              {...params}
              variant="standard"
              label="Your Faction's Castles"
              placeholder="Select zone"
            />
          )}
        />
      </div>
    );
  }
Example #29
Source File: MapEmbed.jsx    From archeage-tools with The Unlicense 5 votes vote down vote up
mapStateToProps = ({ gameData: { zones } }, { zone }) => ({
  zoneName: pathOr(zone, [zone, 'name'])(zones),
})