npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

simple-mui-redux-form

v1.1.1

Published

``` npm install simple-mui-redux-form ```

Downloads

34

Readme

Установка:

npm install simple-mui-redux-form

TextInput - компонент-обертка над mui TextField

По сравнению с TextField имеет 3 дополнительных свойства, и еще 3 свойства получает от компонента высшего порядка WithErrorHandling (см. ниже)

import { TextFieldProps } from "@mui/material"

type TextInputProps = TextFieldProps & {
  inputField: InputField;
  needHelperText?: boolean;
  onchange: (value: string, error: string) => void;
};

Производные от TextInput компоненты:

PasswordInput

type PasswordInputProps = Omit<
  TextInputProps,
  "InputProps" | "autoComplete" | "password"
>;

const PasswordInput: FC<PasswordInputProps & WithHandlingError> = (props) => {
  const { type, handleCLick, passwordVisibility } = useTextInput(true);
  return (
    <TextInput
      type={type}
      InputProps={{
        endAdornment: (
          <PasswordVisibilityButton
            onclick={handleCLick}
            show={passwordVisibility}
          />
        ),
      }}
      {...props}
    ></TextInput>
  );
};

и NotEmptyTextInput

const NotEmptyTextInput: FC<TextInputProps & WithHandlingError> = ({
  validateHelpers = [],
  ...props
}) => {
  return (
    <TextInput
      validateHelpers={[...validateHelpers, notEmpty]}
      {...props}
    ></TextInput>
  );
};

WithErrorHandling (HOC)

добавляет в TextInput свойства для обработки пользовательского ввода:

type WithErrorHandlingProps = {
  validateHelpers?: Array<ValidateHelper>;
  validateOptions?: ValidateOptions;
  mutators?: Array<InputMutator>;
};

export type ValidateHelper = {
  error_text: string;
  validate: InputValidator;
};

export type InputValidator = (
  inputed: string,
  options: ValidateOptions
) => boolean;

export type InputMutator = (inputed: string) => string;

export type ValidateOptions = {
  min?: number;
  max?: number;
  moreThan?: number;
  lessThan?: number;
  minLength?: number;
  maxLength?: number;
  maxAfterDot?: number;
};

Например, нужно задать минимальную длину вводимого текста 8 символов, в этом нам поможет функция-валидатор checkLength

import {checkLength, TextInput} from 'simple-mui-redux-form'

const Min8CharsInput = () => {
  const validator = {validate: checkLength, error_text:'Минимум 8 символов'}
  return (
    <TextInput
      ...
      validateHelpers={[validator]}
      validateOptions={{minLength: 8}}
      ...
  />
)}

createSliceOptions

Облегчает создание слайса формы

import { createSlice } from "@reduxjs/toolkit";
import {
  createSliceOptions,
  isFormValid,
  defaulInputField,
} from "simple-mui-redux-form";
import { RootState } from "..";

type LoginFormFieldName = "username" | "password"

const SignInSlice = createSlice(
  createSliceOptions<LoginFormFieldName>("login-form", {
    username: { ...defaulInputField },
    password: { ...defaulInputField },
  })
);

export const selectIsFormValid = (state: RootState): boolean =>
  isFormValid(state.loginFormState);

export const { setInitialValues, setInputField, setTouchedAll, resetForm } =
  SignInSlice.actions;
export default SignInSlice.reducer;

Что еще есть в пакете:

type InputField = {
  value: string;
  error: string;
  unTouched: boolean;
};
type InputPayload = Omit<InputField, "unTouched">;
// N - объединение (union) имён полей формы
type FormState<N extends string> = {
  [key in N]: InputField;
};
// N - объединение (union) имён полей формы
type FormPayload<N extends string> = {
  [key in N]: string;
};
// N - объединение (union) имён полей формы
const useForm = <N extends string>(
  inputFields: FormState<N>,
  reducer: ActionCreatorWithPreparedPayload<
    [N, string, string],
    WithInputField<N>
  >
) => {
  const dispatch = useDispatch();
  const formPayload = createFormPayload(inputFields);

  const handleChange = (name: N) => {
    return (value: string, error: string) => {
      dispatch(reducer(name, value, error));
    };
  };
  return { formPayload, handleChange };
};
// N - объединение (union) имён полей формы
type WithInputField<N> = {
  inputPayload: InputPayload;
  name: N;
};
const checkDiapason: InputValidator = (
  inputed: string,
  options: ValidateOptions
) => {
  const value = Number(inputed);
  if (isNaN(value)) return false;
  let correct = true;
  const { max, min, moreThan, lessThan } = options;
  if (typeof max === "number") correct = value <= max;
  if (typeof min === "number" && correct) correct = value >= min;
  if (typeof moreThan === "number" && correct) correct = value > moreThan;
  if (typeof lessThan === "number" && correct) correct = value < lessThan;
  return correct;
};
const checkLength: InputValidator = (
  inputed: string,
  options: ValidateOptions
) => {
  let correct = true;
  const { maxLength, minLength } = options;
  if (typeof minLength === "number") correct = inputed.length >= minLength;
  if (typeof maxLength === "number") correct = inputed.length <= maxLength;
  return correct;
};
const checkNotEmpty: InputValidator = (inputed: string) =>
  checkLength(inputed, { minLength: 1 });
const notEmpty: ValidateHelper = {
  validate: checkNotEmpty,
  error_text: "Поле не должно быть пустым",
};
const defaulInputField: InputField = {
  error: "",
  value: "",
  unTouched: true,
};