SHA256
97 lines
7.0 KiB
JavaScript
97 lines
7.0 KiB
JavaScript
import { createTopBar } from '../components/topbar.js';
|
|
import { authService, clearAuthMessages, resetRegistrationFlow, 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}) {
|
|
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);
|
|
form.append(methodLabel,nsLabel,local,full,caseNotice,pwLabel,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();
|
|
}
|
|
function showFull() {
|
|
full.textContent=namespace.value?`Полное имя: ${local.value.trim()}@${namespace.value}`:'Нет доступных namespace этого типа';
|
|
status.textContent='';
|
|
}
|
|
method.addEventListener('change',()=>{inputRevision++;display();});
|
|
namespace.addEventListener('change',()=>{inputRevision++;showFull();});
|
|
local.addEventListener('input',()=>{inputRevision++;showFull();});
|
|
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;
|
|
if(draft.flowType==='free') {
|
|
navigate('registration-email-view');
|
|
return;
|
|
}
|
|
status.textContent='Создаём ключи локально (Argon2id)…';
|
|
const bundle=draft.preGeneratedKeyBundle || await authService.derivePasswordKeyBundle(login,password.value);
|
|
if(disposed || thisRun!==submission)return;
|
|
draft.preGeneratedKeyBundle=bundle;
|
|
navigate('registration-payment-view');
|
|
}catch(error){if(!disposed && thisRun===submission)status.textContent=error.message || 'Не удалось продолжить регистрацию.';}
|
|
finally {if(thisRun===submission)action.disabled=false;}
|
|
});
|
|
screen.append(createTopBar({title:'Регистрация',back:{label:'←',onClick:()=>{resetRegistrationFlow();navigate('start-view');}}}),form);
|
|
return screen;
|
|
}
|