Code Monkey home page Code Monkey logo

sanity-plugin-utils's Introduction

This is a Sanity Studio v3 plugin.

Installation

npm install sanity-plugin-utils

sanity-plugin-utils

Handy hooks and clever components for Sanity Studio v3.

Installation

npm install --save sanity-plugin-utils

or

yarn add sanity-plugin-utils

Usage

useListeningQuery()

Sanity's real-time APIs power excellent editorial experiences. Your plugins should respond to other users collaborating on documents in real time. This hook is a convenient way to perform a GROQ query that responds to changes, along with built-in loading and error states.

The data variable will be constantly updated as changes are made to the data returned by your query. You can also pass in initial data so that it is set in the first render.

import {useListeningQuery} from 'sanity-plugin-utils'

export default function DocumentList() {
  const {data, loading, error} = useListeningQuery<SanityDocument[]>(`*[_type == $type]`, {
    params: {type: 'pet'},
    initialValue: [],
  })

  if (loading) {
    return <Spinner />
  }

  if (error) {
    return <Feedback tone="critical">{error}</Feedback>
  }

  return (
    <Stack>
      {data?.length > 0 ? (
        data.map((pet) => <Card key={pet._id}>{pet.title}</Card>)
      ) : (
        <Feedback>No Pets found</Feedback>
      )}
    </Stack>
  )
}

useProjectUsers()

Hook for getting extended details on all Users in the project. Such as name.

import {useProjectUsers} from 'sanity-plugin-utils'

export default function DocumentList() {
  const users = useProjectUsers({apiVersion: `2023-01-01`})

  return (
    <Stack>
      {users?.length > 0 ? (
        users.map((user) => (
          <Profile key={user.id} {...user}>
        ))
      ) : (
        <Spinner>
      )}
    </Stack>
  )
}

useOpenInNewPane()

Returns a function that will open a document in a new view pane, alongside the current view pane

import {useOpenInNewPane} from 'sanity-plugin-utils'

export default function SidePetOpener(pet: SanityDocument) {
  const openInNewPane = useOpenInNewPane(pet._id, pet._type)

  return (
    <Button onClick={() => openInNewPane()}>
      {pet.title}
    </Button>
  )
}

useImageUrlBuilder()

Returns an image URL builder configured with the current workspace's Project ID and Dataset.

Useful if you have many images in the one component.

import {useImageUrlBuilder} from 'sanity-plugin-utils'

export default function PetPics(pet: SanityDocument) {
  const builder = useImageUrlBuilder({apiVersion: `2023-01-01`})

  return (
    <ul>
      {pet.pics.map((pic) => (
        <li key={pic._key}>
          <img src={builder.source(pic).width(200).height(200).url()} alt={pic.altText} />
        </li>
      ))}
    </ul>
  )
}

useImageUrlBuilderImage()

As above, but pre-configured with an image source.

Useful if you only have one image in your component.

import {useImageUrlBuilderImage} from 'sanity-plugin-utils'

export default function PetPic(pet: SanityDocument) {
  const image = useImageUrlBuilderImage(pet.image, {apiVersion: `2023-01-01`})

  return <img src={image.width(200).height(200).url()} alt={pet.name} />
}

Feedback

Component for consistently displaying feedback in a card with a title, text and an icon.

import {Feedback, useListeningQuery} from 'sanity-plugin-utils'

export default function DocumentList() {
  const {data, loading, error} = useListeningQuery(`*[_type == "task" && !complete]`)

  if (loading) {
    return <Feedback tone="primary" title="Please hold" description="Fetching tasks..." />
  }

  if (error) {
    return (
      <Feedback tone="critical" title="There was an error" description="Please try again later" />
    )
  }

  return data?.length > 0 ? (
    <Feedback tone="caution" title="There are unfinished tasks" description="Please get to work" />
  ) : (
    <Feedback tone="success" title="You're all done" description="You should feel accomplished" />
  )
}

Table, Row and Cell

These components are all @sanity/ui Card's but with their HTML DOM elements and CSS updated to output and behave like tables.

import {Table, Row, Cell} from 'sanity-plugin-utils'

export default function Report(documents) {
  return (
    <Table>
      <thead>
        <Row>
          <Cell>
            <Text>Name</Text>
          </Cell>
          <Cell>
            <Text>Price</Text>
          </Cell>
        </Row>
      </thead>
      <tbody>
        {documents.map((doc) => (
          <Row key={doc._id}>
            <Cell>
              <Text>{doc.title}</Text>
            </Cell>
            <Cell tone={doc.inStock ? `caution` : `primary`}>
              <Text>{doc.price}</Text>
            </Cell>
          </Row>
        ))}
      </tbody>
    </Table>
  )
}

