Bikarhêner:Balyozxane/Gadget-QQ.js

Ji Wîkîferhengê

Zanibe: Piştî weşandinê, ji bo dîtina guhartinan dibe ku hewce be "cache"ya geroka xwe paqij bikî.

  • Firefox / Safari: Pê li Shift û Reload bike an jî Ctrl-F5 an Ctrl-R bike (ji bo Mac: ⌘-R)
  • Google Chrome: Pê li Ctrl-Shift-R (ji bo Mac: ⌘-Shift-R) bike
  • Internet Explorer / Edge: Pê li Ctrl û Refresh bike, an jî Ctrl-F5 bike
  • Opera: Pê li Ctrl-F5 bike.
'use strict'; 
// Binêre: [[Gotûbêja MediaWiki:Gadget-QQ]]
//[[en:MediaWiki:Gadget-QQ.js]]<nowiki> 
/*jshint shadow:true, scripturl:true, undef:true, latedef:true, unused:true, loopfunc:true */
/*globals $, mw, jQuery */

function getInflections(word) {
    var inflections = "";

    $.ajax({
        url: mw.util.wikiScript('api'),
        data: {
            action: 'expandtemplates',
            format: 'json',
            text: `{{#invoke:ku-tewîn-nav|get_comma_separated_forms|${word}|mê û nêr|guherto=hemû}}`,
            prop: 'wikitext'
        },
        type: 'GET',
        success: function (result) {
            inflections = result.expandtemplates.wikitext;
        },
        error: function (xhr) {
            console.log('Error.\nRequest failed.');
        },
        async: false
    });

    return inflections;
}
function getStems(verb) {
    const words = verb.split(' ');

    if (words.length > 1) {
        const firstWord = words[0];
        const lastWord = words[words.length - 1];

        if (firstWord.endsWith("kirin")) {
            const presentStem = "k";
            const pastStem = "kir";
            return { presentStem, pastStem, prefix: lastWord, valahi: true };
        } else if (firstWord.endsWith("bûn")) {
            const presentStem = "b";
            const pastStem = "bû";
            return { presentStem, pastStem, prefix: lastWord, valahi: true };
        } else if (firstWord.endsWith("dan")) {
            const presentStem = "d";
            const pastStem = "da";
            return { presentStem, pastStem, prefix: lastWord, valahi: true };
        } else if (lastWord.endsWith("kirin")) {
            const presentStem = "k";
            const pastStem = lastWord.slice(0, -4);
            return { presentStem, pastStem, prefix: firstWord, valahi: true };
        } else if (lastWord.endsWith("bûn")) {
            const presentStem = "b";
            const pastStem = "bû";
            return { presentStem, pastStem, prefix: firstWord, valahi: true };
        } else if (lastWord.endsWith("dan")) {
            const presentStem = "d";
            const pastStem = "da";
            return { presentStem, pastStem, prefix: firstWord, valahi: true };
        } else {
            return null; // Not a valid verb pattern
        }
    } else {
        if (verb.endsWith("andin")) {
            const presentStem = verb.slice(0, -5) + "în";
            const pastStem = verb.slice(0, -5) + "and";
            return { presentStem, pastStem, prefix: '', valahi: false };
        } else if (verb.endsWith("în")) {
            const presentStem = verb.slice(0, -2);
            const pastStem = verb + "iya";
            return { presentStem, pastStem, prefix: '', valahi: false };
        } else if (verb.endsWith("tin")) {
            const presentStem = verb.slice(0, -3);
            const pastStem = verb.slice(0, -2);
            return { presentStem, pastStem, prefix: '', valahi: false };
        } else {
            return null; // Not a valid verb pattern
        }
    }
}


function getConj(word) {
    var inflections = "";
    const stems = getStems(word);
    var valahi;
    if (stems.valahi) {
        valahi = "erê";
    } else {
        valahi = "na";
    }

    
    $.ajax({
        url: mw.util.wikiScript('api'),
        data: {
            action: 'expandtemplates',
            format: 'json',
            text: `{{#invoke:ku-tewandin|get_comma_separated_forms|${word}|form=negerguhêz|niha=${stems.presentStem}|borî=${stems.pastStem}|pêşgir=${stems.prefix}|valahî=${valahi}}}`,
            prop: 'wikitext'
        },
        type: 'GET',
        success: function (result) {
            inflections = result.expandtemplates.wikitext;
        },
        error: function (xhr) {
            console.log('Error.\nRequest failed.');
        },
        async: false
    });

    return inflections;
}

