MediaWiki:Common.js: відмінності між версіями
Перейти до навігації
Перейти до пошуку
Немає опису редагування Мітка: Скасовано |
Немає опису редагування Мітка: Скасовано |
||
| Рядок 714: | Рядок 714: | ||
══════════════════════════════════════════════ */ | ══════════════════════════════════════════════ */ | ||
mw.loader.getScript('https://unpkg.com/vue@3/dist/vue.global.prod.js').then(function() { | mw.loader.getScript('https://unpkg.com/vue@3/dist/vue.global.prod.js').then(function() { | ||
| Рядок 922: | Рядок 921: | ||
white-space: nowrap; | white-space: nowrap; | ||
} | } | ||
mw.hook('wikipage.content').add(function() { | |||
// Знаходимо місце для вставки (праворуч від табуляції) | |||
var header = document.querySelector('#mw-head') || document.querySelector('.vector-header-container'); | |||
if (header && !document.getElementById('vue-search')) { | |||
// Створюємо контейнер | |||
var searchDiv = document.createElement('div'); | |||
searchDiv.id = 'vue-search'; | |||
searchDiv.style.cssText = 'position: absolute; top: 12px; right: 20px; z-index: 100;'; | |||
header.appendChild(searchDiv); | |||
} | |||
}); | |||
Версія за 15:47, 18 лютого 2026
$(function() {
$('.category-card').each(function() {
var $card = $(this);
var href = $card.attr('data-href');
if (href) {
$card.css('cursor', 'pointer');
$card.on('click', function(e) {
if ($(e.target).closest('a').length === 0) {
window.location.href = href;
}
});
$card.hover(
function() { $card.addClass('card-hover'); },
function() { $card.removeClass('card-hover'); }
);
}
});
});
/* ── Випадкові статті на головній сторінці ── */
/* ══════════════════════════════════════════════
Vue-додаток для сторінки "Викладачі"
Підключає Vue 3 через CDN і монтує на #vue-teachers
══════════════════════════════════════════════ */
mw.hook('wikipage.content').add(function() {
var mountEl = document.getElementById('vue-teachers');
if (!mountEl) return;
// Завантажуємо Vue 3 з CDN
mw.loader.getScript('https://unpkg.com/vue@3/dist/vue.global.prod.js').then(function() {
var apiBase = mw.config.get('wgScriptPath') + '/api.php';
/* ── Парсер інфобоксу ── */
function parseInfobox(wikitext) {
var result = { title: '', occupation: '', faculty: '', image: '' };
if (!wikitext) return result;
var titleMatch = wikitext.match(/\|\s*title\s*=\s*([^\|\n\}]+)/i);
if (titleMatch) result.title = titleMatch[1].trim();
var occMatch = wikitext.match(/\|\s*occupation\s*=\s*([^\|\n\}]+)/i);
if (occMatch) result.occupation = occMatch[1].trim();
var imgMatch = wikitext.match(/\|\s*image\s*=\s*([^\|\n\}]+)/i);
if (imgMatch) result.image = imgMatch[1].trim();
// Факультет з поля title
if (result.title.toLowerCase().includes('схід') || result.title.toLowerCase().includes('слов')) {
result.faculty = 'Факультет східної і слов\'янської філології';
} else if (result.title.toLowerCase().includes('філолог')) {
result.faculty = 'Філологічний факультет';
} else if (result.title.toLowerCase().includes('географ') || result.title.toLowerCase().includes('туризм')) {
result.faculty = 'Інший факультет';
} else {
result.faculty = 'Інший факультет';
}
return result;
}
/* ── Отримати посаду коротко ── */
function getPosition(title) {
if (!title) return 'Викладач';
var t = title.toLowerCase();
if (t.includes('професор')) return 'Професор';
if (t.includes('доцент')) return 'Доцент';
if (t.includes('викладач')) return 'Викладач';
return 'Інше';
}
var app = Vue.createApp({
data() {
return {
teachers: [],
loading: true,
activeFilter: 'Всі',
filters: ['Всі', 'Професор', 'Доцент', 'Викладач'],
preview: null, // об'єкт викладача для превью
previewX: 0, // позиція popup по X
previewY: 0, // позиція popup по Y
previewTimer: null, // таймер затримки
};
},
computed: {
filteredTeachers() {
var vm = this;
var result = this.teachers.filter(function(t) {
var matchFilter = vm.activeFilter === 'Всі' || t.position === vm.activeFilter;
return matchFilter;
});
result = result.slice().sort(function(a, b) {
return a.fullName.localeCompare(b.fullName, 'uk');
});
return result;
}
},
mounted() {
this.loadTeachers();
},
methods: {
showPreview(teacher, event) {
var vm = this;
clearTimeout(vm.previewTimer);
var target = event.currentTarget || event.target;
var rect = target.getBoundingClientRect();
var scrollY = window.scrollY || window.pageYOffset;
var scrollX = window.scrollX || window.pageXOffset;
vm.previewTimer = setTimeout(function() {
// Показуємо зліва або справа залежно від позиції
var spaceRight = window.innerWidth - rect.right;
if (spaceRight > 280) {
vm.previewX = rect.right + scrollX + 12;
} else {
vm.previewX = rect.left + scrollX - 272;
}
vm.previewY = rect.top + scrollY;
vm.preview = teacher;
}, 250);
},
hidePreview() {
clearTimeout(this.previewTimer);
this.previewTimer = setTimeout(() => {
this.preview = null;
}, 150);
},
keepPreview() {
clearTimeout(this.previewTimer);
},
async loadTeachers() {
this.loading = true;
try {
// Крок 1: всі сторінки з категорії Викладачі
var catResp = await fetch(
apiBase + '?action=query&list=categorymembers&cmtitle=Категорія:Викладачі' +
'&cmlimit=50&cmnamespace=0&format=json'
);
var catData = await catResp.json();
var members = catData.query.categorymembers;
if (!members || members.length === 0) {
this.loading = false;
return;
}
var titles = members.map(function(m) { return m.title; }).join('|');
// Крок 2: вміст статей
var pageResp = await fetch(
apiBase + '?action=query&titles=' + encodeURIComponent(titles) +
'&prop=revisions&rvprop=content&format=json'
);
var pageData = await pageResp.json();
var pages = Object.values(pageData.query.pages);
// Крок 3: для кожної статті отримати зображення
var teacherPromises = pages.map(async function(page) {
var content = (page.revisions && page.revisions[0]) ? (page.revisions[0]['*'] || '') : '';
var info = parseInfobox(content);
var imgSrc = null;
if (info.image) {
try {
var imgResp = await fetch(
apiBase + '?action=query&titles=File:' + encodeURIComponent(info.image) +
'&prop=imageinfo&iiprop=url&iiurlwidth=200&format=json'
);
var imgData = await imgResp.json();
var imgPages = Object.values(imgData.query.pages);
if (imgPages[0] && imgPages[0].imageinfo && imgPages[0].imageinfo[0]) {
imgSrc = imgPages[0].imageinfo[0].thumburl || imgPages[0].imageinfo[0].url;
}
} catch(e) {}
}
var pageUrl = mw.config.get('wgArticlePath').replace(
'$1', encodeURIComponent(page.title.replace(/ /g, '_'))
);
return {
fullName: page.title,
title: info.title,
occupation: info.occupation,
faculty: info.faculty,
position: getPosition(info.title),
imgSrc: imgSrc,
pageUrl: pageUrl,
};
});
this.teachers = await Promise.all(teacherPromises);
} catch(e) {
console.error('[Vue Teachers] error:', e);
}
this.loading = false;
}
},
template: `
<div class="vt-app">
<div class="vt-layout">
<!-- Ліва частина: лічильник + картки -->
<div class="vt-main">
<div class="vt-count" v-if="!loading">
Знайдено: <strong>{{ filteredTeachers.length }}</strong> з {{ teachers.length }}
</div>
<div class="vt-loading" v-if="loading">
<div class="vt-spinner"></div>
<span>Завантаження викладачів...</span>
</div>
<div class="vt-empty" v-else-if="!loading && filteredTeachers.length === 0">
<div class="vt-empty-icon">🔍</div>
<p>Нікого не знайдено</p>
<button class="vt-reset-btn" @click="activeFilter = 'Всі'">Скинути фільтри</button>
</div>
<div class="vt-grid" v-else>
<a
v-for="t in filteredTeachers"
:key="t.fullName"
:href="t.pageUrl"
class="vt-card"
@mouseenter="showPreview(t, $event)"
@mouseleave="hidePreview"
>
<div class="vt-card-img-wrap">
<img v-if="t.imgSrc" :src="t.imgSrc" :alt="t.fullName" class="vt-card-img" />
<div v-else class="vt-card-img-placeholder">{{ t.fullName.charAt(0) }}</div>
</div>
<div class="vt-card-body">
<div class="vt-card-position" :class="'pos-' + t.position.toLowerCase()">{{ t.position }}</div>
<div class="vt-card-name">{{ t.fullName }}</div>
<div class="vt-card-occupation" v-if="t.occupation">{{ t.occupation }}</div>
<div class="vt-card-title" v-if="t.title">{{ t.title }}</div>
</div>
</a>
</div>
</div>
<!-- Права панель: фільтри -->
<div class="vt-sidebar">
<div class="vt-sidebar-title">Фільтр</div>
<div class="vt-filters">
<button
v-for="f in filters"
:key="f"
class="vt-filter-btn"
:class="{ active: activeFilter === f }"
@click="activeFilter = f"
>{{ f }}</button>
</div>
</div>
</div>
<!-- Превью попап -->
<teleport to="body">
<a
v-if="preview"
:href="preview.pageUrl"
class="vt-preview"
:style="{ top: previewY + 'px', left: previewX + 'px' }"
@mouseenter="keepPreview"
@mouseleave="hidePreview"
>
<div class="vt-preview-top">
<img v-if="preview.imgSrc" :src="preview.imgSrc" class="vt-preview-img" :alt="preview.fullName" />
<div v-else class="vt-preview-img-placeholder">{{ preview.fullName.charAt(0) }}</div>
<div class="vt-preview-info">
<div class="vt-preview-position" :class="'pos-' + preview.position.toLowerCase()">{{ preview.position }}</div>
<div class="vt-preview-name">{{ preview.fullName }}</div>
</div>
</div>
<div class="vt-preview-divider"></div>
<div class="vt-preview-row" v-if="preview.occupation">
<span class="vt-preview-lbl">Спеціальність</span>
<span class="vt-preview-val">{{ preview.occupation }}</span>
</div>
<div class="vt-preview-row" v-if="preview.title">
<span class="vt-preview-lbl">Посада</span>
<span class="vt-preview-val">{{ preview.title }}</span>
</div>
</a>
</teleport>
</div>
`
});
app.mount('#vue-teachers');
});
});
/* Витягнути назву зображення з вікі-тексту */
function extractImageName(wikitext) {
if (!wikitext) return null;
// 1. Шукаємо в Infobox: | image = Файл.jpg
var infoboxImg = wikitext.match(/\|\s*image\s*=\s*([^\|\n\}]+)/i);
if (infoboxImg) {
var name = infoboxImg[1].trim();
if (name && name.length > 0) return name;
}
// 2. Шукаємо [[Файл:Назва.jpg|...]] або [[File:...]]
var fileMatch = wikitext.match(/\[\[(?:Файл|File|Зображення|Image):([^\|\]]+)/i);
if (fileMatch) {
return fileMatch[1].trim();
}
return null;
}
/* Витягнути перший змістовний абзац */
function extractDescription(wikitext) {
if (!wikitext) return '';
// Прибрати інфобокс {{...}} (може бути багаторядковим)
var text = wikitext;
var depth = 0;
var infoboxEnd = -1;
for (var i = 0; i < text.length; i++) {
if (text[i] === '{') depth++;
else if (text[i] === '}') {
depth--;
if (depth === 0) { infoboxEnd = i + 1; break; }
}
}
if (infoboxEnd > 0) text = text.substring(infoboxEnd);
// Прибрати [[Файл:...]] блоки
text = text.replace(/\[\[(?:Файл|File|Зображення|Image):[^\]]*\]\]/gi, '');
// Прибрати wikitable {| ... |}
text = text.replace(/\{\|[\s\S]*?\|\}/g, '');
// Прибрати шаблони {{...}}
text = text.replace(/\{\{[^}]*\}\}/g, '');
// Прибрати заголовки == ... ==
text = text.replace(/={2,6}[^=\n]+=+/g, '');
// Прибрати вікі-посилання — залишити текст
text = text.replace(/\[\[(?:[^\|\]]*\|)?([^\]]+)\]\]/g, '$1');
// Прибрати зовнішні посилання [url текст]
text = text.replace(/\[[^\s\]]+\s+([^\]]+)\]/g, '$1');
text = text.replace(/\[[^\]]+\]/g, '');
// Прибрати жирний/курсив
text = text.replace(/'{2,3}/g, '');
// Прибрати HTML теги
text = text.replace(/<[^>]+>/g, '');
// Прибрати рядки що починаються з * # : ;
text = text.replace(/^[\*#:;].*/gm, '');
// Прибрати порожні рядки і зайві пробіли
var lines = text.split('\n').map(function(l) { return l.trim(); }).filter(function(l) { return l.length > 20; });
// Взяти перший змістовний рядок
if (lines.length > 0) {
var result = lines[0].substring(0, 160);
if (lines[0].length > 160) result += '…';
return result;
}
return '';
}
function loadRandomArticles() {
var list = document.getElementById('random-articles-list');
if (!list) return;
list.innerHTML = '<div class="random-articles-loading">Завантаження...</div>';
var apiBase = mw.config.get('wgScriptPath') + '/api.php';
// Сторінки які не повинні з'являтись у випадкових статтях
var excludedPages = ['Головна сторінка', 'Структурні підрозділи', 'Викладачі'];
fetch(apiBase + '?action=query&list=random&rnnamespace=0&rnlimit=10&format=json')
.then(function(r) { return r.json(); })
.then(function(data) {
var pages = data.query.random.filter(function(p) {
return excludedPages.indexOf(p.title) === -1;
}).slice(0, 3);
var titles = pages.map(function(p) { return p.title; }).join('|');
return fetch(
apiBase +
'?action=query' +
'&titles=' + encodeURIComponent(titles) +
'&prop=revisions' +
'&rvprop=content' +
'&format=json'
);
})
.then(function(r) { return r.json(); })
.then(function(data) {
var pages = Object.values(data.query.pages);
list.innerHTML = '';
var promises = pages.map(function(page) {
var title = page.title;
var pageUrl = mw.config.get('wgArticlePath').replace(
'$1', encodeURIComponent(title.replace(/ /g, '_'))
);
var content = '';
if (page.revisions && page.revisions[0]) {
content = page.revisions[0]['*'] || '';
}
var excerpt = extractDescription(content);
if (!excerpt) excerpt = 'Немає опису.';
var imgName = extractImageName(content);
if (imgName) {
var fileTitle = imgName.match(/^(Файл|File|Image|Зображення):/i)
? imgName
: 'File:' + imgName;
return fetch(
apiBase +
'?action=query' +
'&titles=' + encodeURIComponent(fileTitle) +
'&prop=imageinfo' +
'&iiprop=url' +
'&iiurlwidth=120' +
'&format=json'
)
.then(function(r) { return r.json(); })
.then(function(imgData) {
var imgPages = Object.values(imgData.query.pages);
var imgSrc = null;
if (imgPages[0] && imgPages[0].imageinfo && imgPages[0].imageinfo[0]) {
imgSrc = imgPages[0].imageinfo[0].thumburl || imgPages[0].imageinfo[0].url;
}
return { title: title, excerpt: excerpt, pageUrl: pageUrl, imgSrc: imgSrc };
})
.catch(function() {
return { title: title, excerpt: excerpt, pageUrl: pageUrl, imgSrc: null };
});
}
return Promise.resolve({ title: title, excerpt: excerpt, pageUrl: pageUrl, imgSrc: null });
});
return Promise.all(promises);
})
.then(function(results) {
var list2 = document.getElementById('random-articles-list');
if (!list2) return;
list2.innerHTML = '';
results.forEach(function(item) {
var thumbHtml = item.imgSrc
? '<img class="random-article-thumb" src="' + item.imgSrc + '" alt="">'
: '<div class="random-article-thumb-placeholder">📄</div>';
var card = document.createElement('a');
card.href = item.pageUrl;
card.className = 'random-article-card';
card.innerHTML =
thumbHtml +
'<div class="random-article-info">' +
'<div class="random-article-title">' + mw.html.escape(item.title) + '</div>' +
'<div class="random-article-excerpt">' + mw.html.escape(item.excerpt) + '</div>' +
'</div>';
list2.appendChild(card);
});
})
.catch(function(err) {
var list3 = document.getElementById('random-articles-list');
if (list3) list3.innerHTML = '<div class="random-articles-loading">Не вдалося завантажити статті.</div>';
console.error('[RA] error:', err);
});
}
/* Запуск */
mw.hook('wikipage.content').add(function() {
var panel = document.getElementById('random-articles-panel');
if (!panel) return;
loadRandomArticles();
var btn = document.getElementById('random-articles-refresh');
if (btn) {
btn.addEventListener('click', function() {
loadRandomArticles();
});
}
});
/* ══════════════════════════════════════════════
ГОЛОВНА СТОРІНКА: покращення
══════════════════════════════════════════════ */
/* ── 2. Анімація чисел статистики ── */
function animateNumber(element, target) {
element.classList.add('animating');
var current = 0;
var increment = target / 60; // 60 кадрів
var timer = setInterval(function() {
current += increment;
if (current >= target) {
current = target;
clearInterval(timer);
setTimeout(function() { element.classList.remove('animating'); }, 100);
}
element.textContent = Math.floor(current);
}, 16); // ~60 FPS
}
mw.hook('wikipage.content').add(function() {
// Запускаємо анімацію тільки на головній сторінці
if (mw.config.get('wgPageName') !== 'Головна_сторінка') return;
var statsNumbers = document.querySelectorAll('.stats-panel-number');
var animated = false;
function checkAndAnimate() {
if (animated) return;
var statsPanel = document.querySelector('.stats-panel');
if (!statsPanel) return;
var rect = statsPanel.getBoundingClientRect();
if (rect.top < window.innerHeight && rect.bottom > 0) {
animated = true;
statsNumbers.forEach(function(el) {
var text = el.textContent.trim();
var num = parseInt(text.replace(/[^\d]/g, ''), 10);
if (!isNaN(num) && num > 0) {
el.textContent = '0';
setTimeout(function() { animateNumber(el, num); }, 200);
}
});
}
}
window.addEventListener('scroll', checkAndAnimate);
checkAndAnimate();
});
/* ── 4. Сортування карточок за прізвищем ── */
mw.hook('wikipage.content').add(function() {
document.querySelectorAll('div[style*="grid-template-columns"]').forEach(function(grid) {
var cards = Array.from(grid.children);
if (cards.length < 2) return;
cards.sort(function(a, b) {
var aLink = a.querySelector('div[style*="flex-grow"] a');
var bLink = b.querySelector('div[style*="flex-grow"] a');
if (!aLink || !bLink) return 0;
var aSurname = aLink.textContent.trim().split(' ')[0];
var bSurname = bLink.textContent.trim().split(' ')[0];
return aSurname.localeCompare(bSurname, 'uk');
});
cards.forEach(function(card) {
grid.appendChild(card);
});
});
});
/* ══════════════════════════════════════════════
MODERN UI: Particles.js фон + прогрес скролла
══════════════════════════════════════════════ */
/* ── 1. Прогрес скролла ── */
mw.hook('wikipage.content').add(function() {
if (mw.config.get('wgPageName') !== 'Головна_сторінка') return;
// Створюємо індикатор
var progressBar = document.createElement('div');
progressBar.className = 'scroll-progress';
document.body.appendChild(progressBar);
function updateProgress() {
var winScroll = document.documentElement.scrollTop || document.body.scrollTop;
var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
var scrolled = (winScroll / height) * 100;
progressBar.style.width = scrolled + '%';
}
window.addEventListener('scroll', updateProgress);
updateProgress();
});
/* ── 2. Particles.js canvas фон ── */
mw.hook('wikipage.content').add(function() {
if (mw.config.get('wgPageName') !== 'Головна_сторінка') return;
var welcomeWrapper = document.querySelector('.welcome-wrapper');
if (!welcomeWrapper) return;
// Створюємо canvas
var canvas = document.createElement('canvas');
canvas.className = 'particles-canvas';
canvas.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:0;';
// Gradient mask для плавного переходу по краях
canvas.style.webkitMaskImage = 'linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,1) 10%, rgba(0,0,0,1) 90%, rgba(0,0,0,0) 100%), linear-gradient(to right, rgba(0,0,0,0) 0%, rgba(0,0,0,1) 10%, rgba(0,0,0,1) 90%, rgba(0,0,0,0) 100%)';
canvas.style.maskImage = 'linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,1) 10%, rgba(0,0,0,1) 90%, rgba(0,0,0,0) 100%), linear-gradient(to right, rgba(0,0,0,0) 0%, rgba(0,0,0,1) 10%, rgba(0,0,0,1) 90%, rgba(0,0,0,0) 100%)';
canvas.style.webkitMaskComposite = 'source-in';
canvas.style.maskComposite = 'intersect';
welcomeWrapper.style.position = 'relative';
welcomeWrapper.insertBefore(canvas, welcomeWrapper.firstChild);
var ctx = canvas.getContext('2d');
canvas.width = welcomeWrapper.offsetWidth;
canvas.height = welcomeWrapper.offsetHeight;
var particles = [];
var particleCount = 40;
var mouse = { x: null, y: null, radius: 100 };
// Частинки
function Particle() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.vx = (Math.random() - 0.5) * 0.5;
this.vy = (Math.random() - 0.5) * 0.5;
this.radius = Math.random() * 2 + 1;
}
Particle.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(255, 215, 0, 0.6)';
ctx.fill();
};
Particle.prototype.update = function() {
if (this.x > canvas.width || this.x < 0) this.vx = -this.vx;
if (this.y > canvas.height || this.y < 0) this.vy = -this.vy;
this.x += this.vx;
this.y += this.vy;
this.draw();
};
// Ініціалізація
for (var i = 0; i < particleCount; i++) {
particles.push(new Particle());
}
// Анімація
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particles.length; i++) {
particles[i].update();
// З'єднання лініями
for (var j = i + 1; j < particles.length; j++) {
var dx = particles[i].x - particles[j].x;
var dy = particles[i].y - particles[j].y;
var distance = Math.sqrt(dx * dx + dy * dy);
if (distance < 120) {
ctx.beginPath();
ctx.strokeStyle = 'rgba(255, 215, 0, ' + (1 - distance / 120) * 0.3 + ')';
ctx.lineWidth = 1;
ctx.moveTo(particles[i].x, particles[i].y);
ctx.lineTo(particles[j].x, particles[j].y);
ctx.stroke();
}
}
}
requestAnimationFrame(animate);
}
animate();
// Resize
window.addEventListener('resize', function() {
canvas.width = welcomeWrapper.offsetWidth;
canvas.height = welcomeWrapper.offsetHeight;
});
});
/* ══════════════════════════════════════════════
VUE ПОШУК - підключення та стилі
══════════════════════════════════════════════ */
mw.loader.getScript('https://unpkg.com/vue@3/dist/vue.global.prod.js').then(function() {
const { createApp } = Vue;
createApp({
data() {
return {
query: '',
results: [],
showResults: false,
loading: false
};
},
watch: {
query(newQuery) {
if (newQuery.length < 2) {
this.results = [];
this.showResults = false;
return;
}
this.searchPages();
}
},
methods: {
searchPages() {
clearTimeout(this.searchTimer);
this.loading = true;
this.searchTimer = setTimeout(() => {
var apiUrl = mw.config.get('wgScriptPath') + '/api.php';
fetch(apiUrl + '?action=opensearch&search=' + encodeURIComponent(this.query) + '&limit=8&format=json')
.then(r => r.json())
.then(data => {
this.results = data[1].map((title, i) => ({
title: title,
url: data[3][i]
}));
this.showResults = true;
this.loading = false;
})
.catch(() => {
this.loading = false;
});
}, 300);
},
selectResult(result) {
window.location.href = result.url;
},
performSearch() {
if (this.query.trim()) {
window.location.href = mw.config.get('wgArticlePath').replace('$1', 'Special:Search?search=' + encodeURIComponent(this.query));
}
},
hideResults() {
setTimeout(() => { this.showResults = false; }, 200);
}
},
template: `
<div class="vue-search-container">
<div class="vue-search-wrapper">
<input
type="text"
v-model="query"
@focus="showResults = results.length > 0"
@blur="hideResults"
@keyup.enter="performSearch"
placeholder="Пошук у вікі..."
class="vue-search-input"
/>
<button @click="performSearch" class="vue-search-btn">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="11" cy="11" r="8"/>
<path d="m21 21-4.35-4.35"/>
</svg>
</button>
</div>
<div v-if="showResults && results.length > 0" class="vue-search-results">
<div
v-for="result in results"
:key="result.title"
@mousedown="selectResult(result)"
class="vue-search-result-item"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
<polyline points="14 2 14 8 20 8"/>
</svg>
<span>{{ result.title }}</span>
</div>
</div>
<div v-if="loading" class="vue-search-loading">Пошук...</div>
</div>
`
}).mount('#vue-search');
});
// CSS для Vue пошуку
.vue-search-container {
position: relative;
width: 320px;
}
.vue-search-wrapper {
display: flex;
gap: 6px;
background: rgba(255, 255, 255, 0.6);
backdrop-filter: blur(10px);
border: 1px solid rgba(0, 61, 130, 0.12);
border-radius: 12px;
padding: 6px;
transition: all 0.2s ease;
}
.vue-search-wrapper:focus-within {
border-color: rgba(0, 61, 130, 0.25);
box-shadow: 0 4px 16px rgba(0, 61, 130, 0.12);
}
.vue-search-input {
flex: 1;
border: none;
background: transparent;
font-family: system-ui, -apple-system, sans-serif;
font-size: 14px;
color: #333;
padding: 8px 12px;
outline: none;
}
.vue-search-input::placeholder {
color: #999;
}
.vue-search-btn {
background: #003d82;
border: none;
border-radius: 8px;
padding: 8px 14px;
color: white;
cursor: pointer;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
}
.vue-search-btn:hover {
background: #002d62;
transform: scale(1.05);
}
.vue-search-results {
position: absolute;
top: 100%;
left: 0;
right: 0;
margin-top: 8px;
background: white;
border: 1px solid rgba(0, 61, 130, 0.12);
border-radius: 12px;
box-shadow: 0 8px 24px rgba(0, 61, 130, 0.15);
overflow: hidden;
z-index: 10000;
backdrop-filter: blur(20px);
}
.vue-search-result-item {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 14px;
cursor: pointer;
transition: all 0.15s;
font-family: system-ui, -apple-system, sans-serif;
font-size: 14px;
color: #333;
border-bottom: 1px solid rgba(0, 61, 130, 0.06);
}
.vue-search-result-item:last-child {
border-bottom: none;
}
.vue-search-result-item:hover {
background: rgba(0, 61, 130, 0.06);
color: #003d82;
}
.vue-search-result-item svg {
flex-shrink: 0;
color: #0645ad;
}
.vue-search-loading {
position: absolute;
top: 100%;
left: 50%;
transform: translateX(-50%);
margin-top: 8px;
padding: 8px 16px;
background: white;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 61, 130, 0.1);
font-size: 13px;
color: #666;
white-space: nowrap;
}
mw.hook('wikipage.content').add(function() {
// Знаходимо місце для вставки (праворуч від табуляції)
var header = document.querySelector('#mw-head') || document.querySelector('.vector-header-container');
if (header && !document.getElementById('vue-search')) {
// Створюємо контейнер
var searchDiv = document.createElement('div');
searchDiv.id = 'vue-search';
searchDiv.style.cssText = 'position: absolute; top: 12px; right: 20px; z-index: 100;';
header.appendChild(searchDiv);
}
});