nlundquist / prism-js-fold

PrismJS plugin adding code folding to JSON & JavaScript objects & arrays via <details> tag insertion.
9 stars 2 forks source link

Getting it working with manual mode #1

Open KiranWells opened 3 years ago

KiranWells commented 3 years ago

When I used this with manual highlighting and Prism.highlight, it simply did nothing. After digging around in the code for a bit, I noticed that:

  1. Fold only activates on the first "on page load" run (the 'before-all-elements-highlight' hook).
  2. Fold is removed by the Prism sanity check or highlighter.
  3. This is easily fixable from a user's standpoint, although it is a bit hacky

Here is what finally got it working for me (using the js and css files directly from GitHub):

let el = document.getElementById("code") // the code element
el.innerHTML = string // the JSON (in this case) to be parsed 
insertFolds(el) // from prism-js-fold
let newstring = el.innerHTML
let html = Prism.highlight(newstring, Prism.languages.json, 'json')
html = html.replace(/&lt;/g, "<")
html = html.replace(/&gt;/g, ">")
// fix the class, open, etc. attributes being converted to span.token.string elements
html = html.replace(/<(\w+) (\w+)=<span class="token string">"(\w*)"<\/span>/g, '<$1 $2="$3"')
el.innerHTML = html

This could possibly be fixed with an "after-highlight" hook, although I am not sure if it works the same as Prism.highlight. My results with a hook always seemed to have the details and summary elements stripped out.

fnep commented 3 years ago

After there was no response for a while, I'm not so sure if this module will be maintained or if it's just here for reference.

First requirement will be to export the insertFolds function. I will send a pull request for this.

Then I made it working by using the insertFolds function like this:

import {insertFolds} from "prism-js-fold";

Prism.highlightElement(codeElement);
insertFolds(codeElement);

… respectively …

import {insertFolds} from "prism-js-fold";

codeElement.innerHTML = Prism.highlight(myJsonContent, Prism.languages.json, 'json');
insertFolds(codeElement);

Is this also working for you, @KiranWells?