import { t, th } from '../i18n/index.js'; import { createTopBar } from '../components/topbar.js'; import { confirmDialog } from '../components/confirm-dialog.js'; import { confirmPublicHistoryAction } from '../services/public-history-consent.js'; import { confirmConsentSteps } from '../components/consent-steps.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_ACCOUNT_ROLE_PRIMARY, PROFILE_SHINE_SHINING, PROFILE_SHINE_UNKNOWN, loadProfileSnapshot, 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', get title() { return t('screens.profile_edit_view.text_001'); } }; function shineStatusLabel(value) { return value === PROFILE_SHINE_SHINING ? t('screens.profile_edit_view.text_011') : t('screens.profile_edit_view.text_012'); } function shiningSteps() { return [ { title: t('dialogs.final.consent.shining_steps.siyayuschiy_ofitsialnyy'), text: t('dialogs.final.consent.shining_steps.otmetit_sebya_siyayuschim_mozhno_i_s_neofitsialnog') }, { title: t('dialogs.final.consent.shining_steps.chto_znachit_siyayuschiy'), text: t('dialogs.final.consent.shining_steps.v_shine_eto_chelovek_kotoryy_zanimaetsya_vnutrenni') }, { title: t('dialogs.final.consent.shining_steps.1_chestnost'), text: t('dialogs.final.consent.shining_steps.siyayuschiy_staraetsya_ne_lgat_i_ne_vvodit_lyudey'), accept: t('dialogs.final.consent.shining_steps.chestnost_moy_printsip') }, { title: t('dialogs.final.consent.shining_steps.2_duhovnoe_izmerenie'), text: t('dialogs.final.consent.shining_steps.vy_dopuskaete_chto_chelovek_ne_tolko_fizicheskoe_t'), accept: t('dialogs.final.consent.shining_steps.mne_blizko_takoe_ponimanie_cheloveka') }, { title: t('dialogs.final.consent.shining_steps.3_razvitie'), text: t('dialogs.final.consent.shining_steps.siyayuschiy_stremitsya_uchitsya_osoznavat_sebya_i'), accept: t('dialogs.final.consent.shining_steps.ya_stremlyus_razvivatsya_i_delitsya_poleznym') }, { title: t('dialogs.final.consent.shining_steps.4_zabota_o_mire'), text: t('dialogs.final.consent.shining_steps.siyayuschiy_staraetsya_delat_mir_vokrug_luchshe_sl'), accept: t('dialogs.final.consent.shining_steps.ya_hochu_prinosit_polzu_lyudyam_i_miru') }, { title: t('dialogs.final.consent.shining_steps.5_svyazi_s_drugimi_siyayuschimi'), text: t('dialogs.final.consent.shining_steps.vzaimnye_znakomstva_i_podtverzhdeniya_drugih_lyude'), accept: t('dialogs.final.consent.shining_steps.ponimayu_chto_set_otsenivaet_ne_tolko_moyu_galochk') }, { title: t('dialogs.final.consent.shining_steps.podtverzhdeniya_drugih'), text: t('dialogs.final.consent.shining_steps.tolko_ofitsialnyy_siyayuschiy_mozhet_podtverzhdat'), accept: t('dialogs.final.consent.shining_steps.budu_podtverzhdat_drugih_dobrosovestno') }, { title: t('dialogs.final.consent.shining_steps.otkrytoe_zayavlenie'), text: t('dialogs.final.consent.shining_steps.otmetka_siyayuschiy_sozdayot_publichnuyu_zapis_eyo'), accept: t('dialogs.final.consent.shining_steps.ya_ponimayu_posledstviya_i_soglasen_na_opublikovat'), button: t('dialogs.final.consent.shining_steps.ya_siyayuschiy') }, ]; } // Ошибка – понятным сообщением внизу экрана, а не окном со стеком вызовов // (подробности остаются в журнале приложения). function showLocalErrorAlert(prefix, error) { showToast(`${prefix}. ${toUserMessage(error, t('screens.profile_edit_view.text_006'))}`, { kind: 'error' }); } 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: t('screens.profile_edit_view.text_005'), 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 = t('dialogs.modals.profile_edit_view.label_003'); 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 statusFlowOpen = false; let currentAvatar = { value: '', source: '', txId: '', pr: '', timeMs: 0 }; const identityEl = topRow.querySelector('[data-profile-identity="true"]'); const avatarSlotEl = topRow.querySelector('[data-profile-avatar-slot="true"]'); 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.classList.toggle('is-shining', currentShineStatus === PROFILE_SHINE_SHINING); avatarSlotEl.append(renderUserAvatar({ login, firstName, lastName, avatar: (currentAvatar?.txId || currentAvatar?.pr) ? { ar: String(currentAvatar.txId || currentAvatar.ar || '').trim(), pr: String(currentAvatar?.pr || '').trim() } : null, size: 'xl', // Как в карточке профиля: без стеклянного кольца, которое вылезало за край экрана. className: 'profile-avatar avatar-plain', official: currentAccountRole === PROFILE_ACCOUNT_ROLE_PRIMARY, })); } function updateStatusesUi() { if (accountRoleBtn) { accountRoleBtn.textContent = t(currentAccountRole === PROFILE_ACCOUNT_ROLE_PRIMARY ? 'screens.registration_identity.official_button' : 'screens.registration_identity.alternative_button'); 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 = t('screens.profile_edit_view.text_021', { value1: 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 shineBtn.classList.add('is-no'); } } 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 || t('screens.profile_edit_view.text_019'))}`; listWrap.append(row); }); } async function refreshProfileSnapshot() { status.className = 'status-line'; status.textContent = t('dialogs.modals.profile_edit_view.label_003'); reloadBtn.disabled = true; shineBtn.disabled = true; try { const snapshot = await loadProfileSnapshot(login); currentFields = snapshot.fields; currentAccountRole = snapshot.accountRole || ''; currentShineStatus = snapshot.shineStatus || ''; currentAvatar = snapshot.avatar || { value: '', source: '', txId: '', pr: '', timeMs: 0 }; syncIdentity(); renderFields(currentFields); updateStatusesUi(); updateAvatarUi(); status.className = 'status-line'; status.textContent = ''; } catch (error) { status.className = 'status-line is-unavailable'; status.textContent = actionErrorText(t('dialogs.modals.profile_edit_view.label_004'), error); showLocalErrorAlert(t('screens.profile_edit_view.text_007'), error); } finally { reloadBtn.disabled = false; shineBtn.disabled = false; } } async function onChangeAvatarClick() { const accepted = await confirmPublicHistoryAction({ title: t('dialogs.final.consent.avatar_history_title'), text: t('dialogs.final.consent.avatar_history_warning'), confirmLabel: t('dialogs.final.consent.choose_avatar'), }); if (!accepted || !screen.isConnected) return; status.className = 'status-line'; status.textContent = t('dialogs.modals.profile_edit_view.label_005'); 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 = t('dialogs.modals.profile_edit_view.label_006'); await refreshProfileSnapshot(); status.className = 'status-line is-available'; status.textContent = t('dialogs.modals.profile_edit_view.label_007'); }, }); if (!status.textContent) { status.className = 'status-line'; } } catch (error) { status.className = 'status-line is-unavailable'; status.textContent = actionErrorText(t('dialogs.modals.profile_edit_view.label_008'), error); } } async function onStatusClick(statusKey) { if (statusKey !== 'shine' || statusFlowOpen) return; statusFlowOpen = true; try { const alreadyOn = currentShineStatus === PROFILE_SHINE_SHINING; const accepted = alreadyOn ? await confirmDialog({ title: t('dialogs.final.consent.remove_shining'), text: t('dialogs.pages.profile_edit_view.text_001'), confirmLabel: t('dialogs.pages.profile_edit_view.confirmLabel_002'), }) : await confirmConsentSteps({ title: t('dialogs.final.consent.shining_title'), steps: shiningSteps() }); if (!accepted || !screen.isConnected) return; status.className = 'status-line'; status.textContent = t('dialogs.modals.profile_edit_view.label_009'); shineBtn.disabled = true; try { await saveProfileStatus(login, 'shine', alreadyOn ? PROFILE_SHINE_UNKNOWN : PROFILE_SHINE_SHINING); if (screen.isConnected) await refreshProfileSnapshot(); } catch (error) { if (!screen.isConnected) return; status.className = 'status-line is-unavailable'; const what = t('screens.profile_edit_view.text_018'); status.textContent = t('screens.profile_edit_view.text_022', { value1: what, value2: toUserMessage(error, t('dialogs.modals.profile_edit_view.label_010')) }); showLocalErrorAlert(t('screens.profile_edit_view.text_023', { value1: what }), error); } finally { if (screen.isConnected) shineBtn.disabled = false; } } finally { statusFlowOpen = false; } } 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(t('screens.profile_edit_view.text_024', { value1: field.label, value2: Number(field.maxLength || 300) }), { kind: 'info' }); return; } if (String(entered).trim() === String(field.value || '').trim()) return; const accepted = await confirmPublicHistoryAction({ title: t('dialogs.final.consent.publish_change_title', { field: field.label }), text: t('dialogs.final.consent.public_history_warning'), confirmLabel: t('dialogs.final.consent.record_yes'), cancelLabel: t('dialogs.final.consent.record_no'), }); if (!accepted || !screen.isConnected) return; status.className = 'status-line'; status.textContent = t('dialogs.modals.profile_edit_view.label_009'); try { await saveProfileParamBlock(login, field.key, entered); await refreshProfileSnapshot(); } catch (error) { status.className = 'status-line is-unavailable'; status.textContent = t('screens.profile_edit_view.text_025', { value1: field.label, value2: toUserMessage(error, t('dialogs.modals.profile_edit_view.label_010')) }); showLocalErrorAlert(t('screens.profile_edit_view.text_026', { value1: field.label }), error); } } listWrap.addEventListener('click', (event) => { const target = event.target; if (!(target instanceof HTMLElement)) 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', () => { const official = currentAccountRole === PROFILE_ACCOUNT_ROLE_PRIMARY; void confirmDialog({ title: accountRoleBtn.textContent, text: t(official ? 'screens.registration_identity.official_help' : 'screens.registration_identity.alternative_help') + '\n\n' + t('screens.registration_identity.immutable'), confirmLabel: t('screens.registration_identity.ok'), infoOnly: true }); }); shineBtn.addEventListener('click', () => onStatusClick('shine')); avatarActionEl?.addEventListener('click', () => { void onChangeAvatarClick(); }); card.append(topRow, badgesRow, status, listWrap); screen.append(card); updateAvatarUi(); refreshProfileSnapshot(); return screen; }