function el(tag, child, attr, events) {
	var node = document.createElement(tag);
 
	if (child) {
		if (typeof child !== 'object')
			child = [child];
		for (var i = 0; i < child.length; ++i) {
			var ch = child[i];
			if ((ch === void(null)) || (ch === null))
				continue;
			else if (typeof ch !== 'object')
				ch = document.createTextNode(String(ch));
			node.appendChild(ch);
		}
	}
 
	if (attr) for (var key in attr) {
		node.setAttribute(key, String(attr[key]));
	}
 
	if (events) for (var key in events) {
		node.addEventListener(key, events[key], false);
	}
 
	return node;
}

var title = mw.config.get('wgTitle');
var backends = {
	gbooks: {
		name: "Google Kitêb ",
		enabled: true,
		
		addResults: function (data, callback) {
			function makeResult(item) {
				var m;

				var year;
				if (item.volumeInfo.publishedDate) {
					if (m = /^(\d+)/.exec(item.volumeInfo.publishedDate))
						year = m[1];
				}
				
				var page;
				if (item.volumeInfo.previewLink) {
					var uri = new mw.Uri(item.volumeInfo.previewLink);
					if (uri.query.pg) {
						if (m = /PA(\d+)/.exec(uri.query.pg))
							page = m[1];
					}
				}
				
				var idents = {};
				if (item.volumeInfo.industryIdentifiers) {
					for (var i = 0; i < item.volumeInfo.industryIdentifiers.length; ++i) {
						var ident = item.volumeInfo.industryIdentifiers[i];
						idents[ident.type] = ident.identifier;
					}
				}
				var isbn = idents.ISBN_13 || idents.ISBN_10;
				
				return {
					generateCitation: function () {
						var result = "#* {{jêder-kitêb|ku|";
						
						if (item.searchInfo && item.searchInfo.textSnippet) {
							result += "jêgirtin=" + item.searchInfo.textSnippet.replace(/<.*?>/g, '').replace(/\n/g, " ");
//							result += item.searchInfo.textSnippet.replace(/[ ]*/g, ' ').replace(/\n/g, " ").replace(/[ ]*?,[ ]*?/g, ", ");
//							result += item.searchInfo.textSnippet.replace(new RegExp("(" + title + "([^( |,|;|\?|\.|\!)]+)?)", "ig"), "'''$1'''");
						}
						
						if (year)
							result += "|sal=" + year;
						else
							result += "";
						
						if (item.volumeInfo.authors)
							result += "|nivîskar=" + item.volumeInfo.authors.join(", ");
						else
							result += "";
						if (item.volumeInfo.previewLink)
							result += "|url=" + item.volumeInfo.previewLink;
						else
							result += "";

						if (item.volumeInfo.title) {
							result += "|sernav=" + item.volumeInfo.title;
							if (item.volumeInfo.subtitle)
								result += ": " + item.volumeInfo.subtitle;
							result += "";
						}
						
						if (item.volumeInfo.publisher)
							result += "|weşanxane=" + item.volumeInfo.publisher;
						else
							result += "";
							
						if (isbn)
							result += "|ISBN=" + isbn + "";
						else
							result += "";
							
						if (page)
							result += "|rûpel=" + page + "}}";
						else
							result += "}}";

						result += "\n";
						
						

						return result;
					},
					
					populateNode: function (node, checkbox) {
						node.appendChild(el('label', [
							checkbox,
							year ? el('strong', year) : el('i', "sal nayê zanîn"),
							item.volumeInfo.authors && ", ",
							item.volumeInfo.authors && item.volumeInfo.authors.join(", "),
							", ",
							el('cite', [
								item.volumeInfo.title,
								item.volumeInfo.subtitle && el('small', [": ", item.volumeInfo.subtitle])
							]),
						]));

						node.appendChild(el('span', [
							item.volumeInfo.publisher && el('span', [
								", ",
								item.volumeInfo.publisher,
							], { 'class': 'publisher' }),
							isbn && el('span', [
								" (",
								el('a', ["ISBN " + isbn], {
									'href': mw.util.getUrl('Special:BookSources/' + isbn)
								}),
								")"
							], { 'class': 'isbn' }),
							page && el('span', [
								", page ",
								page,
							], { 'class': 'page' }),
							
							item.volumeInfo.previewLink && el('small', [
								" [",
								el('a', "veke", {
									'href': item.volumeInfo.previewLink
								}),
								"]"
							]),
							
							item.volumeInfo.infoLink && el('small', [
								" [",
								el('a', "agahî", {
									'href': item.volumeInfo.infoLink
								}),
								"]"
							]),
							
							el('small', [
								" [",
								el('a', "xav", {
									'href': 'javascript:void(0);'
								}, {
									'click': function () {
										alert(JSON.stringify(item, null, '  '));
									}
								}),
								"]"
							])
						]));
						
						if (item.searchInfo && item.searchInfo.textSnippet) {
							var uiQuote = el('blockquote');
							uiQuote.innerHTML = item.searchInfo.textSnippet.replace(/<br>/g, " ");
							node.appendChild(uiQuote);
						}
					}
				};
			}

			if (!data.items) {
				this.uiStatus.textContent = "encam nîne";
				this.uiStatus.style.display = '';
				return;
			}
			
			for (var i = 0; i < data.items.length; ++i) {
				if (data.items[i].searchInfo && data.items[i].searchInfo.textSnippet) {
					if (!/<b>/.test(data.items[i].searchInfo.textSnippet))
						continue; // bogus result
				}
				callback(makeResult(data.items[i]));
			}
			
			this.uiMore.style.display = '';
			this.uiStatus.textContent = "";
			this.data.startIndex += data.items.length;
		},
		
		populateTab: function (tab) {
			var that = this;

			this.uiResults = el('ul');
			this.uiStatus = el('div');
			this.uiMore = el('a', ["zêdetir çavkanî"], {
				'href': 'javascript:void(0);'
			}, {
				'click': function () {
					that.uiStatus.textContent = "ji kerema xwe bisekine...";
					this.style.display = 'none';
					jQuery.ajax({
						url: location.protocol + '//www.googleapis.com/books/v1/volumes',
						dataType: 'jsonp',
						data: that.data
					}).done(function (data) {
						that.addResults(data, that.callback);
					});
				}
			});
			
			tab.appendChild(this.uiResults);
			tab.appendChild(this.uiStatus);
			tab.appendChild(this.uiMore);
		},

		search: function (terms, options, callback) {
			var that = this;
			while (this.uiResults.firstChild)
				this.uiResults.removeChild(this.uiResults.firstChild);

			this.data = {
				q: terms,
				startIndex: 0,
				maxResults: 20
				// orderBy: 'newest' // reverse chronological order; no option for plain chronological order, unforutnately
			};
			this.callback = callback;
			this.uiMore.style.display = 'none';
			this.uiStatus.textContent = "ji kerema xwe bisekine...";
			jQuery.ajax({
				url: location.protocol + '//www.googleapis.com/books/v1/volumes',
				dataType: 'jsonp',
				data: this.data
			}).done(function (data) {
				that.addResults(data, callback);
			});
		}
	},
    gsearch: {
        name: "Google Search",
        enabled: true,
        
        populateTab: function (tab) {
            var that = this;
            
            this.uiResults = el('ul');
            this.uiStatus = el('div');
            
            tab.appendChild(this.uiResults);
            tab.appendChild(this.uiStatus);
        },
		search: function (terms, options, callback) {
		    var that = this;
		    while (this.uiResults.firstChild)
		        this.uiResults.removeChild(this.uiResults.firstChild);
		
		    this.uiStatus.textContent = "Lêgerana Googlê tê vekirin...";
		
		    // Updated regular expression to find items in double quotes
		    var items = terms.match(/"([^"]+)"/g) || [];
		
		    if (items.length === 0) {
		        console.error("No items found.");
		        return;
		    }
		
		    var chunkSize = 30;
		    for (var i = 0; i < items.length; i += chunkSize) {
		        var chunk = items.slice(i, i + chunkSize);
		
		        var searchTerms = chunk.join(" OR ");
		        var searchUrl = 'https://www.google.com/search?q=' + encodeURIComponent(searchTerms + " -wiktionary");
		        var newTab = window.open(searchUrl, '_blank');
		        newTab.focus();
		    }
		}

    }
};
function getForms(cure) {
    var title = mw.config.get('wgTitle');
    var inflections;
    var searchTerms;
    if (cure === "noun") {
        inflections = getInflections(title); // Call getInflections function for Noun
		searchTerms = inflections.split(',').map(term => '"' + term.trim() + '"').join(' OR ');
    } else if (cure === "verb") {
        inflections = getConj(title); // Call getConj function for Verb
		searchTerms = inflections.split(',').map(term => '"' + term.trim() + '"').join(' OR ');
    } else if (cure === "adj") {
        inflections = [
            title,
            title + "tir",
            title + "tirîn",
            "herî " + title,
            "tewrî " + title
        ];
        searchTerms = inflections.map(term => '"' + term.trim() + '"').join(' OR ');
    }

    
    return searchTerms; // Return the generated search terms
}

