MediaWiki:Gadget-scribe.js: diferència entre les revisions

Contingut suprimit Contingut afegit
 
actualització per Tema:Vqmblihaq5gqgcay
 
Línia 1:
/* Translate the following to your language: */
if (!mw.messages.exists('ve-scribe-dialog-title')) {
mw.messages.set({
've-scribe-dialog-title': 'Scribe',
've-scribe-select-section-txt': 'Seleccioneu les seccions que voleu usar en l\'article',
've-scribe-section-textbox-placeholder': 'Comenceu a escriure aquí',
've-scribe-btn-next': 'Següent',
've-scribe-btn-cancel': 'Cancel·la',
've-scribe-btn-done': 'Fet',
've-scribe-button-group-link-btn': 'Enllaça',
've-scribe-button-group-cite-btn': 'Referencia',
've-scribe-no-section-selected-dialog-macsg': 'Seleccioneu una secció',
've-scribe-server-error': 'No s\'ha pogut accedir al servidor',
've-scribe-save-prompt-msg': 'Desar per després?',
've-scribe-edit-summary': 'Pàgina editada usant Scribe',
've-scribe-dialog-action-complete': 'La pàgina ha estat creada \n comproveu la vostra pàgina de proces',
've-scribe-save-dialog-accept': 'sí',
've-scribe-save-dialog-deny': 'No',
've-scribe-launch-prompt-msg': 'Modificació en mode Scribe?',
've-scribe-launch-scribe-accept': 'Sí',
've-scribe-launch-scribe-deny': 'No'
});
}
 
/* _____________________________________________________________________________
* | |
* | === WARNING: GLOBAL GADGET FILE === |
* | Changes to this page affect many users. |
* | Please discuss changes on the talk page or on [[WT:Gadget]] before editing. |
* |_____________________________________________________________________________|
*
* Imported from version 0.0.1 as of 2019-11-04 from [[:en:MediaWiki:Gadget-scribe.js]]
* Using this script allows you to edit articles in underrepresented wikipedias, see [[User:Eugene233/scribe]]
*/
 
/* global mw, ve */
 
