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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@leafygreen-ui/code

v20.2.5

Published

leafyGreen UI Kit Code Blocks

Readme

Code

npm (scoped)

View on MongoDB.design

Installation

PNPM

pnpm add @leafygreen-ui/code

Yarn

yarn add @leafygreen-ui/code

NPM

npm install @leafygreen-ui/code

Source Code Pro Font

In addition to using a limited amount of our standard brand font, this component uses the open-source monospace font "Source Code Pro". For this component to display correctly, loading the following weights / styles of "Source Code Pro" is necessary:

  • 400 / normal
  • 400 / italic
  • 600 / normal

You can find instructions for using Google's CDN for font delivery, and download "Source Code Pro" on Google Fonts.

We recommend using Google's CDN for loading this font to optimize for caching the assets, speeding up loading times for webpages as a result. We use the following HTML in our <head> tags to load the necessary variants of "Source Code Pro":

<link rel="preconnect" href="https://fonts.gstatic.com" />
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:ital,wght@0,400;0,600;1,400&display=swap" rel="stylesheet" />

Example

import Code from '@leafygreen-ui/code';

const codeSnippet = `
function greeting(entity) {
  return \`Hello, \${entity}!\`;
}

console.log(greeting('World'));
`;

const SomeComponentWithPanel = () => (
  <Code
    language="javascript"
    showLineNumbers={true}
    darkMode={true}
    panel={
      <Panel
        onChange={() => {}}
        languageOptions={[]}
        showCustomActionButtons
        customActionButtons={[]}
        onCopy={() => {}}
        title="Title"
      />
    }
  >
    {codeSnippet}
  </Code>
);

const SomeComponentWithoutPanel = () => (
  <Code
    language="javascript"
    showLineNumbers={true}
    onCopy={() => {}}
    darkMode={true}
    copyButtonAppearance="persist"
  >
    {codeSnippet}
  </Code>
);

Props

Code

| Prop | Type | Description | Default | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | children (Required) | string | This is the code snippet that will be rendered in the code block. | '' | | language (Required) | 'javascript', 'typescript', 'cs', 'csharp', 'cpp', 'go', 'http','java', 'perl', 'php', 'python', 'ruby', 'scala', 'swift', 'kotlin','objectivec', 'dart', 'bash', 'shell', 'sql', 'yaml', 'json', 'diff', 'xml', 'none' | The language to highlight the code block as. When set to 'none', no syntax highlighting will be applied. | | | darkMode | boolean | Determines whether or not the component will appear in dark mode. | false | | className | string | Applies a className to the root element's classList. | | | showLineNumbers | boolean | Shows line numbers next to each line of code in the passed code snippet. NOTE: While you can set this to true regardless of the code component being multiline, the line numbers will not be displayed if the multiline prop is true. | false | | lineNumberStart | number | Specifies the number by which to start line numbering. | 1 | | onCopy | () => void | Callback fired when the copy button is clicked. Note: When using the panel prop, the copy button is rendered within the panel itself, so this callback should be passed as a prop to the <Panel> component instead of the <Code> component. | | | expandable | boolean | When true, allows the code block to be expanded and collapsed when there are more lines than specified by collapsedLines. | false | | collapsedLines | number | The number of lines to display when the code block is collapsed (only applies when expandable is true). | 5 | | highlightLines | Array<number | [number, number]> | An optional array of lines to highlight. The array can only contain numbers corresponding to the line numbers to highlight, and / or tuples representing a range (e.g. [6, 10]); | | | copyButtonAppearance | 'none', 'hover', 'persist' | Determines the appearance of the copy button without a panel. The copy button allows the code block to be copied to the user's clipboard by clicking the button. Appearance: * 'hover': the copy button will only appear when the user hovers over the code block. On mobile devices, the copy button will always be visible. * 'persist': the copy button will always be visible. * 'none': the copy button will not be rendered Note: panel cannot be used with copyButtonAppearance. Either use copyButtonAppearance or panel, not both. The <Panel> component will automatically render the copy button to the right of panel and will ignore the copyButtonAppearance prop. | hover | | panel | React.ReactNode | Slot to pass the <Panel/> sub-component which will render the top panel with a language switcher, custom action buttons, and copy button. If no props are passed to the panel sub-component, the panel will render with only the copy button. Note: panel cannot be used with copyButtonAppearance. Either use copyButtonAppearance or panel, not both. The <Panel> component will automatically render the copy button to the right of panel and will ignore the copyButtonAppearance prop. | `` | | isLoading | boolean | Determines whether or not the loading skeleton will be rendered in place of the code block. Iftrue, the language switcher and copy button will be disabled in the top panel. | false | | baseFontSize | '13' | '16' | Determines the base font-size of the component | 13 | | customKeywords | { [key: string]: string } | Custom keywords to be highlighted in the code block. The key is the keyword to be highlighted, and the value is the classname to be applied to the keyword. E.g. customKeywords: {{ 'keyword': 'className' }} | {} |

Panel

