javascriptmediawikivisual-editor

MediaWiki Visual Editor: trim new lines after HTML inserted as block node


First of all, I am no Javscript expert, I am just a general amateur programmer who knows how to copy-paste code and fix it for his needs.

Now, I am creating a gadget for Visual Editor in MW 1.39. I want a button for adding custom HTML tags inline.

This is my code so far:

ve.ui.BibliaCommand = function VeUiBibliaCommand() {
    ve.ui.BibliaCommand.super.call( this, 'Biblia' );
};
OO.inheritClass( ve.ui.BibliaCommand, ve.ui.Command );

ve.ui.BibliaCommand.prototype.execute = function ( surface ) {
    var model = surface.getModel(),
        doc = model.getDocument(),
        range = model.getSelection().getRange(),
        docRange = doc.shallowCloneFromRange( range );

    ve.init.target.getWikitextFragment( docRange, false ).done( function ( wikitext ) {
        var htmlfrag = model.getFragment().insertHtml('<bible>'+wikitext+'</bible>');
    } );
};

ve.ui.commandRegistry.register( new ve.ui.BibliaCommand() );

ve.ui.BibliaTool = function VeUiBibliaTool() {
    ve.ui.BibliaTool.super.apply( this, arguments );
};
OO.inheritClass( ve.ui.BibliaTool, ve.ui.Tool );
ve.ui.BibliaTool.static.name = 'Biblia';
ve.ui.BibliaTool.static.group = 'cite';
ve.ui.BibliaTool.static.icon = 'book';
ve.ui.BibliaTool.static.title = 'Biblia';
ve.ui.BibliaTool.static.commandName = 'Biblia';
ve.ui.toolFactory.register( ve.ui.BibliaTool );

It works and wraps the selected text in the desired tags. But it also inserts a newline before and after the wrapped selection. Any suggestion on how I can remove these newlines?


Solution

  • Okay, I figured it out. I did two replace transactions, in order to remove the newlines inserted before and after the HTLM (2 characters each, since they are CR/LF). It looks like this:

    model.getFragment().insertHtml('<bible>'+wikitext+'</bible>');
    var inicio = model.selection.range.from;
    var mitransac = ve.dm.TransactionBuilder.static.newFromReplacement( doc,  new ve.Range( inicio, inicio+2 ), '' ) 
    model.getFragment().change(mitransac);
    var fin = model.selection.range.to;
    var mitransac2 = ve.dm.TransactionBuilder.static.newFromReplacement( doc,  new ve.Range( fin-2, fin ), '' )
    model.getFragment().change(mitransac2);