Difference between revisions of "MediaWiki:Gadget-Template-Utils.js"

From Refugee Terminology
Jump to navigation Jump to search
(Created page with "var sections = [ 'Normative', 'Research', 'Press', 'Comments' ]; var namespace = mw.config.get('wgCanonicalNamespace'); var url = mw.util.getUrl(); var page = mw.config.g...")
 
 
(9 intermediate revisions by the same user not shown)
Line 13: Line 13:
var pageName = url.substr(url.length - page.length + (namespace.length > 0 ? (namespace.length + 1) : 0));
var pageName = url.substr(url.length - page.length + (namespace.length > 0 ? (namespace.length + 1) : 0));


function makeToolbarTools() {
mw.loader.using('ext.visualEditor.core').then(function() {
    if ( namespace == 'Term' ) {
var rest = new mw.Rest();
        sections.forEach(function(e){
            var url = mw.config.get('wgScript') + '/' + encodeURIComponent( e ) + ":" + encodeURIComponent( pageName );
if (!mw.messages.exists('ve-InsertTemplateDialog-title')) {
            mw.util.addPortletLink( 'p-tb', url+"?veaction=edit", e, 't-tk-sub-'+e.toLowerCase(), e + " subsection" );
mw.messages.set({
            mw.util.addPortletLink('p-cactions', url, e, 'ca-tk-'+e.toLowerCase(), e + " subsection" );
've-InsertTemplateDialog-title': 'Insert Template Source',
        });
've-InsertTemplateDialog-insert': 'Insert',
    }
've-InsertTemplateDialog-placeholder': 'MainPage',
    else if (sections.includes(namespace)) {
've-InsertTemplateDialog-label': 'Template Name',
        var url = mw.config.get('wgScript') + '/' + "Term:" + encodeURIComponent( pageName );
've-InsertTemplateDialog-tool': 'Insert Template'
        mw.util.addPortletLink( 'p-tb', url+"?veaction=edit", "Term", 't-tk-sub-term', "Term page" );
});
        mw.util.addPortletLink('p-cactions', url, "Term", 'ca-tk-term', "Term page" );
}
    }
}
ve.ui.InsertTemplateSourceDialog = function( manager, config) {
//makeToolbarTools();
ve.ui.InsertTemplateSourceDialog.super.call(this, manager, config);
 
};
mw.loader.using(['mediawiki.api']).then( function () {
    var api = new mw.Api();
OO.inheritClass(ve.ui.InsertTemplateSourceDialog, ve.ui.FragmentDialog);
 
    function makePageTools() {
var insertTemplate = function(source) {
        if ( namespace == 'Term' ) {
var model = ve.init.target.getSurface().getModel();
            function addLinks(user) {
var selRange = model.selection.range;
                $(".mw-headline").each(function(_,e){
                    var $e = $(e);
window.selection = selRange;
                    var id = $e.attr('id');
                    if (    $.inArray(id, sections) >= 0
ve.init.target.getSurface().getView().changeModel(transaction, new ve.Range(selRange.start, selRange.start));
                        &&  $e.next().attr('class') != 'mw-editsection'
};
                        &&  $.inArray(id.toLowerCase()+'-edit', user.rights) >= 0) {
                        var base = $('<span class="mw-editsection"></span>');
ve.ui.InsertTemplateSourceDialog.prototype.getActionProcess = function(action) {
                        base.append('<span class="mw-editsection-bracket">[</span>');
var sourceVal = this.sourceInput.getValue();
                        base.append('<a href="/index.php?title='+$e.attr('id')+':'+pageName+'&amp;veaction=edit&amp;section=T-1" class="mw-editsection-visualeditor" title="Edit section: ">edit</a>');
if (action === 'insert') {
                        base.append('<span class="mw-editsection-divider"> | </span>');
return new OO.ui.Process(function() {
                        base.append('<a href="/index.php?title='+$e.attr('id')+':'+pageName+'&amp;action=edit&amp;section=T-1" title="Edit section: ">edit source</a>');
rest.get("/v1/page/"+sourceVal).then(function(res){
                        base.append('<span class="mw-editsection-bracket">]</span>');
                if (res && res.source)
                        base.insertAfter($e);
                    return res.source;
                    }
            }).then(function(source){
                });
            if (source !== undefined) {
            }
insertTemplate(source);
 
this.close();
            api.getUserInfo().then(addLinks);
            }
        }
            }).catch(function(err) {
    }
            console.log(err);
 
            });
    makePageTools();
}, this);
} );
}
return ve.ui.MWMediaDialog.super.prototype.getActionProcess.call( this, action );
};
ve.ui.InsertTemplateSourceDialog.prototype.getBodyHeight = function () {
return 200;
};
ve.ui.InsertTemplateSourceDialog.static.name = 'insert_template';
ve.ui.InsertTemplateSourceDialog.static.title = mw.msg('ve-InsertTemplateDialog-title');
ve.ui.InsertTemplateSourceDialog.static.size = 'medium';
ve.ui.InsertTemplateSourceDialog.static.actions = [
{
'action': 'insert',
'label': mw.msg('ve-InsertTemplateDialog-insert'),
'flags': [ 'constructive' ],
'modes': 'insert'
}
];
ve.ui.InsertTemplateSourceDialog.prototype.initialize = function () {
ve.ui.InsertTemplateSourceDialog.super.prototype.initialize.call( this );
this.panel = new OO.ui.PanelLayout( { '$': this.$, 'scrollable': true, 'padded': true } );
this.inputsFieldset = new OO.ui.FieldsetLayout( {
'$': this.$
} );
// input source
this.sourceInput = new OO.ui.TextInputWidget(
{ '$': this.$, 'multiline': false, 'placeholder': mw.msg('ve-InsertTemplateDialog-placeholder') }
);
this.sourceField = new OO.ui.FieldLayout( this.sourceInput, {
'$': this.$,
'label': mw.msg('ve-InsertTemplateDialog-label')
} );
this.inputsFieldset.$element.append(
this.sourceField.$element
);
this.panel.$element.append( this.inputsFieldset.$element );
this.$body.append( this.panel.$element );
}
ve.ui.windowFactory.register( ve.ui.InsertTemplateSourceDialog );
function InsertTool( toolGroup, config ) {
OO.ui.Tool.call( this, toolGroup, config );
}
OO.inheritClass( InsertTool, OO.ui.Tool );
InsertTool.static.name = 'InsertTool';
InsertTool.static.title = mw.msg('ve-InsertTemplateDialog-tool');
InsertTool.prototype.onSelect = function () {
this.toolbar.getSurface().execute( 'window', 'open', 'insert_template', null );
};
InsertTool.prototype.onUpdateState = function () {
this.setActive( false );
};
ve.ui.toolFactory.register( InsertTool );
});