var uiQuery, uiTitle, uiBackends, uiTabs, uiTabLabels, uiCitationsTab, uiCitations, uiCurTab, uiCurTabLabel, uiForm, nounCheckbox, nounLabel, verbLabel, verbCheckbox, adjCheckbox, adjLabel;

var isNounChecked = false; // Initialize to false
var isAdjChecked = false; // Initialize to false
var isVerbChecked = false; // Initialize to false
var searchTerms;
var uiMain = el('div', [
	uiTitle = el('div', [
		el('strong', "Quiet Quentin"),
		el('a', "veşêre", {
			'href': 'javascript:void(0);',
			'class': 'hide-link'
		}, {
			'click': function () {
				uiMain.style.display = 'none';
			}
		})
	], { 'class': 'title' }),
	uiForm = el('form', [
		el('fieldset', [
			el('legend', "Li çavkaniyan bigere"),
			
			nounCheckbox = el('input', null, { 'type': 'radio', 'name': 'partOfSpeech' }, {
			    'change': function () {
			        if (this.checked) {
			            isNounChecked = true; // Update the checked state when radio button changes
			            isVerbChecked = false; // Uncheck verbCheckbox
			            isAdjChecked = false; // Uncheck verbCheckbox
			            searchTerms = getForms("noun"); // Call getForms if radio button is checked
			            uiQuery.value = searchTerms;
			        }
			    }
			}),
			// Create the label element
			nounLabel = el('label', [
			    nounCheckbox,
			    "Navdêr "
			]),
			
			adjCheckbox = el('input', null, { 'type': 'radio', 'name': 'partOfSpeech' }, {
			    'change': function () {
			        if (this.checked) {
			            isNounChecked = false; // Uncheck nounCheckbox
			            isAdjChecked = true; // Update the checked state when radio button changes
			            isVerbChecked = false; // Uncheck verbCheckbox
			            searchTerms = getForms("adj"); // Call getForms if radio button is checked
			            uiQuery.value = searchTerms;
			        }
			    }
			}),
			// Create the label element
			adjLabel = el('label', [
			    adjCheckbox,
			    "Rengdêr "
			]),
			
			
			verbCheckbox = el('input', null, { 'type': 'radio', 'name': 'partOfSpeech' }, {
			    'change': function () {
			        if (this.checked) {
			            isNounChecked = false; // Uncheck nounCheckbox
			            isAdjChecked = false; // Uncheck verbCheckbox
			            isVerbChecked = true; // Update the checked state when radio button changes
			            searchTerms = getForms("verb"); // Call getForms if radio button is checked
			            uiQuery.value = searchTerms;
			        }
			    }
			}),
			// Create the label element
			verbLabel = el('label', [
			    verbCheckbox,
			    "Lêker"
			]), 
			el('br'),
			uiQuery = el('input', null, {
				'type': 'text',
				'placeholder': "peyv",
				'class': 'search-terms',
				'value': (function () {
					

					var m;
					
					if ([0, 1, 114].indexOf(mw.config.get('wgNamespaceNumber')) !== -1) // main, Talk, Citations
						return '"' + mw.config.get('wgTitle') + '"';

					if (mw.config.get('wgNamespaceNumber') === 100)
						if (m = /[^/]+\/(.*)/.exec(mw.config.get('wgTitle')))
							return m[1];
					if (mw.config.get('wgCanonicalSpecialPageName') === 'search')
						return '"' + document.getElementById('searchText').value + '"';
					return '';
				})()
			}),
			el('input', null, {
				'type': 'submit',
				'value': "Lê bigere"
			}), el('br'),
		

			uiBackends = el('div', [
				el('strong', "Çavkanî"), ": "
			])
		])
	], {
		'action': 'javascript:void(0);'
	}, {
		'submit': function () {
			var hasAny = false;
			for (var key in backends) {
				hasAny = (function (backend) {
					if (!backend.enabled) {
						backend.uiTabLabel.style.display = 'none';
						return hasAny;
					} else {
						backend.uiTabLabel.style.display = '';
						if (!hasAny) {
							uiCurTab.style.display = 'none';
							uiCurTabLabel.classList.remove('active');
							uiCurTab = backend.uiTab;
							uiCurTabLabel = backend.uiTabLabel;
							uiCurTab.style.display = '';
							uiCurTabLabel.classList.add('active');
						}
					}
					
					backend.results = [];

					if (backend.enabled) {
						backend.search(uiQuery.value, null, function (result) {
							backend.results.push(result);

							var node = el('li');
							var checkbox = el('small', [
								"[",
								el('a', "jê bigere", {
									'href': 'javascript:void(0)',
									'class': 'take-link'
								}, {
									click: function () {
										if (result.taken) {
											result.taken = false;
											node.classList.remove('taken');
										} else {
											result.taken = true;
											node.classList.add('taken');
										}
									}
								}),
								" | ",
								el('a', "veşêre", { 'href': 'javascript:void(0)' }, {
									click: function () {
										node.classList.toggle('struck');
									}
								}),
								"] "
							]);
							result.populateNode(node, checkbox);
							backend.uiResults.appendChild(node);
						});
						
						return true;
					}
				})(backends[key]);
			}

			if (hasAny) {
				uiTabs.style.display = '';
				uiTabLabels.style.display = '';
			} else {
				alert("No backends chosen");
				uiTabs.style.display = 'none';
				uiTabLabels.style.display = 'none';
			}
		}
	}),
	uiTabLabels = el('ul', null, {
		'class': 'tab-labels',
		'style': 'display: none;'
	}),
	uiTabs = el('div', null, {
		'class': 'tabs',
		'style': 'display: none;'
	})
], {
	'class': 'kephir-qq',
	'style': 'display: none; position: fixed;'
});
jQuery(uiMain).draggable({
	handle: uiTitle
}).resizable({
	alsoResize: uiTabs
});
document.body.appendChild(uiMain);

