SHA256
357 lines
19 KiB
JavaScript
357 lines
19 KiB
JavaScript
import { t, th } from '../i18n/index.js';
|
||
import { createTopBar } from '../components/topbar.js';
|
||
import { createVisiblePasswordField, createExpandablePasswordTextarea } from '../components/visible-password-field.js';
|
||
import { createSecretGenerationOverlay } from '../components/secret-generation-overlay.js';
|
||
import { confirmPasswordBoundarySpaces } from '../services/password-boundary-warning.js';
|
||
import { createRegistrationStepper } from '../components/registration-stepper.js';
|
||
import { authService, clearAuthMessages, clearRegistrationDraft, state } from '../state.js';
|
||
import { PASSWORD_MAX_LENGTH } from '../services/password-words.js';
|
||
import { getRegistrationNamespaces, checkRegistrationLogin } from '../services/registration-v2-api.js';
|
||
import { savePendingHeaderIdentity } from '../services/pending-header-identity.js';
|
||
import { normalizeFullLogin } from '../services/shine-namespace-service.js';
|
||
|
||
export const pageMeta = { id: 'register-view', get title() { return t('screens.register_view.text_001'); }, showAppChrome: false };
|
||
|
||
export function render({ navigate }) {
|
||
clearAuthMessages();
|
||
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: t('screens.register_view.text_002'), back: { label: '←', onClick: goBack } });
|
||
const keyGeneration = createSecretGenerationOverlay();
|
||
screen.append(header, body, keyGeneration.overlay);
|
||
|
||
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(t('screens.register_view.text_039'));
|
||
}
|
||
function goBack() {
|
||
if (Number(draft.uiStep) === 4) {
|
||
showAccountType();
|
||
return;
|
||
}
|
||
if (Number(draft.uiStep) === 3) {
|
||
showPassword();
|
||
return;
|
||
}
|
||
if (Number(draft.uiStep) === 2) {
|
||
draft.uiStep = 1;
|
||
showLogin();
|
||
return;
|
||
}
|
||
navigate('registration-choice-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, draft.accountType === 1 ? 5 : 4));
|
||
const [heading, description] = title(t('screens.register_view.text_014'), t('screens.register_view.text_015'));
|
||
const label = document.createElement('label');
|
||
label.className = 'stack';
|
||
const labelText = document.createElement('span');
|
||
labelText.className = 'field-label';
|
||
labelText.textContent = t('screens.register_view.text_003');
|
||
const input = document.createElement('input');
|
||
input.className = 'input';
|
||
input.placeholder = t('screens.register_view.text_004');
|
||
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 = t('screens.register_view.text_005');
|
||
const status = statusLine();
|
||
const next = document.createElement('button');
|
||
next.className = 'primary-btn signup-next';
|
||
next.textContent = t('screens.register_view.text_006');
|
||
next.type = 'button';
|
||
next.disabled = isLoading;
|
||
function updateFull() {
|
||
const ns = selectedNamespace();
|
||
fullLogin.textContent = ns ? `${input.value.trim() || t('screens.register_view.text_021')}@${ns.name}` : t('screens.register_view.text_018');
|
||
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 = t('screens.register_view.text_007'); return; }
|
||
let login;
|
||
try {
|
||
const local = input.value.trim();
|
||
if (local.length < Number(ns.minLocalLength)) throw new Error(t('screens.register_view.text_030', { value1: 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 = t('screens.register_view.text_008');
|
||
try {
|
||
const available = await checkRegistrationLogin(login);
|
||
if (!screen.isConnected || thisRequest !== requestId) return;
|
||
if (revision !== inputRevision) throw new Error(t('screens.register_view.text_022'));
|
||
if (!available.loginAvailable) throw new Error(t('screens.register_view.text_023'));
|
||
if (Number(available.namespaceType) !== Number(ns.type)) throw new Error(t('screens.register_view.text_024'));
|
||
if (Number(available.currencyCode ?? 1) !== 1 || Number(ns.currencyCode ?? 1) !== 1) throw new Error(t('screens.register_view.text_025'));
|
||
if (draft.login !== login) {
|
||
if (!confirmFundedWalletChange()) return;
|
||
clearRegistrationDraft({ preserveFlowType: true });
|
||
}
|
||
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 || t('screens.register_view.text_026');
|
||
} 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, draft.accountType === 1 ? 5 : 4));
|
||
const [heading, description] = title(t('screens.register_view.text_016'), t('screens.register_view.text_017'));
|
||
const label = document.createElement('label');
|
||
label.className = 'stack';
|
||
const labelText = document.createElement('span');
|
||
labelText.className = 'field-label';
|
||
labelText.textContent = t('screens.register_view.text_031', { value1: PASSWORD_MAX_LENGTH });
|
||
const input = createExpandablePasswordTextarea();
|
||
input.autocomplete = 'new-password';
|
||
input.maxLength = PASSWORD_MAX_LENGTH;
|
||
input.placeholder = t('screens.register_view.text_009');
|
||
// Never repopulate a successfully submitted secret on returning to this step.
|
||
input.value = '';
|
||
const passwordCount = document.createElement('span');
|
||
passwordCount.className = 'password-length-hint';
|
||
passwordCount.setAttribute('aria-live', 'off');
|
||
const refreshPasswordCount = () => {
|
||
passwordCount.textContent = t('screens.register_view.password_counter', { value1: input.value.length, value2: PASSWORD_MAX_LENGTH });
|
||
};
|
||
label.append(labelText, createVisiblePasswordField(input), passwordCount);
|
||
refreshPasswordCount();
|
||
requestAnimationFrame(() => input.resizePasswordField());
|
||
const guidance = document.createElement('div');
|
||
guidance.className = 'signup-guidance';
|
||
guidance.innerHTML = `
|
||
<strong>${th('screens.register_view.text_034')}</strong>
|
||
<p>${th('screens.register_view.text_035')}</p>
|
||
<p>${th('screens.register_view.text_036')}</p>
|
||
<p class="signup-guidance__warning"><strong>${th('screens.register_view.text_037')}</strong> ${th('screens.register_view.text_038')}</p>
|
||
<p>${flowType === 'free'
|
||
? t('screens.register_view.text_019')
|
||
: t('screens.register_view.text_020')}</p>
|
||
`;
|
||
const status = statusLine();
|
||
const next = document.createElement('button');
|
||
next.className = 'primary-btn signup-next';
|
||
next.type = 'button';
|
||
next.textContent = t('screens.register_view.text_010');
|
||
input.addEventListener('input', () => { inputRevision++; status.textContent = ''; refreshPasswordCount(); });
|
||
input.addEventListener('keydown', event => {
|
||
if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
|
||
event.preventDefault();
|
||
next.click();
|
||
}
|
||
});
|
||
next.addEventListener('click', async () => {
|
||
const value = input.value;
|
||
if (value.length < 1 || value.length > PASSWORD_MAX_LENGTH) {
|
||
status.textContent = t('screens.register_view.text_032', { value1: PASSWORD_MAX_LENGTH });
|
||
return;
|
||
}
|
||
if (!draft.login || !draft.login.includes('@')) { status.textContent = t('screens.register_view.text_011'); return; }
|
||
const warningRevision = inputRevision;
|
||
if (!await confirmPasswordBoundarySpaces(value) || !screen.isConnected) return;
|
||
if (warningRevision !== inputRevision || input.value !== value) { status.textContent = t('screens.register_view.text_012'); return; }
|
||
if (draft.password && draft.password !== value && !confirmFundedWalletChange()) return;
|
||
if (draft.password && draft.password !== value) {
|
||
clearRegistrationDraft({
|
||
preserveFlowType: true,
|
||
preserveLogin: true,
|
||
preserveNamespace: true,
|
||
});
|
||
}
|
||
const revision = inputRevision;
|
||
const thisRequest = ++requestId;
|
||
const needsGeneration = draft.password !== value || !draft.preGeneratedKeyBundle;
|
||
next.disabled = true;
|
||
status.textContent = '';
|
||
if (needsGeneration) keyGeneration.show();
|
||
try {
|
||
// Дать браузеру отрисовать заставку до тяжёлого KDF.
|
||
if (needsGeneration) await new Promise(resolve => setTimeout(resolve, 40));
|
||
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(t('screens.register_view.text_027'));
|
||
draft.preGeneratedKeyBundle = bundle;
|
||
// Hide the password before navigation to prevent a visible flash.
|
||
input.clearPasswordField();
|
||
refreshPasswordCount();
|
||
showAccountType();
|
||
} catch (error) {
|
||
if (screen.isConnected && thisRequest === requestId) status.textContent = error.message || t('screens.register_view.text_028');
|
||
} finally {
|
||
keyGeneration.hide();
|
||
if (screen.isConnected && thisRequest === requestId) next.disabled = false;
|
||
}
|
||
});
|
||
body.append(heading, description, label, guidance, status, next);
|
||
}
|
||
|
||
function showAccountType() {
|
||
draft.uiStep = 3;
|
||
body.replaceChildren(createRegistrationStepper(3, draft.accountType === 1 ? 5 : 4));
|
||
const tr = key => t(`screens.registration_identity.${key}`);
|
||
const [heading, description] = title(tr('title'), tr('immutable'));
|
||
const choices = document.createElement('div'); choices.className = 'stack';
|
||
const option = (type, name, detail) => {
|
||
const label = document.createElement('label'); label.className = 'stack signup-guidance';
|
||
const radio = document.createElement('input'); radio.type = 'radio'; radio.name = 'registration-account-type';
|
||
radio.checked = draft.accountType === type;
|
||
const titleRow = document.createElement('strong'); titleRow.append(radio, ' ' + tr(name));
|
||
const p = document.createElement('p'); p.textContent = tr(detail);
|
||
label.append(titleRow, p); choices.append(label);
|
||
radio.addEventListener('change', () => { draft.accountType = type; next.disabled = false; body.firstElementChild.replaceWith(createRegistrationStepper(3, type === 1 ? 5 : 4)); });
|
||
};
|
||
option(1, 'primary', 'primary_detail');
|
||
option(0, 'alternative', 'alternative_detail');
|
||
const status = statusLine();
|
||
const next = document.createElement('button'); next.type = 'button'; next.className = 'primary-btn signup-next'; next.textContent = tr('next');
|
||
next.disabled = ![0, 1].includes(draft.accountType);
|
||
next.addEventListener('click', () => {
|
||
if (draft.accountType === 1) showPreviousAccounts();
|
||
else if (draft.accountType === 0) { draft.previousAccounts = []; finishIdentity(status); }
|
||
});
|
||
body.append(heading, description, choices, status, next);
|
||
}
|
||
|
||
function finishIdentity(status) {
|
||
try {
|
||
savePendingHeaderIdentity(draft.login, draft.preGeneratedKeyBundle?.blockchainPair?.publicKeyB64, draft);
|
||
navigate(flowType === 'free' ? 'registration-email-view' : 'registration-payment-view');
|
||
} catch (error) { status.textContent = error.message; }
|
||
}
|
||
|
||
function showPreviousAccounts() {
|
||
draft.uiStep = 4;
|
||
body.replaceChildren(createRegistrationStepper(4, 5));
|
||
const tr = key => t(`screens.registration_identity.${key}`);
|
||
const [heading, description] = title(tr('previous_title'), tr('previous_detail'));
|
||
const previous = document.createElement('div'); previous.className = 'stack';
|
||
const disclosure = document.createElement('p'); disclosure.className = 'signup-guidance'; disclosure.textContent = tr('disclosure');
|
||
const list = document.createElement('div'); list.className = 'stack';
|
||
const add = document.createElement('button'); add.type = 'button'; add.className = 'secondary-btn'; add.textContent = tr('add');
|
||
const searchBox = document.createElement('div'); searchBox.className = 'stack'; searchBox.hidden = true;
|
||
const input = document.createElement('input'); input.className = 'input'; input.placeholder = tr('search'); input.autocomplete = 'off';
|
||
const search = document.createElement('button'); search.type = 'button'; search.className = 'secondary-btn'; search.textContent = tr('find');
|
||
const results = document.createElement('div'); results.className = 'stack';
|
||
const status = statusLine();
|
||
searchBox.append(input, search, results);
|
||
previous.append(list, add, searchBox, disclosure);
|
||
const next = document.createElement('button'); next.type = 'button'; next.className = 'primary-btn signup-next'; next.textContent = tr('next');
|
||
let queryRevision = 0;
|
||
function refresh() {
|
||
list.replaceChildren();
|
||
for (const login of draft.previousAccounts) {
|
||
const row = document.createElement('div'); row.className = 'signup-full-login';
|
||
const remove = document.createElement('button'); remove.type = 'button'; remove.className = 'secondary-btn'; remove.textContent = '×';
|
||
remove.setAttribute('aria-label', `${tr('remove')} ${login}`);
|
||
remove.addEventListener('click', () => { draft.previousAccounts = draft.previousAccounts.filter(v => v !== login); refresh(); });
|
||
row.append(login, ' ', remove); list.append(row);
|
||
}
|
||
add.disabled = draft.previousAccounts.length >= 10;
|
||
if (add.disabled || draft.accountType !== 1) { searchBox.hidden = true; results.replaceChildren(); queryRevision++; }
|
||
}
|
||
add.addEventListener('click', () => { searchBox.hidden = false; input.focus(); });
|
||
input.addEventListener('input', () => { queryRevision++; results.replaceChildren(); });
|
||
input.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); search.click(); } });
|
||
search.addEventListener('click', async () => {
|
||
const query = input.value.trim(); if (!query) return;
|
||
const revision = ++queryRevision; results.replaceChildren(); status.textContent = '';
|
||
try {
|
||
const users = await authService.searchPeople(query, { limit: 20 });
|
||
if (!screen.isConnected || draft.uiStep !== 4 || revision !== queryRevision || draft.accountType !== 1) return;
|
||
const seen = new Set([draft.login, ...draft.previousAccounts].map(v => v.toLowerCase()));
|
||
for (const user of users) {
|
||
const login = String(user?.login || '');
|
||
if (!login || seen.has(login.toLowerCase())) continue;
|
||
seen.add(login.toLowerCase());
|
||
const choose = document.createElement('button'); choose.type = 'button'; choose.className = 'secondary-btn';
|
||
choose.textContent = login;
|
||
choose.addEventListener('click', () => {
|
||
if (draft.previousAccounts.length >= 10 || draft.accountType !== 1 || draft.previousAccounts.some(v => v.toLowerCase() === login.toLowerCase())) return;
|
||
draft.previousAccounts.push(login); input.value = ''; searchBox.hidden = true; results.replaceChildren(); queryRevision++; refresh();
|
||
});
|
||
results.append(choose);
|
||
}
|
||
if (!results.childElementCount) status.textContent = tr('not_found');
|
||
} catch (error) { if (screen.isConnected && revision === queryRevision) status.textContent = error.message || tr('search_error'); }
|
||
});
|
||
next.addEventListener('click', () => finishIdentity(status));
|
||
body.append(heading, description, previous, status, next); refresh();
|
||
}
|
||
|
||
if (flowType !== 'free' && flowType !== 'paid') {
|
||
queueMicrotask(() => navigate('registration-choice-view'));
|
||
return screen;
|
||
}
|
||
if (Number(draft.uiStep) === 4 && draft.accountType === 1 && draft.login && draft.preGeneratedKeyBundle) showPreviousAccounts();
|
||
else if (Number(draft.uiStep) === 3 && draft.login && draft.preGeneratedKeyBundle) showAccountType();
|
||
else 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 = t('screens.register_view.text_029');
|
||
if (screen.isConnected && Number(draft.uiStep) === 1) showLogin();
|
||
}).catch(error => {
|
||
isLoading = false;
|
||
fetchError = t('screens.register_view.text_033', { value1: error.message });
|
||
if (screen.isConnected && Number(draft.uiStep) === 1) showLogin();
|
||
});
|
||
return screen;
|
||
}
|