(() => { const specialty = document.querySelector('#council-specialty'); const branch = document.querySelector('#council-branch'); specialty?.addEventListener('change', () => { const names = JSON.parse(specialty.selectedOptions[0].dataset.branches); const previous = branch.value; branch.replaceChildren(...names.map(name => new Option(name[0].toUpperCase() + name.slice(1), name))); if (names.includes(previous)) branch.value = previous; }); const dialog = document.querySelector('[data-council-dialog]'); const form = dialog?.querySelector('[data-edit-form]'); const autoSpecialties = form?.querySelector('[data-specialty-auto]'); const specialtyCheckboxes = form ? Array.from(form.querySelectorAll('[name="specialty_codes"]')) : []; autoSpecialties?.addEventListener('change', () => { specialtyCheckboxes.forEach(input => { input.disabled = autoSpecialties.checked; }); }); let selected; let trigger; let saving = false; const openKey = 'miem.council.openCandidates'; try { const opened = JSON.parse(sessionStorage.getItem(openKey) || '[]'); document.querySelectorAll('[data-employee-id]').forEach(node => { if (opened.includes(node.dataset.employeeId)) node.open = true; }); sessionStorage.removeItem(openKey); } catch (_error) { /* Storage is optional. */ } function activate(article) { document.querySelectorAll('.council__article--active').forEach(node => { node.classList.remove('council__article--active'); }); article.classList.add('council__article--active'); } function positionTooltip(button, tip) { const rect = button.getBoundingClientRect(); tip.style.left = `${Math.max(12, Math.min(rect.left, innerWidth - tip.offsetWidth - 12))}px`; tip.style.top = `${Math.max(12, rect.bottom + tip.offsetHeight + 8 < innerHeight ? rect.bottom + 8 : rect.top - tip.offsetHeight - 8)}px`; } function repositionTooltips() { document.querySelectorAll('[data-warning]').forEach(warning => { const tip = warning.querySelector('[role="tooltip"]'); if (!tip.hidden) positionTooltip(warning.querySelector('button'), tip); }); } function setupArticles(root) { root.querySelectorAll('[data-council-article]').forEach(article => { article.addEventListener('click', event => { if (!event.target.closest('a, button')) activate(article); }); article.addEventListener('keydown', event => { if (event.target === article && ['Enter', ' '].includes(event.key)) { event.preventDefault(); activate(article); article.querySelector('[data-council-edit]').focus(); } }); }); root.querySelectorAll('[data-council-edit]').forEach(button => { button.addEventListener('click', () => { trigger = button; selected = JSON.parse(button.dataset.article); if (form) { form.elements.title.value = selected.title; form.elements.journal.value = selected.journal; form.elements.quartile.value = selected.quartile; autoSpecialties.checked = !selected.manual_specialties; form.querySelector("[data-edit-specialties]").open = selected.manual_specialties; specialtyCheckboxes.forEach(input => { input.checked = selected.specialty_codes.includes(input.value); input.disabled = autoSpecialties.checked; }); form.elements.quartile.disabled = selected.year === null; form.querySelector('[data-edit-error]').hidden = true; form.querySelector('[data-edit-note]').textContent = selected.year === null ? 'Год публикации не указан или неоднозначен. Можно изменить название статьи и журнал; квартиль недоступен.' : `Изменение квартиля применяется ко всем статьям выбранного журнала за ${selected.year} год. Проверьте квартиль при смене журнала.`; } dialog.showModal(); }); }); root.querySelectorAll('[data-warning]').forEach(warning => { const button = warning.querySelector('button'); const tip = warning.querySelector('[role="tooltip"]'); let pinned = false; function show(visible) { tip.hidden = !visible; button.setAttribute('aria-expanded', String(visible)); if (!visible) return; positionTooltip(button, tip); } warning.addEventListener('mouseenter', () => show(true)); warning.addEventListener('mouseleave', () => { if (!pinned && document.activeElement !== button) show(false); }); button.addEventListener('focus', () => show(true)); button.addEventListener('blur', () => { pinned = false; show(false); }); button.addEventListener('click', () => { pinned = !pinned; show(pinned); }); warning.addEventListener('council-tooltip-close', () => { pinned = false; show(false); }); }); } setupArticles(document); document.addEventListener('keydown', event => { if (event.key !== 'Escape') return; document.querySelectorAll('[data-warning] button[aria-expanded="true"]').forEach(button => { button.closest('[data-warning]').dispatchEvent(new Event('council-tooltip-close')); }); }); async function loadArticles(details) { if (details.dataset.loaded || details.dataset.loading) return; const panel = details.querySelector('[data-council-content]'); const status = panel.querySelector('[data-articles-status]'); const content = panel.querySelector('[data-articles-content]'); details.dataset.loading = '1'; panel.setAttribute('aria-busy', 'true'); status.textContent = 'Загружаем публикации…'; try { const response = await fetch(panel.dataset.articlesUrl, {credentials: 'same-origin', signal: AbortSignal.timeout(15000)}); if (!response.ok) throw new Error('Не удалось загрузить публикации. Попробуйте ещё раз.'); content.innerHTML = await response.text(); setupArticles(content); details.dataset.loaded = '1'; status.textContent = 'Публикации загружены'; status.classList.add('council__load-status--done'); } catch (_error) { status.textContent = 'Не удалось загрузить публикации. Проверьте подключение и повторите загрузку.'; const retry = document.createElement('button'); retry.type = 'button'; retry.className = 'button button--secondary'; retry.textContent = 'Повторить загрузку публикаций'; retry.addEventListener('click', () => loadArticles(details)); content.replaceChildren(retry); } finally { delete details.dataset.loading; panel.removeAttribute('aria-busy'); } } document.querySelectorAll('[data-employee-id]').forEach(details => { details.addEventListener('toggle', () => { if (details.open) loadArticles(details); }); if (details.open) loadArticles(details); }); document.addEventListener('scroll', event => { if (event.target instanceof Element && event.target.closest('.council__tooltip')) return; repositionTooltips(); }, true); window.addEventListener('resize', repositionTooltips); if (!dialog) return; dialog.querySelectorAll('[data-edit-close]').forEach(button => { button.addEventListener('click', () => { if (!saving) dialog.close(); }); }); dialog.addEventListener('cancel', event => { if (saving) event.preventDefault(); }); dialog.addEventListener('click', event => { if (event.target === dialog && !saving) dialog.close(); }); dialog.addEventListener('close', () => trigger?.focus()); form?.addEventListener('submit', async event => { event.preventDefault(); if (saving) return; const error = form.querySelector('[data-edit-error]'); const submit = form.querySelector('[type="submit"]'); const payload = { employee_id: selected.employee_id, edit_key: selected.edit_key, revision: selected.revision, title: form.elements.title.value.trim(), journal: form.elements.journal.value.trim(), quartile: selected.year === null ? '' : form.elements.quartile.value, specialty_codes: autoSpecialties.checked ? null : specialtyCheckboxes.filter(input => input.checked).map(input => input.value), }; saving = true; submit.disabled = true; submit.textContent = 'Сохраняем…'; form.setAttribute('aria-busy', 'true'); error.hidden = true; try { const response = await fetch('/admin/council/publications', { method: 'POST', credentials: 'same-origin', headers: {'Content-Type': 'application/json', 'X-Council-Edit': '1'}, body: JSON.stringify(payload), signal: AbortSignal.timeout(15000), }); if (!response.ok) { const data = await response.json(); throw new Error(typeof data.detail === 'string' ? data.detail : 'Проверьте название статьи, журнал и квартиль.'); } try { sessionStorage.setItem(openKey, JSON.stringify(Array.from(document.querySelectorAll('[data-employee-id][open]')).map(node => node.dataset.employeeId))); } catch (_error) { /* Storage is optional. */ } window.location.reload(); } catch (failure) { error.textContent = failure.name === 'TimeoutError' ? 'Не получен ответ сервера. Обновите страницу, чтобы проверить сохранение.' : failure.message === 'Failed to fetch' ? 'Нет связи с сервером. Проверьте подключение и попробуйте ещё раз.' : failure.message; error.hidden = false; } finally { saving = false; submit.disabled = false; submit.textContent = 'Сохранить'; form.removeAttribute('aria-busy'); } }); })();