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

@form-instant/react-input-mapping

v1.6.0

Published

## input-mapping

Downloads

402

Readme

Install

input-mapping

npm

npm i @form-instant/react-input-mapping

bun

bun add @form-instant/react-input-mapping

resolvers

zod

npm

npm i @form-instant/react-resolver-zod

bun

bun add @form-instant/react-resolver-zod

Example

react

constructor new InputMapping

* new Input Mapping

Is the pillar of this set of tools, it consists of an extraction of the native new Map method in javascript, which receives as a parameter an object which works as a mapping of the input types, it also accepts two types as a parameter P are the parameters that each input component will accept and K are additional keys that are added to the input glossary.

import {
  InputMapping
} from "@form-instant/react-input-mapping";

export type ExtendProps = React.InputHTMLAttributes<HTMLInputElement>;
export type P = ParsedField<
  ExtendProps,
  string
>;
export type K = "email" | "password";

const inputMapping = new InputMapping<P, K>({
  fallback: (props) => {
    const { fieldConfig, name, ...prop } = props;

    return <input {...prop} {...fieldConfig} />;
  },
  textarea: () => <textarea />,
  number: (props) => {
    const { fieldConfig, name, ...prop } = props;

    return <input {...prop} {...fieldConfig} />;
  },
  text: (props) => {
    const { fieldConfig, name, ...prop } = props;

    return <input {...prop} {...fieldConfig} />;
  },
  date: () => <input type="date" />,
  email: (props) => {
    const { fieldConfig, name, ...prop } = props;

    return <input {...prop} {...fieldConfig} />;
  },
  password: (props) => {
    const { fieldConfig, name, ...prop } = props;

    return <input {...prop} {...fieldConfig} />;
  },
  select: (props) => {
    const { options } = props;

    return (
      <select>
        {options?.map(([k, v]) => (
          <option key={k} value={k}>
            {v}
          </option>
        ))}
      </select>
    );
  },
});

default keys glossary, all values ​​entered by k will only understand the default listing.

export type INPUT_COMPONENTS_KEYS =
    | 'checkbox'
    | 'date'
    | 'select'
    | 'radio'
    | 'switch'
    | 'textarea'
    | 'number'
    | 'file'
    | 'text'
    | 'fallback';

* create global provider

We created a global provider to be able to access input mapping.

import { createFormInstantContainer } from '@form-instant/react-input-mapping';
import { inputMapping, P, K } from './inputMapping.tsx';

export const { FormInstantInputsProvider, useInputMapping } = createFormInstantContainer<P, K>(
    inputMapping,
);

we add our provider in the root of the vite project "./App.tsx" and next.js "layout.tsx" in the root.

next.js

import { ReactNode } from "react";
import { FormInstantInputsProvider } from "./components/providers";

function Layout({ children }: { children: ReactNode }) {
  return (
    <FormInstantInputsProvider>
      {children}
    </FormInstantInputsProvider>
  );
}

export default Layout;

vite

import "./App.css";
import { Router } from "./router";
import { FormInstantInputsProvider } from "./components/providers";

function App() {
  return (
    <FormInstantInputsProvider>
      <Forms />
    </FormInstantInputsProvider>
  );
}

export default App;

use resolver

To use our resolver we must add the function fieldConfig.

zod

generate provider and hook by use resolver.

import { createFormInstantContainer } from '@form-instant/react-input-mapping';
import { inputMapping, P, K, extendProps } from './inputMapping.tsx';

export const { FormInstantInputsProvider, useInputMapping } = createFormInstantContainer<P, K>(
    inputMapping,
);

add fieldConfig in the zod schema.

import { z } from 'zod';

extendZodWithFieldConfig<React.InputHTMLAttributes<HTMLInputElement>>(z);

export { z };

* build form

  • schema:
import { z } from 'zod';

const formSchema = z.object({
  data: z.object({
    email: z.string().email(),
    password: z.string(),,
    confirm: z.string(),
  })
});

export type formSchemaType = Zod.infer<typeof formSchema>;
  • component
import {
  FormInstantElement,
  FormInstantProvider,
} from "@form-instant/react-resolver-zod";
import { z } from "zod";
import { formSchema, formSchemaType } from "./schema";

export const Forms = () => {
  return (
    <form>
      <h1>your form</h1>
      <FormInstantProvider schema={formSchema}>
        <div>
          <FormInstantElement<formSchemaType> name="security_data" />
          <br />
          <FormInstantElement<formSchemaType> name="personal_data" />
        </div>
      </FormInstantProvider>

      <button type="submit">submit</button>
    </form>
  );
};

special inputs

use-formInstantField

by object

import { Fragment } from "react";
import { ElementMapping, ParsedField, useFormInstantField } from "@form-instant/react-input-mapping";
import { P } from "@/providers";

export const ObjectComp: FC<P> = (props) => {
  const { fiends, fieldConfig, ...prop } = useFormInstantField<P>(props);
  const id = useId();

  return (
    <div {...{ ...fieldConfig, ...prop }}>
      {fiends.map((prop) => {
        return (
          <Fragment key={`${id}-${prop.name.history}`}>
            <ElementMapping formProps={prop} />
          </Fragment>
        );
      })}
    </div>
  );
};