//TODO: make smart insertion
//TODO: make smart insertion

Latest revision as of 00:49, 11 May 2022

var sections = [
	'Normative',
	'Research',
	'Press',
	'Comments'
];

var namespace = mw.config.get('wgCanonicalNamespace');
var url = mw.util.getUrl();
var page = mw.config.get('wgPageName');

var baseLink = url.substr(0, url.length - page.length);
var pageName = url.substr(url.length - page.length + (namespace.length > 0 ? (namespace.length + 1) : 0));

mw.loader.using('ext.visualEditor.core').then(function() {
	var rest = new mw.Rest();
	
	if (!mw.messages.exists('ve-InsertTemplateDialog-title')) {
		mw.messages.set({
			've-InsertTemplateDialog-title': 'Insert Template Source',
			've-InsertTemplateDialog-insert': 'Insert',
			've-InsertTemplateDialog-placeholder': 'MainPage',
			've-InsertTemplateDialog-label': 'Template Name',
			've-InsertTemplateDialog-tool': 'Insert Template'
		});
	}
	
	ve.ui.InsertTemplateSourceDialog = function( manager, config) {
		ve.ui.InsertTemplateSourceDialog.super.call(this, manager, config);	
	};
	
	OO.inheritClass(ve.ui.InsertTemplateSourceDialog, ve.ui.FragmentDialog);
	
	var insertTemplate = function(source) {
		var model = ve.init.target.getSurface().getModel();
		var selRange = model.selection.range;
		
		window.selection = selRange;
		
		ve.init.target.getSurface().getView().changeModel(transaction, new ve.Range(selRange.start, selRange.start));
	};
	
	ve.ui.InsertTemplateSourceDialog.prototype.getActionProcess = function(action) {
		var sourceVal = this.sourceInput.getValue();
		if (action === 'insert') {
			return new OO.ui.Process(function() {
				rest.get("/v1/page/"+sourceVal).then(function(res){
	                if (res && res.source)
	                    return res.source;
            	}).then(function(source){
            		if (source !== undefined) {
						insertTemplate(source);
						this.close();
            		}
            	}).catch(function(err) {
            		console.log(err);
            	});
			}, this);
		}
		return ve.ui.MWMediaDialog.super.prototype.getActionProcess.call( this, action );
	};
	
	ve.ui.InsertTemplateSourceDialog.prototype.getBodyHeight = function () {
		return 200;
	};
	
	ve.ui.InsertTemplateSourceDialog.static.name = 'insert_template';
	ve.ui.InsertTemplateSourceDialog.static.title = mw.msg('ve-InsertTemplateDialog-title');
	ve.ui.InsertTemplateSourceDialog.static.size = 'medium';
	
	ve.ui.InsertTemplateSourceDialog.static.actions = [
		{
			'action': 'insert',
			'label': mw.msg('ve-InsertTemplateDialog-insert'),
			'flags': [ 'constructive' ],
			'modes': 'insert'
		}
	];
	
	ve.ui.InsertTemplateSourceDialog.prototype.initialize = function () {
		ve.ui.InsertTemplateSourceDialog.super.prototype.initialize.call( this );
		this.panel = new OO.ui.PanelLayout( { '$': this.$, 'scrollable': true, 'padded': true } );
		this.inputsFieldset = new OO.ui.FieldsetLayout( {
			'$': this.$
		} );
		// input source
		this.sourceInput = new OO.ui.TextInputWidget(
			{ '$': this.$, 'multiline': false, 'placeholder': mw.msg('ve-InsertTemplateDialog-placeholder') }
		);
		this.sourceField = new OO.ui.FieldLayout( this.sourceInput, {
			'$': this.$,
			'label': mw.msg('ve-InsertTemplateDialog-label')
		} );
	
		this.inputsFieldset.$element.append(
			this.sourceField.$element
		);
		
		this.panel.$element.append(	this.inputsFieldset.$element );
		this.$body.append( this.panel.$element );
	}
	
	ve.ui.windowFactory.register( ve.ui.InsertTemplateSourceDialog );
	
	function InsertTool( toolGroup, config ) {
		OO.ui.Tool.call( this, toolGroup, config );
	}
	OO.inheritClass( InsertTool, OO.ui.Tool );
	 
	InsertTool.static.name = 'InsertTool';
	InsertTool.static.title = mw.msg('ve-InsertTemplateDialog-tool');
	 
	InsertTool.prototype.onSelect = function () {
		this.toolbar.getSurface().execute( 'window', 'open', 'insert_template', null );
	};
	 
	InsertTool.prototype.onUpdateState = function () {
		this.setActive( false );
	};
	 
	ve.ui.toolFactory.register( InsertTool );
});

