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

@crudmates/form-config

v0.0.18

Published

A super flexible tool for creating custom dynamic forms

Downloads

482

Readme

Say goodbye to complex form logic and hello to a streamlined, type-safe form configuration experience. @crudmates/form-config is your go-to library for building robust, dynamic forms with ease.

🚀 Features

  • 🛠 Flexible Configuration: Craft intricate form structures effortlessly using TypeScript interfaces.
  • ✅ Built-in Validation: Aside client-side validation using tools like Zod, @crudmates/form-config also provides built-in validation for your form configuration to ensure data integrity.
  • 📊 Smart Evaluation: Automatically calculate totals and ratios based on your form data.
  • 🧩 Dynamic Decomposition: Strip down your form configuration to the essentials before sending it to the server or storing it in the database. You can also reassemble the configuration later.
  • 🔧 TypeScript-First: Enjoy full TypeScript support for a superior developer experience and fewer runtime errors.
  • 🚀 Seamless Integration: Integrate with popular libraries like React Hook Form and Zod for a seamless development experience.

💪 Why Choose @crudmates/form-config?

  1. Full Ownership and Control of Data: Unlike hosted solutions, maintain complete control over your form configurations and data.

  2. Portability and Flexibility: Easily move your form configurations between projects, backends, or frontend frameworks.

  3. Integration with Custom Systems: Seamlessly incorporate form building capabilities into existing applications or workflows.

  4. Version Control and Collaboration: Store configurations in your project's source code, facilitating team collaboration and change history.

  5. Security and Privacy: Keep sensitive form configurations on your own servers, crucial for meeting security and privacy requirements.

  6. Customization and Extension: Extend functionality beyond out-of-the-box features with custom properties or domain-specific languages.

  7. Offline Capability: Implement offline form building and editing capabilities.

  8. Cost-Effective for Large-Scale Use: More economical for applications generating numerous forms or surveys compared to hosted solutions.

🏁 Quick Start

Installation

Get started in seconds:

npm install @crudmates/form-config

🌟 Basic Usage

Explore real-world examples of @crudmates/form-config in action at this repository. You can also create your own form configuration and see how it works 🎉

import React, { useState } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Config, Item, evaluate, stage, prepare } from '@crudmates/form-config';

// Define your form schema
const formSchema = z.object({
  name: z.string().min(1, 'Name is required'),
  email: z.string().email('Invalid email address'),
  age: z.number().min(18, 'Must be at least 18 years old'),
  country: z.string().min(1, 'Country is required'),
  terms: z.boolean().refine((val) => val === true, 'You must accept the terms'),
});

// Define your form configuration
const formConfig: Config = {
  name: 'registrationForm',
  label: 'Registration Form',
  sections: [
    {
      name: 'personalInfo',
      label: 'Personal Information',
      items: [
        {
          label: 'Name',
          name: 'name',
          type: 'text',
          validation: {
            required: true,
          },
        },
        {
          label: 'Email',
          name: 'email',
          type: 'email',
          validation: {
            required: true,
          },
        },
        {
          label: 'Age',
          name: 'age',
          type: 'number',
          validation: {
            required: true,
            min: 18,
          },
        },
        {
          label: 'Country',
          name: 'country',
          type: 'select',
          options: [
            { label: 'United States', value: 'us' },
            { label: 'United Kingdom', value: 'uk' },
            { label: 'Canada', value: 'ca' },
          ],
          validation: {
            required: true,
          },
        },
        {
          label: 'I accept the terms and conditions',
          name: 'terms',
          type: 'checkbox',
          validation: {
            required: true,
          },
        },
        {
          label: 'Submit',
          name: 'submit',
          type: 'button',
        }
      ],
    },
  ],
};

// Component for rendering form inputs
const FormInput: React.FC<{ field: any; item: Item; error: any }> = ({ field, item, error }) => {
  switch (item.type) {
    case 'text':
    case 'email':
    case 'number':
    case 'checkbox':
      return (
        <div>
          <label htmlFor={item.name}>{item.label}</label>
          <input {...field} id={item.name} type={item.type} />
          {error && <span>{error.message}</span>}
        </div>
      );
    case 'select':
      return (
        <div>
          <label htmlFor={item.name}>{item.label}</label>
          <select {...field} id={item.name}>
            <option value=''>Select a country</option>
            {item.options?.map((option) => (
              <option key={option.name} value={option.name}>
                {option.label}
              </option>
            ))}
          </select>
          {error && <span>{error.message}</span>}
        </div>
      );
    case: 'button':
      return (
        <button type={item?.type as any}>
          {item.label}
        </button>
      )
    default:
      return <></>;
  }
};

// Main form component
const Form: React.FC = () => {
  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm({
    defaultValues: stage(formConfig),
    resolver: zodResolver(formSchema),
  });

  const onSubmit = (data: any) => {
    const preparedData = prepare(data, formConfig);
    // send data to server
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <h1>{formConfig.sections[0].label}</h1>
      {formConfig.sections[0].items.map((item) => (
        <Controller
          key={item.name}
          name={item.name}
          control={control}
          rules={item.validation}
          render={({ field }) => <FormInput field={field} item={item} error={errors[item.name]} />}
        />
      ))}
    </form>
  );
};

export default Form;

📚 API Reference

Core Functions

  • evaluate(config: Config, factor?: number): Config
  • validate(config: Config): string
  • compose(config: Config, sections: Partial<Section>[]): Config
  • decompose(config: Config, options: DecomposeOptions): Partial<Config>
  • stage(config: Config, sectionItem: Record<string, any>): Config
  • evaluateCondition(condition?: Condition, formState?: Record<string, any>): boolean
  • prepare(formState: Record<string, any>, config: Config): Config
  • getChangeGroup(changeGroupOptions: ChangeGroupOptions, value: string): void

🔗 Ecosystem and Related Packages

@crudmates/form-config is framework-agnostic and can be used with any frontend library or framework. Here are some related packages that you may find useful:

  • React: A JavaScript library for building user interfaces. Use React to create dynamic, interactive forms with ease. Learn more.

  • Tailwind CSS: A utility-first CSS framework for rapidly building custom designs. Use Tailwind CSS to style your forms and components. Learn more.

  • React Hook Form: A library for managing form state in React applications. @crudmates/form-config is designed to work seamlessly with React Hook Form. Learn more.

  • Zod: A TypeScript-first schema declaration and validation library. Use Zod to define your form schema and validate your form data. Learn more

📄 License

This project is licensed under the MIT License.

💖 Support the Project

Love this package? Show your support by giving us a ⭐ on GitHub! Feeling extra generous? You can buy us coffee to keep us fueled for more coding adventures!☕️