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

sanity-plugin-conditional-field

v1.0.0

Published

Hide or show a Sanity.io field based on a custom condition set by you.

Downloads

32

Readme

sanity-plugin-conditional-field

Hide or show a Sanity.io field based on a custom condition set by you.


🚨 Warning: the Sanity team has voiced they're currently working on a native solution. The goal of this plugin is to become obsolete.


Installation

Start by enabling it in your studio:

sanity install conditional-field
// or:
yarn install conditional-field

Usage

You can use the ConditionalField component as the inputComponent of whatever field you want to conditionally render:

import ConditionalField from 'sanity-plugin-conditional-field'

export default {
  title: 'Article',
  name: 'article',
  type: 'document',
  fields: [
    {
      name: 'internal',
      title: 'Is this article internal?',
      type: 'boolean',
      validation: (Rule) => Rule.required(),
    },
    {
      name: 'externalUrl',
      type: 'url',
      inputComponent: ConditionalField,
      options: {
        // Simple conditional based on top-level document value
        hide: ({ document }) => document.internal, // hide if internal article
      },
    },
  ],
}

Async conditions

{
  name: 'content',
  title: 'Content',
  type: 'array',
  of: [
    {type: 'block'},
  ]
  inputComponent: ConditionalField,
  options: {
    // Asynchronous conditions
    hide: async ({ document }) => {
      if (document.internal) {
        return true
      }

      const isValidContent = await fetch(`/api/is-valid-content/${document.externalUrl}`)
      return isValidContent ?
    }
  }
}

Nested conditions

Besides the current document, the hide function receives a parents array for accessing contextual data.

It's ordered from closest parents to furthest, meaning parents[0] will always be the object the field is in, and parents[-1] will always be the full document. If the field is at the top-level of the document, parents[0] === document.

Here's an example of it in practice - notice how the link object is nested under an array, which means parents[1] will return the array with all the links:

{
  name: 'links',
  title: 'Links',
  type: 'array',
  of: [
    {
      name: 'link',
      title: 'Link',
      type: 'object',
      fields: [
        {
          name: 'external',
          title: "Links to external websites?",
          type: 'boolean',
        },
        {
          name: 'url',
          title: 'External URL',
          type: 'string',
          inputComponent: ConditionalField,
          options: {
            hide: ({ parents }) => {
              // Parents array exposes the closest parents in order
              // Hence, parents[0] is the current object's value
              return parents[0].external
            },
          },
        },
        {
          name: 'internalLink',
          type: 'reference',
          to: [{ type: "page" }],
          inputComponent: ConditionalField,
          options: {
            hide: ({ parents }) => !parents[0].external
          },
        },
        {
          name: 'flashyLooks',
          type: 'boolean',
          inputComponent: ConditionalField,
          options: {
            // Prevent editors from making the link flashy if this link is not in the first position in the array
            hide: ({ parents }) => ({
              hidden: parents[1]?.indexOf(parents[0]) > 0 || false,
              // Clear field's value if hidden - see below
              clearOnHidden: true
            })
          },
        },
      ],
    },
  ],
},

Deleting values if field is hidden

The hide function can also return an object to determine whether or not existing values should be cleared when the field is hidden. By default, this plugin won't clear values.

{
  name: 'externalUrl',
  type: 'url',
  inputComponent: ConditionalField,
  options: {
    hide: ({ document }) => {
      hidden: !!document.internal,
      // Clear field's value if hidden
      clearOnHidden: true
    },
  },
},

Typescript definitions

If you use Typescript in your schemas, here's how you type your hide functions:

import { HideOption } from 'sanity-plugin-conditional-field'

const hideBoolean: HideOption = false
const hideFunction: HideOption = ({ document, parents }) => ({
  hidden: document._id.includes('drafts.') || parents.length > 2,
})

And here's the shape of the hide options:

type ConditionReturn = boolean | { hidden: boolean; clearOnHidden?: boolean }

export type HideFunction = (props: {
  document: SanityDocument
  parents: Parent[]
}) => ConditionReturn | Promise<ConditionReturn>

export type HideOption = boolean | HideFunction

Shortcomings

🚨 Big red alert: this plugin simply hides fields if conditions aren't met. It doesn't interfere with validation, meaning that if you set a conditioned field as required, editors won't be able to publish documents when it's hidden.

Besides this, the following is true:

  • Async conditions aren't debounced, meaning they'll be fired a lot
  • There's no way of using this field with custom inputs