by array

import { Fragment, useId } from "react";
import { ElementMapping, ParsedField, useFormInstantField } from "@form-instant/react-input-mapping";
import { P } from "@/providers";


export const ArrayComp: FC<P> = (props) => {
  const { fiends, fieldConfig, ...prop } = useFormInstantField<P>(props);
  const id = useId();

  return (
    <div {...{ ...fieldConfig, ...prop }}>
      {fiends.map((prop, index) => {
        return (
          <Fragment key={`${id}-${prop.name.history}`}>
            <div>
              <ElementMapping formProps={prop} />
              <button onClick={() => append()}>+</button>
              <button onClick={() => remove(index)}>-</button>
            </div>
            <br />
            <br />
          </Fragment>
        );
      })}
    </div>
  );
};

reactive schemas

fieldConfig

import { Fragment, useId } from "react";
import { ElementMapping, useFormInstantField } from "@form-instant/react-input-mapping";
import { FormInstantElement, FormInstantProvider } from "@form-instant/react-resolver-zod";
import { P } from "@/providers";
import { z } from '@/zod';

const formSchema = z.object({
  data: z.object({
    email: z.string().email().fieldConfig({
      fieldType: "email",
      placeholder: "[email protected]",
    }),
    password: z.string().fieldConfig({
      fieldType: "password",
      placeholder: "******",
    }),
    confirm: z.string(),
  })
});

export const FromComp = (props) => {

  return (
    <>
      <FormInstantProvider schema={schema}>
        <h1>your form </h1>
        <div>
           <br />
          <FormInstantElement<formSchemaType> name="data" />
        </div>
        <button>
          submit
        </button>
      </FormInstantProvider>
    </>
  );
};

use-schema

useSchema is a hook, receives two values, a callback and a dependencies object, the callback will be executed when the dependencies change, similar to a useEffect, the callback receives as a parameter the same dependencies object, the callback must always return a valid zod schema..

  const [dependencies, setDependencies] = useState({ status: "ok" });

  const { schema } = useSchema((dependencies /* is a dependencies object */) => {
    return formSchema;
  }, dependencies);

Example with react-hook-form we must remember that they can use the form hook or form solution that the developer prefers, in this example shows the usage for conditional rendering using the z.discriminatedUnion method of zod.

When used in z.discriminatedUnion, an array of objects is received, where the first object is the input of the discriminant condition and will have the discriminator type, with this key or the fiendType that you pass in the fiendConfig you can capture this value in the mapping.

import { Fragment, useId } from "react";
import { ElementMapping, ParsedField, useFormInstantField } from "@form-instant/react-input-mapping";
import { FormInstantElement, FormInstantProvider, useSchema } from "@form-instant/react-resolver-zod";
import { FormInstantInputsProvider, useInputMapping } from "@/resolver";
import { P } from "@/providers";
import { z } from '@/zod';

const formSchema = z.object({
  data: z.discriminatedUnion("status", [
    z.object({
      status: z.literal("ok"),

      code: z.string(),
    }),
    z.object({
      status: z.literal("not"),

      birthday: z.coerce.date(),
    }),
  ]),
});

export const FromComp = (props) => {

  // define state by dependecys
  const [dependencies, setDependencies] = useState({ status: "" });

  const { schema } = useSchema(() => {
    return formSchema;
  }, dependencies);

  const form = useForm<Zod.infer<typeof schema>>({
    resolver: zodResolver(schema),
    defaultValues: {
      data: {
        status: "ok",
      },
    },
  });

  useEffect(() => {

    /* This way of capturing and formatting form data was
    taken from the useFormValues ​​hook
    recommended by react-hook-form */
    const fromValues = {
      ...form.getValues(),
      ...form.watch(),
    };

    if (
      !dependencies.status ||
      dependencies.status !== fromValues.data.status
    ) {

      setDependencies((prev) => {
        return {
          ...prev,
          status: fromValues.data.status,
        };
      });
    }
  }, [form.watch(), dependencies]);

  const onSubmit = form.handleSubmit(
    (data) => {
      console.log("data", data);
    },
    (err) => {
      console.log("err", err);
    }
  );

  return (
    <form onSubmit={onSubmit}>
      <FormProvider {...form}>
        <FormInstantProvider schema={schema}>
          <h1>your form </h1>
          <div>
             <br />
            <FormInstantElement<formSchemaType> name="data" />
          </div>
          <button
            onClick={(e) => {
              e.preventDefault();
              const pre = form.getValues("personal_data.status");

              form.setValue(
                "personal_data.status",
                pre === "not" ? "ok" : "not"
              );
            }}
          >
            switch
          </button>
        </FormInstantProvider>
      </FormProvider>
    </form>
  );
};

discriminator component example.

import { FC } from "react";
import { P } from "@/providers";

const discriminator: FC<P> = (props) => {
  const { options } = props;

  return (
    <select>
      {options?.map(([k, v]) => (
        <option key={k} value={k}>
          {v}
        </option>
      ))}
    </select>
  );
}