Files
SHiNE-server/shine-UI/js/pages/profile-edit-view.js
T

511 lines
22 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#39;');
}
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 = `
<div class="row" style="gap:12px; align-items:center;">
<div class="profile-avatar-block" data-change-avatar="true" style="cursor:pointer;">
<div data-profile-avatar-slot="true"></div>
</div>
<div class="profile-identity-lines" data-profile-identity="true">
<div class="profile-identity-line profile-identity-login">${String(login || '').trim() || 'unknown'}</div>
</div>
</div>
<button class="secondary-btn profile-edit-reload" type="button" data-reload="true" hidden>Обновить</button>
`;
const badgesRow = document.createElement('div');
badgesRow.className = 'chip-row profile-edit-statuses';
badgesRow.innerHTML = `
<button class="chip profile-toggle-btn is-no" type="button" data-status="account_role">Тип аккаунта: Не указано</button>
<button class="chip profile-toggle-btn is-no" type="button" data-status="shine">Сияние: Не указано</button>
`;
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 = `
<div class="modal" id="profile-gender-modal">
<div class="modal-card stack">
<h3 class="modal-title">Выбор пола</h3>
<p class="meta-muted">Выберите значение профиля из списка:</p>
<select class="input profile-gender-select" id="profile-gender-select">
${GENDER_OPTIONS.map((item) => (
`<option value="${item.value}" ${item.value === selected ? 'selected' : ''}>${item.label}</option>`
)).join('')}
</select>
<div class="form-actions-grid">
<button class="secondary-btn" id="profile-gender-cancel" type="button">Отмена</button>
<button class="primary-btn" id="profile-gender-save" type="button">Сохранить</button>
</div>
</div>
</div>
`;
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) => (
`<div class="profile-identity-line${idx === lines.length - 1 ? ' profile-identity-login' : ''}">${escapeHtml(line)}</div>`
)).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 = `
<div class="modal" id="profile-status-modal">
<div class="modal-card stack">
<h3 class="modal-title">${escapeHtml(title)}</h3>
<select class="input" id="profile-status-select">
${options.map((item) => `<option value="${escapeHtml(item.value)}" ${item.value === value ? 'selected' : ''}>${escapeHtml(item.label)}</option>`).join('')}
</select>
<div class="form-actions-grid">
<button class="secondary-btn" id="profile-status-cancel" type="button">Отмена</button>
<button class="primary-btn" id="profile-status-save" type="button">Сохранить</button>
</div>
</div>
</div>`;
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 = `
<div class="modal" id="profile-field-edit-modal">
<div class="modal-card stack">
<h3 class="modal-title">Изменить: ${escapeHtml(label)}</h3>
${multiline ? `<textarea
id="profile-field-edit-input"
class="input"
maxlength="${Number(maxLength || 300)}"
rows="${Number(maxLength || 300) > 1000 ? 12 : 4}"
placeholder="${escapeHtml(placeholder || `Введите ${label.toLowerCase()}`)}"
>${escapeHtml(String(value || ''))}</textarea>` : `<input
id="profile-field-edit-input"
class="input"
type="text"
maxlength="${Number(maxLength || 300)}"
placeholder="${escapeHtml(placeholder || `Введите ${label.toLowerCase()}`)}"
value="${escapeHtml(String(value || ''))}"
${suggestions?.length ? 'list="profile-field-edit-suggestions" autocomplete="off"' : ''}
/>${suggestions?.length ? `<datalist id="profile-field-edit-suggestions">${suggestions.map((item) => `<option value="${escapeHtml(item)}"></option>`).join('')}</datalist>` : ''}`}
<div class="meta-muted">До ${Number(maxLength || 300)} символов.</div>
<div class="form-actions-grid">
<button class="secondary-btn" id="profile-field-edit-cancel" type="button">Отмена</button>
<button class="primary-btn" id="profile-field-edit-save" type="button">Сохранить</button>
</div>
</div>
</div>
`;
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 = `<span class="nav-row__hint">${escapeHtml(field.label)}</span><span class="nav-row__label${value ? '' : ' is-empty'}">${escapeHtml(value || 'Не заполнено')}</span>`;
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 = `<span class="nav-row__hint">Пол</span><span class="nav-row__label${genderEmpty ? ' is-empty' : ''}" data-gender-value>${escapeHtml(genderEmpty ? 'Не указан' : genderText)}</span>`;
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;
}