prismjs-fold-json
v1.0.9
Published
plugin for prism to fold json/js
Readme
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:
- after-tokenize handler: Identifies punctuation tokens (
{and[), converting the flat token list into nested structures for folding - 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
highlightfunction through hook integration, therefore works transparently with direct calls toPrism.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-jsonImport 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/[email protected]/themes/prism-coy.min.css">
<!-- Required CSS -->
<link rel="stylesheet"
href="https://unpkg.com/[email protected]/main.css">
</head>
<body>
<script src="https://unpkg.com/[email protected]/components/prism-core.min.js"></script>
<script src="https://unpkg.com/[email protected]/plugins/autoloader/prism-autoloader.min.js"></script>
<!-- Plugin script (load after Prism) -->
<script src="https://unpkg.com/[email protected]/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
