MediaWiki:Common.js: Difference between revisions
From Sanatan Hindu Dharma
No edit summary |
No edit summary |
||
| Line 1,119: | Line 1,119: | ||
// == Combined: Floating Create UI + Parent prompt + Category inject + Change Parent (ES5 safe) == | |||
(function () { | |||
// Ensure mw loader availability | |||
mw.loader.using(['mediawiki.util', 'mediawiki.api']).then(function () { | |||
// --------- Utility: Query param reader (ES5) ---------- | |||
function getQueryParam(name) { | |||
var qs = window.location.search.substring(1); | |||
var pairs = qs.split('&'); | |||
for (var i = 0; i < pairs.length; i++) { | |||
var parts = pairs[i].split('='); | |||
if (decodeURIComponent(parts[0]) === name) { | |||
return parts[1] ? decodeURIComponent(parts[1]) : ''; | |||
} | |||
} | } | ||
return null; | |||
} | } | ||
// --------- Utility: Normalize title string (remove domains, leading slashes, avoid "hi/" inside title) ---------- | |||
function normalizeTitleStr(s) { | |||
s = String(s || ''); | |||
s = s.replace(/^\s+|\s+$/g, ''); | |||
if (!s) return s; | |||
// strip protocol+domain if present | |||
s = s.replace(/^https?:\/\/[^\/]+/i, ''); | |||
// remove leading slashes | |||
if ( | s = s.replace(/^\/+/, ''); | ||
// remove namespace-like hi/ or hi: from the start so titles remain clean | |||
s = s.replace(/^hi\//i, ''); | |||
s = s.replace(/^hi:/i, ''); | |||
s = s.replace(/^\/+/, ''); | |||
return s; | |||
} | } | ||
// --------- Utility: detect language prefix from current pathname ---------- | |||
function detectLanguagePrefix() { | |||
var path = window.location.pathname || ''; | |||
var parts = path.split('/').filter(function (v) { return v && v.length; }); | |||
if (parts.length && parts[0] === 'hi') return 'hi'; | |||
return ''; | |||
} | } | ||
// --------- Inject Category into textarea (for non-VE fallback) ---------- | |||
function injectCategory(category) { | |||
if (!category) return; | |||
var textarea = $('#wpTextbox1'); | |||
if (textarea.length && textarea.val().indexOf('[[' + 'Category:' + category + ']]') === -1) { | |||
textarea.val('[[' + 'Category:' + category + ']]\n\n' + textarea.val()); | |||
var | |||
} | } | ||
} | } | ||
// --------- Floating Create Button (re-usable UI) ---------- | |||
(function createFloatingButton() { | |||
// | |||
try { | try { | ||
if (typeof mw === 'undefined' || !mw.config) return; | if (typeof mw === 'undefined' || !mw.config) return; | ||
| Line 1,381: | Line 1,178: | ||
var groups = mw.config.get('wgUserGroups') || []; | var groups = mw.config.get('wgUserGroups') || []; | ||
var isWriter = groups.indexOf('writer') !== -1; | var isWriter = (groups.indexOf && groups.indexOf('writer') !== -1) || false; | ||
var isLead = groups.indexOf('lead') !== -1; | var isLead = (groups.indexOf && groups.indexOf('lead') !== -1) || false; | ||
var isEditor = groups.indexOf('editor') !== -1; | var isEditor = (groups.indexOf && groups.indexOf('editor') !== -1) || false; | ||
var isAdmin = groups.indexOf('sysop') !== -1; | var isAdmin = (groups.indexOf && groups.indexOf('sysop') !== -1) || false; | ||
if (!(isWriter || isLead || isEditor || isAdmin)) return; | if (!(isWriter || isLead || isEditor || isAdmin)) return; | ||
| Line 1,408: | Line 1,205: | ||
btn.style.boxShadow = '0 4px 10px rgba(0,0,0,0.3)'; | btn.style.boxShadow = '0 4px 10px rgba(0,0,0,0.3)'; | ||
btn.addEventListener('mouseover', function () { | btn.addEventListener('mouseover', function () { btn.style.background = '#005fa3'; }); | ||
btn.addEventListener('mouseout', function () { btn.style.background = '#0078D7'; }); | |||
btn.addEventListener('mouseout', function () { | |||
document.body.appendChild(btn); | document.body.appendChild(btn); | ||
// Popup | // Popup UI | ||
var popup = document.createElement('div'); | var popup = document.createElement('div'); | ||
popup.id = 'createPopupBox'; | popup.id = 'createPopupBox'; | ||
| Line 1,427: | Line 1,220: | ||
popup.style.borderRadius = '12px'; | popup.style.borderRadius = '12px'; | ||
popup.style.padding = '15px'; | popup.style.padding = '15px'; | ||
popup.style.width = ' | popup.style.width = '320px'; | ||
popup.style.display = 'none'; | popup.style.display = 'none'; | ||
popup.style.boxShadow = '0 6px 14px rgba(0,0,0,0.25)'; | popup.style.boxShadow = '0 6px 14px rgba(0,0,0,0.25)'; | ||
| Line 1,433: | Line 1,226: | ||
var html = ''; | var html = ''; | ||
html += '<label style="font-weight:bold;">Select Language</label | html += '<label style="font-weight:bold;display:block;margin-bottom:6px;">Select Language</label>'; | ||
html += '<select id="pageLang" style="width:100%;padding:6px;margin: | html += '<select id="pageLang" style="width:100%;padding:6px;margin-bottom:8px;border:1px solid #ccc;border-radius:5px;">'; | ||
html += '<option value="en">English</option>'; | html += '<option value="en">English</option>'; | ||
html += '<option value="hi">Hindi</option>'; | html += '<option value="hi">Hindi</option>'; | ||
html += '</select>'; | html += '</select>'; | ||
html += '<label style="font-weight:bold;">Create new page</label | html += '<label style="font-weight:bold;display:block;">Create new page</label>'; | ||
html += '<input type="text" id="newPageName" placeholder="Enter page name" style="width:100%;padding:6px;margin-top:4px;border:1px solid #ccc;border-radius:5px;">'; | html += '<input type="text" id="newPageName" placeholder="Enter page name" style="width:100%;padding:6px;margin-top:4px;border:1px solid #ccc;border-radius:5px;">'; | ||
html += '<button id="createPageBtn" style="margin-top:8px;width:100%;background:#0078D7;color:white;border:none;padding:8px;border-radius:6px;cursor:pointer;">Create Page</button>'; | |||
if (isEditor || isAdmin) { | if (isEditor || isAdmin) { | ||
html += '<hr style="margin:10px 0;">'; | html += '<hr style="margin:10px 0;border:none;border-top:1px solid #eee;">'; | ||
html += '<label style="font-weight:bold;">Create new category</label | html += '<label style="font-weight:bold;display:block;">Create new category (always English)</label>'; | ||
html += '<input type="text" id="newCategoryName" placeholder="Enter category name" style="width:100%;padding:6px;margin-top:4px;border:1px solid #ccc;border-radius:5px;">'; | html += '<input type="text" id="newCategoryName" placeholder="Enter category name" style="width:100%;padding:6px;margin-top:4px;border:1px solid #ccc;border-radius:5px;">'; | ||
html += '<button id="createCategoryBtn" style="margin-top:8px;width:100%;background:#28a745;color:white;border:none;padding:8px;border-radius:6px;cursor:pointer;">Create Category</button>'; | |||
html += '<button id="createCategoryBtn" style="margin-top:8px;width:100%;background:#28a745;color:white;border:none;padding: | |||
} | } | ||
| Line 1,458: | Line 1,248: | ||
// Toggle popup | // Toggle popup | ||
btn.addEventListener('click', function () { | btn.addEventListener('click', function () { | ||
if (popup.style.display === 'none') { | if (popup.style.display === 'none' || popup.style.display === '') { | ||
popup.style.display = 'block'; | popup.style.display = 'block'; | ||
} else { | } else { | ||
| Line 1,465: | Line 1,255: | ||
}); | }); | ||
// | // Click handlers (delegated) | ||
popup.addEventListener('click', function (ev) { | popup.addEventListener('click', function (ev) { | ||
var target = ev.target; | var target = ev.target || ev.srcElement; | ||
if (!target) return; | |||
if (target.id === 'createPageBtn') { | if (target.id === 'createPageBtn') { | ||
var | var lang = document.getElementById('pageLang').value || 'en'; | ||
var name = document.getElementById('newPageName').value.replace(/^\s+|\s+$/g, ''); | var name = (document.getElementById('newPageName').value || '').replace(/^\s+|\s+$/g, ''); | ||
if (!name) { | if (!name) { | ||
alert('Please enter a page name'); | alert('Please enter a page name.'); | ||
return; | return; | ||
} | } | ||
var title = name.replace(/\s+/g, '_'); | var title = name.replace(/\s+/g, '_'); | ||
if ( | if (lang === 'hi') { | ||
// Open VE under /hi/ prefix | |||
var base = window.location.protocol + '//' + window.location.host; | |||
var finalUrl = base + '/hi/' + encodeURIComponent(title) + '?action=edit&veaction=edit'; | |||
// add autocategory param? Not set here; UI may add when creating category | |||
window.location.href = finalUrl; | |||
} else { | } else { | ||
// English: use mw.util.getUrl | |||
var href = mw.util.getUrl(title, { action: 'edit', veaction: 'edit' }); | |||
window.location.href = href; | |||
} | } | ||
} | } | ||
if (target.id === 'createCategoryBtn') { | if (target.id === 'createCategoryBtn') { | ||
var cat = document.getElementById('newCategoryName').value.replace(/^\s+|\s+$/g, ''); | var cat = (document.getElementById('newCategoryName').value || '').replace(/^\s+|\s+$/g, ''); | ||
if (!cat) { | if (!cat) { | ||
alert('Please enter a category name'); | alert('Please enter a category name.'); | ||
return; | return; | ||
} | } | ||
// Category creation always English | |||
var cTitle = 'Category:' + cat.replace(/\s+/g, '-'); | var cTitle = 'Category:' + cat.replace(/\s+/g, '-'); | ||
var curl = | var curl = mw.util.getUrl(cTitle, { action: 'edit', veaction: 'edit' }); | ||
window.location.href = curl; | window.location.href = curl; | ||
} | } | ||
}); | }); | ||
} catch (err) { | |||
if (typeof console !== 'undefined' && console.error) console.error('FloatingCreate init error', err); | |||
} | |||
}()); | |||
// --------- Parent / Category workflow ---------- | |||
var api = new mw.Api(); | |||
var username = mw.config.get('wgUserName'); | |||
if (!username) return; | |||
var wgNamespace = mw.config.get('wgNamespaceNumber'); | |||
var wgTitle = mw.config.get('wgTitle'); | |||
var wgPageName = mw.config.get('wgPageName'); | |||
var wgAction = mw.config.get('wgAction'); | |||
var wgCurRevisionId = mw.config.get('wgCurRevisionId'); | |||
var autoCat = getQueryParam('autocategory'); | |||
var skipParent = getQueryParam('skipparent'); | |||
// Category prompt when creating a new Category page | |||
if (wgNamespace === 14) { | |||
var storageKey = 'category_prompt_done_' + wgTitle; | |||
function askAndCreateCategory() { | |||
if (sessionStorage.getItem(storageKey)) return; | |||
sessionStorage.setItem(storageKey, 'done'); | |||
var ask = confirm('✅ You just created the new category "' + wgTitle + '".\n\nDo you want to create a normal page with the same name? It will automatically belong to this category.'); | |||
if (ask) { | |||
var editUrl = mw.util.getUrl(wgTitle, { action: 'edit', veaction: 'edit' }); | |||
// pass autocategory and skipparent param | |||
editUrl += '&autocategory=' + encodeURIComponent(wgTitle) + '&skipparent=1'; | |||
window.location.href = editUrl; | |||
} | |||
} | } | ||
mw.hook('postEdit').add(askAndCreateCategory); | |||
$(window).on('popstate', function () { | |||
if (wgAction !== 'view') return; | |||
if (sessionStorage.getItem(storageKey)) return; | |||
api.get({ | |||
action: 'query', | |||
titles: 'Category:' + wgTitle, | |||
prop: 'info', | |||
format: 'json' | |||
}).done(function (data) { | |||
var pages = data && data.query && data.query.pages; | |||
if (!pages) return; | |||
var pageData; | |||
for (var p in pages) { if (pages.hasOwnProperty(p)) { pageData = pages[p]; break; } } | |||
if (pageData && pageData.missing === undefined) { | |||
askAndCreateCategory(); | |||
} | |||
}); | |||
}); | |||
} | |||
// Inject category into textarea / VE | |||
if (autoCat) { | |||
$(document).ready(function () { injectCategory(autoCat); }); | |||
mw.hook('ve.activationComplete').add(function () { injectCategory(autoCat); }); | |||
} | } | ||
// Reminder banner in edit mode | |||
mw.hook('wikipage.content').add(function ($content) { | |||
} | if (wgAction === 'edit' || wgAction === 'submit') { | ||
}) | var banner = $('<div>').css({ | ||
background: '#fff8c4', | |||
border: '1px solid #e0c14b', | |||
padding: '10px', | |||
marginBottom: '10px', | |||
borderRadius: '6px', | |||
textAlign: 'center', | |||
fontWeight: '600' | |||
}).text('🪶 Tip: Remember to set a parent page before saving.'); | |||
$content.prepend(banner); | |||
// If this is an existing page (has revision), add "Change Parent" button | |||
if (wgCurRevisionId && wgCurRevisionId !== 0) { | |||
var changeBtn = $('<button>').text('Change Parent').css({ | |||
marginLeft: '10px', | |||
background: '#343a40', | |||
color: '#fff', | |||
border: 'none', | |||
padding: '6px 10px', | |||
borderRadius: '4px', | |||
cursor: 'pointer' | |||
}); | |||
changeBtn.on('click', function () { | |||
// open parent selector for existing page, and then attempt to move | |||
askForParent(wgTitle, function (newTitle, finalUrl) { | |||
// If user kept same title, do nothing | |||
if (!newTitle || newTitle === wgTitle) return; | |||
var confirmMove = confirm('Move page "' + wgTitle + '" to "' + newTitle + '"? This will perform a page move (you must have move rights).'); | |||
if (!confirmMove) return; | |||
// Move via API | |||
var token = mw.user.tokens.get('csrfToken'); | |||
api.postWithToken('csrf', { | |||
action: 'move', | |||
from: wgTitle, | |||
to: newTitle, | |||
reason: 'Change parent via Change Parent button', | |||
movetalk: true, | |||
noredirect: false | |||
}).done(function (data) { | |||
if (data && data.move && data.move.newrevid) { | |||
// Success: go to new page view | |||
var newUrl = detectLanguagePrefix() ? (window.location.protocol + '//' + window.location.host + '/' + detectLanguagePrefix() + '/' + encodeURIComponent(newTitle)) : mw.util.getUrl(newTitle); | |||
window.location.href = newUrl; | |||
} else { | |||
alert('Move did not complete. Response: ' + JSON.stringify(data)); | |||
} | |||
}).fail(function (jqXHR) { | |||
var msg = 'Move failed. You may not have permission or there was an error.'; | |||
try { msg += '\n' + jqXHR.responseText; } catch (e) {} | |||
alert(msg); | |||
}); | |||
}); | |||
}); | |||
// place the change button next to banner | |||
$content.find('div').first().append(changeBtn); | |||
} | |||
} | |||
}); | |||
// Parent selection modal | |||
function askForParent(title, callback) { | |||
if (window.parentPromptShown) return; | |||
window.parentPromptShown = true; | |||
var overlay = $('<div>').css({ | |||
position: 'fixed', | |||
top: 0, | |||
left: 0, | |||
width: '100%', | |||
height: '100%', | |||
background: 'rgba(0,0,0,0.5)', | |||
display: 'flex', | |||
justifyContent: 'center', | |||
alignItems: 'center', | |||
zIndex: 999999 | |||
}); | |||
var box = $('<div>').css({ | |||
background: '#fff', | |||
padding: '20px', | |||
borderRadius: '10px', | |||
width: '420px', | |||
textAlign: 'center', | |||
boxShadow: '0 4px 10px rgba(0,0,0,0.3)' | |||
}); | |||
box.append('<h3 style="margin-top:0">Select Parent Page</h3>'); | |||
var input = $('<input type="text" placeholder="Type to search existing pages...">').css({ | |||
width: '100%', | |||
padding: '8px', | |||
border: '1px solid #ccc', | |||
borderRadius: '5px' | |||
}); | |||
var suggestionBox = $('<ul>').css({ | |||
listStyle: 'none', | |||
margin: '10px 0 0', | |||
padding: 0, | |||
maxHeight: '200px', | |||
overflowY: 'auto', | |||
border: '1px solid #ddd', | |||
borderRadius: '5px', | |||
display: 'none', | |||
textAlign: 'left' | |||
}); | |||
var confirmBtn = $('<button>Confirm</button>').css({ | |||
marginTop: '10px', | |||
background: '#007bff', | |||
color: '#fff', | |||
border: 'none', | |||
padding: '8px 14px', | |||
borderRadius: '5px', | |||
cursor: 'pointer' | |||
}); | |||
var skipBtn = $('<button>No Parent</button>').css({ | |||
marginLeft: '8px', | |||
marginTop: '10px', | |||
background: '#6c757d', | |||
color: '#fff', | |||
border: 'none', | |||
padding: '8px 14px', | |||
borderRadius: '5px', | |||
cursor: 'pointer' | |||
}); | |||
box.append(input, suggestionBox, $('<div>').append(confirmBtn, skipBtn)); | |||
overlay.append(box); | |||
$('body').append(overlay); | |||
// Autocomplete search (opensearch) | |||
input.on('input', function () { | |||
var query = (input.val() || '').replace(/^\s+|\s+$/g, ''); | |||
suggestionBox.empty(); | |||
if (!query || query.length < 2) { suggestionBox.hide(); return; } | |||
api.get({ | |||
action: 'opensearch', | |||
search: query, | |||
limit: 8, | |||
namespace: 0 | |||
}).done(function (data) { | |||
var results = (data && data[1]) || []; | |||
suggestionBox.empty(); | |||
if (results && results.length) { | |||
suggestionBox.show(); | |||
for (var i = 0; i < results.length; i++) { | |||
(function (page) { | |||
$('<li>').text(page).css({ padding: '6px 10px', cursor: 'pointer' }) | |||
.hover(function () { $(this).css('background', '#f0f0f0'); }, function () { $(this).css('background', ''); }) | |||
.click(function () { input.val(page); suggestionBox.hide(); }) | |||
.appendTo(suggestionBox); | |||
}(results[i])); | |||
} | |||
} else { suggestionBox.hide(); } | |||
}); | |||
}); | |||
confirmBtn.on('click', function () { | |||
var parentRaw = (input.val() || '').replace(/^\s+|\s+$/g, ''); | |||
if (!parentRaw) { alert('Please select or type a parent page name, or click "No Parent".'); return; } | |||
// Normalize both parent and child title | |||
var parent = normalizeTitleStr(parentRaw); | |||
var child = normalizeTitleStr(title); | |||
if (!parent) { | |||
overlay.remove(); | |||
if (callback) callback(child, buildFinalEditUrl(child)); | |||
return; | |||
} | |||
var newTitle = parent + '/' + child; | |||
// Build final edit URL keeping language prefix if present in initial editor URL | |||
var langPrefix = detectLanguagePrefix(); | |||
var finalUrl; | |||
if (langPrefix) { | |||
finalUrl = window.location.protocol + '//' + window.location.host + '/' + langPrefix + '/' + encodeURIComponent(newTitle) + '?action=edit&veaction=edit'; | |||
if (autoCat) finalUrl += '&autocategory=' + encodeURIComponent(autoCat); | |||
} else { | |||
finalUrl = mw.util.getUrl(newTitle, { action: 'edit', veaction: 'edit' }); | |||
if (autoCat) finalUrl += '&autocategory=' + encodeURIComponent(autoCat); | |||
} | |||
overlay.remove(); | |||
if (callback) callback(newTitle, finalUrl); | |||
}); | |||
skipBtn.on('click', function () { | |||
overlay.remove(); | |||
// No parent, use original title | |||
var child = normalizeTitleStr(title); | |||
var final = buildFinalEditUrl(child); | |||
if (callback) callback(child, final); | |||
}); | |||
overlay.on('click', function (e) { if (e.target === overlay[0]) alert('Please choose a parent or click "No Parent".'); }); | |||
// Helper to build final edit URL for a title | |||
function buildFinalEditUrl(cleanTitle) { | |||
var langPrefix2 = detectLanguagePrefix(); | |||
var final2; | |||
if (langPrefix2) { | |||
final2 = window.location.protocol + '//' + window.location.host + '/' + langPrefix2 + '/' + encodeURIComponent(cleanTitle) + '?action=edit&veaction=edit'; | |||
if (autoCat) final2 += '&autocategory=' + encodeURIComponent(autoCat); | |||
} else { | |||
final2 = mw.util.getUrl(cleanTitle, { action: 'edit', veaction: 'edit' }); | |||
if (autoCat) final2 += '&autocategory=' + encodeURIComponent(autoCat); | |||
} | |||
return final2; | |||
} | |||
} | |||
// Handle new-page flow: prompt only when creating a new page (wgNamespace 0, edit action, revision 0) | |||
function handleNewPage() { | |||
if (wgNamespace !== 0 || wgAction !== 'edit' || wgCurRevisionId !== 0) return; | |||
if (skipParent && autoCat) { | |||
mw.hook('ve.activationComplete').add(function () { injectCategory(autoCat); }); | |||
$(document).ready(function () { injectCategory(autoCat); }); | |||
} else { | |||
askForParent(wgPageName, function (newTitle, finalUrl) { | |||
// Redirect to finalUrl (which preserves /hi/ if needed) | |||
if (finalUrl && window.location.href !== finalUrl) { | |||
window.location.href = finalUrl; | |||
} | |||
}); | |||
} | |||
} | |||
if (wgAction === 'edit') handleNewPage(); | |||
mw.hook('ve.activationComplete').add(handleNewPage); | |||
console.log('Complete Combined Parent + Category + Floating UI workflow loaded.'); | |||
}); // end loader | |||
}()); | |||
Revision as of 09:06, 18 November 2025
mw.loader.using('mediawiki.util').done(function () {
console.log("Common.js loaded safely");
});
/* Any JavaScript here will be loaded for all users on every page load. */
/*
document.addEventListener("DOMContentLoaded", function() {
const btn = document.querySelector(".toggle-btn");
const content = document.querySelector(".toggle-content");
if (btn && content) {
btn.addEventListener("click", function() {
content.style.display = (content.style.display === "block") ? "none" : "block";
});
}
});
// Auto-add parent category when editing/creating a subpage
( function () {
if ( mw.config.get('wgAction') !== 'edit' ) return;
// wgTitle contains title without namespace, e.g. "Ancient-education/Subpage"
var title = mw.config.get('wgTitle') || '';
if ( title.indexOf('/') === -1 ) return; // not a subpage
var parent = title.split('/')[0]; // "Ancient-education"
// jQuery available
$( function () {
var textarea = $('#wpTextbox1');
if ( !textarea.length ) return;
// Only append if not present
var current = textarea.val() || '';
var catTag = '\n[[Category:' + parent + ']]';
if ( current.indexOf(catTag.trim()) === -1 ) {
// Insert the category at the end of the text area (preserve existing text)
textarea.val(current + catTag);
}
} );
}() );
$(document).ready(function () {
// Skip special pages
if (mw.config.get('wgNamespaceNumber') < 0) return;
var $content = $('#mw-content-text');
// Fetch all page titles from the API (main namespace only)
$.get(mw.util.wikiScript('api'), {
action: 'query',
list: 'allpages',
aplimit: 'max',
format: 'json'
}).done(function (data) {
var titles = data.query.allpages.map(function (p) { return p.title; });
var html = $content.html();
titles.forEach(function (title) {
// Safe regex for whole words
var safeTitle = title.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var regex = new RegExp('\\b(' + safeTitle + ')\\b', 'g');
html = html.replace(regex, '<a href="/wiki/' + encodeURIComponent(title.replace(/ /g, '_')) + '">$1</a>');
});
$content.html(html);
});
});
$(document).ready(function() {
if (mw.config.get('wgNamespaceNumber') >= 0) { // Only show on normal pages
var pageName = mw.config.get('wgPageName');
var uploadUrl = mw.util.getUrl('Form:UploadVideo', { 'page': pageName });
$('<div style="position:fixed; bottom:20px; right:20px; background:#007bff; color:white; padding:10px; border-radius:5px; cursor:pointer; font-weight:bold;">Upload a Video</div>')
.click(function() {
window.location.href = uploadUrl;
}).appendTo('body');
}
});
*/
/* Start Pushkar Code */
$('img').attr('loading', 'lazy');
mw.loader.using(['jquery'], function () {
// Load Slick dynamically
$.getScript('https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js')
.done(function () {
$(function () {
// Initialize Slick after content loads
$('.adsBannerSliderHero ').not('.slick-initialized').slick({
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 3000,
dots: false,
arrows: true,
prevArrow: '<button class="prev-arrow"><i class="fas fa-chevron-left"></i></button>',
nextArrow: '<button class="next-arrow"><i class="fas fa-chevron-right"></i></button>',
//adaptiveHeight: true
});
$('.sanatanWisdomSlider').not('.slick-initialized').slick({
slidesToShow: 3,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 3000,
dots: false,
arrows: true,
prevArrow: '<button class="prev-arrow"><i class="fas fa-chevron-left"></i></button>',
nextArrow: '<button class="next-arrow"><i class="fas fa-chevron-right"></i></button>',
responsive: [
{breakpoint: 768, settings: {arrows: false, centerMode: true, slidesToShow: 2 }},
{breakpoint: 480, settings: { arrows: false,slidesToShow: 1}}
],
adaptiveHeight: true
});
$('.latestArticlesSlider').not('.slick-initialized').slick({
slidesToShow: 3,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 3000,
dots: false,
arrows: false,
variableWidth: true,
prevArrow: '<button class="prev-arrow"><i class="fas fa-chevron-left"></i></button>',
nextArrow: '<button class="next-arrow"><i class="fas fa-chevron-right"></i></button>',
responsive: [
{breakpoint: 768, settings: {arrows: false, centerMode: true, slidesToShow: 2 }},
{breakpoint: 480, settings: { arrows: false,slidesToShow: 1}}
],
adaptiveHeight: true
});
});
})
.fail(function () {
console.error('Failed to load Slick Slider JS');
});
});
/* End Pushkar Code */
/* Functions of Slider One */
(function () {
function initSliders() {
var sliders = document.querySelectorAll('.mw-slider');
sliders.forEach(function (slider) {
// Avoid double-init
if (slider._mwSliderInited) return;
slider._mwSliderInited = true;
var viewport = slider.querySelector('.mw-slider-viewport');
var track = slider.querySelector('.mw-slider-track');
var items = Array.from(slider.querySelectorAll('.mw-slider-item'));
var btnPrev = slider.querySelector('.mw-slider-btn.prev');
var btnNext = slider.querySelector('.mw-slider-btn.next');
var currentIndex = 0;
var itemsToShow = getItemsToShow();
var gap = parseFloat(getComputedStyle(track).columnGap || getComputedStyle(track).gap || 16);
function getItemsToShow() {
var w = window.innerWidth;
if (w <= 600) return 1;
if (w <= 900) return 2;
return 3;
}
function updateSizes() {
itemsToShow = getItemsToShow();
// compute single item width including gap
if (!items[0]) return;
var itemRect = items[0].getBoundingClientRect();
gap = parseFloat(getComputedStyle(track).columnGap || getComputedStyle(track).gap || 16);
var single = itemRect.width + gap;
// ensure currentIndex in range
var maxIndex = Math.max(0, items.length - itemsToShow);
currentIndex = Math.min(currentIndex, maxIndex);
// apply transform
var translateX = -currentIndex * single;
track.style.transform = 'translateX(' + translateX + 'px)';
updateButtons();
}
function updateButtons() {
var maxIndex = Math.max(0, items.length - itemsToShow);
if (btnPrev) btnPrev.disabled = currentIndex <= 0;
if (btnNext) btnNext.disabled = currentIndex >= maxIndex;
}
function gotoIndex(index) {
var maxIndex = Math.max(0, items.length - itemsToShow);
currentIndex = Math.max(0, Math.min(maxIndex, index));
updateSizes();
}
if (btnPrev) btnPrev.addEventListener('click', function () {
gotoIndex(currentIndex - 1);
});
if (btnNext) btnNext.addEventListener('click', function () {
gotoIndex(currentIndex + 1);
});
// Keyboard support
slider.addEventListener('keydown', function (e) {
if (e.key === 'ArrowLeft') gotoIndex(currentIndex - 1);
if (e.key === 'ArrowRight') gotoIndex(currentIndex + 1);
});
// Resize handling
var resizeTimeout;
window.addEventListener('resize', function () {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(updateSizes, 120);
});
// Touch / drag support
(function () {
var startX = 0;
var currentTranslate = 0;
var dragging = false;
var pointerId = null;
function pointerDown(e) {
if (e.pointerType === 'mouse' && e.button !== 0) return;
dragging = true;
pointerId = e.pointerId;
startX = e.clientX;
track.style.transition = 'none';
track.setPointerCapture && track.setPointerCapture(pointerId);
}
function pointerMove(e) {
if (!dragging || e.pointerId !== pointerId) return;
var dx = e.clientX - startX;
var itemRect = items[0] && items[0].getBoundingClientRect();
var single = itemRect ? (itemRect.width + gap) : 0;
var baseTranslate = -currentIndex * single;
track.style.transform = 'translateX(' + (baseTranslate + dx) + 'px)';
}
function pointerUp(e) {
if (!dragging || e.pointerId !== pointerId) return;
dragging = false;
track.style.transition = '';
var dx = e.clientX - startX;
var threshold = Math.max(40, (items[0] ? items[0].getBoundingClientRect().width : 200) * 0.15);
if (dx > threshold) {
gotoIndex(currentIndex - 1);
} else if (dx < -threshold) {
gotoIndex(currentIndex + 1);
} else {
updateSizes();
}
try { track.releasePointerCapture(pointerId); } catch (err) {}
pointerId = null;
}
track.addEventListener('pointerdown', pointerDown);
window.addEventListener('pointermove', pointerMove);
window.addEventListener('pointerup', pointerUp);
track.addEventListener('pointercancel', pointerUp);
})();
// Initial sizes
setTimeout(updateSizes, 60);
});
}
// init on DOM ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initSliders);
} else {
initSliders();
}
// If new content is loaded via AJAX on the wiki, re-init
if (window.mw && mw.hook) {
mw.hook('wikipage.content').add(initSliders);
}
})();
/* Full width Slider */
(function () {
function initFullSliders() {
var sliders = document.querySelectorAll('.mw-fullslider');
sliders.forEach(function (slider) {
if (slider._fullSliderInit) return;
slider._fullSliderInit = true;
var track = slider.querySelector('.mw-fullslider-track');
var slides = Array.from(track.children);
var btnPrev = slider.querySelector('.mw-fullslider-btn.prev');
var btnNext = slider.querySelector('.mw-fullslider-btn.next');
var dots = Array.from(slider.querySelectorAll('.mw-fullslider-dots .dot'));
var current = 0;
var slideCount = slides.length;
function goTo(index, animate) {
current = (index % slideCount + slideCount) % slideCount;
var x = -current * slider.clientWidth;
if (animate === false) track.style.transition = 'none';
else track.style.transition = '';
track.style.transform = 'translateX(' + x + 'px)';
updateControls();
if (animate === false) {
// force reflow then restore
void track.offsetWidth;
track.style.transition = '';
}
}
function updateControls() {
if (btnPrev) btnPrev.disabled = false;
if (btnNext) btnNext.disabled = false;
// update dots
dots.forEach(function (d) {
d.classList.toggle('active', +d.getAttribute('data-index') === current);
d.setAttribute('aria-pressed', (+d.getAttribute('data-index') === current).toString());
});
}
if (btnPrev) btnPrev.addEventListener('click', function () { goTo(current - 1); });
if (btnNext) btnNext.addEventListener('click', function () { goTo(current + 1); });
dots.forEach(function (dot) {
dot.addEventListener('click', function () {
var idx = parseInt(this.getAttribute('data-index'), 10);
goTo(idx);
});
});
// Resize handling: ensure slide width matches viewport
var resizeTimer;
function onResize() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function () {
// Recompute translate in case width changed
goTo(current, false);
}, 80);
}
window.addEventListener('resize', onResize);
// Touch / drag support
(function () {
var startX = 0, startTranslate = 0, dragging = false, pointerId = null;
function down(e) {
if (e.pointerType === 'mouse' && e.button !== 0) return;
dragging = true;
pointerId = e.pointerId;
startX = e.clientX;
var style = window.getComputedStyle(track);
var matrix = new WebKitCSSMatrix(style.transform);
startTranslate = matrix.m41 || 0;
track.style.transition = 'none';
e.target.setPointerCapture && e.target.setPointerCapture(pointerId);
}
function move(e) {
if (!dragging || e.pointerId !== pointerId) return;
var dx = e.clientX - startX;
track.style.transform = 'translateX(' + (startTranslate + dx) + 'px)';
}
function up(e) {
if (!dragging || e.pointerId !== pointerId) return;
dragging = false;
track.style.transition = '';
var dx = e.clientX - startX;
var threshold = Math.max(40, slider.clientWidth * 0.12);
if (dx > threshold) goTo(current - 1);
else if (dx < -threshold) goTo(current + 1);
else goTo(current);
try { e.target.releasePointerCapture(pointerId); } catch (err) {}
pointerId = null;
}
track.addEventListener('pointerdown', down);
window.addEventListener('pointermove', move);
window.addEventListener('pointerup', up);
track.addEventListener('pointercancel', up);
})();
// Autoplay (optional): change interval or set autoplay = false
var autoplay = true;
var autoplayInterval = 4500; // ms
var autoplayTimer = null;
function startAutoplay() {
if (!autoplay) return;
stopAutoplay();
autoplayTimer = setInterval(function () { goTo(current + 1); }, autoplayInterval);
}
function stopAutoplay() {
if (autoplayTimer) { clearInterval(autoplayTimer); autoplayTimer = null; }
}
slider.addEventListener('mouseenter', stopAutoplay);
slider.addEventListener('mouseleave', startAutoplay);
slider.addEventListener('focusin', stopAutoplay);
slider.addEventListener('focusout', startAutoplay);
// Respect prefers-reduced-motion
var rmq = window.matchMedia('(prefers-reduced-motion: reduce)');
if (rmq.matches) autoplay = false;
// Ensure initial sizing: make each slide exactly slider.clientWidth
function layoutSlides() {
var w = slider.clientWidth;
slides.forEach(function (s) { s.style.minWidth = w + 'px'; s.style.maxWidth = w + 'px'; });
goTo(current, false);
}
// Wait for images then layout
function imgsReady(cb) {
var imgs = Array.from(slider.querySelectorAll('img'));
var rem = imgs.length;
if (!rem) return cb();
imgs.forEach(function (img) {
if (img.complete) { rem--; if (!rem) cb(); }
else {
img.addEventListener('load', function () { rem--; if (!rem) cb(); });
img.addEventListener('error', function () { rem--; if (!rem) cb(); });
}
});
}
imgsReady(function () {
layoutSlides();
startAutoplay();
window.addEventListener('resize', onResize);
});
// expose for debug (optional)
slider._goTo = goTo;
});
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', initFullSliders);
else initFullSliders();
if (window.mw && mw.hook) mw.hook('wikipage.content').add(initFullSliders);
})();
// --- Disable Tools Option for all users except admin ---
mw.loader.using(['mediawiki.user'], function () {
$(function () {
mw.user.getGroups().then(function (groups) {
// If the user is NOT an admin (sysop)
if (groups.indexOf('sysop') === -1) {
// Disable Tools menu and its dropdown items
$('a, span').filter(function () {
return $(this).text().trim() === 'Tools';
}).each(function () {
const link = $(this);
link.css({
'pointer-events': 'none',
'opacity': '0',
'cursor': 'not-allowed',
'width' : '1px',
'height' : '1px',
'display' : 'none',
});
link.attr('title', 'Restricted to admins');
link.closest('.dropdown').find('a').css({
'pointer-events': 'none',
'opacity': '0.5',
'cursor': 'not-allowed'
});
});
// Disable Tools menu and its dropdown items
$('a, span').filter(function () {
return $(this).text().trim() === 'उपकरण';
}).each(function () {
const link = $(this);
link.css({
'pointer-events': 'none',
'opacity': '0',
'cursor': 'not-allowed',
'width' : '1px',
'height' : '1px',
'display' : 'none',
});
link.attr('title', 'Restricted to admins');
link.closest('.dropdown').find('a').css({
'pointer-events': 'none',
'opacity': '0.5',
'cursor': 'not-allowed'
});
});
// Disable any link to Special:SpecialPages
$('a[href*="Special:SpecialPages"]').css({
'pointer-events': 'none',
'opacity': '0.5',
'cursor': 'not-allowed'
}).attr('title', 'Restricted to admins');
// Disable MediaWiki namespace links
$('a[href*="MediaWiki:"]').css({
'pointer-events': 'none',
'opacity': '0.5',
'cursor': 'not-allowed'
}).attr('title', 'Restricted to admins');
}
});
});
});
// Collapsible Related Pages on Mobile
mw.loader.using('jquery', function () {
$(function () {
var header = $('.page-links-header');
var content = $('.page-links-content');
if (header.length && content.length) {
header.on('click', function () {
$(this).toggleClass('active');
content.toggleClass('open');
});
}
});
});
// Team Dashboard Settings
mw.loader.using(['mediawiki.api', 'mediawiki.util']).then(function () {
(function ($) {
/** ---------- Utility: escape HTML ---------- **/
function escapeHtml(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
/** ---------- Detect TeamDashboard ---------- **/
var pageName = mw.config.get('wgCanonicalSpecialPageName') || '';
if (String(pageName).toLowerCase() !== 'teamdashboard') return;
/** ---------- Accordion UI ---------- **/
function initAccordionOnce() {
$('.accordion-toggle').each(function () {
var $el = $(this);
var targetSel = $el.attr('data-target');
var $target = $(targetSel);
if (!$target.length) return;
if ($el.find('.pa-arrow').length === 0)
$el.prepend('<span class="pa-arrow">▶ </span>');
var saved = localStorage.getItem('pa:' + targetSel);
if (saved === 'open') {
$target.show();
$el.find('.pa-arrow').text('▼ ');
}
if (!$el.data('pa-bound')) {
$el.on('click', function () {
var open = $target.is(':visible');
$target.toggle(!open);
$el.find('.pa-arrow').text(open ? '▶ ' : '▼ ');
localStorage.setItem('pa:' + targetSel, open ? 'closed' : 'open');
});
$el.data('pa-bound', true);
}
});
}
/** ---------- MediaWiki API ---------- **/
var api = new mw.Api();
function getFreshToken() {
return api
.get({
action: 'query',
meta: 'tokens',
type: 'csrf',
format: 'json'
})
.then(function (d) {
return d.query.tokens.csrftoken || '';
})
.catch(function () {
return '';
});
}
/** ---------- POST helper ---------- **/
function postAction(fd) {
return $.ajax({
url: mw.util.getUrl('Special:TeamDashboard'),
type: 'POST',
data: fd,
processData: false,
contentType: false,
headers: { 'X-Requested-With': 'XMLHttpRequest' }
});
}
/** ---------- Approve / Reject / Forward ---------- **/
$(document).on('click', 'button[data-action]', function (e) {
e.preventDefault();
var $btn = $(this);
if ($btn.prop('disabled')) return;
var action = $btn.data('action'),
pageId = $btn.data('page-id');
$btn.prop('disabled', true);
getFreshToken().then(function (token) {
if (!token) {
alert('Session expired, reload.');
$btn.prop('disabled', false);
return;
}
var fd = new FormData();
fd.append('pa_action', action);
fd.append('page_id', pageId);
fd.append('token', token);
if (action === 'forward') {
var txt = $.trim($btn.closest('td').find('input.comment-input').val() || '');
if (txt !== '') fd.append('comment', txt);
}
postAction(fd)
.done(function () {
if (action === 'approve') {
$btn.text('Approved ✓').prop('disabled', true);
$btn.closest('td').prev().prev().text('approved');
} else if (action === 'reject') {
$btn.text('Rejected ✗').prop('disabled', true);
$btn.closest('td').prev().prev().text('rejected');
} else if (action === 'forward') {
$btn.text('Forwarded ➜').prop('disabled', true);
}
})
.fail(function () {
alert('Action failed. Please try again.');
$btn.prop('disabled', false);
});
});
});
/** ---------- Comment submit ---------- **/
$(document).on('click', '.comment-submit', function (e) {
e.preventDefault();
var $btn = $(this);
if ($btn.prop('disabled')) return;
var $wrap = $btn.closest('.ajax-comment-wrap'),
txt = $.trim($wrap.find('input.comment-input').val() || ''),
pageId = $btn.data('page-id');
if (txt === '') return;
$btn.prop('disabled', true);
getFreshToken().then(function (token) {
if (!token) {
alert('Session expired, reload.');
$btn.prop('disabled', false);
return;
}
var fd = new FormData();
fd.append('pa_action', 'comment');
fd.append('page_id', pageId);
fd.append('token', token);
fd.append('comment', txt);
postAction(fd)
.done(function (resp) {
var $td = $btn.closest('td');
var $list = $td.find('.comment-list');
if (!$list.length) {
var box = $('<div class="comment-box"><b>Comments</b><ul class="comment-list"></ul></div>');
$td.append(box);
$list = box.find('.comment-list');
}
var username = mw.config.get('wgUserName') || 'You';
var now = new Date();
var istOffset = 5.5 * 60 * 60 * 1000; // UTC+5:30
var ist = new Date(now.getTime() + istOffset);
var timestamp =
ist.getFullYear() +
'-' +
String(ist.getMonth() + 1).padStart(2, '0') +
'-' +
String(ist.getDate()).padStart(2, '0') +
' ' +
String(ist.getHours()).padStart(2, '0') +
':' +
String(ist.getMinutes()).padStart(2, '0') +
':' +
String(ist.getSeconds()).padStart(2, '0');
var li = $('<li/>').html(
'<b>' +
escapeHtml(username) +
'</b> <span class="date">(' +
timestamp +
' IST)</span><br>' +
escapeHtml(txt) +
' <button class="edit-comment-btn">✏️</button>'
);
$list.prepend(li);
$wrap.find('input.comment-input').val('');
})
.fail(function () {
alert('Could not add comment. Try again.');
})
.always(function () {
$btn.prop('disabled', false);
});
});
});
/** ---------- Enter key submits comment ---------- **/
$(document).on('keypress', 'input.comment-input', function (e) {
if (e.which === 13) {
e.preventDefault();
$(this).closest('.ajax-comment-wrap').find('.comment-submit').trigger('click');
}
});
/** ---------- Delete comment ---------- **/
$(document).on('click', '.delete-comment-btn', function (e) {
e.preventDefault();
var $btn = $(this);
if ($btn.prop('disabled')) return;
if (!confirm('Delete this comment?')) return;
var commentId = $btn.data('comment-id'),
pageId = $btn.data('page-id');
$btn.prop('disabled', true);
getFreshToken().then(function (token) {
if (!token) {
alert('Session expired.');
$btn.prop('disabled', false);
return;
}
var fd = new FormData();
fd.append('pa_action', 'delete_comment');
fd.append('comment_id', commentId);
fd.append('page_id', pageId);
fd.append('token', token);
postAction(fd)
.done(function () {
$btn.closest('li').fadeOut(200, function () {
$(this).remove();
});
})
.fail(function () {
alert('Delete failed.');
})
.always(function () {
$btn.prop('disabled', false);
});
});
});
/** ---------- ✏️ Edit comment (new feature) ---------- **/
$(document).on('click', '.edit-comment-btn', function () {
var $btn = $(this);
var $li = $btn.closest('li');
var oldText = $li
.clone()
.children()
.remove()
.end()
.text()
.trim();
var pageId = $li.closest('td').find('.comment-submit').data('page-id');
var commentId = $btn.data('comment-id');
if ($li.find('.edit-comment-area').length) return;
var $area = $('<textarea class="edit-comment-area"></textarea>').val(oldText);
var $save = $('<button class="pa-btn save-edit">Save</button>');
var $cancel = $('<button class="pa-btn danger cancel-edit">Cancel</button>');
$li.append($area, $save, $cancel);
$save.on('click', function () {
var newText = $.trim($area.val());
if (!newText) return alert('Comment cannot be empty.');
getFreshToken().then(function (token) {
var fd = new FormData();
fd.append('pa_action', 'edit_comment');
fd.append('comment_id', commentId);
fd.append('page_id', pageId);
fd.append('comment', newText);
fd.append('token', token);
postAction(fd)
.done(function (resp) {
if (resp.ok) {
$area.remove();
$save.remove();
$cancel.remove();
$btn.before(' ' + escapeHtml(newText) + ' <em>(edited)</em> ');
} else {
alert(resp.error || 'Edit failed.');
}
})
.fail(function () {
alert('Edit failed.');
});
});
});
$cancel.on('click', function () {
$area.remove();
$save.remove();
$cancel.remove();
});
});
/** ---------- Search Filter ---------- **/
$(document).on('input', '.search-input', function () {
var q = $(this).val().toLowerCase();
$('.dashboard-table tbody tr').each(function () {
var t = $(this).text().toLowerCase();
$(this).toggle(t.indexOf(q) !== -1);
});
});
/** ---------- Init ---------- **/
initAccordionOnce();
setTimeout(initAccordionOnce, 700);
})(jQuery);
});
(function () {
mw.loader.using(['ext.visualEditor.desktopArticleTarget.init', 'oojs-ui', 'jquery']).done(function () {
/* --------------------------------------------------
Add "SEO" button to VisualEditor toolbar
-------------------------------------------------- */
if (mw.config.get('wgIsArticle')) {
mw.hook('ve.activationComplete').add(function () {
try {
var veTarget = ve.init && ve.init.target;
var toolbar = veTarget && veTarget.toolbar;
if (!toolbar) return;
if (toolbar.$element.find('.ve-ui-toolbar-seoButton').length) return;
var seoButton = new OO.ui.ButtonWidget({
label: 'SEO',
icon: 'settings',
classes: ['ve-ui-toolbar-seoButton']
});
seoButton.on('click', function () {
openSEODialog(veTarget);
});
toolbar.$element.find('.oo-ui-toolbar-actions').append(seoButton.$element);
} catch (e) {
console.error('[SEO] Toolbar init error:', e);
}
});
}
/* --------------------------------------------------
SEO Dialog definition
-------------------------------------------------- */
function openSEODialog(veTarget) {
var surface = veTarget.surface;
var model = surface.getModel();
var docText = '';
try {
docText = model.getDocument().data.getText(true);
console.log("DOC TEXT =", docText);
} catch (e) {
var txt = document.getElementById('wpTextbox1');
if (txt) docText = txt.value;
}
/* ===================================================================
ADDED BLOCK: Extract SEO from VisualEditor COMMENT nodes ⭐
=================================================================== */
var oldTitle = '', oldDesc = '', oldKeys = '';
var match = /<!--\s*SEO\s+title=(.*?)\s+description=([\s\S]*?)\s+keywords=([\s\S]*?)\s*-->/i.exec(docText);
if (match) {
oldTitle = match[1].trim();
oldDesc = match[2].trim();
oldKeys = match[3].trim();
}
/* ===================================================================
DO NOT USE OLD REGEX — VE hides comments in comment nodes ⭐
=================================================================== */
// Input fields (your original code)
var titleInput = new OO.ui.TextInputWidget({ placeholder: 'Meta Title', value: oldTitle });
var descInput = new OO.ui.MultilineTextInputWidget({ placeholder: 'Meta Description', rows: 3, value: oldDesc });
var keysInput = new OO.ui.TextInputWidget({ placeholder: 'Meta Keywords', value: oldKeys });
// Define dialog (your original code)
var SEODialog = function (cfg) { SEODialog.super.call(this, cfg); };
OO.inheritClass(SEODialog, OO.ui.ProcessDialog);
SEODialog.static.name = 'seoDialog';
SEODialog.static.title = 'SEO Settings';
SEODialog.static.size = 'larger';
SEODialog.static.actions = [
{ action: 'save', label: 'Save', flags: ['primary', 'progressive'] },
{ action: 'cancel', label: 'Cancel', flags: ['safe'] }
];
SEODialog.prototype.initialize = function () {
SEODialog.super.prototype.initialize.apply(this, arguments);
var panel = new OO.ui.PanelLayout({ padded: true, expanded: true });
panel.$element.append(
$('<label>').text('Meta Title'),
titleInput.$element,
$('<br><label>').text('Meta Description'),
descInput.$element,
$('<br><label>').text('Meta Keywords'),
keysInput.$element
);
this.$body.append(panel.$element);
};
SEODialog.prototype.getBodyHeight = function () {
return 420;
};
/* --------------------------------------------------
Save / Cancel buttons
-------------------------------------------------- */
SEODialog.prototype.getActionProcess = function (action) {
var dialog = this;
if (action === 'save') {
return new OO.ui.Process(function () {
var t = titleInput.getValue().trim();
var d = descInput.getValue().trim();
var k = keysInput.getValue().trim();
var newSEOComment =
'<!--SEO ' +
'title=' + mw.html.escape(t) + ' ' +
'description=' + mw.html.escape(d) + ' ' +
'keywords=' + mw.html.escape(k) +
' -->\n';
var newText = docText.replace(/<!--SEO[\s\S]*?-->/i, '');
newText = newSEOComment + newText;
try {
var docLen = model.getDocument().data.getLength();
model.getLinearFragment(new ve.Range(0, docLen)).insertContent(newText);
mw.notify('✔️ SEO data saved.');
} catch (err) {
var ta = document.querySelector('textarea#wpTextbox1');
if (ta) ta.value = newText;
mw.notify('✔️ SEO data saved (fallback).');
}
dialog.close({ action: 'cancel' });
});
}
if (action === 'cancel') {
return new OO.ui.Process(function () {
dialog.close({ action: 'cancel' });
});
}
return SEODialog.super.prototype.getActionProcess.call(this, action);
};
// Window manager (your original code)
var wm = window._seoWM || new OO.ui.WindowManager();
if (!window._seoWM) {
window._seoWM = wm;
$(document.body).append(wm.$element);
}
var dlg = new SEODialog();
wm.addWindows([dlg]);
wm.openWindow(dlg);
}
});
})();
// == Showing Template as default footer
$(document).ready(function () {
// Remove Chameleon’s default footer
$('.footercontainer, #footer, #mw-footer').remove();
// Prevent duplicate inserts
if ($('#mw-custom-footer').length) return;
// --- Detect Hindi language ---
var pathParts = window.location.pathname.split('/').filter(Boolean);
var isHindi = pathParts.length > 0 && pathParts[0].toLowerCase() === 'hi';
// Choose template
var templateName = isHindi ? 'Custom-footer-Hindi' : 'Custom-footer';
// Load chosen footer
$.ajax({
url: '/index.php?title=Template:' + templateName + '&action=render',
type: 'GET',
success: function (data) {
const footer = $('<div id="mw-custom-footer"></div>').html(data);
$('body').append(footer);
},
error: function () {
console.warn('⚠️ Custom footer could not be loaded.');
}
});
});
// == Combined: Floating Create UI + Parent prompt + Category inject + Change Parent (ES5 safe) ==
(function () {
// Ensure mw loader availability
mw.loader.using(['mediawiki.util', 'mediawiki.api']).then(function () {
// --------- Utility: Query param reader (ES5) ----------
function getQueryParam(name) {
var qs = window.location.search.substring(1);
var pairs = qs.split('&');
for (var i = 0; i < pairs.length; i++) {
var parts = pairs[i].split('=');
if (decodeURIComponent(parts[0]) === name) {
return parts[1] ? decodeURIComponent(parts[1]) : '';
}
}
return null;
}
// --------- Utility: Normalize title string (remove domains, leading slashes, avoid "hi/" inside title) ----------
function normalizeTitleStr(s) {
s = String(s || '');
s = s.replace(/^\s+|\s+$/g, '');
if (!s) return s;
// strip protocol+domain if present
s = s.replace(/^https?:\/\/[^\/]+/i, '');
// remove leading slashes
s = s.replace(/^\/+/, '');
// remove namespace-like hi/ or hi: from the start so titles remain clean
s = s.replace(/^hi\//i, '');
s = s.replace(/^hi:/i, '');
s = s.replace(/^\/+/, '');
return s;
}
// --------- Utility: detect language prefix from current pathname ----------
function detectLanguagePrefix() {
var path = window.location.pathname || '';
var parts = path.split('/').filter(function (v) { return v && v.length; });
if (parts.length && parts[0] === 'hi') return 'hi';
return '';
}
// --------- Inject Category into textarea (for non-VE fallback) ----------
function injectCategory(category) {
if (!category) return;
var textarea = $('#wpTextbox1');
if (textarea.length && textarea.val().indexOf('[[' + 'Category:' + category + ']]') === -1) {
textarea.val('[[' + 'Category:' + category + ']]\n\n' + textarea.val());
}
}
// --------- Floating Create Button (re-usable UI) ----------
(function createFloatingButton() {
try {
if (typeof mw === 'undefined' || !mw.config) return;
if (!mw.config.exists('wgUserName') || !mw.config.get('wgUserName')) return;
var groups = mw.config.get('wgUserGroups') || [];
var isWriter = (groups.indexOf && groups.indexOf('writer') !== -1) || false;
var isLead = (groups.indexOf && groups.indexOf('lead') !== -1) || false;
var isEditor = (groups.indexOf && groups.indexOf('editor') !== -1) || false;
var isAdmin = (groups.indexOf && groups.indexOf('sysop') !== -1) || false;
if (!(isWriter || isLead || isEditor || isAdmin)) return;
if (document.getElementById('floatingCreateBtn')) return;
// Floating button
var btn = document.createElement('button');
btn.id = 'floatingCreateBtn';
btn.appendChild(document.createTextNode('+'));
btn.style.position = 'fixed';
btn.style.bottom = '30px';
btn.style.right = '30px';
btn.style.width = '60px';
btn.style.height = '60px';
btn.style.borderRadius = '50%';
btn.style.background = '#0078D7';
btn.style.color = '#fff';
btn.style.fontSize = '32px';
btn.style.border = 'none';
btn.style.cursor = 'pointer';
btn.style.zIndex = '9999';
btn.style.boxShadow = '0 4px 10px rgba(0,0,0,0.3)';
btn.addEventListener('mouseover', function () { btn.style.background = '#005fa3'; });
btn.addEventListener('mouseout', function () { btn.style.background = '#0078D7'; });
document.body.appendChild(btn);
// Popup UI
var popup = document.createElement('div');
popup.id = 'createPopupBox';
popup.style.position = 'fixed';
popup.style.bottom = '100px';
popup.style.right = '30px';
popup.style.background = '#fff';
popup.style.border = '2px solid #ccc';
popup.style.borderRadius = '12px';
popup.style.padding = '15px';
popup.style.width = '320px';
popup.style.display = 'none';
popup.style.boxShadow = '0 6px 14px rgba(0,0,0,0.25)';
popup.style.zIndex = '10000';
var html = '';
html += '<label style="font-weight:bold;display:block;margin-bottom:6px;">Select Language</label>';
html += '<select id="pageLang" style="width:100%;padding:6px;margin-bottom:8px;border:1px solid #ccc;border-radius:5px;">';
html += '<option value="en">English</option>';
html += '<option value="hi">Hindi</option>';
html += '</select>';
html += '<label style="font-weight:bold;display:block;">Create new page</label>';
html += '<input type="text" id="newPageName" placeholder="Enter page name" style="width:100%;padding:6px;margin-top:4px;border:1px solid #ccc;border-radius:5px;">';
html += '<button id="createPageBtn" style="margin-top:8px;width:100%;background:#0078D7;color:white;border:none;padding:8px;border-radius:6px;cursor:pointer;">Create Page</button>';
if (isEditor || isAdmin) {
html += '<hr style="margin:10px 0;border:none;border-top:1px solid #eee;">';
html += '<label style="font-weight:bold;display:block;">Create new category (always English)</label>';
html += '<input type="text" id="newCategoryName" placeholder="Enter category name" style="width:100%;padding:6px;margin-top:4px;border:1px solid #ccc;border-radius:5px;">';
html += '<button id="createCategoryBtn" style="margin-top:8px;width:100%;background:#28a745;color:white;border:none;padding:8px;border-radius:6px;cursor:pointer;">Create Category</button>';
}
popup.innerHTML = html;
document.body.appendChild(popup);
// Toggle popup
btn.addEventListener('click', function () {
if (popup.style.display === 'none' || popup.style.display === '') {
popup.style.display = 'block';
} else {
popup.style.display = 'none';
}
});
// Click handlers (delegated)
popup.addEventListener('click', function (ev) {
var target = ev.target || ev.srcElement;
if (!target) return;
if (target.id === 'createPageBtn') {
var lang = document.getElementById('pageLang').value || 'en';
var name = (document.getElementById('newPageName').value || '').replace(/^\s+|\s+$/g, '');
if (!name) {
alert('Please enter a page name.');
return;
}
var title = name.replace(/\s+/g, '_');
if (lang === 'hi') {
// Open VE under /hi/ prefix
var base = window.location.protocol + '//' + window.location.host;
var finalUrl = base + '/hi/' + encodeURIComponent(title) + '?action=edit&veaction=edit';
// add autocategory param? Not set here; UI may add when creating category
window.location.href = finalUrl;
} else {
// English: use mw.util.getUrl
var href = mw.util.getUrl(title, { action: 'edit', veaction: 'edit' });
window.location.href = href;
}
}
if (target.id === 'createCategoryBtn') {
var cat = (document.getElementById('newCategoryName').value || '').replace(/^\s+|\s+$/g, '');
if (!cat) {
alert('Please enter a category name.');
return;
}
// Category creation always English
var cTitle = 'Category:' + cat.replace(/\s+/g, '-');
var curl = mw.util.getUrl(cTitle, { action: 'edit', veaction: 'edit' });
window.location.href = curl;
}
});
} catch (err) {
if (typeof console !== 'undefined' && console.error) console.error('FloatingCreate init error', err);
}
}());
// --------- Parent / Category workflow ----------
var api = new mw.Api();
var username = mw.config.get('wgUserName');
if (!username) return;
var wgNamespace = mw.config.get('wgNamespaceNumber');
var wgTitle = mw.config.get('wgTitle');
var wgPageName = mw.config.get('wgPageName');
var wgAction = mw.config.get('wgAction');
var wgCurRevisionId = mw.config.get('wgCurRevisionId');
var autoCat = getQueryParam('autocategory');
var skipParent = getQueryParam('skipparent');
// Category prompt when creating a new Category page
if (wgNamespace === 14) {
var storageKey = 'category_prompt_done_' + wgTitle;
function askAndCreateCategory() {
if (sessionStorage.getItem(storageKey)) return;
sessionStorage.setItem(storageKey, 'done');
var ask = confirm('✅ You just created the new category "' + wgTitle + '".\n\nDo you want to create a normal page with the same name? It will automatically belong to this category.');
if (ask) {
var editUrl = mw.util.getUrl(wgTitle, { action: 'edit', veaction: 'edit' });
// pass autocategory and skipparent param
editUrl += '&autocategory=' + encodeURIComponent(wgTitle) + '&skipparent=1';
window.location.href = editUrl;
}
}
mw.hook('postEdit').add(askAndCreateCategory);
$(window).on('popstate', function () {
if (wgAction !== 'view') return;
if (sessionStorage.getItem(storageKey)) return;
api.get({
action: 'query',
titles: 'Category:' + wgTitle,
prop: 'info',
format: 'json'
}).done(function (data) {
var pages = data && data.query && data.query.pages;
if (!pages) return;
var pageData;
for (var p in pages) { if (pages.hasOwnProperty(p)) { pageData = pages[p]; break; } }
if (pageData && pageData.missing === undefined) {
askAndCreateCategory();
}
});
});
}
// Inject category into textarea / VE
if (autoCat) {
$(document).ready(function () { injectCategory(autoCat); });
mw.hook('ve.activationComplete').add(function () { injectCategory(autoCat); });
}
// Reminder banner in edit mode
mw.hook('wikipage.content').add(function ($content) {
if (wgAction === 'edit' || wgAction === 'submit') {
var banner = $('<div>').css({
background: '#fff8c4',
border: '1px solid #e0c14b',
padding: '10px',
marginBottom: '10px',
borderRadius: '6px',
textAlign: 'center',
fontWeight: '600'
}).text('🪶 Tip: Remember to set a parent page before saving.');
$content.prepend(banner);
// If this is an existing page (has revision), add "Change Parent" button
if (wgCurRevisionId && wgCurRevisionId !== 0) {
var changeBtn = $('<button>').text('Change Parent').css({
marginLeft: '10px',
background: '#343a40',
color: '#fff',
border: 'none',
padding: '6px 10px',
borderRadius: '4px',
cursor: 'pointer'
});
changeBtn.on('click', function () {
// open parent selector for existing page, and then attempt to move
askForParent(wgTitle, function (newTitle, finalUrl) {
// If user kept same title, do nothing
if (!newTitle || newTitle === wgTitle) return;
var confirmMove = confirm('Move page "' + wgTitle + '" to "' + newTitle + '"? This will perform a page move (you must have move rights).');
if (!confirmMove) return;
// Move via API
var token = mw.user.tokens.get('csrfToken');
api.postWithToken('csrf', {
action: 'move',
from: wgTitle,
to: newTitle,
reason: 'Change parent via Change Parent button',
movetalk: true,
noredirect: false
}).done(function (data) {
if (data && data.move && data.move.newrevid) {
// Success: go to new page view
var newUrl = detectLanguagePrefix() ? (window.location.protocol + '//' + window.location.host + '/' + detectLanguagePrefix() + '/' + encodeURIComponent(newTitle)) : mw.util.getUrl(newTitle);
window.location.href = newUrl;
} else {
alert('Move did not complete. Response: ' + JSON.stringify(data));
}
}).fail(function (jqXHR) {
var msg = 'Move failed. You may not have permission or there was an error.';
try { msg += '\n' + jqXHR.responseText; } catch (e) {}
alert(msg);
});
});
});
// place the change button next to banner
$content.find('div').first().append(changeBtn);
}
}
});
// Parent selection modal
function askForParent(title, callback) {
if (window.parentPromptShown) return;
window.parentPromptShown = true;
var overlay = $('<div>').css({
position: 'fixed',
top: 0,
left: 0,
width: '100%',
height: '100%',
background: 'rgba(0,0,0,0.5)',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
zIndex: 999999
});
var box = $('<div>').css({
background: '#fff',
padding: '20px',
borderRadius: '10px',
width: '420px',
textAlign: 'center',
boxShadow: '0 4px 10px rgba(0,0,0,0.3)'
});
box.append('<h3 style="margin-top:0">Select Parent Page</h3>');
var input = $('<input type="text" placeholder="Type to search existing pages...">').css({
width: '100%',
padding: '8px',
border: '1px solid #ccc',
borderRadius: '5px'
});
var suggestionBox = $('<ul>').css({
listStyle: 'none',
margin: '10px 0 0',
padding: 0,
maxHeight: '200px',
overflowY: 'auto',
border: '1px solid #ddd',
borderRadius: '5px',
display: 'none',
textAlign: 'left'
});
var confirmBtn = $('<button>Confirm</button>').css({
marginTop: '10px',
background: '#007bff',
color: '#fff',
border: 'none',
padding: '8px 14px',
borderRadius: '5px',
cursor: 'pointer'
});
var skipBtn = $('<button>No Parent</button>').css({
marginLeft: '8px',
marginTop: '10px',
background: '#6c757d',
color: '#fff',
border: 'none',
padding: '8px 14px',
borderRadius: '5px',
cursor: 'pointer'
});
box.append(input, suggestionBox, $('<div>').append(confirmBtn, skipBtn));
overlay.append(box);
$('body').append(overlay);
// Autocomplete search (opensearch)
input.on('input', function () {
var query = (input.val() || '').replace(/^\s+|\s+$/g, '');
suggestionBox.empty();
if (!query || query.length < 2) { suggestionBox.hide(); return; }
api.get({
action: 'opensearch',
search: query,
limit: 8,
namespace: 0
}).done(function (data) {
var results = (data && data[1]) || [];
suggestionBox.empty();
if (results && results.length) {
suggestionBox.show();
for (var i = 0; i < results.length; i++) {
(function (page) {
$('<li>').text(page).css({ padding: '6px 10px', cursor: 'pointer' })
.hover(function () { $(this).css('background', '#f0f0f0'); }, function () { $(this).css('background', ''); })
.click(function () { input.val(page); suggestionBox.hide(); })
.appendTo(suggestionBox);
}(results[i]));
}
} else { suggestionBox.hide(); }
});
});
confirmBtn.on('click', function () {
var parentRaw = (input.val() || '').replace(/^\s+|\s+$/g, '');
if (!parentRaw) { alert('Please select or type a parent page name, or click "No Parent".'); return; }
// Normalize both parent and child title
var parent = normalizeTitleStr(parentRaw);
var child = normalizeTitleStr(title);
if (!parent) {
overlay.remove();
if (callback) callback(child, buildFinalEditUrl(child));
return;
}
var newTitle = parent + '/' + child;
// Build final edit URL keeping language prefix if present in initial editor URL
var langPrefix = detectLanguagePrefix();
var finalUrl;
if (langPrefix) {
finalUrl = window.location.protocol + '//' + window.location.host + '/' + langPrefix + '/' + encodeURIComponent(newTitle) + '?action=edit&veaction=edit';
if (autoCat) finalUrl += '&autocategory=' + encodeURIComponent(autoCat);
} else {
finalUrl = mw.util.getUrl(newTitle, { action: 'edit', veaction: 'edit' });
if (autoCat) finalUrl += '&autocategory=' + encodeURIComponent(autoCat);
}
overlay.remove();
if (callback) callback(newTitle, finalUrl);
});
skipBtn.on('click', function () {
overlay.remove();
// No parent, use original title
var child = normalizeTitleStr(title);
var final = buildFinalEditUrl(child);
if (callback) callback(child, final);
});
overlay.on('click', function (e) { if (e.target === overlay[0]) alert('Please choose a parent or click "No Parent".'); });
// Helper to build final edit URL for a title
function buildFinalEditUrl(cleanTitle) {
var langPrefix2 = detectLanguagePrefix();
var final2;
if (langPrefix2) {
final2 = window.location.protocol + '//' + window.location.host + '/' + langPrefix2 + '/' + encodeURIComponent(cleanTitle) + '?action=edit&veaction=edit';
if (autoCat) final2 += '&autocategory=' + encodeURIComponent(autoCat);
} else {
final2 = mw.util.getUrl(cleanTitle, { action: 'edit', veaction: 'edit' });
if (autoCat) final2 += '&autocategory=' + encodeURIComponent(autoCat);
}
return final2;
}
}
// Handle new-page flow: prompt only when creating a new page (wgNamespace 0, edit action, revision 0)
function handleNewPage() {
if (wgNamespace !== 0 || wgAction !== 'edit' || wgCurRevisionId !== 0) return;
if (skipParent && autoCat) {
mw.hook('ve.activationComplete').add(function () { injectCategory(autoCat); });
$(document).ready(function () { injectCategory(autoCat); });
} else {
askForParent(wgPageName, function (newTitle, finalUrl) {
// Redirect to finalUrl (which preserves /hi/ if needed)
if (finalUrl && window.location.href !== finalUrl) {
window.location.href = finalUrl;
}
});
}
}
if (wgAction === 'edit') handleNewPage();
mw.hook('ve.activationComplete').add(handleNewPage);
console.log('Complete Combined Parent + Category + Floating UI workflow loaded.');
}); // end loader
}());
