prismjs-fold-json

1.0.9 • Public • Published

Prism.js JSON Folding Plugin

A Prism.js plugin that adds code folding support for JSON objects and arrays. Demo
The algorithm should work for any C-like language. JSON/JavaScript/Java are supported by default. You can add more languages by setting the PRISM_FOLD_HOOK_LANGUAGES environment variable.

How It Works

This plugin processes Prism tokens and wraps {} and [] blocks in <details> tags to enable folding functionality.

It implements two Prism hooks:

  1. after-tokenize handler: Identifies punctuation tokens ({ and [), converting the flat token list into nested structures for folding
  2. wrap handler: Adds <details> and <summary> tags before final HTML output

Key Differences from Similar Solutions

this implementation:

  • Inspired by prism-js-fold, uses semantic HTML <details> without JavaScript event handlers
  • Leverages Prism's low-level highlight function through hook integration, therefore works transparently with direct calls to Prism.highlight()
  • Processes tokens split by Prism's native parser instead of relying on regular expressions

Setup

Node.js Installation

Install via npm:

npm install prismjs-fold-json

Import after Prism:

const Prism = require('prismjs');
require('prismjs-fold-json');

// Example usage
const html = Prism.highlight(
  JSON.stringify({ a: [1, 2] }, null, 4),
  Prism.languages.json,
  "json"
);

Note: For Vue/React projects, import CSS in your entry file:

import 'prismjs-fold-json/main.css';

CDN Usage

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" 
          href="https://unpkg.com/prismjs@1.29.0/themes/prism-coy.min.css">
    <!-- Required CSS -->
    <link rel="stylesheet" 
          href="https://unpkg.com/prismjs-fold-json@1.x.x/main.css">
</head>
<body>
    <script src="https://unpkg.com/prismjs@1.29.0/components/prism-core.min.js"></script>
    <script src="https://unpkg.com/prismjs@1.29.0/plugins/autoloader/prism-autoloader.min.js"></script>
    <!-- Plugin script (load after Prism) -->
    <script src="https://unpkg.com/prismjs-fold-json@1.x.x/index.js"></script>
</body>
</html>

Known Issues

Browser-specific <details> tag behavior:

  • Chromium ≥128: Creates new lines
  • Other browsers: Adds extra indentation spaces

The implementation handles these differences through adaptive logic. If issues persist, try setting the PRISM_IN_CHROME_LIKE environment variable with these values:
auto (default) | new | old | none

Readme

Keywords

Package Sidebar

Install

npm i prismjs-fold-json

Weekly Downloads

2

Version

1.0.9

License

ISC

Unpacked Size

13.6 kB

Total Files

5

Last publish

Collaborators

  • xyty007