Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@sanity/code-input

sanity-io84.2kMIT5.1.2TypeScript support: included

Sanity input component for code, powered by CodeMirror

sanity, cms, headless, realtime, content, code-input, sanity-plugin, code-editor

readme

@sanity/code-input

This is a Sanity Studio v3 plugin. For the v2 version, please refer to the v2-branch.

What is it?

Code input for Sanity.

A subset of languages and features are exposed by default. More can be added via the plugin options.

Code input

Click the line numbers to toggle line highlighting.

Installation

npm install @sanity/code-input

Usage

Add it as a plugin in sanity.config.ts (or .js):

import {codeInput} from '@sanity/code-input'

export default defineConfig({
  // ...
  plugins: [codeInput()],
})

Now you can use the code type in your schema types:

import {defineType, defineField} from 'sanity'

defineType({
  // [...]
  fields: [
    defineField({
      type: 'code',
      name: 'myCodeField',
      title: 'My code field',
    }),
  ],
})

Options

  • language - Default language for this code field.
  • languageAlternatives - Array of languages that should be available (se its format in the example below)
  • withFilename - Boolean option to display input field for filename
//...fields,
defineField({
  type: 'code',
  name: 'myCodeField',
  title: 'Code with all options',
  options: {
    language: 'javascript',
    languageAlternatives: [
      {title: 'Javascript', value: 'javascript'},
      {title: 'HTML', value: 'html'},
      {title: 'CSS', value: 'css'},
    ],
    withFilename: true,
  },
})

Code input with all options in dark mode

Add support for more languages

Only a subset of languages are have syntax highlighting support by default (see full list here).

Mode: Reuse an existing language

Some languages are similar enough, that reusing one of the default highlighters will be "good enough". To reuse an existing language, specify mode for a value in languageAlternatives:

//...fields,
defineField({
  name: 'zhOnly',
  type: 'code',
  options: {
    language: 'zh',
    languageAlternatives: [
      //Adds support for zh language, using sh syntax highlighting
      {title: 'ZH', value: 'zh', mode: 'sh'},
    ],
  },
})

Add more languages

You can add support for additional languages, or override existing ones, by providing a codeModes array to the plugin. codeModes should be an array where each value is an object with a name and a loader function. The loader function should return a codemirror Extension or a Promise that resolves to Extension.

The loader function will be invoked when the language is selected.

For a full list of officialy code-mirror languages, see:

Example: Add support for CodeMirror 6 language (Angular)

We can add support for a CodeMirror 6 lang package:

// sanity.config.js

// ... in the plugins array of defineConfig, where we add the codeInput plugin
codeInput({
  codeModes: [
    {
      name: 'angular',
      // dynamic import the angular package, and initialize the plugin after it is loaded
      // This way, the language is only when it is selected
      loader: () => import('@codemirror/lang-angular').then(({angular}) => angular()),
    },
  ],
})
// in a code field, you can now use rust as a language as a value, or mode
defineField({
  name: 'exampleRust',
  title: 'Example usage',
  type: 'code',
  options: {
    languageAlternatives: [
      {title: 'Javascript', value: 'javascript'},
      {title: 'Angular', value: 'angular'},
      {title: 'Angular-like', value: 'angular-like', mode: 'angular'}, // uses angular highlighter
    ],
  },
})

For this to work, you will have to run npm i @codemirror/lang-angular as this package is not included by @sanity/code-input.

Example: Add support for CodeMirror 5 legacy language (Rust)

We can add support for any CodeMirror 5 legacy language using CodeMirror 6 StreamLanguage.

// sanity.config.js
import {StreamLanguage} from '@codemirror/language'

// ... in the plugins array of defineConfig, where we add the codeInput plugin
codeInput({
  codeModes: [
    {
      name: 'rust',
      // dynamic import so the language is only be loaded on demand
      loader: () =>
        import('@codemirror/legacy-modes/mode/rust').then(({rust}) => StreamLanguage.define(rust)),
    },
  ],
})
// in a code field, you can now use rust as a language as a value, or mode
defineField({
  name: 'exampleRust',
  title: 'Example usage',
  type: 'code',
  options: {
    languageAlternatives: [
      {title: 'Javascript', value: 'javascript'},
      {title: 'Rust', value: 'rust'},
      {title: 'Rust-like', value: 'rust-like', mode: 'rust'}, // uses rust highlighter
    ],
  },
})

Note: @sanity/code-input already includes the @codemirror/legacy-modes and @codemirror/language dependencies, so no need to install them explicitly.

Data model

{
  _type: 'code',
  language: 'js',
  highlightedLines: [1, 2],
  code: 'const foo = "bar"\nconsole.log(foo.toUpperCase())\n// BAR',
  filename: 'available when enabled'
}

Example usage in frontend (React)

You can use any syntax highlighter you want - but not all of them might support highlighted lines or the syntax you've defined.

As outlined above, the actual code is stored in a code property, so if your schema has a field called codeExample of type code, the property you'd want to pass to the highlighter would be codeExample.code.

Here's an example using react-refractor:

import React from 'react'
import Refractor from 'react-refractor'
import js from 'refractor/lang/javascript'

Refractor.registerLanguage(js)

export function Code(props) {
  return (
    <Refractor
      // In this example, `props` is the value of a `code` field
      language={props.language}
      value={props.code}
      markers={props.highlightedLines}
    />
  )
}

Other syntax highlighters include:

License

MIT-licensed. See LICENSE.

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.

UI Workshop

Run workshop dev

To test the CodeMirror lazy component.

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.

changelog

📓 Changelog

All notable changes to this project will be documented in this file. See Conventional Commits for commit guidelines.

5.1.2 (2024-12-16)

