Provides an API to add previewers.
This plugins provides a constructor that can be accessed through Prism.plugins.Previewer
.
Once a previewer has been instanciated, an HTML element is appended to the document body. This element will appear when specific tokens are hovered.
new Prism.plugins.Previewer(type, updater, supportedLanguages)
type
: the token type this previewer is associated to.
The previewer will be shown when hovering tokens of this type.
updater
: the function that will be called each time an associated token is hovered.
This function takes the text content of the token as its only parameter.
The previewer HTML element can be accessed through the keyword this
.
This function must return true
for the previewer to be shown.
supportedLanguages
: an optional array of supported languages.
The previewer will be available only for those.
Defaults to '*'
, which means every languages.
This is a simplified version of the color previewer plugin.
First, you need to add specific tokens to the grammar. For hexadecimal CSS colors, it might look like this:
Prism.languages.insertBefore('css', 'important', {
'color': /\B#(?:[0-9a-f]{3}){1,2}\b/i
});
Then, the previewer can be instanciated. The updater function will set the background color of the previewer HTML element, based of the hovered token.
new Prism.plugins.Previewer('color', function(value) {
// Reset the background color
this.style.backgroundColor = '';
// Set the background color to the value of the current hovered token
this.style.backgroundColor = value;
// Returns true if the color is valid, false otherwise
return !!this.style.backgroundColor;
}, 'css');
Now, with a bit of CSS to style the previewer, the result would be something like this:
div {
color: #dd4a68;
background: #669900;
border: 1px solid #ee9900;
}