MediaWiki:Gadget-visual-editor-mermaid-support.js
Note : après avoir enregistré vos modifications, il se peut que vous deviez forcer le rechargement complet du cache de votre navigateur pour voir les changements.
/* This gadget allows the rendering of diagrams within the visual editor when using the Mermaid extension. */
mw.libs.ve.addPlugin(function(target) {
console.log("Loading visual-editor-mermaid-support");
/* Makes sure Mermaid scripts are loaded in case a diagram is added to a page that did not previously
* contained one. Not ideal, this should be done when a user adds a script. */
mw.loader.load('ext.mermaid');
// Trigger the rendering of all Mermaid diagrams on the page.
mw.hook( 've.activationComplete' ).add( function () {
$('.ext-mermaid').each(function() { renderMermaid(this); }); // TO DO: Work everytime?
/* Add a hook to re render diagrams when the parameters to a diagram are modified
* AND Add a hook if new Flowchart is created */
var mutationObserverAddedMermaid = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
// Verify if paramWindow has Flowchart template
if (mutation.addedNodes){
mutation.addedNodes.forEach(function(addedNode) {
if ($(addedNode).hasClass('ext-mermaid')){
renderMermaid($(addedNode));
}
});
}
});
});
mutationObserverAddedMermaid.observe(document.querySelector('.ve-ce-documentNode'), {
childList: true,
});
});
// Trigger the rendering of all Mermaid diagrams on the page when the visual editor is closed
mw.hook( 've.deactivationComplete' ).add( function () {
$('.ext-mermaid').each(function() { renderMermaid(this); } );
});
});
// Render Mermaid on an HTML element containing a definition.
function renderMermaid(el){
// Function which renders mermaid instead of init
// Adapted from https://github.com/SemanticMediaWiki/Mermaid/blob/2.2.0/res/ext.mermaid.js
var that = $(el);
var id = 'ext-mermaid-' + (new Date().getTime());
var data = that.data( 'mermaid' );
if(!data) { return; } // Called on an invalid element.
that.find('.mermaid-dots').hide();
that.children().not( ".mermaid-dots" ).remove(); // Remove previous flowchart
that.append( '<div id=' + id + '> ' + data.content + ' </div>');
mermaid.initialize(data.config);
mermaid.init(undefined, $( "#" + id ));
}