//TODO: make smart insertion
mw.loader.using(['mediawiki.api', 'oojs']).then( function () {
    var api = new mw.Api();
    var rest = new mw.Rest();

    function makeVisualTools() {
        if (namespace != 'Term') return;
        
        //Create and register command
        
        var commandName = 'insertSections';
        var title = 'Insert Term Template';
        
        var template = [];
        
        var pageTemplates = {};
        
        var promises = [];
        
        sections.forEach(function(e){
            //Create template
            template = template.concat([
                {
                    type: 'mwTransclusionBlock',
                    attributes: {
                        mw: {
                            parts: [ {
                                template: {
                                    i:0,
                                    target: {
                                        href: "./"+e+":"+pageName,
                                        wt: e+":"+pageName
                                    }
                                },
                                params: {}
                            } ]
                        }
                    }
                },
                { type: '/mwTransclusionBlock' },
                { type: 'paragraph' },
                { type: '/paragraph' }
            ]);
            //Gather template
            promises.push(rest.get("/v1/page/Template:"+e).then(function(res){
                if (res && res.source)
                {
                    pageTemplates[e] = res.source;
                }
            }));
        });
        
        Promise.all(promises).then(function(){
            //console.log(pageTemplates);
        });
        
        var InsertSectionsCommand = function(name) {
            InsertSectionsCommand.super.call( this, name );
            this.subcommand = new ve.ui.Command( commandName, 'content', 'insert', {
                args: [ template, false, true ],
                supportedSelections: [ 'linear' ]
            });
        }
        OO.inheritClass( InsertSectionsCommand, ve.ui.Command );
        
        InsertSectionsCommand.prototype.execute = function(surface, args, source) {
            sections.forEach(function(section){
                var tm = pageTemplates[section];
                api.create(section+":"+pageName, {}, tm !== undefined ? tm : 'Section: '+section);
            });
            
            var ret = this.subcommand.execute(surface, args, source);
            
            return ret;
        }
        
        ve.ui.commandRegistry.register(new InsertSectionsCommand(commandName));

        //Create and register tool
        function SectionTemplater() {
            SectionTemplater.parent.apply( this, arguments );
        }
        OO.inheritClass( SectionTemplater, ve.ui.MWTransclusionDialogTool );

        SectionTemplater.static.name = 'sectiontemplater';
        SectionTemplater.static.group = 'insert';
        SectionTemplater.static.title = title;
        SectionTemplater.static.commandName = commandName;
        ve.ui.toolFactory.register( SectionTemplater );
    }

    //Initialize
    mw.hook( 've.loadModules' ).add( function( addPlugin ) {
        addPlugin( function() {
            return mw.loader.using( [ 'ext.visualEditor.core', 'ext.visualEditor.mwwikitext', 'ext.visualEditor.mwtransclusion' ] )
                .then( function() {
                    makeVisualTools();
                } );
        } );
    } );
} );