students: модалка профиля ученика с вкладками и разделами

Переписан #profileDataModal: вкладки (об ученике, фото и лица, контакты),
сетка строк 12 колонок с сохранением порядка, чипы тегов, счётчики символов
и процентные метры. Контракт с сервером не менялся — GET/PUT
/api/students/:id/profile по-прежнему принимает плоский объект профиля.

- Источник истины для массивов — pfState, а не DOM: pfRenderSkills и
  остальные перестраивают innerHTML списка целиком, поэтому сохранение
  фокуса при перерисовке не завязываем
- Запись в состояние только через data-pf="<kind>.<idx>.<field>",
  data-pf-kind обязан совпадать с ключом в pfState, проценты идут через
  pfInt() — иначе сервер вернёт 400 на нецелом числе
- pfValidate() проверяет проценты и href контактов до сохранения
- pfE() экранирует и кавычки: esc() из admin.js трогает только текст,
  в value="…" без него атрибут рвётся
- Dirty-состояние через pfBaseline/pfMarkDirty; closeProfileData()
  возвращает false, если пользователь отказался закрывать форму —
  вызовы оборачивают в if (closeProfileData())
- Поле #pfStatus занято статусом ученика, подпись в футере — #pfSaveHint
- CSS-блок /* --- Профиль ученика (#profileDataModal) --- */ в admin.css
- Раздел 3m в AGENTS.md

