Difference between revisions of "MediaWiki:Common.js"
From cm2.liecourt.com
(Fill database) |
|||
(2 intermediate revisions by 2 users not shown) | |||
Line 79: | Line 79: | ||
var times = []; | var times = []; | ||
− | for (var i = | + | for (var i = 10; i < 22; i++) { |
var hour = i; | var hour = i; | ||
var pm = 'AM'; | var pm = 'AM'; |
Latest revision as of 10:08, 25 August 2022
/* Any JavaScript here will be loaded for all users on every page load. <script>*/ $(document).ready(function () { createPageTogglers = document.querySelectorAll('[data-creatpage]'); if(createPageTogglers && createPageTogglers.length > 0){ createPageTogglers.forEach(function(el){ el.addEventListener( "click", function () { createPage( ) }) }) } }) console.log('uyfuyfuy' ); var createPage = function (current_namespace, current_pagename) { console.log("working"); var hiddenInput = document.querySelector('#time-slot-field'); mw.loader.using(["oojs-ui-windows", 'mediawiki.widgets.DateInputWidget']).then(function () { // Example: Using getSetupProcess() to configure a window with data passed // at the time the window is opened. // Make a subclass of ProcessDialog function PageCreateDialog(config) { PageCreateDialog.super.call(this, config); } OO.inheritClass(PageCreateDialog, OO.ui.ProcessDialog); // Specify a name for .addWindows() PageCreateDialog.static.name = "createPageDialog"; PageCreateDialog.static.title = "Select a Time Slot"; // Specify the static configurations: title and action set PageCreateDialog.static.actions = [ { flags: "primary", label: "Continue", action: "open", }, { flags: "safe", label: "Cancel", }, ]; // Customize the initialize() function to add content and layouts: PageCreateDialog.prototype.initialize = function () { var dialol = this; PageCreateDialog.super.prototype.initialize.call(this); this.panel = new OO.ui.PanelLayout({ padded: true, expanded: false, }); this.content = new OO.ui.FieldsetLayout(); var date = new Date(); // month = date.getMonth() + 1; this.urlInput = new mw.widgets.DateInputWidget({ value: date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() }); this.field = new OO.ui.FieldLayout(this.urlInput, { label: "Day", align: "top", }); var times = []; for (var i = 10; i < 22; i++) { var hour = i; var pm = 'AM'; if (i > 12) { hour = i - 12; pm = 'PM'; } times.push( new OO.ui.ButtonOptionWidget( { label: hour + ':00' + ' - ' + hour + ':15 ' + pm }) ); times.push( new OO.ui.ButtonOptionWidget( { label: hour + ':15' + ' - ' + hour + ':30 ' + pm }) ); times.push( new OO.ui.ButtonOptionWidget( { label: hour + ':30' + ' - ' + hour + ':45 ' + pm }) ); times.push( new OO.ui.ButtonOptionWidget( { label: hour + ':45' + ' - ' + (hour + 1) + ':00 ' + pm }) ); } this.slotSelect = new OO.ui.ButtonSelectWidget( { items: times } ); this.slotsWrapper = new OO.ui.FieldLayout( new OO.ui.Widget( { content: [ new OO.ui.HorizontalLayout( { items: [ this.slotSelect ] }) ] }), { label: "Time", align: "top", }); this.content.addItems([this.field, this.slotsWrapper]); this.panel.$element.append(this.content.$element); this.$body.append(this.panel.$element); var that = this; this.urlInput.on( 'change', function () { // The value will always be a valid date or empty string, malformed input is ignored that.updateSlots(); } ); }; PageCreateDialog.prototype.updateSlots = function () { var that = this; var date = that.urlInput.getValue().split('-'); var month = date[1]; var year = date[0]; var day = date[2]; that.slotSelect.items.forEach(function(item){ item.setDisabled(false); }) var params = { action: 'ask', query: '[[Slot month::' + month + ']][[Slot day::' + day + ']][[Slot year::' + year + ']]|?Slot|limit=500', formatversion: 2, format: 'json' } var api = new mw.Api; api.post(params).done(function(data){ if (data.query.results) { console.log(data.query.results) Object.entries(data.query.results).forEach(function(slot){ var date = slot[1].printouts.Slot[0].fulltext || slot[1].printouts.Slot[0]; var time = date.split('/')[1]; var item = that.slotSelect.getItemFromLabel(time); if(item){ item.setDisabled(true); } }) // ["Workflow/90"].printouts.Slot[0] } }) // ask query function here, and disbale results // selectItemByLabel(label).setDisabled(true); }; // Specify any additional functionality required by the window (disable opening an empty URL, in this case) // Specify the dialog height (or don't to use the automatically generated height). PageCreateDialog.prototype.getBodyHeight = function () { // Note that "expanded: false" must be set in the panel's configuration for this to work. // When working with a stack layout, you can use: // return this.panels.getCurrentItem().$element.outerHeight( true ); return this.panel.$element.outerHeight(true) + 200; }; // Use getSetupProcess() to set up the window with data passed to it at the time // of opening (e.g., url: 'http://www.mediawiki.org', in this example). PageCreateDialog.prototype.getSetupProcess = function (data) { data = data || {}; var nuthis = this; return PageCreateDialog.super.prototype.getSetupProcess .call(this, data) .next(function () { // Set up contents based on data var val = hiddenInput.value; if (val) { var split = val.split('/'); nuthis.urlInput.setValue(split[0]); nuthis.slotSelect.selectItemByLabel(split[1]) } nuthis.updateSlots(); }, this); }; var boiler = ""; // Specify processes to handle the actions. PageCreateDialog.prototype.getActionProcess = function (action) { var nuthis = this; if (action === "open") { // Create a new process to handle the action return new OO.ui.Process(function () { var day = nuthis.urlInput.getValue(); var time = nuthis.slotSelect.findSelectedItem().label; console.log(day, time) hiddenInput.value = day + '/' + time; var button = document.querySelector('#time-slot-button'); button.innerText = day + ' • ' + time; return 800; }).next(function(){ nuthis.close({action: action}); return true; }) } // Fallback to parent handler return PageCreateDialog.super.prototype.getActionProcess.call(this, action); }; // Use the getTeardownProcess() method to perform actions whenever the dialog is closed. // This method provides access to data passed into the window's close() method // or the window manager's closeWindow() method. PageCreateDialog.prototype.getTeardownProcess = function (data) { return PageCreateDialog.super.prototype.getTeardownProcess .call(this, data) .first(function () { // Perform any cleanup as needed }, this); }; // Create and append a window manager. var windowManager = new OO.ui.WindowManager(); $(document.body).append(windowManager.$element); // Create a new process dialog window. var createPageDialog = new PageCreateDialog(); // Add the window to window manager using the addWindows() method. windowManager.addWindows([createPageDialog]); // Open the window! windowManager.openWindow(createPageDialog); }); }; /*** * REMOVE FILE * **/ document.querySelectorAll('[data-removefile]').forEach(function(el){ el.addEventListener('click', function(){ console.log(el.dataset.removefile) var r = confirm("Are you sure?"); if (r == true) { var params = { action: 'delete', title: el.dataset.removefile, format: 'json' }, api = new mw.Api(); api.postWithToken( 'csrf', params ).done( function ( data ) { console.log( data ); el.remove(); } ); } }) }) /** * POLLING FOR USER PAGES **/ var pollWrapper = document.querySelector('[data-poll]'); var fps = 30; var now; var then; var interval = 100000/fps; var delta; function poll(now) { if (!then) { then = now; } requestAnimationFrame(poll); delta = now - then; if (delta > interval) { then = now - (delta % interval); if(pollWrapper.dataset.poll == 'Messages'){ goPolling() }else{ workflowPolling() } } } if(pollWrapper){ poll(); } var polledWorkflows = false; function workflowPolling(){ var params = { action: 'ask', query: '[[Workflow::' + pollWrapper.dataset.workflow + ']]|?Modification date', formatversion: 2, format: 'json' }; var api = new mw.Api(); api.post( params ).done( function ( data ) { if(data.query.results) { var flows = Object.entries(data.query.results).map(function(entrie){ return entrie[1].printouts['Modification date'][0].timestamp }) if(polledWorkflows && flows.sort().join() != polledWorkflows.sort().join()){ console.log('found something new', flows); console.log('polled', polledWorkflows); reloadSection() } else { console.log('polling, but found nothing new'); } polledWorkflows = flows } }) } var polledJurors = false; function goPolling(){ var user = mw.config.values.wgRelevantUserName; var params = { action: 'ask', query: '[[Class::Workflow]][[Random juror::User:' + user + ']] OR [[Random judge::User:' + user + ']]', formatversion: 2, format: 'json' }; var api = new mw.Api(); api.post( params ).done( function ( data ) { if(data.query.results) { var newKeys = Object.keys(data.query.results); if(polledJurors && newKeys.sort().join() != polledJurors.sort().join()){ console.log('found something new', newKeys); console.log('polled', polledJurors); reloadSection() } else { console.log('polling, but found nothing new'); } polledJurors = newKeys; } }) } function reloadSection(){ var template = pollWrapper.dataset.poll; var paramters = pollWrapper.dataset.parameters.replaceAll('^', '|') var params = { action: 'parse', text: '{{' + template + '|' + paramters + '|Fullpagename=' + mw.config.values.wgPageName.replaceAll('_', ' ') + '}}', contentmodel: 'wikitext', wrapoutputclass: '', disableeditsection: true, disablelimitreport: true, disabletoc: true, formatversion: 2, format: 'json' }, api = new mw.Api(); api.post( params ).done( function ( data ) { if(data.parse){ if(template == 'Messages'){ $(pollWrapper).html(data.parse.text) } else { $('#mw-content-text').html(data.parse.text) } } }) } function logmeout(){ var params = { action: 'logout', format: 'json' }, api = new mw.Api(); api.postWithToken( 'csrf', params ).done( function ( data ) { console.log( data, 'we logged you out' ); window.location = mw.config.values.wgServer + '/index.php/Main_Page'; } ); } $( document ).ready(function() { if ($('.WSShowOnSelect') ) { WsShowOnSelect(); } $('body.action-edit #wpTextbox1, body.action-submit #wpTextbox1').keydown(function(event) { var x = event.keyCode; if (x == 13 ) { if(!event.shiftKey){ var insert = document.execCommand('insertText', false, '<!-- \n -->'); if(insert){ event.preventDefault(); $('#wpTextbox1').focus() insert } } } }) // Start of esc save $('body.action-edit, body.action-submit').keydown(function() { var x = event.keyCode; if (x == 27) { $.ajax({ url :'/api.php?action=query&meta=tokens&format=json', type: 'GET', dataType: 'json', success : function(result){ var token = result.query.tokens.csrftoken; $("input[name='wpEditToken']").attr("value", token ); saveEdit(); } }); }else{ mw.confirmCloseWindow(); $('#wpSave, #wpPreview, #wpDiff').on('click', function(){ $( window ).off( 'beforeunload' ); }) } }) if($('body').hasClass('action-submit')){ $('#top').prepend('<button class="btn btn-success enable-live-mode">Enable live mode</button>'); $(document).on('click','.enable-live-mode', function(){ if($(this).hasClass('btn-success')){ liveMode(); $(this).removeClass('btn-success'); $(this).text('Live mode is on'); }else{ $(this).addClass('btn-success'); $('body.action-submit textarea').off("change keyup paste"); $(this).text('Enable live mode'); } }); } }); window.saveEdit = function() { $.ajax({ url : $('form.mw-editform').attr('action'), type : 'POST', data :$('form.mw-editform').serialize(), success : function(html) { $( window ).off( 'beforeunload' ); mw.notify( 'Saved' ); if($('body').hasClass('action-submit')){ var parser = new DOMParser(); var doc = parser.parseFromString(html, "text/html"); var elem = doc.querySelectorAll('.mw-content-ltr')[0]; $('.mw-content-ltr').html(elem); } } }) }; window.liveMode = function() { var oldVal = ""; $('body.action-submit textarea').on("change keyup paste", function() { var currentVal = $(this).val(); if(currentVal == oldVal) { return; //check to prevent multiple simultaneous triggers } oldVal = currentVal; var text = encodeURIComponent($('textarea').val()); $.ajax({ url: '/api.php?action=parse&format=json&formatversion=2&title=New&text='+text+'&pst=&prop=text%7Cmodules%7Cjsconfigvars&preview=true&disableeditsection=true&uselang=en', dataType: 'json', success: function (x) { $('#wikiPreview').html(x.parse.text); } }); }); }; /* End of Esc Save */ /***** WSForm: loading Select2 ****/ $( document ).ready(function() { if ($('select[data-inputtype="ws-select2"]')[0]) { mw.loader.load('/extensions/WSForm/select2.min.css', 'text/css'); $.getScript('/extensions/WSForm/select2.min.js').done(function() { $('select[data-inputtype="ws-select2"]').each(function() { var selectid = $(this).attr('id'); var selectoptionsid = 'select2options-' + selectid; var select2config = $("input#" + selectoptionsid).val(); var F = new Function(select2config); return (F()); }); }); } }); /* End of WSForm: Select2 */ (function($) { $.fn.autogrow = function() { return this.each(function() { var textarea = this; $.fn.autogrow.resize(textarea); $(textarea).focus(function() { textarea.interval = setInterval(function() { $.fn.autogrow.resize(textarea); }, 500); }).blur(function() { clearInterval(textarea.interval); }); }); }; $.fn.autogrow.resize = function(textarea) { var lineHeight = parseInt($(textarea).css('line-height'), 10); var lines = textarea.value.split('\n'); var columns = textarea.cols; var lineCount = 0; /** * measures the text pixel width * @param text * @returns {*|jQuery} */ function textMeasure(text) { var div = document.createElement('div'); document.body.appendChild(div); $(div).css({ position: 'absolute', left: -1000, top: -1000, display: 'none' }); $(div).html(text); const width = $(div).outerWidth(); $(div).remove(); return width; } $.each(lines, function() { lineCount += Math.ceil(textMeasure(this) / ($(textarea).innerWidth() - 125)) || 1; // lineCount += Math.ceil(this.length / columns) || 1; }); var height = lineHeight * (lineCount + 1); $(textarea).css('height', height); }; })(jQuery); $('textarea.form-control').autogrow(); /* WSSHOWONSELECT */ /** * applying show on select on the page and make sure everyting will be handled as needed */ function WsShowOnSelect() { var selectArray = []; $('.WSShowOnSelect').find('[data-wssos-show]').each(function (index, elm) { if ( $(elm).is('option') ) { var isInArray = false; var selectParent = $(elm).parent()[0]; for ( var i = 0; i < selectArray.length; i++ ) { if ( $(selectParent).is($(selectArray[i])) ) { isInArray = true; } } if ( !isInArray ) { selectArray.push(selectParent); handleSelect(selectParent); } } else if ( $(elm).is('input[type=radio]') ) { handleRadio(elm); } else if ( $(elm).is('input[type=checkbox]') ) { handleCheckbox(elm); } else if ( $(elm).is('button') ) { handleButton(elm); } }); } /** * handle the radio button changes, show what is needed * @param radioElm */ function handleRadio(radioElm) { var pre_wssos_value = $(radioElm).data('wssos-show'); var pre_parent_wssos = $(radioElm).parentsUntil('.WSShowOnSelect').parent()[0]; var pre_wssos_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_wssos_value+'"]'); if ( $(radioElm).parent().hasClass('WSShowOnSelect') ) { pre_parent_wssos = $(radioElm).parent()[0]; pre_wssos_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_wssos_value+'"]'); } if ( radioElm.checked ) { $(pre_wssos_elm).removeClass('hidden'); putAllTypesDataInName(pre_wssos_elm); } else { putAllTypesNameInData(pre_wssos_elm); } $(pre_parent_wssos).find('input[type=radio][name="'+ radioElm.name +'"]').on('change', function () { var wssos_value = $(this).data('wssos-show'); var parent_wssos = $(this).parentsUntil('.WSShowOnSelect').parent()[0]; var wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]'); if ( $(this).parent().hasClass('WSShowOnSelect') ) { parent_wssos = $(this).parent()[0]; wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]'); } $(parent_wssos).find('input[name="'+this.name+'"][type="radio"]').each(function(index, radiobtn) { var radio_hide_data_attr = $(radiobtn).data('wssos-show'); $(parent_wssos).find('[data-wssos-value="'+radio_hide_data_attr+'"]').addClass('hidden'); putAllTypesNameInData($(parent_wssos).find('[data-wssos-value="'+radio_hide_data_attr+'"]')); }); if ( this.checked ) { wssos_elm.removeClass('hidden'); putAllTypesDataInName(wssos_elm); } else { wssos_elm.addClass('hidden'); putAllTypesNameInData(wssos_elm); } }); } /** * handle the checkbox changes, show what is needed * @param checkElm */ function handleCheckbox(checkElm) { var pre_wssos_value = $(checkElm).data('wssos-show'); var pre_parent_wssos = $(checkElm).parentsUntil('.WSShowOnSelect').parent()[0]; var pre_wssos_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_wssos_value+'"]'); if ( $(checkElm).parent().hasClass('WSShowOnSelect') ) { pre_parent_wssos = $(checkElm).parent()[0]; pre_wssos_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_wssos_value+'"]'); } if ( checkElm.checked ) { pre_wssos_elm.removeClass('hidden'); // set the dataset value of data-name-attribute back in the name attribute putAllTypesDataInName(pre_wssos_elm); // set the name value of the unchecked element in the value of data-name-attribute and remove the name attribute if ( $(checkElm).has('data-wssos-show-unchecked') ) { var pre_unchecked_value = $(checkElm).data('wssos-show-unchecked'); var pre_unchecked_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_unchecked_value+'"]'); putAllTypesNameInData(pre_unchecked_elm); } } else { // set data-name-attribute to the value of name attribute and remove the name attribute putAllTypesNameInData(pre_wssos_elm); if ( $(checkElm).has('data-wssos-show-unchecked') ) { var pre_unchecked_value = $(checkElm).data('wssos-show-unchecked'); var pre_unchecked_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_unchecked_value+'"]'); $(pre_unchecked_elm).removeClass('hidden'); // set the name attribute to the value of data-name-attribute putAllTypesDataInName(pre_unchecked_elm); } } $(checkElm).on('change', function(e) { e.stopPropagation(); var wssos_value = $(this).data('wssos-show'); var parent_wssos = $(this).parentsUntil('.WSShowOnSelect').parent()[0]; var wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]'); if ( $(this).parent().hasClass('WSShowOnSelect') ) { parent_wssos = $(this).parent()[0]; wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]'); } if ( this.checked ) { wssos_elm.removeClass('hidden'); putAllTypesDataInName(wssos_elm); } else { wssos_elm.addClass('hidden'); putAllTypesNameInData(wssos_elm); } if ( $(this).has('data-wssos-show-unchecked') ) { var wssos_unchecked_value = $(this).data('wssos-show-unchecked'); var wssos_unchecked_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_unchecked_value+'"]'); if ( this.checked ) { wssos_unchecked_elm.addClass('hidden'); putAllTypesNameInData(wssos_unchecked_elm); } else { wssos_unchecked_elm.removeClass('hidden'); putAllTypesDataInName(wssos_unchecked_elm); } } }); } /** * handle the select box changes to show what is needed on select * @param selectElm */ function handleSelect(selectElm) { var selectVal = $(selectElm).val(); $(selectElm).children().each(function (index, option) { var wssos_value = $(option).data('wssos-show'); var parent_wssos = $(option).parentsUntil('.WSShowOnSelect').parent()[0]; var wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]'); if ( option.selected || $(option).val() === selectVal) { wssos_elm.removeClass('hidden'); putAllTypesDataInName(wssos_elm); } else { wssos_elm.addClass('hidden'); putAllTypesNameInData(wssos_elm); } }); $(selectElm).on('change', function () { $(this).children().each(function (index, option) { var wssos_value = $(option).data('wssos-show'); var parent_wssos = $(this).parentsUntil('.WSShowOnSelect').parent()[0]; var wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]'); if ( option.selected ) { wssos_elm.removeClass('hidden'); putAllTypesDataInName(wssos_elm); } else { wssos_elm.addClass('hidden'); putAllTypesNameInData(wssos_elm); } }); }); } function handleButton(btnElm) { var pre_wssos_value = $(this).data('wssos-show'); var pre_parent_wssos = $(this).parentsUntil('.WSShowOnSelect').parent()[0]; var pre_wssos_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_wssos_value+'"]'); // set up the start and make sure the element is hidden $(pre_wssos_elm).addClass('hidden'); putAllTypesNameInData(pre_wssos_elm); // add on click listener to the button $(btnElm).on('click', function(e) { var wssos_value = $(this).data('wssos-show'); var parent_wssos = $(this).parentsUntil('.WSShowOnSelect').parent()[0]; var wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]'); // possibility to hide the wanted element back if an option if ( !$(wssos_elm).hasClass('hidden') ) { $(wssos_elm).addClass('hidden'); putAllTypesNameInData(wssos_elm); } else { $(wssos_elm).removeClass('hidden'); putAllTypesDataInName(wssos_elm); } }); } /** * find all different types which name attribute should go to the dataset * @param elm */ function putAllTypesNameInData(elm) { putNameAttrValueInDataset($(elm).find('input,select,textarea')); putRequiredInDataset($(elm).find('input,select,textarea')); } /** * find all different types which data-attribute should go to the name-attribute * @param elm */ function putAllTypesDataInName(elm) { putDatasetValueBackInName($(elm).find('input,select,textarea')); putDatasetInRequired($(elm).find('input,select,textarea')); } /** * set the name attribute value to the dataset data-name-attribute, remove the name attribute * @param elm */ function putNameAttrValueInDataset($elm) { $.each($elm, function (index, elm) { if ( $(elm).attr('name') !== '' ) { var name = $(elm).attr('name'); if (name) { $(elm).attr('data-name-attribute', name); $(elm).removeAttr('name'); } } }); } /** * set the name attribute to the value of the data-name-attribute * @param elm */ function putDatasetValueBackInName($elm) { $.each($elm, function(index, elm) { if ( $(elm).attr('data-name-attribute') !== '' ) { var datasetName = $(elm).data('name-attribute'); if (datasetName) { $(elm).attr('name', datasetName); } } }); } /** * set the required attr in the dataset data-ws-required * @param $elm */ function putRequiredInDataset($elm) { $.each($elm, function (index, elm) { if ( $(elm).is(':required') ) { $(elm).attr('data-ws-required', true); $(elm).prop('required', false); } }); } /** * if the element has data-ws-required the make the element required * @param $elm */ function putDatasetInRequired($elm) { $.each($elm, function (index, elm) { if ( $(elm).data('ws-required') ) { $(elm).prop('required', true); } }) } /* END OF WSSHOWONSELECT */ $( document ).ready(function() { if( $('.redirect-link').length > 0 ) { $('.redirect-link a')[0].click(); } })