Code Monkey home page Code Monkey logo

sanity-quick-fields's Introduction

Sanity.io Quick Fields

Sanity.io Schema is awesome, but the definition files get long.

This quickFields() / qF() function will help you compose fields in a more concise way.

// Before...
fields: [
    {
        name: 'title',
        title: 'Title',
        type: 'string',
    },
    {
        name: 'published',
        title: 'Published',
        type: 'date',
    },
],

// After...
fields: [
    qF('title'),
    qF('published', 'date'),
],

Get started

npm i sanity-quick-fields
or
yarn add sanity-quick-fields

Inside any Sanity document import the qF() or quickFields() functions. They both do the same thing.

import { qF } from "sanity-quick-fields";

Parameters

qF(name, type, options, validation);

name (string or Array)

Pass a string for the field's name, and qF will automatically generate a Capital Case version for the title.

qF('currentLocation')

{ name: 'currentLocation', title: 'Current Location', type: 'string' }

You can overwrite this behaviour by passing in an Array instead, with name and title in that order.

qF(['linkedIn', 'LinkedIn'])

{ name: 'linkedIn', title: 'LinkedIn', type: 'string' }

type (string)

Defaults to stringqF() will pass along whatever type you feed the function, so if it doesn't exist in Sanity, you'll probably get an error.

qF('quantity', 'number')

{ name: 'quantity', title: 'Quantity', type: 'number' }

options (Object)

Pass in an Object of any additional options you need to pass into the field. These are inserted directly into the options key.

qF('dateOfBirth', 'date', { dateFormat: 'YY-MM-DD' })

{
    name: 'dateOfBirth',
    title: 'Date Of Birth',
    type: 'date',
    options: {
      dateFormat: 'YY-MM-DD',
    },
}

You can pass in rows here on the text field type. It's smart enough to store that outside of options (why is it this way Sanity, why?!).

validation (function or Object or Array)

A function is passed as is:

qF('title', 'string', {}, Rule => Rule.required().max(50).error('Required and max 50 chars.'))

{
    name: 'title',
    type: 'string',
    validation: Rule => Rule.required().max(50).error('Required and max 50 chars.')
}
qF('title', 'string', {}, Rule => [
  Rule.required().max(50).error('Required and max 50 chars.'),
  Rule.regex(/^[-a-z0-9]+$/g).error('Only a-z, 0-9, and -.'),
  Rule.min(10).warning('Should be at least 10 chars')
])

{
    name: 'title',
    type: 'string',
    validation: Rule => [
        Rule.required().max(50).error('Required and max 50 chars.'),
        Rule.regex(/^[-a-z0-9]+$/g).error('Only a-z, 0-9, and -.'),
        Rule.min(10).warning('Should be at least 10 chars')
    ]
}

An Object or Array will generate the corresponding function.
The above examples can be defined as follows:

qF('title', 'string', {}, { error: 'Required and max 50 chars.', required: true, max: 50 })

qF('title', 'string', {}, [
  { error: 'Required and max 50 chars.', required: true, max: 50 },
  { error: 'Only a-z, 0-9, and -.', regex: /^[-a-z0-9]+$/g },
  { warning: 'Should be at least 10 chars', min: 10 }
])

Quick Field Builder, Methods

For fields that have children, there are two different functions with helper methods.

qFB() / quickFieldsBuilder()

You can pass in the same first three params as above, but also append .children() and .preview() methods.

Unfortunately you also need to end with .toObject to prevent a Type warning in Sanity.

.children() (Array)

If creating an Array or Object type, pass an Array of fields. This is where nesting qF() becomes powerful.

qFB('contact', 'object')
  .children([qF('name'), qF('email')])
  .toObject

{
    name: 'contact',
    title: 'Contact',
    type: 'object',
    fields: [
        { name: 'name', title: 'Name', type: 'string' },
        { name: 'email', title: 'Email', type: 'string' },
    ],
}

.preview() (Object)

Pass in an object to fill out the select key in preview. This has limited usefulness as you probably want to customise the preview further. But it's a neat shortcut.

qFB('contact', 'object')
  .children([qF('name'), qF('email')])
  .preview({title: 'name', subtitle: 'email'})
  .toObject

{
    name: 'contact',
    title: 'Contact',
    type: 'object',
    fields: [
        { name: 'name', title: 'Name', type: 'string' },
        { name: 'email', title: 'Email', type: 'string' },
    ],
    preview: {
      select: {
        title: 'name',
        subtitle: 'email'
      }
    }
}

Mix and match

qF works best on simple fields, but for more complex fields it probably makes more sense to write them in full. And that's fine, you can selectively use the function where it makes sense.

fields: [
  qF("title"),
  {
    name: "slug",
    title: "Slug",
    type: "slug",
    validation: (Rule) =>
      Rule.required().custom((slug) => {
        const regex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
        return regex.test(slug.current);
      }),
    options: {
      source: "title",
      maxLength: 96,
    },
  },
  qF("body", "bodyPortableText"),
];

Thanks

This library is insired by ACF Builder, the best way by far to compose Advanced Custom Fields!

sanity-quick-fields's People

Contributors

simeongriggs avatar

Stargazers

Imani 'K!ΠG' Niyigena  avatar Matt Rintoul avatar Matthew Borgman avatar Piotr Tomczewski avatar Sophia Michelle Andren avatar Stefan Riđošić avatar Pascal Polleunus avatar David Chhour avatar Abraham Anak Agung avatar Jonathan Land avatar Jacob Størdahl avatar Mike Wagz avatar Geoff Ball avatar Eric Howey avatar  avatar Jesper Paulsen avatar Jérôme Pott avatar

Watchers

James Cloos avatar  avatar

sanity-quick-fields's Issues

Feature Request: Validation

First, thanks for this plugins 😀

As you haven't implemented validation, is there a catch? If not, please, this would be very useful!

And even better if you can provide an easier way to configure basic common things like require, min/max, regex, error/warning messages 😁

For example: qF(name, type, options, validation)

validation can be a function, that is passed as is:

Rule => Rule.required().max(50).error('Required and max 50 chars.')
Rule => [
  Rule.required().max(50).error('Required and max 50 chars.'),
  Rule.regex(/^[-a-z0-9]+$/g).error('Only a-z, 0-9, and -.'),
  Rule.min(10).warning('Should be at least 10 chars')
]

validation can be an object:

{ error: 'Required and max 50 chars.', required: true, max: 50 }

validation can be an array:

[
  { error: 'Required and max 50 chars.', required: true, max: 50 },
  { error: 'Only a-z, 0-9, and -.', regex: /^[-a-z0-9]+$/g },
  { warning: 'Should be at least 10 chars', min: 10 }
]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.