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

@zeachco/declarative-forms

v1.0.6

Published

A library that drives form changes and reactions, allows for a layer of abstraction on the frontend while offering advanced customization and validation capabilities

Downloads

2

Readme

Declarative-forms

A library helper to generate complex forms and offer a system to decorate them.

Table of Contents

Mission

To abstract as much as possible the hierarchy and functionality of data structures and allow constructing a UX-suffisant ecosystem to represent and collect information to the user.

Guidelines (WIP)

  1. Avoid as much as possible coupling logic between different nodes. If you do, ensure you fail fast throwing errors and isolate the coupling into hooks or utilities to make the relation obvious
  2. Try to type as much as possible critical objects such as sharedContext, SchemaNode and schema's meta attributes
  3. Server should not be concerned with UX decisions nor relations between nodes if it does not need to. But it is responsible for providing the context necessary to recognize what's expected for each node and can pass configuration through the meta attribute if a spec does not fit the mission of the library directly
  4. If a feature is shoehorned into the library, there is a good chance it can also be made by building around the library.
  5. Retrocompatibility is crucial, mark @deprecated functions if you want to remove them, create a new method if you want to change its behaviour, use {@link DeclarativeFormContext.features} if the behaviour change's scope is too large or core to the library
  6. For defining the schema's structure, there are no DOs and DONTs but you can try to keep the schema as close as possible to the mission and place what doesn't fit right into meta if really needed (use good judgement). The goal is to have a JSON that's as minimal as possible, but still offers enough information to structure an abstract layout that presents and collects information. Right now, the schema is generated by code but could also be generated through a WYSIWYG editor in the future and we have to take that into consideration (reusing similar patterns across node types, having similar relations across different structure depths, etc.)

Contribution

dev up or yarn to install dependencies dev build or yarn build to create a consumable package

Usage in code

Schema structure

Create a context to be shared across the form

let say we work from this network request

{
  "firstName": {
    "type": "string",
    "value": "John",
    "validators": [{"name": "Presence"}],
    "labels": {
      "label": "First name",
      "description": "Birth given first name"
    }
  },
  "lastName": {
    "type": "string",
    "value": "Smith",
    "validators": [{"name": "Presence"}],
    "labels": {
      "label": "Last name",
      "description": "Birth given last name"
    }
  },
  "age": {
    "type": "integer",
    "value": 30,
    "validators": [
      {"name": "Presence"},
      {"name": "Format", "format": "[1-9][0-9]"}
    ]
  },
  "medicalNumber": {
    "type": "string",
    "validators": [
      {
        "name": "Presence",
        "message": "We need your medical number to verify your identity"
      },
      {"name": "Format", "format": "[A-Z]{4}-?[0-9]{6}-?[0-9]{2}"}
    ],
    "labels": {
      "label": "Medical insurance number",
      "helpText": "This is the number at the top of your Medical card, 4 letters followed by 8 digits"
    }
  }
}

We can create our root SchemaNode from:

import {DeclarativeFormContext} from '@shopify/declarative-forms';
import {decorate} from 'decoratorFactory';
import request from 'request.json';

const {values, schema, labels} = request;

const context = new DeclarativeFormContext({
  values,
  decorate,
  translators,
  sharedContext,
});

const root = new SchemaNode(context, schema);

Now let's look at decorators. decorators can be found at

export function decorate(context) {
  context
    .where(({depth}) => depth === 0)
    .prependWith(HeaderBanner)
    .appendWith(FooterActions);

  context.where(({type}) => type === 'string').replaceWith(TextField);

  context.where(({type}) => type === 'boolean').replaceWith(CheckBoxComponent);

  context
    // Allows for granular selectors, eveything from the SchemaNode is accessible to help filtering
    .where(({schema}: SchemaNode) => Boolean(schema.options?.length))
    // Additional props can receive a factory that read the current node
    .replaceWith(SelectComponent, ({schema}) => ({
      preselectFirstItem: !!schema.meta.preselect,
    }));
}

Once you have you have a node, you can simply render it with

import {renderNodes} from '@shopify/declarative-forms';

function ReactComponent({request}) {
  const root: SchemaNode = useMemoizedRootNodeFromRequest(request);

  return <Layout>{renderNodes(root)}</Layout>;
}

Or you can render sub parts of the schema

import {renderNodes} from '@shopify/declarative-forms';

function ReactComponent({request}) {
  const root: SchemaNode = useMemoizedRootNodeFromRequest(request);

  return <Layout>{renderNodes(root.children.medicalNumber)}</Layout>;
}

Shared context mechanics

You can have a state-self-managed context shared across all the components and available at the consumer level, it's on the context object called sharedContext.

When creating a context

const context = new DeclarativeFormContext({
  values,
  decorate,
  translators,
  sharedContext, // <---- this is the shared context
});

const root = new SchemaNode(context, schema);

it's structure is extendable with anything and useNode will expose this context and react to it's changes.

from anywhere in the code you can

node.context.updateContext({
  anySortofFlag: true,
});

then from any React component

function CustomComponent({node}: NodeProps) {
  const {
    sharedContext: {anySortofFlag},
  } = useNode(node);
  return <Modal visible={anySortofFlag} />;
}

and the component will automatically react to the changes

Documentation

the full API documentation is available at https://zeachco.github.io/declarative-forms/ you can run a local version of this by simply running yarn start (make sure to have the depedencies installed before with yarn).

This will create a local folder docs/ that you might want to clean up before committing some code changes, leaving the docs in place will not cause any harm but it will polluate the git diff on your next PR with autogenerated files.

Jump in the code

If you can't click those links, it's probably because you are viewing the the README.md directly instead of browsing the advanced documentation at https://zeachco.github.io/declarative-forms/

library features

  • {@link DeclarativeFormContext.features}

Frontend validation

  • {@link SchemaNode.setErrors}
  • {@link SchemaNode.validateAll}
  • {@link presenceValidator}
  • {@link formatValidator}
  • {@link lengthValidator}

Back to top