var uiCitationsHash;

function regenerateCitations() {
	var result = [];

	for (var key in backends) {
		var results = backends[key].results;
		for (var j = 0; j < results.length; ++j) {
			if (results[j].taken)
				result.push(results[j].generateCitation());
		}
	}
	result = result.join('');

	if (uiCitationsHash.checked) {
		result = result.replace(/^/mg, '#').replace(/#$/, '');
	}
	
	uiCitations.value = result;
}

uiTabs.appendChild(uiCurTab = uiCitationsTab = el('div', [
	uiCitations = el('textarea', null, {
		'rows': 20,
		'cols': 80
	}), el('br'),
	el('label', [
		uiCitationsHash = el('input', null, { 'type': 'checkbox' }, {
			'change': function () {
				regenerateCitations();
			}
		}),
		"Li pêşiya her rêzê # zêde bike"
	])
], { 'style': 'display: none' }));

uiTabLabels.appendChild(uiCurTabLabel = el('li', [
	el('a', "Çavkaniyên ku hatine girtin", {
		'href': 'javascript:void(0);'
	}, {
		'click': function () {
			regenerateCitations();
			
			uiCurTab.style.display = 'none';
			uiCurTabLabel.classList.remove('active');
			uiCurTab = uiCitationsTab;
			uiCurTabLabel = this;
			uiCurTab.style.display = '';
			uiCurTabLabel.classList.add('active');
		}	
	})
], { 'class': 'citations-tab' }));

for (var key in backends) {
	(function (backend) {
		uiBackends.appendChild(el('label', [
			el('input', null, {
				'type': 'checkbox',
				'checked': backend.enabled ? 'checked' : ''
			}, {
				'change': function () {
					backend.enabled = this.checked;
				}
			}),
			backend.name
		]));
		
		backend.uiTab = el('div', [], {
			'style': 'display: none;'
		});
		backend.uiTabLabel = el('li', [
			el('a', backend.name, { 'href': 'javascript:void(0);' }, {
				'click': function () {
					uiCurTab.style.display = 'none';
					uiCurTabLabel.classList.remove('active');
					uiCurTab = backend.uiTab;
					uiCurTabLabel = backend.uiTabLabel;
					uiCurTab.style.display = '';
					uiCurTabLabel.classList.add('active');
				}	
			})
		]);
		backend.populateTab(backend.uiTab);
		uiTabs.appendChild(backend.uiTab);
		uiTabLabels.appendChild(backend.uiTabLabel);
	})(backends[key]);
}

var link = mw.util.addPortletLink(mw.config.get('skin') === 'vector' ? 'p-views' : 'p-cactions',
	'javascript:void(0);', 'QQ', 'p-kephir-qq', "Jêgirtinan lê bigere", '9'
);
link.addEventListener('click', function () {
	uiMain.style.display = '';
	uiQuery.focus();
}, false);
//</nowiki>