Bug Fixes

  • warnings from styled-components on language input render (#112) (4c71607)

5.1.1 (2024-12-14)

Bug Fixes

  • deps: upgrade @sanity/icons to v3 (2870c01)

5.1.0 (2024-12-14)

Features

  • support react 19, upgrade build tooling (#111) (d9d2826)

5.0.0 (2024-11-28)

⚠ BREAKING CHANGES

  • deps: Update dependency @sanity/ui to v2 (#94)

Bug Fixes

  • deps: Update dependency @sanity/ui to v2 (#94) (7178d87)

4.1.4 (2024-04-09)

Bug Fixes

  • remove incorrect autocomplete from GROQ (#103) (1f45acb)

4.1.3 (2024-02-21)

Bug Fixes

4.1.2 (2023-12-15)

Bug Fixes

  • deps: allow styled-components v6 as peer dependency (#89) (2ba3bf2)
  • deps: update codemirror (#52) (d883481)
  • deps: update codemirror (#65) (b866640)
  • deps: update codemirror (#66) (5d1605e)
  • deps: update dependencies (non-major) (#32) (5f2ab52)
  • deps: update dependencies (non-major) to v4.20.2 (#67) (ec2dcef)
  • update package description (codemirror, not ace) (3b769e2)

4.1.1 (2023-05-10)

Bug Fixes

  • editor should no longer crash when highlightlines are unsorted (e2f9d98)

4.1.0 (2023-03-01)

Features

  • richer preview component (5b751e9)

4.0.0 (2023-01-16)

⚠ BREAKING CHANGES

  • api for configuring custom languages has changed. Consult the README for details.

Features

  • click line-number to highlight line (8e5cf07)
  • replaced AceEditor with CodeMirror as code editor (ef4fe48)

Bug Fixes

  • deps: applied npx @sanity/plugin-kit inject (9ccfe69)
  • implement sanity theming (9566cd2)
  • improved highlighted line color (c151e95)
  • refactored default language (2111776)
  • render focus ring (5fc3cc1)
  • wrap lines (301640e)

3.0.1 (2022-12-06)

Bug Fixes

  • preview for portable text and arrays now works in 3.0.0+ (f4dfd0a)

3.0.0 (2022-11-25)

⚠ BREAKING CHANGES

  • this version does not work in Sanity Studio v2

Features

  • initial Sanity Studio v3 release (045dd4b)

Bug Fixes

  • @sanity/ui 1.0.0-beta.31 (b4d6575)
  • code-definition extension to intrinsics should work again (c7b3c1f)
  • compiled for dev-preview.22 (bb9a6a7)
  • compiled for sanity 3.0.0-rc.0 (46085b7)
  • compiled for sanity 3.0.0-rc.0 (ccf2b61)
  • deps: dev-preview.21 (89ecdc3)
  • deps: pin dependencies (#28) (59d92d9)
  • deps: pkg-utils & @sanity/plugin-kit (ba975f9)
  • deps: react-dom as peer (bee9c70)
  • deps: sanity ^3.0.0 (works with rc.3) (764c10a)
  • deps: sanity 3.0.0-dev-preview.17 and ui 0.38 (4bef2ab)
  • deps: update dependency @sanity/icons to v1.3.9-beta.3 (#30) (9b49361)
  • deps: update dependency ace-builds to ^1.12.5 (#8) (ae169c7)
  • deps: update sanity packages to v1 (major) (#10) (260a911)
  • lazy load AceEditor to allow server side rendering the input (d1d173b)
  • makes PreviewCode also load ace async (#11) (16eb077)
  • preview component now uses v3 api correctly (280b620)
  • preview is now dev-preview.17 compatible (58a75d9)
  • setup changelog generator (a52df38)
  • update lockfile (cf401bb)
  • use @sanity/semantic-release-preset (fb0c785)

3.0.0-v3-studio.15 (2022-11-04)

Bug Fixes

  • deps: pkg-utils & @sanity/plugin-kit (ba975f9)

3.0.0-v3-studio.14 (2022-11-04)

Bug Fixes

  • deps: pin dependencies (#28) (59d92d9)
  • deps: update dependency @sanity/icons to v1.3.9-beta.3 (#30) (9b49361)
  • deps: update dependency ace-builds to ^1.12.5 (#8) (ae169c7)

3.0.0-v3-studio.13 (2022-11-02)

Bug Fixes

  • compiled for sanity 3.0.0-rc.0 (46085b7)
  • compiled for sanity 3.0.0-rc.0 (ccf2b61)

3.0.0-v3-studio.12 (2022-10-27)

Bug Fixes

  • @sanity/ui 1.0.0-beta.31 (b4d6575)
  • compiled for dev-preview.22 (bb9a6a7)

3.0.0-v3-studio.11 (2022-10-07)

Bug Fixes

  • code-definition extension to intrinsics should work again (c7b3c1f)

3.0.0-v3-studio.10 (2022-10-07)

Bug Fixes

3.0.0-v3-studio.9 (2022-09-15)

Bug Fixes

  • preview is now dev-preview.17 compatible (58a75d9)

3.0.0-v3-studio.8 (2022-09-15)

Bug Fixes

  • deps: react-dom as peer (bee9c70)
  • deps: sanity 3.0.0-dev-preview.17 and ui 0.38 (4bef2ab)

3.0.0-v3-studio.7 (2022-08-17)

Bug Fixes

  • makes PreviewCode also load ace async (#11) (16eb077)

3.0.0-v3-studio.6 (2022-08-17)

Bug Fixes

  • deps: update sanity packages to v1 (major) (#10) (260a911)

3.0.0-v3-studio.5 (2022-08-17)

Bug Fixes

  • use @sanity/semantic-release-preset (fb0c785)

3.0.0-v3-studio.4 (2022-08-16)

Bug Fixes