import { createTopBar } from '../components/topbar.js'; import { actionErrorText, toUserMessage } from '../services/ui-error-texts.js'; import { showToast } from '../services/channels-ux.js'; import { profile } from '../mock-data.js'; import { authService, state } from '../state.js'; import { PROFILE_GENDER_FEMALE, PROFILE_GENDER_MALE, PROFILE_GENDER_UNKNOWN, PROFILE_ACCOUNT_ROLE_PRIMARY, PROFILE_ACCOUNT_ROLE_NON_VOTING, PROFILE_SHINE_SHINING, PROFILE_SHINE_UNKNOWN, PROFILE_SHINE_NOT_INTERESTED, loadProfileSnapshot, saveProfileGender, saveProfileParamBlock, saveProfileStatus, } from '../services/user-profile-params.js'; import { buildIdentityLines } from '../services/user-connections.js'; import { openAvatarWizard } from '../components/avatar-wizard.js'; import { renderUserAvatar } from '../components/avatar-image.js'; export const pageMeta = { id: 'profile-edit-view', title: 'Редактирование профиля' }; function accountRoleLabel(value) { if (value === PROFILE_ACCOUNT_ROLE_PRIMARY) return 'Основной аккаунт'; if (value === PROFILE_ACCOUNT_ROLE_NON_VOTING) return 'Не учитывать мой голос'; return 'Не указано'; } function shineStatusLabel(value) { if (value === PROFILE_SHINE_SHINING) return 'Сияющий'; if (value === PROFILE_SHINE_NOT_INTERESTED) return 'Сияние неинтересно'; if (value === PROFILE_SHINE_UNKNOWN) return 'Неизвестно'; return 'Не указано'; } // Ошибка – понятным сообщением внизу экрана, а не окном со стеком вызовов // (подробности остаются в журнале приложения). function showLocalErrorAlert(prefix, error) { showToast(`${prefix}. ${toUserMessage(error, 'Попробуйте ещё раз.')}`, { kind: 'error' }); } function genderLabel(value) { if (value === PROFILE_GENDER_MALE) return 'Мужской'; if (value === PROFILE_GENDER_FEMALE) return 'Женский'; return 'Не указан'; } const GENDER_OPTIONS = Object.freeze([ { value: PROFILE_GENDER_MALE, label: 'Мужской' }, { value: PROFILE_GENDER_FEMALE, label: 'Женский' }, { value: PROFILE_GENDER_UNKNOWN, label: 'Не указан' }, ]); function escapeHtml(text) { return String(text || '') .replaceAll('&', '&') .replaceAll('<', '<') .replaceAll('>', '>') .replaceAll('"', '"') .replaceAll("'", '''); } export function render({ navigate, chrome }) { const login = state.session.login || profile.login; const screen = document.createElement('section'); screen.className = 'stack profile-screen'; chrome?.setTopbar( createTopBar({ title: 'Редактирование профиля', back: { label: '←', onClick: () => navigate('profile-view') }, }), ); const card = document.createElement('div'); card.className = 'stack profile-edit-card'; const topRow = document.createElement('div'); topRow.className = 'row'; topRow.innerHTML = `
`; const badgesRow = document.createElement('div'); badgesRow.className = 'chip-row profile-edit-statuses'; badgesRow.innerHTML = ` `; const status = document.createElement('div'); status.className = 'status-line'; status.textContent = 'Загрузка параметров...'; const listWrap = document.createElement('div'); listWrap.className = 'nav-list profile-param-list'; const reloadBtn = topRow.querySelector('[data-reload="true"]'); const accountRoleBtn = badgesRow.querySelector('[data-status="account_role"]'); const shineBtn = badgesRow.querySelector('[data-status="shine"]'); const avatarActionEl = topRow.querySelector('[data-change-avatar="true"]'); let currentFields = []; let currentAccountRole = ''; let currentShineStatus = ''; let currentGender = PROFILE_GENDER_UNKNOWN; let currentAvatar = { value: '', source: '', txId: '', sha256Hex: '', timeMs: 0 }; const identityEl = topRow.querySelector('[data-profile-identity="true"]'); const avatarSlotEl = topRow.querySelector('[data-profile-avatar-slot="true"]'); function openGenderPickerModal(initialGender) { const root = document.getElementById('modal-root'); if (!root) return Promise.resolve(null); root.innerHTML = ''; const selected = GENDER_OPTIONS.some((item) => item.value === initialGender) ? initialGender : PROFILE_GENDER_UNKNOWN; root.innerHTML = ` `; return new Promise((resolve) => { const modal = root.querySelector('#profile-gender-modal'); const selectEl = root.querySelector('#profile-gender-select'); const saveEl = root.querySelector('#profile-gender-save'); const cancelEl = root.querySelector('#profile-gender-cancel'); if (!(modal instanceof HTMLElement) || !(selectEl instanceof HTMLSelectElement)) { root.innerHTML = ''; resolve(null); return; } const close = (value = null) => { root.innerHTML = ''; resolve(value); }; modal.addEventListener('click', (event) => { if (event.target === modal) close(null); }); cancelEl?.addEventListener('click', () => close(null)); saveEl?.addEventListener('click', () => close(selectEl.value || PROFILE_GENDER_UNKNOWN)); window.setTimeout(() => selectEl.focus(), 0); }); } function syncIdentity() { if (!identityEl) return; const firstName = currentFields.find((field) => field.key === 'first_name')?.value || ''; const lastName = currentFields.find((field) => field.key === 'last_name')?.value || ''; const lines = buildIdentityLines({ login, firstName, lastName }); identityEl.innerHTML = lines.map((line, idx) => ( `
${escapeHtml(line)}
` )).join(''); } function updateAvatarUi() { if (!(avatarSlotEl instanceof HTMLElement)) return; const firstName = String(currentFields.find((field) => field.key === 'first_name')?.value || '').trim(); const lastName = String(currentFields.find((field) => field.key === 'last_name')?.value || '').trim(); avatarSlotEl.innerHTML = ''; avatarSlotEl.append(renderUserAvatar({ login, firstName, lastName, avatar: (currentAvatar?.txId || currentAvatar?.sha256Hex) ? { ar: String(currentAvatar.txId || currentAvatar.ar || '').trim(), sha256Hex: String(currentAvatar?.sha256Hex || '').trim().toLowerCase() } : null, size: 'xl', // Как в карточке профиля: без стеклянного кольца, которое вылезало за край экрана. className: 'profile-avatar avatar-plain', })); } function updateStatusesUi() { if (accountRoleBtn) { accountRoleBtn.textContent = `Тип аккаунта: ${accountRoleLabel(currentAccountRole)}`; accountRoleBtn.classList.remove('is-no', 'is-yes-official', 'is-yes-shine', 'is-not-interested'); accountRoleBtn.classList.add(currentAccountRole === PROFILE_ACCOUNT_ROLE_PRIMARY ? 'is-yes-official' : 'is-no'); } if (shineBtn) { shineBtn.textContent = `Сияние: ${shineStatusLabel(currentShineStatus)}`; shineBtn.classList.remove('is-no', 'is-yes-official', 'is-yes-shine', 'is-not-interested'); if (currentShineStatus === PROFILE_SHINE_SHINING) shineBtn.classList.add('is-yes-shine'); else if (currentShineStatus === PROFILE_SHINE_NOT_INTERESTED) shineBtn.classList.add('is-not-interested'); else shineBtn.classList.add('is-no'); } } function updateGenderUi() { const genderValueEl = listWrap.querySelector('[data-gender-value]'); if (!genderValueEl) return; genderValueEl.textContent = genderLabel(currentGender); } function openStatusPickerModal({ title, value, options }) { const root = document.getElementById('modal-root'); if (!root) return Promise.resolve(null); root.innerHTML = ` `; return new Promise((resolve) => { const modal = root.querySelector('#profile-status-modal'); const selectEl = root.querySelector('#profile-status-select'); const close = (next = null) => { root.innerHTML = ''; resolve(next); }; modal?.addEventListener('click', (event) => { if (event.target === modal) close(null); }); root.querySelector('#profile-status-cancel')?.addEventListener('click', () => close(null)); root.querySelector('#profile-status-save')?.addEventListener('click', () => close(selectEl?.value || null)); window.setTimeout(() => selectEl?.focus(), 0); }); } function openFieldEditModal({ label, value, placeholder = '', maxLength = 300, multiline = false, suggestions = null }) { const root = document.getElementById('modal-root'); if (!root) return Promise.resolve(null); root.innerHTML = ` `; return new Promise((resolve) => { const modal = root.querySelector('#profile-field-edit-modal'); const inputEl = root.querySelector('#profile-field-edit-input'); const saveEl = root.querySelector('#profile-field-edit-save'); const cancelEl = root.querySelector('#profile-field-edit-cancel'); if (!(modal instanceof HTMLElement) || (!(inputEl instanceof HTMLInputElement) && !(inputEl instanceof HTMLTextAreaElement))) { root.innerHTML = ''; resolve(null); return; } const close = (nextValue = null) => { root.innerHTML = ''; resolve(nextValue); }; modal.addEventListener('click', (event) => { if (event.target === modal) close(null); }); cancelEl?.addEventListener('click', () => close(null)); saveEl?.addEventListener('click', () => close(inputEl.value)); inputEl.addEventListener('keydown', (event) => { if (!multiline && event.key === 'Enter') { event.preventDefault(); close(inputEl.value); } }); window.setTimeout(() => { inputEl.focus(); inputEl.selectionStart = inputEl.value.length; inputEl.selectionEnd = inputEl.value.length; }, 0); }); } function renderFields(fields) { listWrap.innerHTML = ''; fields.forEach((field) => { const row = document.createElement('button'); row.type = 'button'; row.className = 'nav-row profile-param-item'; row.dataset.editField = field.key; const value = String(field.value || '').trim(); row.innerHTML = `${escapeHtml(field.label)}${escapeHtml(value || 'Не заполнено')}`; listWrap.append(row); if (field.key === 'last_name') { const genderRow = document.createElement('button'); genderRow.type = 'button'; genderRow.className = 'nav-row profile-param-item'; genderRow.dataset.editGender = 'true'; const genderText = genderLabel(currentGender); const genderEmpty = genderText === 'Не указан'; genderRow.innerHTML = `Пол${escapeHtml(genderEmpty ? 'Не указан' : genderText)}`; listWrap.append(genderRow); } }); } async function refreshProfileSnapshot() { status.className = 'status-line'; status.textContent = 'Загрузка параметров...'; reloadBtn.disabled = true; accountRoleBtn.disabled = true; shineBtn.disabled = true; try { const snapshot = await loadProfileSnapshot(login); currentFields = snapshot.fields; currentAccountRole = snapshot.accountRole || ''; currentShineStatus = snapshot.shineStatus || ''; currentGender = snapshot.gender || PROFILE_GENDER_UNKNOWN; currentAvatar = snapshot.avatar || { value: '', source: '', txId: '', sha256Hex: '', timeMs: 0 }; syncIdentity(); renderFields(currentFields); updateStatusesUi(); updateGenderUi(); updateAvatarUi(); status.className = 'status-line'; status.textContent = ''; } catch (error) { status.className = 'status-line is-unavailable'; status.textContent = actionErrorText('Не удалось загрузить параметры', error); showLocalErrorAlert('Не удалось загрузить профиль', error); } finally { reloadBtn.disabled = false; accountRoleBtn.disabled = false; shineBtn.disabled = false; } } async function onChangeAvatarClick() { status.className = 'status-line'; status.textContent = 'Открываем мастер аватара...'; try { await openAvatarWizard({ login, storagePwd: state.session.storagePwdInMemory, gateway: state.entrySettings.arweaveServer, navigate, onStatus: (message) => { status.className = 'status-line'; status.textContent = String(message || ''); }, onAvatarSaved: async () => { status.className = 'status-line'; status.textContent = 'Сохраняем аватар в профиль...'; await refreshProfileSnapshot(); status.className = 'status-line is-available'; status.textContent = 'Аватар обновлён.'; }, }); if (!status.textContent) { status.className = 'status-line'; } } catch (error) { status.className = 'status-line is-unavailable'; status.textContent = actionErrorText('Не удалось открыть мастер аватара', error); } } async function onStatusClick(statusKey) { const isAccountRole = statusKey === 'account_role'; const picked = await openStatusPickerModal({ title: isAccountRole ? 'Роль аккаунта' : 'Статус сияния', value: isAccountRole ? currentAccountRole : currentShineStatus, options: isAccountRole ? [ { value: PROFILE_ACCOUNT_ROLE_PRIMARY, label: 'Основной аккаунт' }, { value: PROFILE_ACCOUNT_ROLE_NON_VOTING, label: 'Не учитывать мой голос' }, ] : [ { value: PROFILE_SHINE_SHINING, label: 'Сияющий' }, { value: PROFILE_SHINE_UNKNOWN, label: 'Неизвестно' }, { value: PROFILE_SHINE_NOT_INTERESTED, label: 'Сияние мне неинтересно' }, ], }); if (!picked) return; status.className = 'status-line'; status.textContent = 'Сохранение в блокчейн...'; try { await saveProfileStatus(login, statusKey, picked); await refreshProfileSnapshot(); } catch (error) { status.className = 'status-line is-unavailable'; const what = isAccountRole ? 'тип аккаунта' : 'сияние'; status.textContent = `Не удалось изменить ${what}. ${toUserMessage(error, 'Попробуйте ещё раз.')}`; showLocalErrorAlert(`Не удалось изменить ${what}`, error); } } async function onEditFieldClick(fieldKey) { const field = currentFields.find((item) => item.key === fieldKey); if (!field) return; const entered = await openFieldEditModal({ label: field.label, value: field.value || '', placeholder: field.placeholder || '', maxLength: field.maxLength || 300, multiline: Boolean(field.multiline), suggestions: field.suggestions, }); if (entered === null) return; if (String(entered).length > Number(field.maxLength || 300)) { showToast(`В поле «${field.label}» – не больше ${Number(field.maxLength || 300)} символов.`, { kind: 'info' }); return; } status.className = 'status-line'; status.textContent = 'Сохранение в блокчейн...'; try { await saveProfileParamBlock(login, field.key, entered); await refreshProfileSnapshot(); } catch (error) { status.className = 'status-line is-unavailable'; status.textContent = `Не удалось изменить поле «${field.label}». ${toUserMessage(error, 'Попробуйте ещё раз.')}`; showLocalErrorAlert(`Не удалось изменить поле «${field.label}»`, error); } } async function onGenderClick() { const nextGender = await openGenderPickerModal(currentGender); if (!nextGender) return; status.className = 'status-line'; status.textContent = 'Сохранение в блокчейн...'; try { await saveProfileGender(login, nextGender); await refreshProfileSnapshot(); } catch (error) { status.className = 'status-line is-unavailable'; status.textContent = `Не удалось изменить пол. ${toUserMessage(error, 'Попробуйте ещё раз.')}`; showLocalErrorAlert('Не удалось изменить пол', error); } } listWrap.addEventListener('click', (event) => { const target = event.target; if (!(target instanceof HTMLElement)) return; const genderRow = target.closest('[data-edit-gender="true"]'); if (genderRow) { onGenderClick(); return; } const fieldRow = target.closest('[data-edit-field]'); const fieldKey = String(fieldRow?.getAttribute('data-edit-field') || ''); if (!fieldKey) return; onEditFieldClick(fieldKey); }); reloadBtn.addEventListener('click', refreshProfileSnapshot); accountRoleBtn.addEventListener('click', () => onStatusClick('account_role')); shineBtn.addEventListener('click', () => onStatusClick('shine')); avatarActionEl?.addEventListener('click', () => { void onChangeAvatarClick(); }); card.append(topRow, badgesRow, status, listWrap); screen.append(card); updateAvatarUi(); refreshProfileSnapshot(); return screen; }