lodash#upperFirst JavaScript Examples

The following examples show how to use lodash#upperFirst. 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: rollup.config.js    From web-performance-monitor with MIT License 6 votes vote down vote up
out = [
  {
    file: pkg.main,
    format: 'cjs'
  },
  {
    file: pkg.module,
    format: 'esm'
  },
  {
    file: pkg.browser,
    format: 'umd',
    name: filename
      .split('-')
      .map((i) => upperFirst(i))
      .join('')
  }
]
Example #2
Source File: generate.js    From dls-icons with MIT License 4 votes vote down vote up
async function generate() {
  clearDir(SVG_DIR)
  clearDir(path.join(DATA_DIR, 'icons'))

  ICON_PACKS.forEach((pack) => {
    let iconsDir = path.join(getPackDir(pack), 'src/icons')
    clearDir(iconsDir)
  })

  Promise.all(
    (await getSVGFiles()).map(async ({ slug, content }) => {
      let file = `${slug}.svg`
      let { el, content: svg, width, height } = await normalizeSVG(
        content,
        file
      )

      fs.writeFileSync(path.join(SVG_DIR, file), svg, 'utf8')

      let name = camelCase(slug)
      let Name = upperFirst(name)

      let iconCode = stringifyObject(
        {
          name: `icon-${slug}`,
          content: el.children.map((child) => stringify(child)).join(''),
          width: Number(width),
          height: Number(height),
        },
        {
          indent: '  ',
        }
      )

      let tplData = {
        name,
        Name,
        icon: iconCode,
      }

      let dataModuleCode = renderTpl(DATA_TPL, tplData)
      let iconModuleCode = renderTpl(ICON_TPL, tplData)

      fs.writeFileSync(path.join(DATA_DIR, `icons/${Name}.js`), dataModuleCode, 'utf8')

      ICON_PACKS.forEach((pack) => {
        let iconsDir = path.join(getPackDir(pack), 'src/icons')
        fs.writeFileSync(path.join(iconsDir, `${Name}.js`), iconModuleCode, 'utf8')
      })

      return { slug, name, Name, file }
    })
  ).then((icons) => {
    let dataIndex = icons
      .map((data) => renderTpl(DATA_EXPORT_TPL, data))
      .join('')

    fs.writeFileSync(path.join(DATA_DIR, 'index.js'), dataIndex, 'utf8')

    let iconIndex =
      icons.map((data) => renderTpl(ICON_EXPORT_TPL, data)).join('') +
      `export createIcon from './createIcon'\n`

    ICON_PACKS.concat(DATA_PACK).forEach((pack) => {
      let packDir = getPackDir(pack)
      if (pack !== DATA_PACK) {
        fs.writeFileSync(path.join(packDir, 'src/index.js'), iconIndex, 'utf8')
      }

      let readmeFile = path.join(packDir, 'README.md')
      let readmeContent = fs.readFileSync(readmeFile, 'utf8')

      let cols = 5
      let prefix = pack === DATA_PACK ? 'data' : 'Icon'
      let iconTable =
        '<table><tbody>' +
        Array.from({ length: Math.ceil(icons.length / cols) })
          .map((_, i) => {
            return Array.from({ length: cols })
              .map((_, j) => icons[i * cols + j])
              .map(
                (icon) =>
                  `<td align="center">${
                    icon
                      ? `<img src="https://raw.githubusercontent.com/ecomfe/dls-icons/master/svg/${icon.file}" height="24"/><br/><sub>${prefix}${icon.Name}</sub>`
                      : ''
                  }</td>`
              )
              .join('')
          })
          .map((row) => `<tr>${row}</tr>`)
          .join('') +
        '</tbody></table>'
      fs.writeFileSync(
        readmeFile,
        commentMark(readmeContent, {
          icons: iconTable,
        }),
        'utf8'
      )
    })

    console.log(`Normalized ${icons.length} icons.`)
  })
}
Example #3
Source File: language-panel.js    From horondi_admin with MIT License 4 votes vote down vote up
LanguagePanel = ({ lang, inputOptions }) => {
  const styles = useStyles();

  const {
    values,
    touched,
    errors,
    inputs,
    handleChange,
    handleBlur,
    setFieldValue
  } = inputOptions;
  const inputsTextfields = inputs.filter((input) => !input.isEditor);
  const inputsEditor = inputs.filter((input) => input.isEditor);

  return (
    <>
      <div className={styles.languagePanel}>
        <Typography className={styles.title} component='h1' variant='h5'>
          {lang.toUpperCase()}
        </Typography>
        <Paper className={styles.inputPanel}>
          {map(inputsTextfields, (input) => {
            const inputName = lang + upperFirst(input.name);
            return (
              <React.Fragment key={input.name}>
                <TextField
                  data-cy={`${lang}-${input.name}`}
                  data-testid='title-edit-input'
                  id={inputName}
                  className={styles.textField}
                  variant='outlined'
                  label={input.label[lang]}
                  error={touched[inputName] && !!errors[inputName]}
                  multiline
                  value={values[inputName]}
                  onChange={handleChange}
                  onBlur={handleBlur}
                  {...input.props}
                />
                {touched[inputName] && errors[inputName] && (
                  <div
                    data-cy={`${lang}-${input.name}-error`}
                    className={styles.error}
                  >
                    {errors[inputName]}
                  </div>
                )}
              </React.Fragment>
            );
          })}
          {map(inputsEditor, (input) => {
            const inputName = lang + upperFirst(input.name);
            const setEditorValue = (value) => {
              values[inputName] = value;
            };
            return (
              <>
                <Editor
                  value={values[inputName]}
                  placeholder={input.label[lang]}
                  onBlur={handleBlur}
                  onEditorChange={(value) => {
                    setFieldValue(inputName, value.toString());
                    setEditorValue(value);
                  }}
                  setFiles={input.setFiles}
                  data-cy={`${lang}-${input.name}`}
                  label={lang}
                  id={`${lang}-${input.name}`}
                  key={lang}
                />
                {touched[`${lang}-${input.name}`] && errors[inputName] && (
                  <div
                    data-cy={`${lang}-${input.name}-error`}
                    className={styles.error}
                  >
                    {errors[inputName]}
                  </div>
                )}
              </>
            );
          })}
        </Paper>
      </div>
    </>
  );
}
Example #4
Source File: index.js    From strapi-plugins with MIT License 4 votes vote down vote up
AuthPage = ({
  hasAdminUser,
  // -- add locationState from location props
  location: { search, state: locationState },
  // -- --- --
  match: {
    params: { authType },
  },
}) => {
  const [reducerState, dispatch] = useReducer(reducer, initialState);
  const codeRef = useRef();
  const abortController = new AbortController();

  const { signal } = abortController;
  codeRef.current = getQueryParameters(search, 'code');

  // -- small hack if coming from logout
  // -- for Strapi to reload content-types
  const history = useHistory();

  useEffect(() => {
    if (locationState && locationState.reload) {
      history.replace({
        pathname: `/auth/${authType}`,
        state: {},
      });

      window.location.reload();
    }
  }, []);
  // -- --- --

  useEffect(() => {
    // Set the reset code provided by the url
    if (authType === 'reset-password') {
      dispatch({
        type: 'ON_CHANGE',
        keys: ['code'],
        value: codeRef.current,
      });
    } else {
      // Clean reducer upon navigation
      dispatch({
        type: 'RESET_PROPS',
      });
    }

    return () => {
      abortController.abort();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [authType, codeRef]);
  const { didCheckErrors, errors, modifiedData, submitSuccess, userEmail } = reducerState.toJS();
  const handleChange = ({ target: { name, value } }) => {
    dispatch({
      type: 'ON_CHANGE',
      keys: name.split('.'),
      value,
    });
  };

  const handleSubmit = async e => {
    e.preventDefault();
    const schema = forms[authType].schema;
    let formErrors = {};

    try {
      await schema.validate(modifiedData, { abortEarly: false });

      if (modifiedData.news === true) {
        request('https://analytics.strapi.io/register', {
          method: 'POST',
          body: pick(modifiedData, ['email', 'username']),
          signal,
        }).catch(() => {
          // ignore error
        });
      }

      try {
        const requestEndPoint = forms[authType].endPoint;
        const requestURL = `/admin/auth/${requestEndPoint}`;
        const body = omit(modifiedData, 'news');

        if (authType === 'forgot-password') {
          set(body, 'url', `${strapi.remoteURL}/auth/reset-password`);
        }

        const { jwt, user, ok } = await request(requestURL, {
          method: 'POST',
          body,
          signal,
        });

        if (authType === 'forgot-password' && ok === true) {
          dispatch({
            type: 'SUBMIT_SUCCESS',
            email: modifiedData.email,
          });
        } else {
          auth.setToken(jwt, modifiedData.rememberMe);
          auth.setUserInfo(user, modifiedData.rememberMe);
        }
      } catch (err) {
        const formattedError = formatErrorFromRequest(err);

        if (authType === 'login') {
          formErrors = {
            global: formattedError,
            identifier: formattedError,
            password: formattedError,
          };
        } else if (authType === 'forgot-password') {
          formErrors = { email: formattedError[0] };
        } else {
          strapi.notification.error(get(formattedError, '0.id', 'notification.error'));
        }
      }
    } catch (err) {
      formErrors = getYupInnerErrors(err);
    }

    dispatch({
      type: 'SET_ERRORS',
      formErrors,
    });
  };

  // Redirect the user to the login page if the endpoint does not exist
  if (!Object.keys(forms).includes(authType)) {
    return <Redirect to="/" />;
  }

  // Redirect the user to the homepage if he is logged in
  if (auth.getToken()) {
    return <Redirect to="/" />;
  }

  if (!hasAdminUser && authType !== 'register') {
    return <Redirect to="/auth/register" />;
  }

  // Prevent the user from registering to the admin
  if (hasAdminUser && authType === 'register') {
    return <Redirect to="/auth/login" />;
  }

  const globalError = get(errors, 'global.0.id', '');
  const shouldShowFormErrors = !isEmpty(globalError);

  return (
    <>
      <PageTitle title={upperFirst(authType)} />
      <Wrapper authType={authType} withSuccessBorder={submitSuccess}>
        <NavTopRightWrapper>
          <LocaleToggle isLogged className="localeDropdownMenuNotLogged" />
        </NavTopRightWrapper>
        <div className="wrapper">
          <div className="headerContainer">
            {authType === 'register' ? (
              <FormattedMessage id="Auth.form.header.register" />
            ) : (
                <img src={LogoStrapi} alt="strapi-logo" />
              )}
          </div>
          <div className="headerDescription">
            {authType === 'register' && <FormattedMessage id="Auth.header.register.description" />}
          </div>
          {/* TODO Forgot success style */}
          <div className="formContainer bordered">
            <form onSubmit={handleSubmit}>
              <div className="container-fluid">
                {shouldShowFormErrors && (
                  <div className="errorsContainer">
                    <FormattedMessage id={globalError} />
                  </div>
                )}
                <div className="row" style={{ textAlign: 'start' }}>
                  {submitSuccess && (
                    <div className="forgotSuccess">
                      <FormattedMessage id="Auth.form.forgot-password.email.label.success" />
                      <br />
                      <p>{userEmail}</p>
                    </div>
                  )}
                  {!submitSuccess &&
                    forms[authType].inputs.map((row, index) => {
                      return row.map(input => {
                        return (
                          <Input
                            {...input}
                            autoFocus={index === 0}
                            didCheckErrors={didCheckErrors}
                            errors={errors}
                            key={input.name}
                            noErrorsDescription={shouldShowFormErrors}
                            onChange={handleChange}
                            value={modifiedData[input.name]}
                          />
                        );
                      });
                    })}
                  <div
                    className={`${
                      authType === 'login' ? 'col-6 loginButton' : 'col-12 buttonContainer'
                      }`}
                  >
                    <Button
                      color="primary"
                      className={submitSuccess ? 'buttonForgotSuccess' : ''}
                      type="submit"
                      style={authType === 'login' ? {} : { width: '100%' }}
                    >
                      <FormattedMessage
                        id={`Auth.form.button.${
                          submitSuccess ? 'forgot-password.success' : authType
                          }`}
                      />
                    </Button>
                  </div>
                </div>
              </div>
            </form>
          </div>
          <div className="linkContainer">
            {authType !== 'register' && authType !== 'reset-password' && (
              <Link to={`/auth/${authType === 'login' ? 'forgot-password' : 'login'}`}>
                <FormattedMessage
                  id={`Auth.link.${authType === 'login' ? 'forgot-password' : 'ready'}`}
                />
              </Link>
            )}
          </div>
          {authType === 'register' && (
            <div className="logoContainer">
              <img src={LogoStrapi} alt="strapi-logo" />
            </div>
          )}
        </div>
      </Wrapper>
    </>
  );
}