Добавить трёхшаговый UI регистрации

This commit is contained in:
AidarKC
2026-11-05 00:04:05 +03:00
parent c13734cbc9
commit 41d5e79f83
19 changed files with 900 additions and 170 deletions
+222 -87
View File
@@ -1,102 +1,237 @@
import { createTopBar } from '../components/topbar.js';
import { authService, clearAuthMessages, resetRegistrationFlow, state } from '../state.js';
import { createRegistrationStepper } from '../components/registration-stepper.js';
import { authService, clearAuthMessages, state } from '../state.js';
import { PASSWORD_MAX_LENGTH } from '../services/password-words.js';
import { getRegistrationNamespaces, checkRegistrationLogin } from '../services/registration-v2-api.js';
import { normalizeFullLogin } from '../services/shine-namespace-service.js';
export const pageMeta = { id: 'register-view', title: 'Регистрация', showAppChrome: false };
export function render({navigate}) {
export function render({ navigate }) {
clearAuthMessages();
const screen=document.createElement('section'); screen.className='stack registration-screen';
const form=document.createElement('div'); form.className='card stack registration-form';
const method=document.createElement('select'); method.className='input';
method.innerHTML='<option value="1">Регистрация через Solana</option><option value="2">Бесплатная регистрация</option>';
method.value=state.registrationDraft.flowType==='free'?'2':'1';
const namespace=document.createElement('select'); namespace.className='input';
const local=document.createElement('input'); local.className='input'; local.placeholder='Логин (без @)';
local.autocomplete='off';local.spellcheck=false;local.autocapitalize='off';
local.value=String(state.registrationDraft.login || '').split('@')[0];
const full=document.createElement('p'); full.className='meta-muted';
const caseNotice=document.createElement('p'); caseNotice.className='meta-muted';
caseNotice.textContent='Регистр букв в логине сохранится навсегда. Например, AlexSmith@shine нельзя будет переименовать в alexsmith@shine. При входе и поиске регистр не важен.';
const password=document.createElement('input'); password.className='input';password.type='password';
password.autocomplete='new-password';password.maxLength=PASSWORD_MAX_LENGTH;
password.placeholder='Пароль';password.value=state.registrationDraft.password || '';
const status=document.createElement('p'); status.className='status-line';status.setAttribute('aria-live','polite');
const action=document.createElement('button');action.className='primary-btn';action.textContent='Проверить логин и продолжить';
const nsLabel=document.createElement('label');nsLabel.className='stack';nsLabel.textContent='Пространство имён'; nsLabel.append(namespace);
const methodLabel=document.createElement('label');methodLabel.className='stack'; methodLabel.textContent='Способ регистрации';methodLabel.append(method);
const pwLabel=document.createElement('label');pwLabel.className='stack';pwLabel.textContent='Пароль (ключи остаются только у вас)';pwLabel.append(password);
const passwordHelp=document.createElement('p');passwordHelp.className='meta-muted';
passwordHelp.hidden=true;
passwordHelp.textContent='После проверки логина мы сгенерируем ключи из вашего пароля на этом устройстве. Это занимает несколько секунд и делает массовый подбор паролей значительно сложнее.';
form.append(methodLabel,nsLabel,local,full,caseNotice,pwLabel,passwordHelp,status,action);
let namespaces=[]; let disposed=false; let inputRevision=0; let submission=0;
const feeToSol = fee => (Number(fee || '0')/1e9).toFixed(6);
function selected() { return namespaces.find(n=>n.name===namespace.value); }
function display() {
namespace.replaceChildren();
for (const ns of namespaces.filter(n=>Number(n.type)===Number(method.value))) {
const opt=document.createElement('option');opt.value=ns.name;
opt.textContent=`@${ns.name} · от ${ns.minLocalLength} симв. · ${feeToSol(ns.registrationFeeLamports)} SOL`;
namespace.append(opt);
}
if (state.registrationDraft.login.includes('@')) {
const wanted=state.registrationDraft.login.split('@')[1];
if([...namespace.options].some(x=>x.value===wanted))namespace.value=wanted;
}
showFull();
const draft = state.registrationDraft;
const screen = document.createElement('section');
screen.className = 'stack registration-screen signup-wizard';
const body = document.createElement('div');
body.className = 'card stack registration-form signup-wizard__body';
const header = createTopBar({ title: 'Регистрация в SHiNE', back: { label: '←', onClick: goBack } });
screen.append(header, body);
let namespaces = [];
let isLoading = true;
let fetchError = '';
let inputRevision = 0;
let requestId = 0;
let localDraft = String(draft.login || '').split('@')[0];
const flowType = draft.flowType;
function confirmFundedWalletChange() {
const balance = Number(state.registrationPayment?.balanceSOL || 0);
if (balance <= 0) return true;
return window.confirm('Внимание: кошелёк уже пополнен. Изменение логина или пароля создаст другой кошелёк! Средства останутся на старом адресе, и для доступа к ним потребуется прежний пароль. Продолжить?');
}
function showFull() {
full.textContent=namespace.value?`Полное имя: ${local.value.trim()}@${namespace.value}`:'Нет доступных namespace этого типа';
status.textContent='';
function goBack() {
if (Number(draft.uiStep) === 2) {
draft.uiStep = 1;
showLogin();
return;
}
navigate('registration-choice-view');
}
method.addEventListener('change',()=>{inputRevision++;display();});
namespace.addEventListener('change',()=>{inputRevision++;showFull();});
local.addEventListener('input',()=>{inputRevision++;showFull();});
function showPasswordHelp() { passwordHelp.hidden=!password.value; }
password.addEventListener('input',()=>{inputRevision++;showPasswordHelp();});
showPasswordHelp();
void getRegistrationNamespaces().then(data=>{
if(disposed)return;namespaces=Array.isArray(data.namespaces)?data.namespaces:[];display();
if(!namespaces.length)status.textContent='Solana namespace ещё не синхронизированы с сервером';
}).catch(error=>{if(!disposed)status.textContent=`Не удалось получить namespace: ${error.message}`;});
action.addEventListener('click',async()=>{
const ns=selected();if(!ns){status.textContent='Выберите доступный namespace';return;}
let login;
try {
login=normalizeFullLogin(`${local.value.trim()}@${ns.name}`);
if(local.value.trim().length < Number(ns.minLocalLength))throw new Error(`Логин не короче ${ns.minLocalLength} символов`);
if(!password.value || password.value.length>PASSWORD_MAX_LENGTH)throw new Error('Введите непустой пароль допустимой длины');
}catch(error){status.textContent=error.message;return;}
const thisRun=++submission;
const thisInputRevision=inputRevision;
action.disabled=true;status.textContent='Проверяем выбранный логин…';
try {
const check=await checkRegistrationLogin(login);
if(disposed || thisRun!==submission)return;
if(thisInputRevision!==inputRevision)throw new Error('Данные формы изменились. Проверьте их и повторите попытку.');
if(!check.loginAvailable)throw new Error('Этот логин уже занят');
if(Number(check.namespaceType)!==Number(method.value))throw new Error('Тип namespace изменился. Обновите список.');
const draft=state.registrationDraft;
const changed=draft.login!==login || draft.password!==password.value;
draft.login=login;draft.password=password.value;draft.flowType=method.value==='2'?'free':'paid';
draft.namespaceFeeLamports=String(check.registrationFeeLamports||ns.registrationFeeLamports);
draft.namespaceServerLogin=ns.defaultServerLogin||'';
if(changed)draft.preGeneratedKeyBundle=null;
status.textContent='Генерируем ключи из вашего пароля… Это нужно, чтобы сделать массовый подбор паролей значительно сложнее.';
const bundle=draft.preGeneratedKeyBundle || await authService.derivePasswordKeyBundle(login,password.value);
if(disposed || thisRun!==submission)return;
draft.preGeneratedKeyBundle=bundle;
if(draft.flowType==='free') {
navigate('registration-email-view');
// Кнопка назад TopBar создана один раз, переход между шагами — внутри страницы.
function statusLine() {
const status = document.createElement('p');
status.className = 'status-line';
status.setAttribute('aria-live', 'polite');
return status;
}
function title(text, detail) {
const heading = document.createElement('h1');
heading.className = 'signup-title';
heading.textContent = text;
const subtitle = document.createElement('p');
subtitle.className = 'signup-lead';
subtitle.textContent = detail;
return [heading, subtitle];
}
function selectedNamespace() {
const candidates = namespaces.filter(n => Number(n.type) === (flowType === 'free' ? 2 : 1));
return candidates.find(n => String(n.name).toLowerCase() === (flowType === 'free' ? 'free' : 'shine')) || candidates[0];
}
function showLogin() {
draft.uiStep = 1;
body.replaceChildren(createRegistrationStepper(1));
const [heading, description] = title('Выберите логин', 'Уникальное имя, под которым вас будут знать в SHiNE. После регистрации его написание изменить нельзя.');
const label = document.createElement('label');
label.className = 'stack';
const labelText = document.createElement('span');
labelText.className = 'field-label';
labelText.textContent = 'Ваш логин';
const input = document.createElement('input');
input.className = 'input';
input.placeholder = 'Например, Alex';
input.autocomplete = 'off';
input.autocapitalize = 'off';
input.spellcheck = false;
input.value = localDraft;
label.append(labelText, input);
const fullLogin = document.createElement('p');
fullLogin.className = 'signup-full-login';
const caseInfo = document.createElement('p');
caseInfo.className = 'meta-muted';
caseInfo.textContent = 'Регистр сохраняется: Alex и alex при проверке считаются одним логином, но отображаться будет выбранное написание.';
const status = statusLine();
const next = document.createElement('button');
next.className = 'primary-btn signup-next';
next.textContent = 'Продолжить';
next.type = 'button';
next.disabled = isLoading;
function updateFull() {
const ns = selectedNamespace();
fullLogin.textContent = ns ? `${input.value.trim() || 'ВашЛогин'}@${ns.name}` : 'Пока нет доступного пространства имён';
status.textContent = fetchError;
next.disabled = isLoading || !ns;
}
input.addEventListener('input', () => { inputRevision++; localDraft = input.value; updateFull(); });
next.addEventListener('click', async () => {
const ns = selectedNamespace();
if (!ns) { status.textContent = 'Пространство имён пока недоступно'; return; }
let login;
try {
const local = input.value.trim();
if (local.length < Number(ns.minLocalLength)) throw new Error(`Минимальная длина логина: ${ns.minLocalLength} символов.`);
login = normalizeFullLogin(`${local}@${ns.name}`);
} catch (error) { status.textContent = error.message; return; }
const revision = inputRevision;
const thisRequest = ++requestId;
next.disabled = true;
status.textContent = 'Проверяем доступность логина…';
try {
const available = await checkRegistrationLogin(login);
if (!screen.isConnected || thisRequest !== requestId) return;
if (revision !== inputRevision) throw new Error('Логин изменился. Нажмите «Продолжить» ещё раз.');
if (!available.loginAvailable) throw new Error('Такой логин уже занят. Попробуйте другой.');
if (Number(available.namespaceType) !== Number(ns.type)) throw new Error('Тип регистрации изменился. Вернитесь к выбору аккаунта.');
if (draft.login !== login) {
if (!confirmFundedWalletChange()) return;
state.registrationPayment.walletAddress = '';
state.registrationPayment.balanceSOL = '0.0000';
draft.preGeneratedKeyBundle = null;
draft.challengeId = '';
draft.challengeExpiresAtMs = 0;
}
draft.login = login;
draft.namespaceFeeLamports = String(available.registrationFeeLamports ?? ns.registrationFeeLamports ?? 0);
draft.namespaceServerLogin = ns.defaultServerLogin || '';
draft.uiStep = 2;
showPassword();
} catch (error) {
if (screen.isConnected && thisRequest === requestId) status.textContent = error.message || 'Ошибка проверки логина.';
} finally {
if (screen.isConnected && thisRequest === requestId) next.disabled = false;
}
});
body.append(heading, description, label, fullLogin, caseInfo, status, next);
updateFull();
}
function showPassword() {
draft.uiStep = 2;
body.replaceChildren(createRegistrationStepper(2));
const [heading, description] = title('Придумайте пароль', 'На вашем устройстве из логина и пароля создаются криптографические ключи доступа. Приватные ключи не хранятся на сервере.');
const label = document.createElement('label');
label.className = 'stack';
const labelText = document.createElement('span');
labelText.className = 'field-label';
labelText.textContent = `Пароль (от 12 до ${PASSWORD_MAX_LENGTH} символов)`;
const row = document.createElement('div');
row.className = 'signup-password-row';
const input = document.createElement('input');
input.className = 'input';
input.type = 'password';
input.autocomplete = 'new-password';
input.maxLength = PASSWORD_MAX_LENGTH;
input.placeholder = 'Ваш секретный пароль';
input.value = draft.password || '';
const toggle = document.createElement('button');
toggle.className = 'secondary-btn';
toggle.type = 'button';
toggle.textContent = 'Показать';
toggle.setAttribute('aria-label', 'Показать или скрыть пароль');
toggle.addEventListener('click', () => {
input.type = input.type === 'password' ? 'text' : 'password';
toggle.textContent = input.type === 'password' ? 'Показать' : 'Скрыть';
});
row.append(input, toggle);
label.append(labelText, row);
const guidance = document.createElement('div');
guidance.className = 'signup-guidance';
guidance.innerHTML = `
<strong>Лучший пароль — тот, который вы точно помните.</strong>
<p>Подойдёт своя длинная фраза, 12 случайных слов через дефис или случайный код из 50 символов. Не используйте известные цитаты и очевидные последовательности. Можно добавить цифры и специальные знаки.</p>
<p>На привычном устройстве обычно не придётся вводить пароль при каждом входе: рабочие ключи сохраняются локально. Для входа с нового устройства пароль — ваш резервный способ доступа.</p>
<p class="signup-guidance__warning"><strong>Не теряйте пароль!</strong> Мы не можем восстановить его или ваши ключи. Если доступ к ключам на всех устройствах утрачен, зашифрованная личная переписка может оказаться недоступна.</p>
<p>${flowType === 'free'
? 'В бесплатном аккаунте смена пароля недоступна. После перехода на полноценный аккаунт появится возможность его менять.'
: 'Для полноценного аккаунта поддерживается смена пароля: необходимые зашифрованные сообщения перешифровываются на вашем устройстве, а не на сервере.'}</p>
`;
const status = statusLine();
const next = document.createElement('button');
next.className = 'primary-btn signup-next';
next.type = 'button';
next.textContent = 'Продолжить';
input.addEventListener('input', () => { inputRevision++; status.textContent = ''; });
next.addEventListener('click', async () => {
const value = input.value;
if (value.length < 12 || value.length > PASSWORD_MAX_LENGTH) {
status.textContent = `Введите пароль длиной от 12 до ${PASSWORD_MAX_LENGTH} символов.`;
return;
}
navigate('registration-payment-view');
}catch(error){if(!disposed && thisRun===submission)status.textContent=error.message || 'Не удалось продолжить регистрацию.';}
finally {if(thisRun===submission)action.disabled=false;}
if (!draft.login || !draft.login.includes('@')) { status.textContent = 'Сначала выберите логин.'; return; }
if (draft.password && draft.password !== value && !confirmFundedWalletChange()) return;
if (draft.password && draft.password !== value) {
state.registrationPayment.walletAddress = '';
state.registrationPayment.balanceSOL = '0.0000';
draft.challengeId = '';
draft.challengeExpiresAtMs = 0;
}
const revision = inputRevision;
const thisRequest = ++requestId;
next.disabled = true;
status.textContent = 'Генерируем ключи из пароля на этом устройстве…';
try {
const changed = draft.password !== value;
draft.password = value;
if (changed) draft.preGeneratedKeyBundle = null;
const bundle = draft.preGeneratedKeyBundle || await authService.derivePasswordKeyBundle(draft.login, value);
if (!screen.isConnected || thisRequest !== requestId) return;
if (revision !== inputRevision) throw new Error('Пароль изменился. Нажмите «Продолжить» ещё раз.');
draft.preGeneratedKeyBundle = bundle;
navigate(flowType === 'free' ? 'registration-email-view' : 'registration-payment-view');
} catch (error) {
if (screen.isConnected && thisRequest === requestId) status.textContent = error.message || 'Не удалось создать ключи.';
} finally {
if (screen.isConnected && thisRequest === requestId) next.disabled = false;
}
});
body.append(heading, description, label, guidance, status, next);
}
if (flowType !== 'free' && flowType !== 'paid') {
queueMicrotask(() => navigate('registration-choice-view'));
return screen;
}
if (Number(draft.uiStep) === 2 && draft.login) showPassword();
else showLogin();
void getRegistrationNamespaces().then(data => {
namespaces = Array.isArray(data.namespaces) ? data.namespaces : [];
isLoading = false;
if (!selectedNamespace()) fetchError = 'Сервер пока не предоставил пространство имён для выбранного типа регистрации.';
if (screen.isConnected && Number(draft.uiStep) === 1) showLogin();
}).catch(error => {
isLoading = false;
fetchError = `Не удалось загрузить пространства имён: ${error.message}`;
if (screen.isConnected && Number(draft.uiStep) === 1) showLogin();
});
screen.append(createTopBar({title:'Регистрация',back:{label:'←',onClick:()=>{resetRegistrationFlow();navigate('start-view');}}}),form);
return screen;
}