(function () {
/* Translate the following to your wiki language: */
var api = new mw.Api(),
if (!mw.messages.exists('ve-scribe-dialog-title')) {
chosenReferences = [],
fieldsetContainer = [],mw.messages.set({
've-scribe-add-reference-label': 'AFEGEIX',
stackPanels = [],
've-scribe-add-reference-again-label': 'AFEGEIX DE NOU',
stack,
've-scribe-dialog-title': 'Scribe',
slideIndex = 0,
've-scribe-editing-ideas-txt': 'Editing Ideas?',
selectedRefIndex = 0,
've-scribe-launch-prompt-msg': 'Modificació en mode Scribe?',
sectionUrlTemplateData = [];
've-scribe-launch-scribe-accept': 'Sí',
viewControl = 0,
've-scribe-launch-scribe-deny': 'No',
 
've-scribe-new-section-txt': 'Secció nova?',
/**
've-scribe-server-error': 'No s\'ha pogut accedir al servidor',
* Create a checkbox to represent section to select.
've-scribe-search-score-label': 'Search score',
*
've-scribe-suggested-sestion-txt': 'Seccions suggerides',
* @param {Object} section - The section to be used to create checkbox.
've-scribe-wikipedia-label': 'Wikipedia',
* @return {Object} - The itemFieldLayout containing the section element.
've-scribe-wikipedia-domain-label': 'Wikipedia domain'
*/
 
function makeSectionHomeItem(section) {
var homeItem, itemFieldLayout;
homeItem = new OO.ui.CheckboxInputWidget({
value: section.number,
id: 'input-' + section.number,
required: true,
classes: ['mw-scribe-checkbox']
});
itemFieldLayout = new OO.ui.FieldLayout(
homeItem,
{ label: section.line, align: 'inline' });
return itemFieldLayout;
}
 
/**
* Create a StackLayout.
*
* @param {Object} stackPanels - The panels to be added to the stack.
* @return {Object} - The StackLayout containing panels.
*/
 
function makeStack(stackPanels) {
return new OO.ui.StackLayout({
classes: ['container'],
items: stackPanels,
padded: true
});
}
/* _____________________________________________________________________________
* | |
* | === WARNING: GLOBAL GADGET FILE === |
* | Changes to this page affect many users. |
* | Please discuss changes on the talk page or on [[WT:Gadget]] before editing. |
* |_____________________________________________________________________________|
*
* Imported from version 0.0.1 as of 2019-11-04 from [[:en:MediaWiki:Gadget-scribe.js]]
* Using this script allows you to edit articles in underrepresented wikipedias, see [[User:Eugene233/scribe]]
*/
 
/* global mw, ve */
var chosenReferences = [],
* Create a FieldsetLayout.
* scribe = {},
sectionUrlTemplateData = [],
* @param {Object} contentElements - The elements added to the fielset.
selectedSection = '',
* @return {Object} - The FieldsetLayout.
*/ slideIndex = 0;
 
function createFieldSetcreateElement(contentElementstype, id, className, displayText) {
var fieldset = new OO.ui.FieldsetLayout({element;
switch (type) classes: ['container'],{
align:case 'inlinep',:
padded: true element = $('<p>');
}) element['0'].id = id;
fieldset element.addItemsaddClass(contentElementsclassName);
element.append(displayText);
return fieldset;
break;
case 'div':
element = $('<div>');
element['0'].id = id;
element.addClass(className);
break;
case 'span':
element = $('<span>');
element['0'].id = id;
element.addClass(className);
element.append(displayText);
break;
case 'a':
element = $('<a>');
element['0'].id = id;
element.addClass(className);
element.append(displayText);
break;
case 'ul':
element = $('<ul>');
element['0'].id = id;
element.addClass(className);
element.append(displayText);
break;
case 'li':
element = $('<ul>');
element['0'].id = id;
element.addClass(className);
element.append(displayText);
break;
default:
break;
}
return element;
}
function addChild(parent, child) {
parent.append(child);
}
 
/**
* Insert arbitrary content on VE surface
*
*
* @param {String} sectionNumber the section number
* @param {StringObject} sectionNamesurfaceModel the name of the sectionsurface model
* @param {Object} data the data to be written on surface
*/
 
function getFieldsetSectionDataStructureinsertContent(sectionNumbersurfaceModel, sectionNamedata) {
var// Insert data =and place cursor {};afterwards
surfaceModel.getFragment().collapseToEnd().insertContent(data).collapseToEnd().select();
data.section = sectionName;
data.number = sectionNumber;
return data;
}
 
function buildEmptyParagraph() {
/**
return [{ type: 'paragraph' }, { type: '/paragraph' }]
* Adds fioelset elements to PanelLayout
*
* @param {String} sectionNumber the number of the section
* @param {String} sectionName the name of the section
* @param {Object} fieldSetContentElements the fieldset content with elements
*/
 
function addPanelElementsToPanel(sectionNumber, sectionName, fieldSetContentElements) {
var fieldSet,
panel;
fieldSet = createFieldSet(fieldSetContentElements);
panel = new OO.ui.PanelLayout({
expanded: false,
align: 'center',
classes: ['container']
});
if (sectionName != 'undefined' && sectionNumber != -1) {
fieldsetContainer.push(getFieldsetSectionDataStructure(sectionNumber, sectionName));
}
panel.$element.append(fieldSet.$element);
return panel;
}
 
/**
* CreatesAdd thewrite first view shownsection to the user onVE launchsurface.
*
* @param {Object} pageTitle - The page which is actively under edit.
* @param {Object} articleSections - The sections in the page.
* @return {Object} - The panel containing elements of the edit interface.
*/
 
function createHomeViewwriteSectionToSurface(pageTitle, articleSectionssectionTextData) {
var surfaceModel = ve.init.target.getSurface().getModel(),
var articleNameLabel, articleLegend, homeFieldSet, homePanel,
homeElements = [], homeviewElementsReferenceSectionData = [];
ReferenceSectionData.push({ type: 'mwHeading', attributes: { level: 2 } });
 
sectionTextData.forEach(function (character) {
articleNameLabel = new OO.ui.LabelWidget({
label: pageTitle,ReferenceSectionData.push(character);
align: 'left',
padded: true,
id: 'mw-scribe-action-page-title'
});
ReferenceSectionData.push({ type: '/mwHeading' });
insertContent(surfaceModel, ReferenceSectionData);
 
articleLegend// =add a new OO.ui.LabelWidget({paragraph to create space
insertContent(surfaceModel, buildEmptyParagraph());
label: mw.msg('ve-scribe-select-section-txt'),
selectedSection = padded: true,sectionTextData;
classes: ['mw-scribe-select-info']
});
 
homeElements.push(articleNameLabel);
homeElements.push(articleLegend);
 
articleSections.forEach(function (section) {
var sectionLine = makeSectionHomeItem(section);
homeElements.push(sectionLine);
});
homeFieldSet = createFieldSet(homeElements);
homePanel = addPanelElementsToPanel(-1, 'undefined', homeFieldSet);
 
homeviewElements.push(homePanel);
homeviewElements.push(homeFieldSet);
return homeviewElements;
}
 
/**
* Loads all references into the slider
* @param {Object} slides - the slides to be added to ref section.
*/
 
function loadAllReferenceSlides(slides) {
var i;
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
$('.mw-scribe-ref-box').removeClass('activeref');
}
$('.mw-scribe-ref-box').addClass('activeref');
}
 
Linha 197 ⟶ 125:
*/
 
function showSlide(indexslideIndex, slides) {
for (var i = 0; i < slides.length; i++) {
if (i === indexslideIndex) {
slides[i].style.display = "block";
$('.ve-scribe-ref-box').addClass('activeref');
} else {
slides[i].style.display = "none";
$('.ve-scribe-ref-box').removeClass('activeref');
}
}
if (slides[slideIndex].classList.contains('used-ref')) {
}
$('#ve-scribe-choose-ref')['0'].innerHTML = mw.msg('ve-scribe-add-reference-again-label')
 
/**
* Makes the HTML conntent for the slider
* @param {Number} section_number - the section number under edit
* @return {HTMLObjectElement} - the html object to be added on the slider
*/
 
function makeSliderHtml(section_number) {
// TODO: We have to generate the sections with id mw-scribe-ref-box
// dynamically given the data we have from resources
var html = '<div id="mw-scribe-slider-' + section_number + '">' +
'<div class="slideshow-container" id="slideshow-container-' + section_number + '">' +
'<a class="prev">&#10094;</a> ' +
'<a class="next">&#10095;</a>' +
'</div>' +
'</div>';
return html;
}
 
/**
* Add slider child nodes with server infomation
* @param {Number} section_number - the section number under edit.
* @param {String} active_section_title - the section title of active section.
*/
 
function addSliderSectionChildNodes(section_number, active_section_title) {
if ($("#slideshow-container-" + (section_number - 1).toString())) {
var slides1 = $("#slideshow-container-" + (section_number - 1).toString()).children('.mySlides' + section_number.toString())
 
for (var i = 0; i < slides1.length; i++) {
if (slides1[i].className.split(' ')[0]) {
slides1[i].className = "";
}
}
}
// $.get('https://tools.wmflabs.org/scribe/api/v1/references?section=' + mw.config.get( 'wgTitle' ).toLowerCase())
$.get('https://tools.wmflabs.org/scribe/api/v1/references?section=' + active_section_title + '&article=' + mw.config.get('wgTitle'))
.done(function (response) {
var slides = [],
resource = response.resources;
resource.forEach(function (item) {
$("#slideshow-container-" + section_number.toString()).append(
'<div class="fade mySlides' + section_number.toString() + '">' +
'<div class="text">' +
'<div class=\'mw-scribe-ref-box\'>' +
'<p class=\'mw-scribe-ref-title\'>' + item.publication_title + '</p>' +
'<p class=\'mw-scribe-ref-text\'>' + item.content + '</p>' +
'<div class=\'mw-scribe-ref-link-box\'>' +
'<a class=\'mw-scribe-ref-link\'>' + item.url + '</a>' +
'<p id=\'mw-scribe-' + section_number.toString() + '-ref-data\'></p>' +
'</div>' +
'</div>' +
'</div>' +
'<a id="mw-scribe-view-ref">view</a>' +
'</div>');
$("#mw-scribe-" + section_number.toString() + "-ref-data").hide();
$.get('https://tools.wmflabs.org/scribe/api/v1/references/resources?link=https://www.mmb.cat/fons-i-colleccions/biblioteca/').done(
function (data) {
 
$("#mw-scribe-" + section_number.toString() + "-ref-data").text(
data.publication_date + '_' +
data.publication_title + '_' +
data.publisher_name + '_' +
data.retrieved_date);
}
);
});
slides = document.getElementsByClassName("mySlides" + section_number.toString());
loadAllReferenceSlides(slides);
slides[0].style.display = "block";
});
}
 
/**
* Constructs link which VE should recognize
* @param {String} url the selected url in reference section
*/
 
function createReferenceLink(selectedRefIndex) {
return ' [' + selectedRefIndex + ']';
}
 
/**
* Insert a cite link at the cursor position in the editor
*
* @param {TextInputWidget} textEditor the text editor
* @param {String} link the formatted url to insert
*/
 
function insertLinkAtCursorPosition(textEditor, link) {
//IE support
if (document.selection) {
textEditor.focus();
sel = document.selection.createRange();
sel.text = link;
}
//MOZILLA and others
else if (textEditor.selectionStart || textEditor.selectionStart == '0') {
var startPos = textEditor.selectionStart;
var endPos = textEditor.selectionEnd;
textEditor.value = textEditor.value.substring(0, startPos) + link + textEditor.value.substring(endPos, textEditor.value.length);
textEditor.selectionStart = startPos + link.length;
textEditor.selectionEnd = startPos + link.length;
} else {
$('#ve-scribe-choose-ref')['0'].innerHTML = mw.msg('ve-scribe-add-reference-label');
textEditor.value += link;
}
textEditor.focus();
}
 
/**
*
* @param {ButtonWidget} referenceAddButton the button to be activated
* @param {String} sectionNumber the section number currently under edit
*/
 
function addReferenceButtonClickAction(referenceAddButton, sectionNumber) {
referenceAddButton.on('click', function () {
var selectedUrl = $('.activeref')[0].lastChild.firstChild.innerHTML;
var editor = $('.section-' + sectionNumber + 'text-editor')[0].firstChild;
var selectRefData = {};
selectRefData.url = selectedUrl.replace(' ', ''); // replace the extra space at begining of url
selectRefData.data = $("#mw-scribe-" + sectionNumber.toString() + "-ref-data")[0].innerText;
// We add the chosen reference URL to the list of chosen references
chosenReferences.push(selectedUrl);
sectionUrlTemplateData.push(selectRefData);
insertLinkAtCursorPosition(editor, createReferenceLink(selectedRefIndex + 1));
selectedRefIndex++;
});
}
 
/**
* Creates PanelLayout of a section's edit interface.
*
* @param {Object} section - The section whose edit interface we want to create.
* @return {Object} - The panel containing elements of the edit interface.
*/
 
function createEditSectionPanel(section) {
var sectionTitle, editSurface, referenceAddButton, editButtonGroup,
referenceSection, editSectionFieldSet, sectionFieldSetItems = [], editSectionPanel, html;
sectionTitle = new OO.ui.LabelWidget({
label: section.line,
align: 'left',
padded: true,
id: 'mw-scribe-section-' + section.number + '-title',
classes: ['mw-scribe-section-name-text']
});
 
editSurface = new OO.ui.MultilineTextInputWidget({
rows: 17,
autosize: true,
placeholder: mw.msg('ve-scribe-section-textbox-placeholder'),
id: '#mw-scribe-section-' + section.number + '-text-editor',
classes: ['section-' + section.number + 'text-editor', 'mw-scribe-text-editor'],
autofocus: true
});
 
referenceAddButton = new OO.ui.ButtonWidget({
label: '',
align: 'center',
icon: 'articleAdd',
flags: [
'primary',
'progressive'
],
classes: ['mw-scribe-ref-btn']
});
 
// we define the action when the ref button is clicked
addReferenceButtonClickAction(referenceAddButton, section.number);
 
referenceSection = new OO.ui.LabelWidget({
id: 'mw-scribe-reference-anchor-' + section.number,
classes: ['mw-scribe-reference-section']
});
 
sectionFieldSetItems.push(sectionTitle);
sectionFieldSetItems.push(editSurface);
sectionFieldSetItems.push(referenceAddButton);
sectionFieldSetItems.push(referenceSection);
 
editSectionPanel = addPanelElementsToPanel(section.number, section.line, sectionFieldSetItems);
return editSectionPanel;
}
 
/**
* Create an instance of a dialog.
*
* @param {Object} config - dialog configuration.
* Note: Changing this name ScribeDialog means changing the dialog
* name name below.
*/
 
function ScribeDialog(config) {
ScribeDialog.parent.call(this, config);
}
 
/**
* Return a promise from the api call.
*
* @param {Object} pageTitle - The current page the user is editing with ve.
* @return {Object} - The promise.
*/
 
function getArticleListPromise(pageTitle) {
var article_list = api.get({
action: 'parse',
page: pageTitle,
format: 'json',
formatversion: 2,
prop: 'sections'
});
return article_list;
}
 
Linha 426 ⟶ 147:
*/
 
function activeOnClickEventForNext(nextClass, sectionNumberslides) {
var slides = document.getElementsByClassName("mySlides" + sectionNumber);
$(nextClass).on('click', function () {
if (slideIndex === slides.length - 1) {
Linha 442 ⟶ 162:
*/
 
function activeOnClickEventForPrev(prevClass, sectionNumberslides) {
var slides = document.getElementsByClassName("mySlides" + sectionNumber);
$(prevClass).on('click', function () {
if (slideIndex - 1 < 0) {
slideIndex = slides.length;
}
slideIndex--;
Linha 454 ⟶ 173:
 
/**
* RemoveLoads spaceall fromreferences contentinto urlthe slider
* @param {Object} slides - the slides to be added to ref section.
*
* @param {String} entryUrl url to process
*/
 
function removeSpaceFromLinkloadAllReferenceSlides(entryUrlslides) {
var i;
// remove white space from begining of the url
entryUrlfor (i = entryUrl.replace('0; ',i '')< slides.length; i++) {
slides[i].style.display = "none";
return entryUrl;
$('.ve-scribe-ref-box').removeClass('activeref');
}
 
/**
* Replace text citation from text editor with actual links
*
* @param {Object} chosenReferences array of selected refs
* @param {String} content the content with citations
*/
 
function replaceCiteTextWithLink(chosenReferences, content) {
// check for citations in content before replacing
if (content.includes('[') && content.includes(']')) {
for (var index = 0; index < chosenReferences.length; index++) {
var element = chosenReferences[index];
if (content.includes('[' + (index + 1).toString() + ']')) {
var temp = content.replace('[' + (index + 1).toString() + ']', removeSpaceFromLink(element));
content = temp;
}
}
return content;
} else {
return content;
}
}
 
function createReferenceSlider(surface) {
/**
var slider = createElement('div', 've-scribe-slider', 'slideshow-container', ''),
* Build the edit data to be used on VE surface
previousArrow = createElement('a', '', 'prev', '&#10094;'),
*
nextArrow = createElement('a', '', 'next', '&#10095;');
* @param {Object} chosenReferences list of selected references
* @param {Object} editData list of objects with edit data
*/
 
addChild(slider['0'], previousArrow['0']);
function buildVeEditData(chosenReferences, editData) {
varaddChild(slider['0'], replacedContentnextArrow['0']);
editDatasurface.forEachappend(function (sectionDataslider['0']) {;
$('#editing-ideas-tip').hide();
replacedContent = replaceCiteTextWithLink(chosenReferences, sectionData.content);
$('#ve-scribe-slider').hide();
sectionData.content = replacedContent.split(' ');
});
return editData;
}
 
/**
* Insert reference to VE surface
* Build section data object
*
* @param {StringObject} data stringsurfaceModel ofthe sectionsurface textmodel
* @param {Object} data the data to be written
*/
*/
 
function buildsectionData(data) {
var sectionData = [];
sectionData.push({ type: 'mwHeading', attributes: { level: 2 } });
data.split('').forEach(function (element) {
sectionData.push(element);
});
sectionData.push({ type: '/mwHeading' });
return sectionData;
}
 
/**
* Insert reference to VE surface
*
* @param {Object} surfaceModel the surface model
* @param {Object} data the data to be written
*/
 
function insertReference(surfaceModel, data) {
var origFragment = surfaceModel.getFragment();
var referenceModel = new ve.dm.MWReferenceModel(surfaceModel.getDocument());
 
// Prepare and insert an empty reference
referenceModel.insertInternalItem(surfaceModel);
Linha 540 ⟶ 218:
new ve.dm.LinearSelection(referenceModel.findInternalItem(surfaceModel).getChildren()[0].getRange())
);
 
// Insert new contents
// Insert new content
refContentsFragment.insertContent(data);
 
// Place cursor after the inserted reference node
origFragment.collapseToEnd().select();
}
 
/**
* Insert arbitrary content on VE surface
*
* @param {Object} surfaceModel the surface model
* @param {Object} data the data to be written on surface
*/
 
function insertContent(surfaceModel, data) {
// Insert data and place cursor afterwards
surfaceModel.getFragment().collapseToEnd().insertContent(data).collapseToEnd();
}
 
Linha 566 ⟶ 234:
*/
 
function builRefTemplate(sectionUrlTemplateDataSelectUrlData, entryUrlselectUrl) {
// Server object of the form [publication_date, publication_title,publisher_name, retrieved_date]
// we remove the white space from begining of the url
entryUrlvar first = entryUrl.replace('SelectUrlData[2] != ',undefined' ? SelectUrlData[2] : '');,
last = SelectUrlData[2] != 'undefined' ? SelectUrlData[2] : '',
var templateData;
title = SelectUrlData[1] != 'undefined' ? SelectUrlData[1] : '',
sectionUrlTemplateData.forEach(function (sectionData) {
date = SelectUrlData[3] != 'undefined' ? SelectUrlData[3] : '',
if (sectionData.url === entryUrl) {
templateDatatemplate = sectionData.data;[
} else {
templateData = type: 'mwTransclusionInline';,
} attributes: {
}); mw: {
parts: [
// gives us an object [publication_date, publication_title,publisher_name, retrieved_date] from server
templateData = templateData.split('_'); {
template: {
var template = [
target: {
type href: 'mwTransclusionInline./Template:Cite_web',
attributes wt: {'Cite web'
mw: { },
parts params: [{
first: { wt: first },
template last: { wt: last },
target title: { wt: title },
href date: './Template{ wt:Cite_web' date },
url: { wt: 'CiteselectUrl web'}
},
params: {
first: { wt: templateData[2] },
last: { wt: templateData[2] },
title: { wt: templateData[1] },
date: { wt: 'January 2, 2015' }, //templateData[3]
url: { wt: entryUrl }
}
}
}]
]}
}
},
{ type: '/mwTransclusionInline' },
{ type: '/mwTransclusionInline' }];
];
 
return template;
}
 
/**
* Sends post request to scribe server with stats data
* Write section data to ve surface
**/
* @param {Object} sectionEditData Edit data of a particular section
*/
 
function writeSectionEditDataObjectsendStatsData(sectionUrlTemplateData, sectionEditDatastatsData) {
$.post({
var surfaceModel = ve.init.target.getSurface().getModel();
url: 'https://tools.wmflabs.org/scribe/api/v1/stats',
insertContent(surfaceModel, buildsectionData(sectionEditData.section));
data: JSON.stringify(statsData),
sectionEditData.content.forEach(function (content) {
ifcontentType: (content.includes('httpapplication/json')) {
}).done(function (response) {
var citeTemplate = builRefTemplate(sectionUrlTemplateData, content);
}).fail(function (error) {
insertReference(surfaceModel, citeTemplate);
console.log("Error encountered: insertContent(surfaceModelsendStatsData", ' 'error);
} else {)
insertContent(surfaceModel, content.split(''));
// insert a space after every word
insertContent(surfaceModel, ' ');
}
});
}
 
function activateAddReferenceOnclickListerner(referenceAddButton, refDataNode, slides) {
/**
referenceAddButton.on('click', function () {
* Add references section to VE surface.
var selectRefData = [], selectedUrl, statsData = {},
*/
surfaceModel = ve.init.target.getSurface().getModel();
 
$('.ve-scribe-reference-slider-slides')['0'].childNodes.forEach(function (node) {
function wrtieReferenceListSection() {
if (node.style.display === 'block') {
var surfaceModel = ve.init.target.getSurface().getModel(),
selectedUrl = node.firstChild.childNodes['2'].innerHTML
referenceSection = 'References', ReferenceSectionData = [];
selectRefData = node.firstChild.childNodes['4'].innerHTML.split('_')
ReferenceSectionData.push({ type: 'mwHeading', attributes: { level: 2 } });
}
referenceSection.split('').forEach(function (character) {
ReferenceSectionData.push(character});
});
ReferenceSectionData.push({ type: '/mwHeading' });
insertContent(surfaceModel, ReferenceSectionData);
}
 
// we build template for select link to cite on VE Surface
/**
templateData = builRefTemplate(selectRefData, selectedUrl);
* construct the content to be saved in the User's Sandbox
insertReference(surfaceModel, templateData);
*
slides = $('.ve-scribe-reference-slider-slides')['0'].childNodes;
* @param {Object} editData The edit data from the interface elements
slides.forEach(function (slide) {
*/
if (slide.style.display === 'block') {
slide.className = slide.className + ' used-ref';
$('#ve-scribe-choose-ref')['0'].innerHTML = mw.msg('ve-scribe-add-reference-again-label');
}
});
 
// send stats (references_used and section under edit) to the server side
function constructSanboxPageContent(editData) {
statsData.article = mw.config.get('wgTitle');
var sandboxPageContent;
sandboxPageContent statsData.ref = ''selectedUrl;
statsData.selectedSection = selectedSection.join("");
editData.forEach(function (contentData) {
sendStatsData(statsData)
sandboxPageContent += '\n== ' + contentData.section + ' == \n' + contentData.content + '\n';
});
return sandboxPageContent;
}
 
function activateCloseSliderOnclickListener(cancelSlider) {
/**
cancelSlider.on('click', function () {
*
$('#ve-scribe-slider').hide();
* @param {Object} sandboxData The data to be edited
* @param {String} username The name of the currently logged in user
*/
 
function CreateSanboxSubpage(sandboxData, username) {
var date, pageTitle;
pageTitle = 'User:' + username + '/sandbox/' + mw.config.get('wgTitle');
date = new Date();
api.postWithToken('csrf', {
action: 'edit',
summary: mw.msg('ve-scribe-edit-summary'),
title: pageTitle,
appendtext: sandboxData,
basetimestamp: date.toISOString()
}).done(function () {
mw.loader.using('mediawiki.notify', function () {
mw.notify(mw.msg('ve-scribe-dialog-action-complete'),
{ type: 'info' },
{ title: mw.config.get('ve-scribe-dialog-title') }
);
});
});
}
 
function buildSlideContent(sectionName) {
/**
// sectionName not used at the moment
* Builds scribe interface dialog
// sectionName = $('#editing-ideas-tip')['0'].childNodes['1'].id;
* @param {Object} articleSectionsPromise - promise from article section api call
*/
 
var slideContent = createElement('div', '', 've-scribe-reference-slider-slides', '', ''),
function buildDialogView(articleSectionsPromise) {
cancelSlider = createElement('a', 've-scribe-cancel-ref-suggest', 'oo-ui-iconElement-icon oo-ui-icon-close', ''),
articleSectionsPromise.done(function (data) {
addRefLinnk = createElement('a', 've-scribe-choose-ref', '', 'ADD');
var articleSections = data.parse.sections,
selectedSectionsToEdit = [];
 
// remove previous slider if there was
OO.inheritClass(ScribeDialog, OO.ui.ProcessDialog);
if ($('#ve-scribe-slider')) {
ScribeDialog.static.name = 'scribeDialog';
ScribeDialog.static.title = mw.msg$('#ve-scribe-dialog-titleslider').remove();
ScribeDialogcreateReferenceSlider($('.static.actions = ve-ce-documentNode')['0']);
{}
action: 'continue', modes: 'edit', label: mw.msg('ve-scribe-btn-next'), flags: ['primary',
'constructive']
},
{ modes: ['edit', 'final'], label: mw.msg('ve-scribe-btn-cancel'), flags: 'safe' },
{ modes: 'final', action: 'save', label: mw.msg('ve-scribe-btn-done'), flags: 'primary' }
];
 
$.get('https://tools.wmflabs.org/scribe/api/v1/references?section=' +
ScribeDialog.prototype.initialize = function () {
sectionName + '&article=' + mw.config.get('wgTitle'))
ScribeDialog.parent.prototype.initialize.apply(this, arguments);
.then(function (response) {
var resource = response.resources,
article_name = response.article_name;
 
resource.forEach(function (item) {
// use the sections to create the elements in the home view
// append the data to the slider display items
homeviewElements = createHomeView(mw.config.get('wgTitle'), articleSections);
var sliderText = createElement('div', '', 've-scribe-slider-text', ''),
stackPanels.push(homeviewElements[0]);
refBox = createElement('div', '', 've-scribe-ref-box', ''),
refTitle = createElement('span', '', 've-scribe-ref-title', item.publication_title),
refText = createElement('span', '', 've-scribe-ref-text', item.content),
refUrl = createElement('a', '', 've-scribe-ref-link', item.url),
refData = createElement('p', '', 've-scribe-ref-data', ''),
refDomainData = createElement('span', '', 've-scribe-ref-domain-data', '');
 
addChild(slideContent['0'], sliderText['0']);
// Home Page FieldSet Elements for the Home view used to determine which
// sections goes on nextaddChild(sliderText['0'], panelsrefBox['0']);
homePageFieldSetElements = homeviewElements addChild(refBox['0'], refTitle[1'0']);
addChild(refBox['0'], refText['0']);
addChild(refBox['0'], refUrl['0']);
addChild(refBox['0'], refDomainData['0']);
addChild(refBox['0'], refData['0']);
 
// // For all the selected sections we create an edit panel and add to stack$('#ve-scribe-slider')['0'].append(slideContent['0']);
articleSections sliderText.forEachhide(function (section) {;
var editSectionInterface = createEditSectionPanel(section);
stackPanels.push(editSectionInterface);
});
 
// createfill athe newref-data stacknode with itemsthe data from server ararayfor ofreference panels
$.get('https://tools.wmflabs.org/scribe/api/v1/domain?link=' + item.url)
stack = makeStack(stackPanels);
this.stackLayout = stack; .done(
this.$body.append function (this.stackLayout.$elementdata); {
var wp = mw.msg('ve-scribe-wikipedia-label') + ': ' + data.wikipedia_score,
this.stackLayout.setItem(stackPanels[0]);
wp_domain = mw.msg('ve-scribe-wikipedia-domain-label') + ': ' + data.wikipedia_score,
};
black_list = mw.msg('ve-scribe-search-score-label') + ': ' + data.search_result_score;
 
refDomainData['0'].innerText = wp + ' | ' + wp_domain + ' | ' + black_list;
ScribeDialog.prototype.getSetupProcess = function (data) {
return ScribeDialog.super.prototype.getSetupProcess.call( });
this, data)
.next(function () {
this.actions.setMode('edit');
}, this);
};
 
// get the domain information for the particular reference url
ScribeDialog.prototype.getActionProcess = function (action) {
$.get('https://tools.wmflabs.org/scribe/api/v1/references/resources?url=' + item.url)
var dialog, sectionNumber, activeSectionTitle;
.done(
function (data) {
refData['0'].innerHTML =
data.publication_date + '_' +
data.publication_title + '_' +
data.publisher_name + '_' +
data.retrieved_date;
}
);
refData.hide();
});
addChild($('#ve-scribe-slider')['0'], addRefLinnk['0']);
addChild($('#ve-scribe-slider')['0'], cancelSlider['0']);
 
//var removingslides the= class which enalbes a reference to be selected by defualt$('#ve-scribe-slider')['0'].childNodes['2'].childNodes;
$loadAllReferenceSlides('.mw-scribe-ref-box').removeClass('activeref'slides);
 
// Thedisplay Donethe buttonfirst hasreference beendata clickedin the slides
if (actionslides['0'].style.display === 'saveblock') {;
// we get the fieldsetContentData from the container of fieldsets
var editData = [];
// the data in the fieldset container is extracted into the data object
// we will use write to VE interface
fieldsetContainer.forEach(function (container) {
var editDataObject = {};
var text = $('.section-' + container.number + 'text-editor')[0].firstChild.value.toString();
if (text != '') {
editDataObject.section = container.section;
editDataObject.content = text;
editData.push(editDataObject);
}
});
 
//activate Edit DataonClick islistener foundfor inprev 'editData'and variablenet
// get the choice of the useractiveOnClickEventForNext('s action (sandbox or.next', publishslides);
OO.ui.confirmactiveOnClickEventForPrev(mw'.msg('ve-scribe-save-prompt-msgprev', slides),;
slideIndex = {0;
actions: [
{ action: 'accept', label: mw.msg('ve-scribe-save-dialog-accept'), flags: ['primary', 'progressive'] },
{ action: 'reject', label: mw.msg('ve-scribe-save-dialog-deny'), flags: ['primary', 'destructive'] }
]
}
).done(function (confirmed) {
if (confirmed) {
//Saving Info to sandBox
api.get({
action: 'query',
meta: 'userinfo'
}).then(function (data) {
if (data.query.userinfo.id !== 0) { //User is logged in
CreateSanboxSubpage(constructSanboxPageContent(editData), data.query.userinfo.name);
} else {
console.log('User is not logged in but with ip', data.query.userinfo.name);
}
});
 
// activate ADD on click } else {Listener
activateAddReferenceOnclickListerner($('#ve-scribe-choose-ref'), slides);
//Writing info to VE
activateCloseSliderOnclickListener($('#ve-scribe-cancel-ref-suggest'));
var surfaceData = buildVeEditData(chosenReferences, editData)
},
surfaceData.forEach(function (data) {
// error routine
writeSectionEditDataObject(sectionUrlTemplateData, data);
function (error) });{
// hide the slider since there is no // we write the reference sectionref lastdata
wrtieReferenceListSection$('#ve-scribe-slider').hide();
OO.ui.alert(mw.msg('ve-scribe-server-error')).done(function () }{
});
// Here we close the dialog after processing
dialog = this;
return new OO.ui.Process(function () {
// do something about the edit
dialog.close();
});
} else if (action === 'continue' && viewControl <
(stackPanels.length)) {
homePageFieldSetElements.items.forEach(function (e) {
if (e.align == 'inline') {
if (e.fieldWidget.selected === true) {
selectedSectionsToEdit.push(Number(e.fieldWidget.value));
}
}
});
});
}
 
function addEditTipOnclickListener(sectionIdeasTip, surface) {
if ((viewControl + 1) === selectedSectionsToEdit.length) {
sectionIdeasTip.on('click', function () {
this.actions.setMode('final');
//hide the new section tip }tag
$('#editing-ideas-tip').hide();
 
// We test ofpopulate the sections toreference beslider edittedwith havedata beenfrom chosenserver
if buildSlideContent(selectedSectionsToEdit.length !== $('#editing-ideas-tip')['0 &&'])
// $( '#ve-scribe-slider' )[ '0' ].prepend( buildSlideContent( sectionName )[ '0' ] );
viewControl < selectedSectionsToEdit[viewControl]) {
$('#ve-scribe-slider').show();
$('#ve-scribe-show-header-icon').hide()
});
}
 
function ShowEditIdeaTip(surface) {
// sectionNumber is the section number the user chose to edit
var tipSpan = createElement('span', 'editing-ideas-tip', '', ''),
sectionNumber = selectedSectionsToEdit[viewControl];
tipIcon = createElement('span', '', '', ''),
this.stackLayout.setItem(stackPanels[sectionNumber]);
tipText = createElement('a', '', 've-scribe-sm-suggest-text', mw.msg('ve-scribe-editing-ideas-txt'));
addChild(tipSpan['0'], tipIcon['0']);
addChild(tipSpan['0'], tipText['0']);
surface.append(tipSpan['0']);
 
addEditTipOnclickListener($('#editing-ideas-tip'), surface);
// current panel Item slider is built here
$('#ve-scribe-new-section-tip').hide();
var currentPanelItem = this.stackLayout.getCurrentItem()
createReferenceSlider(surface);
}
 
function addSectionItemOnclickListener(sectionContainer, surface) {
var currentRefLSider = document.getElementById('mw-scribe-reference-anchor-' + sectionNumber)
var sectionContainerElements = sectionContainer['0'].childNodes;
currentRefLSider.innerHTML = makeSliderHtml(sectionNumber)
if (sectionContainerElements.length != 0) {
sectionContainerElements.forEach(function (section) {
var seectionId = section.firstChild.id;
$('#' + seectionId).on('click', function () {
 
// indicate that the section has been clicked -- change color
$('#' + seectionId).addClass('active-seection');
// we have to write the section title into the ve surface here
var sectionTextData = $('#' + seectionId)['0'].firstChild.data.split('');
writeSectionToSurface(sectionTextData);
 
activeOnClickEventForNext$('.next#editing-ideas-tip', sectionNumber).toStringshow());
// hide reference activeOnClickEventForPrev('.prev', sectionNumber.toString());panel
slideIndex = 0$('#ve-scribe-slider').hide();
$('#editing-ideas-tip')['0'].childNodes['1'].id = $('#' + seectionId)['0'].firstChild.data;
});
});
}
}
 
function addShowScribeHeaderMenuOnclickListener(expandScribeHeaderMenu) {
// We get the active section title to be able to get suggestion links from server
expandScribeHeaderMenu.on('click', function () {
activeSectionTitle = $('#mw-scribe-section-' + sectionNumber + '-title').text();
$('#ve-scribe-show-header-icon').hide()
// Populate the edit box with the content of the sections from the article
populateEditSectionTextBox$('#ve-scribe-sm-header').slideDown(sectionNumber);
});
}
 
function addHideScribeHeaderMenuOnclickListener(collapseScribeHeaderIcon, mobileHeader) {
// We Add the slider section for edit view
collapseScribeHeaderIcon.on('click', function () {
addSliderSectionChildNodes(sectionNumber, activeSectionTitle);
$('#ve-scribe-sm-header').slideUp();
$('#ve-scribe-show-header-icon').show()
});
}
 
function buildScribeHeader(mobileHeader, surface) {
} else if (selectedSectionsToEdit.length === 0) {
var header = OO.ui.alert(mw.msgcreateElement('div', 've-scribe-nosm-section-selected-dialog-msgheader')).done(function, ('header', '') {,
tagContainer = createElement('span', 've-scribe-sm-idea-label', '', ''),
sectionHeaderIcon = createElement('span', 've-scribe-header-tip-icon', 'oo-ui-iconElement-icon oo-ui-icon-bell', ''),
collapseScribeHeaderIcon = createElement('span', 've-scribe-hide-header-icon',
'oo-ui-indicatorElement-indicator oo-ui-indicator-up', ''),
expandScribeHeaderIcon = createElement('span', 've-scribe-show-header-icon',
'oo-ui-indicatorElement-indicator oo-ui-indicator-down', '<p>Scribe</p>'),
sectionHeaderText = createElement('span', '', 've-scribe-sm-suggest-text',
mw.msg('ve-scribe-suggested-sestion-txt')),
sectionTagList = createElement('ul', 've-scribe-section-container', 'tags-container', '');
 
// Each section should appear as a });tagListItem
$.get('https://tools.wmflabs.org/scribe/api/v1/sections?article=' + mw.config.get('wgTitle'))
viewControl--;
.then(function (data) }{
var articleSections = viewControl++data.parse.sections;
selectedSectionsToEdit = [];
} else {
//closing the dialog
// dialog.close();
window.location.reload();
}
return ScribeDialog.parent.prototype.getActionProcess
.call(this, action);
};
 
// set thehide heightloader: ofwhen thedata dialogis boxfetched
$('#scribe-pg-bar').hide()
ScribeDialog.prototype.getBodyHeight = function () {
return $(window).height();
};
 
articleSections.forEach(function (section) {
ve.init.target.getActions().bsCancelAdded = true;
var sectionTagListItem = createElement('li',
windowManager = new OO.ui.WindowManager();
'', 'tags',
$(document.body).append(windowManager.$element);
'<a class="tag" id="section-' + section.number + '">' +
// set the width of the dialog
ProcessDialog = new ScribeDialog({} section.line + '</a>');
 
ProcessDialog.size = 'large';
dialog = new ScribeDialog(); // add the sections in to the container
windowManager.addWindows addChild(sectionTagList[dialog'0'], sectionTagListItem['0']);
windowManager.openWindow(dialog });
 
});
// If the request does not complete we don't add anything to interface
addChild(tagContainer['0'], sectionHeaderIcon['0']);
addChild(tagContainer['0'], sectionHeaderText['0']);
addChild(tagContainer['0'], collapseScribeHeaderIcon['0']);
addChild(header['0'], tagContainer['0']);
addChild(header['0'], sectionTagList['0']);
 
mobileHeader.append(expandScribeHeaderIcon['0']);
mobileHeader.append(header['0']);
 
// set every section's onclick listener using the container
addSectionItemOnclickListener(sectionTagList, surface);
addHideScribeHeaderMenuOnclickListener(collapseScribeHeaderIcon, mobileHeader);
addShowScribeHeaderMenuOnclickListener(expandScribeHeaderIcon, mobileHeader);
expandScribeHeaderIcon.hide();
},
 
// error routine
// give feedback to user
function (error) {
// hide the loader: Nothing happened
$('#scribe-pg-bar').hide()
// display error message to client
OO.ui.alert(mw.msg('ve-scribe-server-error')).done(function () {
});
});
}
 
function buildScribeLoader() {
/**
return new OO.ui.ProgressBarWidget({
* Populates text box in edit section with page data
* @param {Number} - section number under activeprogress: editfalse,
id: 'scribe-pg-bar'
*/
})
}
 
function addNewSectionTipOnclickListener(sectionIdeasTip, surface, mobileHeader) {
function populateEditSectionTextBox(sectionNumber) {
apisectionIdeasTip.geton('click', function () {
action://hide 'query',the new section tip tag
titles: mwsectionIdeasTip.config.gethide('wgTitle'),;
 
format: 'json',
formatversion://display 2,header with sections
rvprop: 'content'buildScribeHeader(mobileHeader, surface);
 
prop: 'revisions',
rvsection: sectionNumber$('#scribe-pg-bar').show()
 
}).then(function (data) {
// display the edit tips tag
var sectionContent = data.query.pages[0].revisions[0].content;
if ShowEditIdeaTip(sectionContent !== 'undefined'surface) {;
 
//We get the text input element and add its section content for editing
//hide the edit tip tag
$('.section-' + sectionNumber + 'text-editor')[0].firstChild.value = sectionContent;
} else {$('#editing-ideas-tip').hide();
$('.section-' + sectionNumber + 'text-editor')[0].firstChild.value = '';
}
});
}
 
mw.hook('ve.activationComplete').add(function showNewSectionTip(surface) {
var tipSpan = createElement('span', 've-scribe-new-section-tip', 'editing-tip', ''),
var articleSectionsPromise, homePageFieldSetElements, page_sections;
tipText = createElement('a', 'editing-idea-link', 've-scribe-sm-suggest-text',
console.log('activated VE with success!')
mw.msg('ve-scribe-new-section-txt'));
articleSectionsPromise = getArticleListPromise(mw.config.get('wgTitle'));
addChild(tipSpan['0'], tipText['0']);
OO.ui.confirm(mw.msg('ve-scribe-launch-prompt-msg'),
{
actions: [
{ action: 'accept', label: mw.msg('ve-scribe-launch-scribe-accept'), flags: ['primary', 'progressive'] },
{ action: 'reject', label: mw.msg('ve-scribe-launch-scribe-deny') }
]
}
).done(function (confirmed) {
if (confirmed) {
new mw.Api().get({
action: "query",
titles: [mw.config.get('wgTitle')],
}).then(function (ret) {
$.each(ret.query.pages, function () {
if (this.missing !== "") {
buildDialogView(articleSectionsPromise);
 
var scribeLoader = } else {buildScribeLoader();
surface.prepend(scribeLoader.$element)
console.log('page title', mw.config.get('wgTitle'))
 
buildDialogView(
surface['0'].append(tipSpan['0']);
$.get('https://tools.wmflabs.org/scribe/api/v1/sections?article=' + mw.config.get('wgTitle')));
addNewSectionTipOnclickListener($('#ve-scribe-new-section-tip'), surface['0'], mobileHeader);
}
 
mw.hook('ve.activationComplete').add(function () {
// we check if article exists in scribe before we launch
$.get('https://tools.wmflabs.org/scribe/api/v1/sections?article=' + mw.config.get('wgTitle')).done(
function (data) {
console.log('data', data)
if (!data) {
console.log('Article data does not exist on scribe')
} else {
OO.ui.confirm(mw.msg('ve-scribe-launch-prompt-msg'),
{
actions: [
{
action: 'accept',
label: mw.msg('ve-scribe-launch-scribe-accept'),
flags: ['primary', 'progressive']
},
{ action: 'reject', label: mw.msg('ve-scribe-launch-scribe-deny') }
]
}
).done(function (confirmed) {
if (confirmed) {
var surface = $('.ve-init-mw-desktopArticleTarget-originalContent');
mobileHeader = $('.oo-ui-toolbar-bar')['0'];
showNewSectionTip(surface, mobileHeader);
// hide the loader inititally
$('#scribe-pg-bar').hide()
}
});
// We set the width of our frame to the width of the device}
});
$('.oo-ui-window-frame').css('width', $(document).width());
$('.oo-ui-window-frame').css('height', $(document).height());
}, function (error) {
OO.ui.alert(mw.msg('ve-scribe-server-error')).done(function () {
});
});
}
});
});
}());