Синтаксис проверен (node --check public/js/students.js), в браузере не
тестировалось.
This commit is contained in:
dev
2026-10-10 14:42:54 +03:00
parent 8479fbb68d
commit 22466629c8
4 changed files with 648 additions and 142 deletions
+71
View File
@@ -290,6 +290,77 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;b
.face-stage .face-box{pointer-events:auto}
.face-empty{color:var(--muted);font-size:.78rem}
.face-ref-profile-btn[hidden]{display:none}
/* --- Профиль ученика (#profileDataModal) --- */
.pf-modal{padding:0;max-width:960px;width:min(96vw,960px);max-height:92dvh;overflow:hidden}
.pf-form{display:flex;flex-direction:column;min-height:0;max-height:92dvh;gap:0}
.pf-head{display:flex;align-items:center;gap:14px;padding:18px 22px 14px;border-bottom:1px solid var(--border);flex-shrink:0}
.pf-head-avatar{width:46px;height:46px;border-radius:12px;overflow:hidden;background:var(--bg);border:1px solid var(--border);display:flex;align-items:center;justify-content:center;font-size:.9rem;font-weight:700;color:var(--muted);flex-shrink:0}
.pf-head-avatar img{width:100%;height:100%;object-fit:cover;display:block}
.pf-head-text{flex:1;min-width:0}
.pf-head-text h3{font-size:1rem;font-weight:700;margin:0 0 2px}
.pf-head-name{display:block;font-size:.86rem;color:var(--accent);font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.pf-tabs{display:flex;gap:4px;padding:10px 22px;border-bottom:1px solid var(--border);overflow-x:auto;scrollbar-width:none;flex-shrink:0}
.pf-tabs::-webkit-scrollbar{display:none}
.pf-tab{display:inline-flex;align-items:center;gap:7px;padding:8px 14px;border-radius:999px;border:1px solid transparent;background:none;color:var(--muted);font-size:.84rem;font-weight:600;cursor:pointer;white-space:nowrap;font-family:inherit;transition:all .15s}
.pf-tab svg{width:15px;height:15px}
.pf-tab:hover{color:var(--text);background:var(--bg)}
.pf-tab.is-active{color:var(--accent);background:rgba(37,99,235,.08);border-color:rgba(37,99,235,.2)}
.pf-tab-count{background:var(--border);color:var(--muted);border-radius:999px;padding:0 6px;font-size:.7rem;font-weight:700;line-height:1.5em}
.pf-tab.is-active .pf-tab-count{background:var(--accent);color:#fff}
.pf-tab-count:empty{display:none}
.pf-body{flex:1;min-height:0;overflow-y:auto;padding:20px 22px;display:flex;flex-direction:column}
.pf-pane{display:none;flex-direction:column;gap:16px}
.pf-pane.is-active{display:flex}
.pf-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px 16px}
.pf-grid .pf-full{grid-column:1/-1}
.pf-modal .settings-field label{display:flex;align-items:center;gap:8px}
@media(max-width:640px){.pf-grid{grid-template-columns:1fr}}
.pf-count{margin-left:auto;font-size:.74rem;font-weight:500;color:var(--muted)}
.pf-count.warn{color:#ef4444}
.pf-chips{display:flex;flex-wrap:wrap;gap:6px}
.pf-chips:empty{display:none}
.pf-chip{display:inline-flex;align-items:center;gap:6px;background:var(--bg);border:1px solid var(--border);border-radius:999px;padding:4px 6px 4px 12px;font-size:.78rem;font-weight:600;color:var(--text)}
.pf-chip button{background:none;border:none;color:var(--muted);cursor:pointer;font-size:.9rem;line-height:1;padding:0 3px;display:flex}
.pf-chip button:hover{color:#ef4444}
.pf-block-head{display:flex;align-items:center;justify-content:space-between;gap:12px;padding-bottom:10px;border-bottom:1px solid var(--border)}
.pf-block-head h4{margin:0;font-size:.92rem;font-weight:700}
.pf-block-head:not(:first-child){margin-top:8px}
.pf-add{display:inline-flex;align-items:center;gap:7px;background:var(--card);border:1px dashed var(--border);border-radius:10px;padding:8px 14px;font-size:.82rem;font-weight:600;color:var(--accent);cursor:pointer;font-family:inherit;transition:all .15s}
.pf-add:hover{border-color:var(--accent);background:rgba(37,99,235,.05)}
.pf-add svg{width:15px;height:15px}
.pf-list{display:flex;flex-direction:column;gap:10px}
.pf-list:empty::after{content:'Пока пусто';color:var(--muted);font-size:.84rem;padding:4px 2px}
.pf-row{display:grid;gap:10px;background:var(--bg);border:1px solid var(--border);border-radius:12px;padding:12px 54px 12px 12px;grid-template-columns:repeat(12,minmax(0,1fr));align-items:center;position:relative}
.pf-row:hover{border-color:rgba(37,99,235,.35)}
.pf-row-head{grid-column:span 12;font-size:.72rem;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.03em}
.pf-f{display:flex;flex-direction:column;gap:5px;min-width:0}
.pf-f > span{font-size:.74rem;font-weight:600;color:var(--muted)}
.pf-f input,.pf-f textarea,.pf-f select{background:var(--card);border:1px solid var(--border);color:var(--text);border-radius:9px;padding:8px 11px;font-size:.86rem;outline:none;font-family:inherit;width:100%;transition:border-color .15s,box-shadow .15s}
.pf-f textarea{min-height:64px;resize:vertical;line-height:1.5}
.pf-f input:focus,.pf-f textarea:focus,.pf-f select:focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(37,99,235,.12)}
.pf-f input.invalid,.pf-f textarea.invalid{border-color:#ef4444;box-shadow:0 0 0 3px rgba(239,68,68,.1)}
.pf-f input[type=number]{width:100%}
.pf-meter{height:6px;border-radius:999px;background:var(--border);overflow:hidden}
.pf-meter i{display:block;height:100%;background:var(--accent);border-radius:999px;transition:width .2s}
.pf-row-del{position:absolute;top:10px;right:10px;width:32px;height:32px;display:flex;align-items:center;justify-content:center}
.pf-row-del svg{width:15px;height:15px}
.pf-empty{color:var(--muted);font-size:.82rem}
.pf-row-wide{grid-column:span 12}
.pf-media{grid-column:span 2}
.pf-media-lg{grid-column:span 4}
.pf-mid{grid-column:span 3}
@media(max-width:820px){.pf-media,.pf-media-lg,.pf-mid{grid-column:span 12}}
.pf-err{grid-column:span 12;display:none;color:#ef4444;font-size:.76rem;font-weight:600}
.pf-row.is-invalid .pf-err{display:block}
.pf-actions{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
.pf-actions .hint{font-size:.8rem;color:var(--muted);line-height:1.45}
.pf-foot{display:flex;align-items:center;justify-content:space-between;gap:14px;padding:14px 22px;border-top:1px solid var(--border);background:var(--card);flex-shrink:0;flex-wrap:wrap}
.pf-status{font-size:.8rem;color:var(--muted);display:flex;align-items:center;gap:7px;min-height:1.2em}
.pf-status svg{width:14px;height:14px;flex-shrink:0}
.pf-status.dirty{color:#b45309;font-weight:600}
.pf-foot-btns{display:flex;gap:8px;margin-left:auto}
.pf-head .icon-btn{flex-shrink:0}
.btn-primary.ghost.spinning svg{animation:spin 1s linear infinite}
.p-faces{position:absolute;right:8px;top:8px;background:rgba(15,23,42,.72);color:#e2e8f0;font-size:.68rem;font-weight:700;padding:2px 7px;border-radius:999px;pointer-events:none;display:inline-flex;align-items:center;gap:4px}
.p-faces svg{width:12px;height:12px}
+444 -63
View File
@@ -245,21 +245,249 @@ async function exportStudentProfile(id) {
let profileDataId = null;
let profilePhotos = [];
let pfState = null;
let pfBaseline = '';
let pfActiveTab = 'general';
const PF_CONTACT_ICONS = ['mail', 'send', 'phone', 'github', 'globe', 'link', 'at-sign'];
function pfE(s) {
return esc(s === null || s === undefined ? '' : String(s)).replace(/"/g, '&quot;');
}
function pfBlankState() {
return { tags: [], contacts: [], skills: [], achievements: [], experience: [], education: [] };
}
function pfStr(v) {
return v === null || v === undefined ? '' : String(v);
}
function pfInt(v) {
const s = pfStr(v).trim();
if (!s) return null;
const n = Number(s);
return Number.isInteger(n) ? n : NaN;
}
function pfInput(kind, i, f, row, o) {
const cls = `pf-f${o.span ? ' ' + o.span : ''}`;
return `<label class="${cls}"><span>${esc(o.label)}</span>` +
`<input type="text" data-pf="${kind}.${i}.${f}" value="${pfE(row[f])}" placeholder="${pfE(o.ph || '')}"${o.max ? ` maxlength="${o.max}"` : ''}></label>`;
}
function pfNum(kind, i, f, row, o) {
const cls = `pf-f${o.span ? ' ' + o.span : ''}`;
return `<label class="${cls}"><span>${esc(o.label)}</span>` +
`<input type="text" inputmode="numeric" data-pf-num data-pf="${kind}.${i}.${f}" value="${pfE(row[f])}" placeholder="0–100"></label>`;
}
function pfArea(kind, i, f, row, o) {
return `<label class="pf-f pf-row-wide"><span>${esc(o.label)}</span>` +
`<textarea data-pf="${kind}.${i}.${f}" placeholder="${pfE(o.ph || '')}"${o.max ? ` maxlength="${o.max}"` : ''}>${esc(pfStr(row[f]))}</textarea></label>`;
}
function pfDel() {
return `<button type="button" class="icon-btn pf-row-del" data-pf-del title="Удалить строку"><i data-lucide="trash-2"></i></button>`;
}
function pfMeter(kind, i, field, raw) {
const n = Number(pfStr(raw).trim());
const w = pfStr(raw).trim() !== '' && Number.isFinite(n) ? Math.max(0, Math.min(100, n)) : 0;
return `<div class="pf-meter pf-row-wide" data-pf-meter="${kind}.${i}.${field}"><i style="width:${w}%"></i></div>`;
}
function pfErr(text) {
return `<span class="pf-err">${esc(text)}</span>`;
}
function pfRenderSkills() {
const wrap = document.getElementById('pfSkills');
if (!wrap) return;
wrap.innerHTML = pfState.skills.map((s, i) => `
<div class="pf-row" data-pf-kind="skills" data-pf-idx="${i}">
<div class="pf-row-head pf-row-wide">Навык ${i + 1}</div>
${pfInput('skills', i, 'group', s, { label: 'Группа', span: 'pf-mid', ph: 'Вёрстка', max: 80 })}
${pfInput('skills', i, 'name', s, { label: 'Навык', span: 'pf-media-lg', ph: 'HTML5 · семантика', max: 120 })}
${pfInput('skills', i, 'level', s, { label: 'Уровень', span: 'pf-mid', ph: 'Изучен', max: 40 })}
${pfNum('skills', i, 'value', s, { label: 'Прогресс, %', span: 'pf-mid' })}
${pfMeter('skills', i, 'value', s.value)}
${pfDel()}
${pfErr('Прогресс — целое число от 0 до 100')}
</div>`).join('');
}
function pfRenderAchievements() {
const wrap = document.getElementById('pfAchievements');
if (!wrap) return;
wrap.innerHTML = pfState.achievements.map((a, i) => `
<div class="pf-row" data-pf-kind="achievements" data-pf-idx="${i}">
${pfInput('achievements', i, 'value', { value: a }, { label: 'Достижение', span: 'pf-row-wide', ph: 'Победа на хакатоне Digital City', max: 200 })}
${pfDel()}
</div>`).join('');
}
function pfRenderExperience() {
const wrap = document.getElementById('pfExperience');
if (!wrap) return;
wrap.innerHTML = pfState.experience.map((e, i) => `
<div class="pf-row" data-pf-kind="experience" data-pf-idx="${i}">
<div class="pf-row-head pf-row-wide">Проект / место работы ${i + 1}</div>
${pfInput('experience', i, 'title', e, { label: 'Заголовок', span: 'pf-row-wide', ph: 'Хакатон Digital City', max: 160 })}
${pfInput('experience', i, 'company', e, { label: 'Организация', span: 'pf-media-lg', max: 160 })}
${pfInput('experience', i, 'period', e, { label: 'Период', span: 'pf-media-lg', ph: 'Март 2024', max: 80 })}
${pfInput('experience', i, 'date', e, { label: 'Дата', span: 'pf-mid', ph: '03.2024', max: 40 })}
${pfInput('experience', i, 'badge', e, { label: 'Бейдж', span: 'pf-mid', ph: '2 место', max: 40 })}
${pfArea('experience', i, 'description', e, { label: 'Описание', ph: 'Прототип карты заявок', max: 800 })}
${pfInput('experience', i, 'tags', e, { label: 'Теги через запятую', span: 'pf-row-wide', ph: 'Vue 3, Leaflet', max: 400 })}
${pfDel()}
</div>`).join('');
}
function pfRenderEducation() {
const wrap = document.getElementById('pfEducation');
if (!wrap) return;
wrap.innerHTML = pfState.education.map((m, i) => `
<div class="pf-row" data-pf-kind="education" data-pf-idx="${i}">
<div class="pf-row-head pf-row-wide">Модуль ${i + 1}</div>
${pfInput('education', i, 'module', m, { label: 'Тема модуля', span: 'pf-media-lg', ph: 'JavaScript: основы языка', max: 200 })}
${pfNum('education', i, 'progress', m, { label: 'Прогресс, %', span: 'pf-mid' })}
${pfInput('education', i, 'grade', m, { label: 'Оценка', span: 'pf-mid', ph: '4,7', max: 80 })}
${pfInput('education', i, 'teacher', m, { label: 'Преподаватель', span: 'pf-media-lg', max: 150 })}
${pfMeter('education', i, 'progress', m.progress)}
${pfDel()}
${pfErr('Прогресс — целое число от 0 до 100')}
</div>`).join('');
}
function pfContactIconOptions(current) {
const list = current && !PF_CONTACT_ICONS.includes(current) ? [current, ...PF_CONTACT_ICONS] : PF_CONTACT_ICONS;
return list.map(n => `<option value="${pfE(n)}"${current === n ? ' selected' : ''}>${esc(n)}</option>`).join('');
}
function pfRenderContacts() {
const wrap = document.getElementById('pfContacts');
if (!wrap) return;
wrap.innerHTML = pfState.contacts.map((c, i) => `
<div class="pf-row" data-pf-kind="contacts" data-pf-idx="${i}">
<label class="pf-f pf-mid"><span>Иконка</span>
<select data-pf="contacts.${i}.icon">${pfContactIconOptions(c.icon)}</select>
</label>
${pfInput('contacts', i, 'label', c, { label: 'Подпись', span: 'pf-media-lg', ph: '@nickname', max: 120 })}
${pfInput('contacts', i, 'href', c, { label: 'Ссылка', span: 'pf-media-lg', ph: 'https://t.me/nickname', max: 500 })}
${pfDel()}
${pfErr('Ссылка должна начинаться с http://, https://, mailto:, tel:, / или # — либо быть email')}
</div>`).join('');
}
function pfRenderTags() {
const wrap = document.getElementById('pfTags');
if (!wrap) return;
wrap.innerHTML = pfState.tags.map((t, i) => `
<span class="pf-chip">${esc(t)}<button type="button" data-pf-tag-del="${i}" title="Убрать тег">✕</button></span>`).join('');
}
function pfRenderCounts() {
const set = (id, n) => { const el = document.getElementById(id); if (el) el.textContent = n ? String(n) : ''; };
set('pfCountSkills', pfState.skills.length);
set('pfCountAbout', pfState.achievements.length + pfState.experience.length + pfState.education.length);
set('pfCountContacts', pfState.contacts.length);
}
function pfRenderAll() {
pfRenderTags();
pfRenderSkills();
pfRenderAchievements();
pfRenderExperience();
pfRenderEducation();
pfRenderContacts();
pfRenderCounts();
renderIcons();
}
function pfUpdateMeters() {
document.querySelectorAll('#profileDataModal [data-pf-meter]').forEach(m => {
const input = document.querySelector(`#profileDataModal [data-pf="${m.dataset.pfMeter}"]`);
if (!input) return;
const s = input.value.trim();
const n = Number(s);
const w = s !== '' && Number.isFinite(n) ? Math.max(0, Math.min(100, n)) : 0;
const bar = m.firstElementChild;
if (bar) bar.style.width = w + '%';
});
}
function pfUpdateCounters() {
const pair = (id, max) => {
const el = document.getElementById(id);
const inp = document.getElementById(id.replace('Count', ''));
if (!el || !inp) return;
const n = inp.value.length;
el.textContent = `${n} / ${max}`;
el.classList.toggle('warn', n > max * 0.9);
};
pair('pfBioCount', 2000);
pair('pfQuoteCount', 300);
}
function pfSetTab(tab) {
pfActiveTab = tab;
document.querySelectorAll('#pfTabs .pf-tab').forEach(b => b.classList.toggle('is-active', b.dataset.pfTab === tab));
document.querySelectorAll('#profileDataModal .pf-pane').forEach(p => p.classList.toggle('is-active', p.dataset.pfPane === tab));
const body = document.querySelector('#profileDataModal .pf-body');
if (body) body.scrollTop = 0;
}
function pfMarkDirty() {
const st = document.getElementById('pfSaveHint');
if (!st || !pfState) return;
const dirty = JSON.stringify(collectProfile()) !== pfBaseline;
st.classList.toggle('dirty', dirty);
st.innerHTML = dirty ? '<i data-lucide="triangle-alert"></i>Есть несохранённые изменения' : '';
if (dirty) renderIcons();
}
function pfRenderHeadAvatar(photoPath, name) {
const el = document.getElementById('pfHeadAvatar');
if (!el) return;
if (photoPath) el.innerHTML = `<img src="${esc(thumbSrc(photoPath))}" alt="">`;
else el.textContent = studentInitials(name);
}
function openProfileData(id) {
profileDataId = id;
pfState = pfBlankState();
const known = allStudents.find(s => s.id === id);
document.getElementById('profileDataTitle').textContent = (known && known.name) || 'Загрузка…';
pfRenderHeadAvatar('', known && known.name);
pfRenderAll();
pfUpdateCounters();
pfSetTab('general');
const saveBtn = document.getElementById('profileDataSaveBtn');
saveBtn.disabled = true;
document.getElementById('profileDataModal').classList.add('open');
loadGroupOptions();
loadStudentPhotos(id);
fetch(`${API}/api/students/${id}/profile`, { headers: hdr() })
.then(r => (r.ok ? r.json() : Promise.reject(new Error('load'))))
.then(data => fillProfileForm(data.profile, data.name, data.photo_path))
.catch(() => fillProfileForm(null, '', ''));
document.getElementById('profileDataModal').classList.add('open');
.then(data => {
fillProfileForm(data.profile, data.name, data.photo_path);
saveBtn.disabled = false;
})
.catch(() => {
fillProfileForm(null, (known && known.name) || 'Профиль ученика', '');
showToast('Не удалось загрузить профиль, сохранение недоступно', true);
});
}
function closeProfileData() {
function closeProfileData(skipCheck) {
if (!skipCheck && pfState && JSON.stringify(collectProfile()) !== pfBaseline) {
if (!confirm('Есть несохранённые изменения. Закрыть без сохранения?')) return false;
}
document.getElementById('profileDataModal').classList.remove('open');
profileDataId = null;
pfState = null;
return true;
}
async function openStudentFaces(id, name) {
@@ -488,15 +716,16 @@ function renderStudentPhotos() {
const wrap = document.getElementById('pfPhotos');
if (!wrap) return;
const main = document.getElementById('pfPhoto').value.trim();
pfRenderHeadAvatar(main, document.getElementById('profileDataTitle').textContent);
if (!profilePhotos.length) {
wrap.innerHTML = '<span class="hint" style="margin:0">Пока нет загруженных фото</span>';
wrap.innerHTML = '<span class="pf-empty">Пока нет загруженных фото</span>';
return;
}
wrap.innerHTML = profilePhotos.map(p => `
<div class="pf-photo${p.photo_path === main ? ' main' : ''}" data-pf-set="${p.id}" title="Сделать главным">
<img src="${esc(p.photo_path)}" alt="" loading="lazy">
<img src="${esc(thumbSrc(p.photo_path))}" alt="" loading="lazy">
${p.photo_path === main ? '<span class="pf-badge">Главная</span>' : ''}
<button type="button" class="pf-del" data-pf-del="${p.id}" title="Удалить фото">✕</button>
<button type="button" class="pf-del" data-pf-del-photo="${p.id}" title="Удалить фото">✕</button>
</div>
`).join('');
}
@@ -504,7 +733,7 @@ function renderStudentPhotos() {
async function uploadStudentPhoto(file) {
if (!profileDataId || !file) return;
if (!file.type.startsWith('image/')) {
alert('Можно загружать только изображения');
showToast('Можно загружать только изображения', true);
return;
}
showToast('Загружаем фото...');
@@ -518,10 +747,10 @@ async function uploadStudentPhoto(file) {
showToast('Фото загружено');
} else {
const e = await res.json().catch(() => ({}));
alert(e.error || 'Не удалось загрузить фото');
showToast(e.error || 'Не удалось загрузить фото', true);
}
} catch (err) {
alert('Ошибка при загрузке фото');
showToast('Ошибка при загрузке фото', true);
}
}
@@ -537,10 +766,10 @@ async function setMainStudentPhoto(pid) {
showToast('Главное фото обновлено');
} else {
const e = await res.json().catch(() => ({}));
alert(e.error || 'Не удалось выбрать главное фото');
showToast(e.error || 'Не удалось выбрать главное фото', true);
}
} catch (err) {
alert('Ошибка при выборе главного фото');
showToast('Ошибка при выборе главного фото', true);
}
}
@@ -555,65 +784,100 @@ async function delStudentPhoto(pid) {
showToast('Фото удалено');
} else {
const e = await res.json().catch(() => ({}));
alert(e.error || 'Не удалось удалить фото');
showToast(e.error || 'Не удалось удалить фото', true);
}
} catch (err) {
alert('Ошибка при удалении фото');
showToast('Ошибка при удалении фото', true);
}
}
function fillProfileForm(profile, name, photoPath) {
const p = profile || {};
if (!pfState) pfState = pfBlankState();
const set = (id, v) => { document.getElementById(id).value = v === null || v === undefined ? '' : String(v); };
document.getElementById('profileDataTitle').textContent = name || 'Профиль ученика';
pfRenderHeadAvatar(photoPath, name);
set('pfRole', p.role); set('pfStatus', p.status); set('pfStatusNote', p.status_note);
set('pfCity', p.city); set('pfMentor', p.mentor); set('pfJoined', p.joined);
set('pfBio', p.bio); set('pfQuote', p.quote);
set('pfTags', (p.tags || []).join(', '));
set('pfContacts', (p.contacts || []).map(c => [c.icon || 'link', c.label, c.href || ''].join(' | ')).join('\n'));
set('pfAchievements', (p.achievements || []).join('\n'));
set('pfSkills', (p.skills || []).map(s => [s.group || 'Навыки', s.name, s.level || '', s.value === null || s.value === undefined ? '' : s.value].join(' | ')).join('\n'));
set('pfExperience', (p.experience || []).map(e => [e.title, e.company || '', e.period || '', e.date || '', e.badge || '', e.description || '', (e.tags || []).join(',')].join(' | ')).join('\n'));
set('pfEducation', (p.education || []).map(m => [m.module, m.progress === null || m.progress === undefined ? '' : m.progress, m.grade || '', m.teacher || ''].join(' | ')).join('\n'));
pfState.tags = (p.tags || []).slice();
pfState.contacts = (p.contacts || []).map(c => ({ icon: c.icon || 'link', label: c.label || '', href: c.href || '' }));
pfState.skills = (p.skills || []).map(s => ({
group: s.group || 'Навыки', name: s.name || '', level: s.level || '',
value: s.value === null || s.value === undefined ? '' : String(s.value),
}));
pfState.achievements = (p.achievements || []).slice();
pfState.experience = (p.experience || []).map(e => ({
title: e.title || '', company: e.company || '', period: e.period || '', date: e.date || '',
badge: e.badge || '', description: e.description || '', tags: (e.tags || []).join(', '),
}));
pfState.education = (p.education || []).map(m => ({
module: m.module || '',
progress: m.progress === null || m.progress === undefined ? '' : String(m.progress),
grade: m.grade || '', teacher: m.teacher || '',
}));
set('pfPhoto', photoPath || '');
document.getElementById('pfTagsInput').value = '';
pfRenderAll();
pfUpdateCounters();
pfBaseline = JSON.stringify(collectProfile());
pfMarkDirty();
}
const PF_HREF_RE = /^(https?:\/\/|mailto:|tel:|\/|#)/i;
const PF_EMAIL_RE = /^[\w.+-]+@[\w-]+\.[\w.-]{2,}$/;
function pfValidHref(v) {
const s = String(v || '').trim();
if (!s || s.length > 500) return true;
return PF_HREF_RE.test(s) || PF_EMAIL_RE.test(s);
}
function pfValidate() {
let firstBad = null;
document.querySelectorAll('#profileDataModal .pf-row').forEach(row => {
let bad = '';
const num = row.querySelector('[data-pf-num]');
if (num && num.value.trim() !== '' && Number.isNaN(pfInt(num.value))) bad = 'Прогресс — целое число от 0 до 100';
if (!bad) {
const href = row.querySelector('[data-pf$=".href"]');
if (href && !pfValidHref(href.value)) bad = 'Ссылка должна начинаться с http://, https://, mailto:, tel:, / или # — либо быть email';
}
row.classList.toggle('is-invalid', !!bad);
const control = row.querySelector('[data-pf-num]') || row.querySelector('[data-pf$=".href"]');
if (control) control.classList.toggle('invalid', !!bad);
if (bad && !firstBad) firstBad = row;
});
return firstBad;
}
function collectProfile() {
const val = id => document.getElementById(id).value.trim();
const lines = id => val(id).split('\n').map(s => s.trim()).filter(Boolean);
const cols = line => line.split('|').map(s => s.trim());
const intOrNull = s => (s === '' || s === null || s === undefined ? null : Number(s));
if (!pfState) return null;
const val = id => { const el = document.getElementById(id); return el ? el.value.trim() : ''; };
const tr = s => { const v = String(s === null || s === undefined ? '' : s).trim(); return v || null; };
const out = {
role: val('pfRole') || null,
status: val('pfStatus') || null,
status_note: val('pfStatusNote') || null,
city: val('pfCity') || null,
mentor: val('pfMentor') || null,
joined: val('pfJoined') || null,
bio: val('pfBio') || null,
quote: val('pfQuote') || null,
tags: val('pfTags') ? val('pfTags').split(',').map(s => s.trim()).filter(Boolean) : [],
contacts: lines('pfContacts').map(l => {
const c = cols(l);
return { icon: c[0] || 'link', label: c[1] || '', href: c[2] || '' };
}).filter(c => c.label),
achievements: lines('pfAchievements'),
skills: lines('pfSkills').map(l => {
const c = cols(l);
return { group: c[0] || 'Навыки', name: c[1] || '', level: c[2] || null, value: intOrNull(c[3]) };
}).filter(s => s.name),
experience: lines('pfExperience').map(l => {
const c = cols(l);
return {
title: c[0] || '', company: c[1] || null, period: c[2] || null, date: c[3] || null,
badge: c[4] || null, description: c[5] || null,
tags: c[6] ? c[6].split(',').map(s => s.trim()).filter(Boolean) : [],
};
}).filter(e => e.title),
education: lines('pfEducation').map(l => {
const c = cols(l);
return { module: c[0] || '', progress: intOrNull(c[1]), grade: c[2] || null, teacher: c[3] || null };
}).filter(m => m.module),
role: tr(val('pfRole')),
status: tr(val('pfStatus')),
status_note: tr(val('pfStatusNote')),
city: tr(val('pfCity')),
mentor: tr(val('pfMentor')),
joined: tr(val('pfJoined')),
bio: tr(val('pfBio')),
quote: tr(val('pfQuote')),
tags: pfState.tags.slice(),
contacts: pfState.contacts.map(c => ({ icon: c.icon || 'link', label: tr(c.label), href: tr(c.href) })).filter(c => c.label),
achievements: pfState.achievements.map(a => String(a || '').trim()).filter(Boolean),
skills: pfState.skills.map(s => ({
group: tr(s.group) || 'Навыки', name: tr(s.name), level: tr(s.level), value: pfInt(s.value),
})).filter(s => s.name),
experience: pfState.experience.map(e => ({
title: tr(e.title), company: tr(e.company), period: tr(e.period), date: tr(e.date),
badge: tr(e.badge), description: tr(e.description),
tags: String(e.tags || '').split(',').map(s => s.trim()).filter(Boolean),
})).filter(e => e.title),
education: pfState.education.map(m => ({
module: tr(m.module), progress: pfInt(m.progress), grade: tr(m.grade), teacher: tr(m.teacher),
})).filter(m => m.module),
};
const hasData = Object.keys(out).some(k => (Array.isArray(out[k]) ? out[k].length : out[k]));
return hasData ? out : null;
@@ -622,6 +886,17 @@ function collectProfile() {
async function saveProfileData(e) {
e.preventDefault();
if (!profileDataId) return;
const bad = pfValidate();
if (bad) {
pfSetTab(bad.dataset.pfKind === 'skills' ? 'skills' : bad.dataset.pfKind === 'contacts' ? 'contacts' : 'about');
bad.scrollIntoView({ block: 'center', behavior: 'smooth' });
const f = bad.querySelector('input, textarea, select');
if (f) f.focus();
showToast('Проверьте выделенные поля', true);
return;
}
const btn = document.getElementById('profileDataSaveBtn');
if (btn) btn.disabled = true;
const body = { profile: collectProfile() };
const photoPath = document.getElementById('pfPhoto').value.trim();
body.photo_path = photoPath || null;
@@ -629,14 +904,15 @@ async function saveProfileData(e) {
method: 'PUT',
headers: hdrJson(),
body: JSON.stringify(body),
});
if (res.ok) {
closeProfileData();
}).catch(() => null);
if (btn) btn.disabled = false;
if (res && res.ok) {
closeProfileData(true);
loadStudents();
showToast('Данные профиля сохранены');
} else {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Не удалось сохранить данные профиля');
const err = res ? await res.json().catch(() => ({})) : {};
showToast(err.error || 'Не удалось сохранить данные профиля', true);
}
}
@@ -826,6 +1102,112 @@ document.getElementById('studentList').addEventListener('click', e => {
document.getElementById('profileDataForm').addEventListener('submit', saveProfileData);
document.getElementById('profileDataCancelBtn').addEventListener('click', closeProfileData);
document.getElementById('profileDataCloseBtn').addEventListener('click', closeProfileData);
document.getElementById('pfTabs').addEventListener('click', e => {
const b = e.target.closest('[data-pf-tab]');
if (b) pfSetTab(b.dataset.pfTab);
});
function pfReadRowControl(el) {
const path = el.dataset.pf;
if (!path) return null;
const parts = path.split('.');
const field = parts.pop();
const row = el.closest('[data-pf-kind]');
if (!row) return null;
const kind = row.dataset.pfKind;
const idx = parseInt(row.dataset.pfIdx, 10);
if (!pfState || !Array.isArray(pfState[kind]) || !pfState[kind][idx]) return null;
return { row: pfState[kind][idx], field };
}
document.getElementById('profileDataForm').addEventListener('input', e => {
const t = e.target;
if (t.id === 'pfBio' || t.id === 'pfQuote') pfUpdateCounters();
const target = pfReadRowControl(t);
if (target) {
target.row[target.field] = t.value;
const row = t.closest('.pf-row');
if (row && row.classList.contains('is-invalid')) {
row.classList.remove('is-invalid');
t.classList.remove('invalid');
}
pfUpdateMeters();
pfMarkDirty();
return;
}
if (pfState) pfMarkDirty();
});
document.getElementById('profileDataForm').addEventListener('change', e => {
const target = pfReadRowControl(e.target);
if (target) { target.row[target.field] = e.target.value; pfUpdateMeters(); pfMarkDirty(); }
});
document.getElementById('profileDataForm').addEventListener('click', e => {
const del = e.target.closest('[data-pf-del]');
if (del) {
const row = del.closest('[data-pf-kind]');
if (!row || !pfState) return;
pfState[row.dataset.pfKind].splice(parseInt(row.dataset.pfIdx, 10), 1);
pfRenderAll();
pfMarkDirty();
return;
}
const tagDel = e.target.closest('[data-pf-tag-del]');
if (tagDel) {
pfState.tags.splice(parseInt(tagDel.dataset.pfTagDel, 10), 1);
pfRenderTags();
pfMarkDirty();
}
});
document.getElementById('pfTagsInput').addEventListener('keydown', e => {
if (e.key !== 'Enter' && e.key !== ',') return;
e.preventDefault();
const input = e.currentTarget;
const add = raw => {
String(raw || '').split(',').map(s => s.trim()).filter(Boolean).forEach(t => {
if (t.length > 40) return;
if (pfState.tags.length >= 20) return;
if (!pfState.tags.includes(t)) pfState.tags.push(t);
});
};
add(input.value);
input.value = '';
pfRenderTags();
pfMarkDirty();
});
const pfAddRow = (kind, limit, make, render) => () => {
if (!pfState) return;
if (pfState[kind].length >= limit) { showToast(`Максимум ${limit} строк`, true); return; }
pfState[kind].push(make());
render();
renderIcons();
pfMarkDirty();
const rows = document.querySelectorAll(`#profileDataModal [data-pf-kind="${kind}"]`);
const last = rows[rows.length - 1];
if (last) {
last.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
const f = last.querySelector('input, textarea, select');
if (f) f.focus();
}
};
document.getElementById('pfSkillsAdd').addEventListener('click', pfAddRow('skills', 80, () => ({ group: '', name: '', level: '', value: '' }), pfRenderSkills));
document.getElementById('pfAchievementsAdd').addEventListener('click', pfAddRow('achievements', 40, () => '', pfRenderAchievements));
document.getElementById('pfExperienceAdd').addEventListener('click', pfAddRow('experience', 30, () => ({ title: '', company: '', period: '', date: '', badge: '', description: '', tags: '' }), pfRenderExperience));
document.getElementById('pfEducationAdd').addEventListener('click', pfAddRow('education', 60, () => ({ module: '', progress: '', grade: '', teacher: '' }), pfRenderEducation));
document.getElementById('pfContactsAdd').addEventListener('click', pfAddRow('contacts', 20, () => ({ icon: 'link', label: '', href: '' }), pfRenderContacts));
document.getElementById('profileDataModal').addEventListener('keydown', e => {
if (e.key === 'Escape' && !e.target.matches('textarea, select')) {
e.stopPropagation();
closeProfileData();
}
});
document.getElementById('pfPhotoUploadBtn').addEventListener('click', () => document.getElementById('pfPhotoFile').click());
document.getElementById('pfPhotoFile').addEventListener('change', e => {
const f = e.target.files && e.target.files[0];
@@ -833,8 +1215,8 @@ document.getElementById('pfPhotoFile').addEventListener('change', e => {
if (f) uploadStudentPhoto(f);
});
document.getElementById('pfPhotos').addEventListener('click', e => {
const del = e.target.closest('[data-pf-del]');
if (del) { delStudentPhoto(parseInt(del.dataset.pfDel, 10)); return; }
const del = e.target.closest('[data-pf-del-photo]');
if (del) { delStudentPhoto(parseInt(del.dataset.pfDelPhoto, 10)); return; }
const set = e.target.closest('[data-pf-set]');
if (set) setMainStudentPhoto(parseInt(set.dataset.pfSet, 10));
});
@@ -859,8 +1241,7 @@ document.getElementById('profileDataModal').addEventListener('click', e => { if
document.getElementById('pfFacesBtn').addEventListener('click', () => {
const pid = profileDataId;
const name = document.getElementById('profileDataTitle').textContent;
closeProfileData();
openStudentFaces(pid, name);
if (closeProfileData()) openStudentFaces(pid, name);
});
document.getElementById('studentFacesCloseBtn').addEventListener('click', closeStudentFaces);
document.getElementById('studentFacesModal').addEventListener('click', e => { if (e.target === e.currentTarget) closeStudentFaces(); });
+113 -77
View File
@@ -137,87 +137,123 @@
</div>
<div class="modal-overlay" id="profileDataModal">
<div class="edit-modal" style="max-width:900px;width:96%;max-height:92dvh;overflow-y:auto">
<h3>Данные профиля: <span id="profileDataTitle" style="color:var(--accent)"></span></h3>
<form id="profileDataForm" style="display:grid;grid-template-columns:1fr 1fr;gap:12px 16px">
<div class="settings-field">
<label>Роль / направление</label>
<input type="text" id="pfRole" class="settings-input" placeholder="Например: Ученик направления «Frontend-разработка»">
</div>
<div class="settings-field">
<label>Статус</label>
<input type="text" id="pfStatus" class="settings-input" placeholder="Активно учится">
</div>
<div class="settings-field">
<label>Примечание к статусу</label>
<input type="text" id="pfStatusNote" class="settings-input" placeholder="учится с сентября 2022">
</div>
<div class="settings-field">
<label>Город</label>
<input type="text" id="pfCity" class="settings-input">
</div>
<div class="settings-field">
<label>Наставник</label>
<input type="text" id="pfMentor" class="settings-input">
</div>
<div class="settings-field">
<label>В академии с</label>
<input type="text" id="pfJoined" class="settings-input" placeholder="В академии с сентября 2022">
</div>
<div class="settings-field" style="grid-column:1/-1">
<label>О себе</label>
<textarea id="pfBio" class="settings-input" style="min-height:70px" placeholder="Короткий рассказ ученика о себе"></textarea>
</div>
<div class="settings-field">
<label>Цитата</label>
<input type="text" id="pfQuote" class="settings-input" placeholder="«Мой принцип: сначала понять, потом написать»">
</div>
<div class="settings-field">
<label>Теги (через запятую)</label>
<input type="text" id="pfTags" class="settings-input" placeholder="HTML, CSS, JavaScript">
</div>
<div class="settings-field">
<label>Контакты — строка: Иконка | Подпись | Ссылка</label>
<textarea id="pfContacts" class="settings-input" style="min-height:64px" placeholder="mail | maria@example.com | mailto:maria@example.com&#10;send | @nickname | https://t.me/nickname"></textarea>
<span class="hint">Иконки: mail, send, phone, github, globe, link, at-sign</span>
</div>
<div class="settings-field">
<label>Достижения — по одному в строке</label>
<textarea id="pfAchievements" class="settings-input" style="min-height:64px"></textarea>
</div>
<div class="settings-field">
<label>Навыки — строка: Группа | Навык | Уровень | %</label>
<textarea id="pfSkills" class="settings-input" style="min-height:64px" placeholder="Вёрстка | HTML5 · семантика | Изучен | 95"></textarea>
</div>
<div class="settings-field">
<label>Опыт работы — строка: Заголовок | Организация | Период | Дата | Бейдж | Описание | Теги (через запятую)</label>
<textarea id="pfExperience" class="settings-input" style="min-height:64px" placeholder="Хакатон Digital City | Академия | Март 2024 | 03.2024 | Хакатон | Прототип карты заявок, 2 место | Vue 3, Leaflet"></textarea>
</div>
<div class="settings-field">
<label>Прогресс по модулям — строка: Тема модуля | Прогресс % | Оценка | Преподаватель</label>
<textarea id="pfEducation" class="settings-input" style="min-height:64px" placeholder="JavaScript: основы языка | 100 | Оценка 4,7 | Игорь Дёмин"></textarea>
</div>
<div class="settings-field" style="grid-column:1/-1">
<label>Фотографии ученика</label>
<input type="hidden" id="pfPhoto">
<div class="pf-photos" id="pfPhotos"></div>
<div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-top:6px">
<input type="file" id="pfPhotoFile" accept="image/*" hidden>
<button type="button" class="btn-primary ghost" id="pfPhotoUploadBtn">Загрузить фото</button>
<span class="hint">Клик по фото — сделать главным. Можно вставить из буфера обмена (Ctrl+V)</span>
<div class="edit-modal pf-modal">
<form id="profileDataForm" class="pf-form">
<div class="pf-head">
<div class="pf-head-avatar" id="pfHeadAvatar"></div>
<div class="pf-head-text">
<h3>Профиль ученика</h3>
<span class="pf-head-name" id="profileDataTitle"></span>
</div>
<button type="button" class="icon-btn" id="profileDataCloseBtn" title="Закрыть (Esc)"><i data-lucide="x"></i></button>
</div>
<div class="settings-field" style="grid-column:1/-1">
<label>Распознавание лиц</label>
<div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap">
<button type="button" class="btn-primary ghost" id="pfFacesBtn">Эталоны и фото с учеником</button>
<span class="hint">Задать эталонные фото для распознавания и посмотреть, где ученик уже найден на фото.</span>
<nav class="pf-tabs" id="pfTabs">
<button type="button" class="pf-tab is-active" data-pf-tab="general"><i data-lucide="user"></i>Основное</button>
<button type="button" class="pf-tab" data-pf-tab="skills"><i data-lucide="sparkles"></i>Навыки<span class="pf-tab-count" id="pfCountSkills"></span></button>
<button type="button" class="pf-tab" data-pf-tab="about"><i data-lucide="briefcase"></i>Опыт<span class="pf-tab-count" id="pfCountAbout"></span></button>
<button type="button" class="pf-tab" data-pf-tab="contacts"><i data-lucide="at-sign"></i>Контакты<span class="pf-tab-count" id="pfCountContacts"></span></button>
<button type="button" class="pf-tab" data-pf-tab="media"><i data-lucide="image"></i>Фото и лица</button>
</nav>
<div class="pf-body">
<section class="pf-pane is-active" data-pf-pane="general">
<div class="pf-grid">
<div class="settings-field">
<label>Роль / направление</label>
<input type="text" id="pfRole" class="settings-input" maxlength="200" placeholder="Ученик направления «Frontend-разработка»">
</div>
<div class="settings-field">
<label>Статус</label>
<input type="text" id="pfStatus" class="settings-input" maxlength="60" placeholder="Активно учится">
</div>
<div class="settings-field">
<label>Примечание к статусу</label>
<input type="text" id="pfStatusNote" class="settings-input" maxlength="120" placeholder="учится с сентября 2022">
</div>
<div class="settings-field">
<label>Город</label>
<input type="text" id="pfCity" class="settings-input" maxlength="120">
</div>
<div class="settings-field">
<label>Наставник</label>
<input type="text" id="pfMentor" class="settings-input" maxlength="150">
</div>
<div class="settings-field">
<label>В академии с</label>
<input type="text" id="pfJoined" class="settings-input" maxlength="120" placeholder="сентябрь 2022">
</div>
<div class="settings-field pf-full">
<label>Цитата<span class="pf-count" id="pfQuoteCount"></span></label>
<input type="text" id="pfQuote" class="settings-input" maxlength="300" placeholder="«Мой принцип: сначала понять, потом написать»">
</div>
<div class="settings-field pf-full">
<label>Теги</label>
<div class="pf-chips" id="pfTags"></div>
<input type="text" id="pfTagsInput" class="settings-input" maxlength="40" placeholder="Добавьте тег и нажмите Enter">
</div>
<div class="settings-field pf-full">
<label>О себе<span class="pf-count" id="pfBioCount"></span></label>
<textarea id="pfBio" class="settings-input" maxlength="2000" rows="4" placeholder="Короткий рассказ ученика о себе"></textarea>
</div>
</div>
</section>
<section class="pf-pane" data-pf-pane="skills">
<div class="pf-list" id="pfSkills"></div>
<button type="button" class="pf-add" id="pfSkillsAdd"><i data-lucide="plus"></i>Добавить навык</button>
</section>
<section class="pf-pane" data-pf-pane="about">
<div class="pf-block-head">
<h4>Достижения</h4>
<button type="button" class="pf-add" id="pfAchievementsAdd"><i data-lucide="plus"></i>Добавить</button>
</div>
<div class="pf-list" id="pfAchievements"></div>
<div class="pf-block-head">
<h4>Опыт и проекты</h4>
<button type="button" class="pf-add" id="pfExperienceAdd"><i data-lucide="plus"></i>Добавить</button>
</div>
<div class="pf-list" id="pfExperience"></div>
<div class="pf-block-head">
<h4>Прогресс по модулям</h4>
<button type="button" class="pf-add" id="pfEducationAdd"><i data-lucide="plus"></i>Добавить модуль</button>
</div>
<div class="pf-list" id="pfEducation"></div>
</section>
<section class="pf-pane" data-pf-pane="contacts">
<div class="pf-list" id="pfContacts"></div>
<button type="button" class="pf-add" id="pfContactsAdd"><i data-lucide="plus"></i>Добавить контакт</button>
</section>
<section class="pf-pane" data-pf-pane="media">
<div class="pf-block-head"><h4>Фотографии ученика</h4></div>
<input type="hidden" id="pfPhoto">
<div class="pf-photos" id="pfPhotos"></div>
<div class="pf-actions">
<input type="file" id="pfPhotoFile" accept="image/*" hidden>
<button type="button" class="btn-primary ghost" id="pfPhotoUploadBtn"><i data-lucide="upload"></i>Загрузить фото</button>
<span class="hint">Клик по фото — сделать главным. Можно вставить из буфера обмена (Ctrl+V)</span>
</div>
<div class="pf-block-head"><h4>Распознавание лиц</h4></div>
<div class="pf-actions">
<button type="button" class="btn-primary ghost" id="pfFacesBtn"><i data-lucide="scan-face"></i>Эталоны и фото с учеником</button>
<span class="hint">Задать эталонные фото для распознавания и посмотреть, где ученик уже найден на фото.</span>
</div>
</section>
</div>
<div class="pf-foot">
<span class="pf-status" id="pfSaveHint"></span>
<div class="pf-foot-btns">
<button type="button" class="btn-primary ghost" id="profileDataCancelBtn">Отмена</button>
<button type="submit" class="btn-primary" id="profileDataSaveBtn">Сохранить</button>
</div>
</div>
<div style="grid-column:1/-1;display:flex;justify-content:flex-end;gap:8px">
<button type="button" class="btn-primary ghost" id="profileDataCancelBtn">Отмена</button>
<button type="submit" class="btn-primary">Сохранить</button>
</div>
</form>
</div>
</div>