UserSelectMenu

A Menu component for searching and interacting with users. Requires Users to be passed into the component.

import {UserSelectMenu} from 'sanity-plugin-utils'

export default function Report() {
  const users = useProjectUsers({apiVersion: `2023-01-01`})
  const [selectedUsers, setSelectedUsers] = useState([])
  
  return (
    <UserSelectMenu
      userList={users}
      value={selectedUsers}
      onAdd={(id) => selectedUsers((current) => [...current, id])}
      onRemove={(id) => setSelectedUsers((current) => current.filter((id) => id !== id))}
      onClear={() => setSelectedUsers([])}
    >
  )
}

License

MIT © Simeon Griggs See LICENSE

License

MIT © Simeon Griggs

Develop & test

This plugin uses @sanity/plugin-kit with default configuration for build & watch scripts.

See Testing a plugin in Sanity Studio on how to run this plugin with hotreload in the studio.

Release new version

Run "CI & Release" workflow. Make sure to select the main branch and check "Release new version".

Semantic release will only release on configured branches, so it is safe to run release on any branch.

sanity-plugin-utils's People

Contributors

simeongriggs avatar semantic-release-bot avatar matthewborgman avatar

Stargazers

Simon Calem avatar M avatar Christopher Daniel Dean avatar Imani 'K!ΠG' Niyigena  avatar  avatar Aulon Mujaj avatar Jordi avatar Andy Fitzgerald avatar Noah Gentile avatar Sigurd Heggemsnes avatar  avatar Thomas Bassetto @ DNV avatar Tarje Lavik avatar Nick Beattie avatar Luke Jackson avatar Ezekiel Aquino avatar Fred Carlsen avatar Subhan Bakhtiyarov avatar Saskia avatar Cody Olsen avatar Ash avatar

Watchers

James Cloos avatar  avatar

sanity-plugin-utils's Issues

vite Compliation error on `sanity/structure`

Description of error

There's an open PR here: sanity-io/sanity-plugin-documents-pane#64

It mentions an issue with sanity-plugin-utils. They say they think that where sanity/structure is used, the package should be @sanity/structure, in this file:

https://github.com/SimeonGriggs/sanity-plugin-utils/blob/main/src/hooks/useOpenInNewPane.tsx#L3

I'm not sure if that's the correct resolution or not. I had a look at changing the package to @sanity/structure, but that didn't seem to be the right fix

Which versions of Sanity are you using?

3.21.3

What operating system are you using?

MacOS

Which versions of Node.js / npm are you running?

Node: 18.17.1
npm: 10.2.5
pnpm: 8.14.0

Error message

sanity:dev: The plugin "vite:dep-pre-bundle" was triggered by this import
sanity:dev:
sanity:dev: ../../node_modules/.pnpm/sanity-plugin-utils@1.6.4_@sanity[email protected][email protected]_react-fast-compare@3.2.2_react@18_dl6nsyrbpmk4iah6t67kasu2im/node_modules/sanity-plugin-utils/lib/index.esm.js:5:30:
sanity:dev: 5 │ import { usePaneRouter } from 'sanity/structure';
sanity:dev: ╵ ~~~~~~~~~~~~~~~~~~
sanity:dev:
sanity:dev: 3:56:38 AM [vite] error while updating dependencies:
sanity:dev: Error: Build failed with 2 errors:
sanity:dev: ../../node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js:1373:21: ERROR: [plugin: vite:dep-pre-bundle] Missing "./structure" specifier in "sanity" package
sanity:dev: ../../node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js:1373:21: ERROR: [plugin: vite:dep-pre-bundle] Missing "./structure" specifier in "sanity" package

Update peer dependency @sanity/ui

Currently with the last version of @sanity/ui and sanity-plugin-utils, npm i results in:

npm ERR! Found: @sanity/[email protected]
npm ERR! node_modules/@sanity/ui
npm ERR!   @sanity/ui@"1.2.5" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer @sanity/ui@"1.2.2" from [email protected]
npm ERR! node_modules/sanity-plugin-utils
npm ERR!   sanity-plugin-utils@"1.0.3" from the root project

Please update the dependency or set version of peer dependency to "^.1.2.2"

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.