| Prop | Type | Description | Default | | ------------------------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | showCustomActionButtons | boolean | Shows custom action buttons in the panel if set to true and there is at least one item in customActionButtons. | false | | customActionButtons | Array<React.ReactElement> | An array of custom action buttons using the IconButton component. For example: [<IconButton><Icon glyph="Cloud" /></IconButton>, <IconButton><Icon glyph="Code" /></IconButton>] | [] | | title | string | Shows a filename-like title in the window chrome frame. | '' | | languageOptions | Array<LanguageOption> | An array of language options. When provided, a LanguageSwitcher dropdown is rendered. | | | onChange | (language: LanguageOption) => void | A change handler triggered when the language is changed. Invalid when no languageOptions are provided. | | onCopy | () => void | Callback fired when Code is copied. | |

interface LanguageOption {
  displayName: string;
  language: Language;
  image?: React.ReactElement;
}

Test Harnesses

getTestUtils()

getTestUtils() is a util that allows consumers to reliably interact with LG Code in a product test suite. If the Code component cannot be found, an error will be thrown.

Usage

import { getTestUtils } from '@leafygreen-ui/code';

const utils = getTestUtils(lgId?: `lg-${string}`); // lgId refers to the custom `data-lgid` attribute passed to `Code`. It defaults to 'lg-code' if left empty.

Single Code component

import { render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import Code, { getTestUtils } from '@leafygreen-ui/code';

...

test('code', () => {
  render(
    <Code
      language="javascript"
      panel={
        <Panel
          onChange={() => {}}
          languageOptions={languageOptions}
          title="Title"
        />
      }
    >
      {codeSnippet}
    </Code>
  );

  const { getLanguage, getLanguageSwitcherUtils, getIsLoading, getCopyButtonUtils, getExpandButtonUtils } = getTestUtils();
  const { getInput, getOptions, getOptionByValue, getInputValue, isDisabled: isLanguageSwitcherDisabled } = getLanguageSwitcherUtils();
  const { getButton, queryButton, findButton, isDisabled } = getCopyButtonUtils();
  const { getButton, queryButton, findButton } = getExpandButtonUtils();

  expect(getLanguage()).toBe('javascript');
  expect(getTitle()).toBe('Title');
  expect(getInput()).toBeInTheDocument();
  expect(getOptions()).toHaveLength(2);
  expect(getOptionByValue('js')).toBeInTheDocument();
  expect(getInputValue()).toBe('javascript');
  expect(isLanguageSwitcherDisabled()).toBe(false);
  expect(getIsLoading()).toBe(false);
  expect(getCopyButtonUtils().getButton()).toBeInTheDocument();
  expect(getCopyButtonUtils().findButton()).toBeInTheDocument();
  expect(getCopyButtonUtils().queryButton()).toBeInTheDocument();
  expect(getCopyButtonUtils().isDisabled()).toBe(false);
  expect(getExpandButtonUtils().getButton()).toBeInTheDocument();
  expect(getExpandButtonUtils().findButton()).toBeInTheDocument();
  expect(getExpandButtonUtils().queryButton()).toBeInTheDocument();
  expect(isExpanded()).toBe(false);
});

Multiple Code components

When testing multiple Code components, it is recommended to add the custom data-lgid attribute to each Code.

import { render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Code, getTestUtils } from '@leafygreen-ui/code';

...

test('code', () => {
  render(
    <>
      <Code
        language="javascript"
        panel={<Panel/>}
        data-lgid="lg-code-1"
      >
      {codeSnippet}
      </Code>
      <Code
        language="python"
        panel={<Panel/>}
        data-lgid="lg-code-2"
      >
        {codeSnippet}
      </Code>
    </>
  );

  const testUtils1 = getTestUtils('lg-code-1');
  const testUtils2 = getTestUtils('lg-code-2');

  // First Code
  expect(testUtils1.getLanguage()).toBe('javascript');

  // Second Code
  expect(testUtils2.getLanguage()).toBe('python');
});

Test Utils

const {
  getLanguage,
  getIsLoading,
  getTitle,
  queryPanel,
  getLanguageSwitcherUtils: {
    getInput,
    getOptions,
    getOptionByValue,
    isDisabled,
  },
  getCopyButtonUtils: { getButton, queryButton, findButton, isDisabled },
  getExpandButtonUtils: { getButton, queryButton, findButton },
} = getTestUtils();

| Util | Description | Returns | | ---------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | | getLanguage() | Returns the current language of the code block | string | | getLanguageSwitcherUtils() | Returns utils for interacting with the language switcher | LanguageSwitcherUtils | | getIsLoading() | Returns whether the code block is in loading state | boolean | | getCopyButtonUtils() | Returns utils for interacting with the copy button | Button test utils return type | | getExpandButtonUtils() | Returns utils for interacting with the expand button | Button test utils return type | | getIsExpanded() | Returns whether the code block is expanded | boolean | | getTitle() | Returns the title of the code block | string | null | | queryPanel() | Returns the panel element | HTMLElement | null |

LanguageSwitcherUtils

| Util | Description | Returns | | --------------------------------- | ------------------------------------------------- | ----------------------- | | getInput() | Returns the language switcher trigger | HTMLButtonElement | | getInputValue() | Returns the language switcher input value | string | | getOptions() | Returns all options in the language switcher | Array<HTMLElement> | | getOptionByValue(value: string) | Returns the option element by its value | HTMLElement | null | | isDisabled() | Returns whether the language switcher is disabled | boolean |