SHA256
CORE/CONTENT test5593 и адаптация UI
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
|
||||
export const pageMeta = { id: 'access-keys-view', get title() { return t('screens.access_keys_view.text_001'); } };
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
chrome?.setTopbar(createTopBar({ title: t('screens.access_keys_view.text_002'), back: { label: '←', onClick: () => navigate('settings-view') } }));
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'nav-list';
|
||||
actions.innerHTML = `
|
||||
<button type="button" class="nav-row" id="access-keys-show"><span class="nav-row__label">${th('screens.access_keys_view.text_003')}</span><span class="nav-row__hint">${th('screens.access_keys_view.text_004')}</span></button>
|
||||
<button type="button" class="nav-row" id="access-keys-rotate"><span class="nav-row__label">${th('screens.access_keys_view.text_005')}</span><span class="nav-row__hint">${th('screens.access_keys_view.text_006')}</span></button>
|
||||
`;
|
||||
actions.querySelector('#access-keys-show').addEventListener('click', () => navigate('show-keys-view'));
|
||||
actions.querySelector('#access-keys-rotate').addEventListener('click', () => navigate('key-rotation-view'));
|
||||
screen.append(actions);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,656 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { base64ToBytes, bytesToBase58, publicKeyB64FromPkcs8Ed25519 } from '../services/crypto-utils.js';
|
||||
import { loadEncryptedUserSecrets } from '../services/key-vault.js';
|
||||
import { resolveShineServerByServerLogin } from '../services/shine-server-resolver.js';
|
||||
import { readShineUserPda, updateShineUserPdaOnSolana } from '../services/shine-user-pda-service.js';
|
||||
import { getTopupSiteUrl } from '../services/solana-wallet-service.js';
|
||||
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'access-servers-view', get title() { return t('screens.access_servers_view.text_001'); } };
|
||||
const MAX_ACCESS_SERVERS = 1;
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value || '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function normalizeLogin(value) {
|
||||
return String(value || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function equalBytes(a, b) {
|
||||
const left = a instanceof Uint8Array ? a : new Uint8Array(a || []);
|
||||
const right = b instanceof Uint8Array ? b : new Uint8Array(b || []);
|
||||
if (left.length !== right.length) return false;
|
||||
for (let i = 0; i < left.length; i += 1) {
|
||||
if (left[i] !== right[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function uniqueLogins(values) {
|
||||
const seen = new Set();
|
||||
const result = [];
|
||||
(Array.isArray(values) ? values : []).forEach((value) => {
|
||||
const login = normalizeLogin(value);
|
||||
if (!login || seen.has(login)) return;
|
||||
seen.add(login);
|
||||
result.push(login);
|
||||
if (result.length >= MAX_ACCESS_SERVERS) return;
|
||||
});
|
||||
return result.slice(0, MAX_ACCESS_SERVERS);
|
||||
}
|
||||
|
||||
function shortenSignature(value) {
|
||||
const text = String(value || '').trim();
|
||||
if (text.length <= 16) return text;
|
||||
return `${text.slice(0, 8)}...${text.slice(-8)}`;
|
||||
}
|
||||
|
||||
function isInsufficientFundsForRentError(error) {
|
||||
const text = [
|
||||
error?.message,
|
||||
error?.transactionMessage,
|
||||
Array.isArray(error?.logs) ? error.logs.join('\n') : '',
|
||||
Array.isArray(error?.transactionLogs) ? error.transactionLogs.join('\n') : '',
|
||||
Array.isArray(error?.simulationLogs) ? error.simulationLogs.join('\n') : '',
|
||||
].filter(Boolean).join('\n').toLowerCase();
|
||||
return text.includes('insufficient funds') && text.includes('rent');
|
||||
}
|
||||
|
||||
function clientAddressFromPublicB64(publicKeyB64) {
|
||||
const bytes = base64ToBytes(publicKeyB64);
|
||||
if (bytes.length !== 32) throw new Error(t('screens.access_servers_view.text_006'));
|
||||
return bytesToBase58(bytes);
|
||||
}
|
||||
|
||||
async function clientAddressFromPrivatePkcs8(privatePkcs8B64) {
|
||||
return clientAddressFromPublicB64(await publicKeyB64FromPkcs8Ed25519(privatePkcs8B64));
|
||||
}
|
||||
|
||||
function createConfirmModal() {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!(root instanceof HTMLElement)) return null;
|
||||
|
||||
let onConfirm = null;
|
||||
let onCancel = null;
|
||||
|
||||
const close = () => {
|
||||
root.innerHTML = '';
|
||||
onConfirm = null;
|
||||
onCancel = null;
|
||||
};
|
||||
|
||||
return {
|
||||
open({
|
||||
title,
|
||||
text,
|
||||
note = '',
|
||||
confirmLabel = t('dialogs.remaining.pages.access_servers_view.createconfirmmodal.da'),
|
||||
cancelLabel = t('dialogs.remaining.pages.access_servers_view.createconfirmmodal.net'),
|
||||
onConfirm: confirmHandler,
|
||||
onCancel: cancelHandler,
|
||||
}) {
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="access-servers-confirm-modal">
|
||||
<div class="modal-card stack">
|
||||
<h3 class="modal-title" id="access-servers-dialog-title"></h3>
|
||||
<p class="meta-muted" id="access-servers-dialog-text" style="white-space:pre-wrap; line-height:1.45;"></p>
|
||||
<p class="meta-muted" id="access-servers-dialog-note"${note ? '' : ' hidden'} style="white-space:pre-wrap; line-height:1.45;"></p>
|
||||
<div class="auth-footer-actions">
|
||||
<button class="ghost-btn" type="button" id="access-servers-dialog-cancel"></button>
|
||||
<button class="primary-btn" type="button" id="access-servers-dialog-confirm"></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
const modal = root.querySelector('#access-servers-confirm-modal');
|
||||
const titleEl = root.querySelector('#access-servers-dialog-title');
|
||||
const textEl = root.querySelector('#access-servers-dialog-text');
|
||||
const noteEl = root.querySelector('#access-servers-dialog-note');
|
||||
const cancelBtn = root.querySelector('#access-servers-dialog-cancel');
|
||||
const confirmBtn = root.querySelector('#access-servers-dialog-confirm');
|
||||
if (!(modal instanceof HTMLElement)
|
||||
|| !(titleEl instanceof HTMLElement)
|
||||
|| !(textEl instanceof HTMLElement)
|
||||
|| !(noteEl instanceof HTMLElement)
|
||||
|| !(cancelBtn instanceof HTMLButtonElement)
|
||||
|| !(confirmBtn instanceof HTMLButtonElement)) {
|
||||
close();
|
||||
return;
|
||||
}
|
||||
|
||||
titleEl.textContent = String(title || t('dialogs.modals.access_servers_view.label_006'));
|
||||
textEl.textContent = String(text || '');
|
||||
if (note) {
|
||||
noteEl.hidden = false;
|
||||
noteEl.textContent = String(note);
|
||||
} else {
|
||||
noteEl.hidden = true;
|
||||
noteEl.textContent = '';
|
||||
}
|
||||
cancelBtn.textContent = String(cancelLabel || t('dialogs.modals.access_servers_view.label_007'));
|
||||
confirmBtn.textContent = String(confirmLabel || t('dialogs.modals.access_servers_view.label_008'));
|
||||
onConfirm = confirmHandler || null;
|
||||
onCancel = cancelHandler || null;
|
||||
|
||||
modal.addEventListener('click', (event) => {
|
||||
if (event.target === modal) close();
|
||||
});
|
||||
cancelBtn.addEventListener('click', async () => {
|
||||
const handler = onCancel;
|
||||
close();
|
||||
if (typeof handler === 'function') await handler();
|
||||
});
|
||||
confirmBtn.addEventListener('click', async () => {
|
||||
const handler = onConfirm;
|
||||
close();
|
||||
if (typeof handler === 'function') await handler();
|
||||
});
|
||||
},
|
||||
destroy() {
|
||||
close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createPasswordModal() {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!(root instanceof HTMLElement)) return null;
|
||||
|
||||
return {
|
||||
open({ title, text, note = '' }) {
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="access-servers-password-modal">
|
||||
<div class="modal-card stack">
|
||||
<h3 class="modal-title" id="access-servers-password-title"></h3>
|
||||
<p class="meta-muted" id="access-servers-password-text" style="white-space:pre-wrap; line-height:1.45;"></p>
|
||||
<p class="meta-muted" id="access-servers-password-note"${note ? '' : ' hidden'} style="white-space:pre-wrap; line-height:1.45;"></p>
|
||||
<label class="stack" style="gap:0.35rem;">
|
||||
<span class="field-label">${t('dialogs.modals.access_servers_view.label_002')}</span>
|
||||
<input class="input" id="access-servers-password-input" type="password" autocomplete="current-password" placeholder="${t('dialogs.modals.access_servers_view.label_001')}" />
|
||||
</label>
|
||||
<p class="meta-muted">${t('dialogs.modals.access_servers_view.label_003')}</p>
|
||||
<div class="form-actions-grid">
|
||||
<button class="secondary-btn" type="button" id="access-servers-password-cancel">${t('dialogs.modals.access_servers_view.label_004')}</button>
|
||||
<button class="primary-btn" type="button" id="access-servers-password-confirm">${t('dialogs.modals.access_servers_view.label_005')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const modal = root.querySelector('#access-servers-password-modal');
|
||||
const titleEl = root.querySelector('#access-servers-password-title');
|
||||
const textEl = root.querySelector('#access-servers-password-text');
|
||||
const noteEl = root.querySelector('#access-servers-password-note');
|
||||
const inputEl = root.querySelector('#access-servers-password-input');
|
||||
const cancelBtn = root.querySelector('#access-servers-password-cancel');
|
||||
const confirmBtn = root.querySelector('#access-servers-password-confirm');
|
||||
if (!(modal instanceof HTMLElement)
|
||||
|| !(titleEl instanceof HTMLElement)
|
||||
|| !(textEl instanceof HTMLElement)
|
||||
|| !(noteEl instanceof HTMLElement)
|
||||
|| !(inputEl instanceof HTMLInputElement)
|
||||
|| !(cancelBtn instanceof HTMLButtonElement)
|
||||
|| !(confirmBtn instanceof HTMLButtonElement)) {
|
||||
root.innerHTML = '';
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
titleEl.textContent = String(title || t('dialogs.modals.access_servers_view.label_001'));
|
||||
textEl.textContent = String(text || '');
|
||||
if (note) {
|
||||
noteEl.hidden = false;
|
||||
noteEl.textContent = String(note);
|
||||
} else {
|
||||
noteEl.hidden = true;
|
||||
noteEl.textContent = '';
|
||||
}
|
||||
|
||||
const close = (result = null) => {
|
||||
root.innerHTML = '';
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
modal.addEventListener('click', (event) => {
|
||||
if (event.target === modal) close(null);
|
||||
});
|
||||
cancelBtn.addEventListener('click', () => close(null));
|
||||
inputEl.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
confirmBtn.click();
|
||||
}
|
||||
});
|
||||
confirmBtn.addEventListener('click', () => {
|
||||
const password = String(inputEl.value || '');
|
||||
if (!password.trim()) {
|
||||
inputEl.focus();
|
||||
return;
|
||||
}
|
||||
close({ password });
|
||||
});
|
||||
window.setTimeout(() => inputEl.focus(), 0);
|
||||
});
|
||||
},
|
||||
destroy() {
|
||||
root.innerHTML = '';
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
const sessionLogin = normalizeLogin(state.session.login);
|
||||
const solanaEndpoint = String(state.entrySettings.solanaServer || '').trim();
|
||||
const storagePwd = String(state.session.storagePwdInMemory || '').trim();
|
||||
|
||||
let disposed = false;
|
||||
let operationBusy = false;
|
||||
let currentAccessServers = [];
|
||||
let selectedCandidate = null;
|
||||
let suggestionsLoading = false;
|
||||
|
||||
const confirmModal = createConfirmModal();
|
||||
const passwordModal = createPasswordModal();
|
||||
|
||||
const introCard = document.createElement('div');
|
||||
introCard.className = 'settings-intro';
|
||||
introCard.innerHTML = `
|
||||
<strong>${th('screens.access_servers_view.text_020')}</strong>
|
||||
<p class="meta-muted">${th('screens.access_servers_view.text_021')}</p>
|
||||
<p class="meta-muted">${th('screens.access_servers_view.text_022')}</p>
|
||||
`;
|
||||
|
||||
const listCard = document.createElement('div');
|
||||
listCard.className = 'card stack';
|
||||
const listTitle = document.createElement('p');
|
||||
listTitle.className = 'field-label';
|
||||
listTitle.textContent = t('dialogs.modals.access_servers_view.label_009');
|
||||
const listHint = document.createElement('p');
|
||||
listHint.className = 'meta-muted';
|
||||
listHint.textContent = sessionLogin
|
||||
? t('screens.access_servers_view.text_017', { value1: sessionLogin })
|
||||
: t('screens.access_servers_view.text_003');
|
||||
const listBody = document.createElement('div');
|
||||
listBody.className = 'stack';
|
||||
const listStatus = document.createElement('p');
|
||||
listStatus.className = 'meta-muted';
|
||||
listStatus.textContent = t('dialogs.modals.access_servers_view.label_010');
|
||||
listCard.append(listTitle, listHint, listBody, listStatus);
|
||||
|
||||
const addCard = document.createElement('div');
|
||||
addCard.className = 'card stack';
|
||||
const addTitle = document.createElement('p');
|
||||
addTitle.className = 'field-label';
|
||||
addTitle.textContent = t('dialogs.modals.access_servers_view.label_011');
|
||||
const addHint = document.createElement('p');
|
||||
addHint.className = 'meta-muted';
|
||||
addHint.textContent = t('dialogs.modals.access_servers_view.label_012');
|
||||
const addInput = document.createElement('input');
|
||||
addInput.className = 'input';
|
||||
addInput.type = 'text';
|
||||
addInput.autocomplete = 'off';
|
||||
addInput.placeholder = t('dialogs.modals.access_servers_view.label_013');
|
||||
const suggestEl = document.createElement('div');
|
||||
suggestEl.className = 'profile-relative-search-suggest';
|
||||
suggestEl.hidden = true;
|
||||
const addStatus = document.createElement('p');
|
||||
addStatus.className = 'meta-muted';
|
||||
addStatus.textContent = t('dialogs.modals.access_servers_view.label_014');
|
||||
const addButton = document.createElement('button');
|
||||
addButton.className = 'primary-btn';
|
||||
addButton.type = 'button';
|
||||
addButton.textContent = t('dialogs.modals.access_servers_view.label_015');
|
||||
addButton.disabled = true;
|
||||
addCard.append(addTitle, addHint, addInput, suggestEl, addStatus, addButton);
|
||||
addCard.hidden = true;
|
||||
const changeServerToggle = document.createElement('button');
|
||||
changeServerToggle.type = 'button';
|
||||
changeServerToggle.className = 'secondary-btn';
|
||||
changeServerToggle.textContent = t('dialogs.modals.access_servers_view.label_016');
|
||||
changeServerToggle.setAttribute('aria-expanded', 'false');
|
||||
changeServerToggle.addEventListener('click', () => {
|
||||
addCard.hidden = !addCard.hidden;
|
||||
changeServerToggle.setAttribute('aria-expanded', String(!addCard.hidden));
|
||||
});
|
||||
|
||||
const refreshAddButton = () => {
|
||||
addButton.disabled = operationBusy
|
||||
|| (!selectedCandidate && !normalizeLogin(addInput.value));
|
||||
};
|
||||
|
||||
const setOperationBusy = (busy) => {
|
||||
operationBusy = busy;
|
||||
addInput.disabled = busy;
|
||||
refreshAddButton();
|
||||
listBody.querySelectorAll('button').forEach((button) => {
|
||||
button.disabled = busy;
|
||||
});
|
||||
};
|
||||
|
||||
const setSelectedCandidate = (candidate) => {
|
||||
selectedCandidate = candidate;
|
||||
refreshAddButton();
|
||||
if (candidate) {
|
||||
addInput.value = candidate.login;
|
||||
addStatus.textContent = t('screens.access_servers_view.text_018', { value1: candidate.login, value2: candidate.url ? ` (${candidate.url})` : '' });
|
||||
} else {
|
||||
addStatus.textContent = t('dialogs.modals.access_servers_view.label_017');
|
||||
}
|
||||
};
|
||||
|
||||
const renderServerList = () => {
|
||||
listBody.innerHTML = '';
|
||||
if (!currentAccessServers.length) {
|
||||
const empty = document.createElement('p');
|
||||
empty.className = 'meta-muted';
|
||||
empty.textContent = t('dialogs.modals.access_servers_view.label_018');
|
||||
listBody.append(empty);
|
||||
return;
|
||||
}
|
||||
|
||||
currentAccessServers.forEach((server) => {
|
||||
const row = document.createElement('div');
|
||||
row.innerHTML = `
|
||||
<span style="display:block; text-align:left;">
|
||||
<strong>${escapeHtml(server.login)}</strong>
|
||||
<span class="meta-muted" style="display:block; margin-top:0.2rem;">${escapeHtml(server.url || t('screens.access_servers_view.text_007'))}</span>
|
||||
</span>
|
||||
`;
|
||||
listBody.append(row);
|
||||
});
|
||||
};
|
||||
|
||||
const loadCurrentServers = async () => {
|
||||
if (!sessionLogin) {
|
||||
currentAccessServers = [];
|
||||
renderServerList();
|
||||
listStatus.textContent = t('dialogs.modals.access_servers_view.label_019');
|
||||
return;
|
||||
}
|
||||
if (!solanaEndpoint) {
|
||||
currentAccessServers = [];
|
||||
renderServerList();
|
||||
listStatus.textContent = t('dialogs.modals.access_servers_view.label_020');
|
||||
return;
|
||||
}
|
||||
|
||||
listStatus.textContent = t('dialogs.modals.access_servers_view.label_021');
|
||||
try {
|
||||
const parsed = await readShineUserPda({ login: sessionLogin, solanaEndpoint });
|
||||
const logins = uniqueLogins(parsed?.accessServers);
|
||||
const rows = [];
|
||||
for (const login of logins) {
|
||||
try {
|
||||
const resolved = await resolveShineServerByServerLogin({ serverLogin: login, solanaEndpoint });
|
||||
rows.push({ login: resolved.serverLogin, url: resolved.httpBase });
|
||||
} catch {
|
||||
rows.push({ login, url: '' });
|
||||
}
|
||||
}
|
||||
currentAccessServers = rows;
|
||||
renderServerList();
|
||||
refreshAddButton();
|
||||
listStatus.textContent = rows.length
|
||||
? t('screens.access_servers_view.text_004')
|
||||
: t('screens.access_servers_view.text_005');
|
||||
} catch (error) {
|
||||
currentAccessServers = [];
|
||||
renderServerList();
|
||||
refreshAddButton();
|
||||
listStatus.textContent = actionErrorText(t('dialogs.modals.access_servers_view.label_022'), error);
|
||||
}
|
||||
};
|
||||
|
||||
const renderSuggestions = (items) => {
|
||||
suggestEl.innerHTML = '';
|
||||
if (!items.length) {
|
||||
suggestEl.hidden = true;
|
||||
return;
|
||||
}
|
||||
suggestEl.hidden = false;
|
||||
suggestEl.innerHTML = items.map((item) => (
|
||||
`<button type="button" class="ui-button profile-relative-suggest-item" data-login="${escapeHtml(item.login)}" data-url="${escapeHtml(item.url || '')}">
|
||||
${escapeHtml(item.login)}
|
||||
<span class="meta-muted" style="display:block; margin-top:0.2rem;">${escapeHtml(item.url || t('screens.access_servers_view.text_008'))}</span>
|
||||
</button>`
|
||||
)).join('');
|
||||
};
|
||||
|
||||
const showTopupRequiredStatus = (target, clientAddress) => {
|
||||
const address = String(clientAddress || '').trim();
|
||||
const topupUrl = address ? getTopupSiteUrl(address) : '/devnet-topup';
|
||||
target.innerHTML = `
|
||||
<span style="display:block; margin-bottom:0.55rem;">
|
||||
${th('screens.access_servers_view.text_023')}
|
||||
</span>
|
||||
${address ? `<span style="display:block; overflow-wrap:anywhere; margin-bottom:0.55rem;">${th('remaining.html_access_servers_view.wallet')}${escapeHtml(address)}</span>` : ''}
|
||||
<a class="primary-btn" href="${escapeHtml(topupUrl)}" target="_blank" rel="noopener" style="display:inline-flex; text-decoration:none;">${th('screens.access_servers_view.text_024')}</a>
|
||||
`;
|
||||
};
|
||||
|
||||
const loadSuggestions = async () => {
|
||||
const prefix = normalizeLogin(addInput.value);
|
||||
if (suggestionsLoading || prefix.length < 2 || operationBusy) {
|
||||
suggestEl.hidden = true;
|
||||
suggestEl.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
suggestionsLoading = true;
|
||||
try {
|
||||
const logins = await authService.searchUsers(prefix, { isServer: true });
|
||||
const items = [];
|
||||
for (const login of logins.slice(0, 6)) {
|
||||
try {
|
||||
const resolved = await resolveShineServerByServerLogin({ serverLogin: login, solanaEndpoint });
|
||||
items.push({ login: resolved.serverLogin, url: resolved.httpBase });
|
||||
} catch {
|
||||
// Если server PDA повреждена, не показываем подсказку.
|
||||
}
|
||||
}
|
||||
if (!disposed) renderSuggestions(items);
|
||||
} catch (error) {
|
||||
if (!disposed) {
|
||||
suggestEl.hidden = true;
|
||||
suggestEl.innerHTML = '';
|
||||
addStatus.textContent = actionErrorText(t('dialogs.modals.access_servers_view.label_023'), error);
|
||||
}
|
||||
} finally {
|
||||
suggestionsLoading = false;
|
||||
}
|
||||
};
|
||||
|
||||
const resolveAccessServerSigningMaterial = async (currentPda) => {
|
||||
if (!sessionLogin) throw new Error(t('screens.access_servers_view.text_009'));
|
||||
if (!storagePwd) throw new Error(t('screens.access_servers_view.text_010'));
|
||||
|
||||
let saved = null;
|
||||
try {
|
||||
saved = await loadEncryptedUserSecrets(sessionLogin, storagePwd);
|
||||
} catch {
|
||||
saved = null;
|
||||
}
|
||||
|
||||
const savedRoot = String(saved?.rootKey || '').trim();
|
||||
const savedBlockchain = String(saved?.blockchainKey || '').trim();
|
||||
const savedClient = String(saved?.clientKey || '').trim();
|
||||
if (savedRoot && savedBlockchain && savedClient) {
|
||||
return {
|
||||
rootPrivatePkcs8B64: savedRoot,
|
||||
blockchainPrivatePkcs8B64: savedBlockchain,
|
||||
clientPrivatePkcs8B64: savedClient,
|
||||
payerAddress: await clientAddressFromPrivatePkcs8(savedBlockchain),
|
||||
};
|
||||
}
|
||||
|
||||
const passwordResult = await passwordModal?.open({
|
||||
title: t('dialogs.final.server.password_needed_title'),
|
||||
text: t('dialogs.final.server.password_needed_text'),
|
||||
note: savedClient
|
||||
? t('dialogs.final.server.saved_access_key')
|
||||
: t('dialogs.final.server.missing_keys'),
|
||||
});
|
||||
if (!passwordResult) {
|
||||
throw new Error(t('screens.access_servers_view.text_011'));
|
||||
}
|
||||
|
||||
const keyBundle = await authService.derivePasswordKeyBundle(sessionLogin, passwordResult.password);
|
||||
const derivedBlockchainPublic = base64ToBytes(keyBundle.blockchainPair.publicKeyB64);
|
||||
const derivedClientPublic = base64ToBytes(keyBundle.clientPair.publicKeyB64);
|
||||
const activeBlockchain = currentPda.forks?.at(-1)?.blockchainKey;
|
||||
if (!activeBlockchain || !equalBytes(derivedBlockchainPublic, activeBlockchain)) {
|
||||
throw new Error(t('screens.access_servers_view.text_012'));
|
||||
}
|
||||
if (!equalBytes(derivedClientPublic, currentPda.clientKey)) {
|
||||
throw new Error(t('screens.access_servers_view.text_013'));
|
||||
}
|
||||
if (!equalBytes(base64ToBytes(keyBundle.rootPair.publicKeyB64), currentPda.rootKey)) {
|
||||
throw new Error('Root Key не соответствует PDA');
|
||||
}
|
||||
|
||||
await authService.persistSelectedKeys(sessionLogin, storagePwd, keyBundle);
|
||||
|
||||
return {
|
||||
rootPrivatePkcs8B64: keyBundle.rootPair.privatePkcs8B64,
|
||||
blockchainPrivatePkcs8B64: keyBundle.blockchainPair.privatePkcs8B64,
|
||||
clientPrivatePkcs8B64: keyBundle.clientPair.privatePkcs8B64,
|
||||
payerAddress: clientAddressFromPublicB64(keyBundle.blockchainPair.publicKeyB64),
|
||||
};
|
||||
};
|
||||
|
||||
const updateAccessServers = async (nextLogins, {
|
||||
statusTarget,
|
||||
successText,
|
||||
inFlightText,
|
||||
} = {}) => {
|
||||
const target = statusTarget instanceof HTMLElement ? statusTarget : listStatus;
|
||||
if (!sessionLogin) throw new Error(t('screens.access_servers_view.text_014'));
|
||||
if (!solanaEndpoint) throw new Error(t('screens.access_servers_view.text_015'));
|
||||
if (operationBusy) return;
|
||||
|
||||
const normalizedList = uniqueLogins(nextLogins);
|
||||
if (normalizedList.length > 1) {
|
||||
throw new Error(t('screens.access_servers_view.text_016'));
|
||||
}
|
||||
setOperationBusy(true);
|
||||
target.textContent = String(inFlightText || t('dialogs.modals.access_servers_view.label_024'));
|
||||
let signingMaterial = null;
|
||||
try {
|
||||
const currentPda = await readShineUserPda({ login: sessionLogin, solanaEndpoint });
|
||||
signingMaterial = await resolveAccessServerSigningMaterial(currentPda);
|
||||
const tx = await updateShineUserPdaOnSolana({
|
||||
login: sessionLogin,
|
||||
solanaEndpoint,
|
||||
rootPrivatePkcs8B64: signingMaterial.rootPrivatePkcs8B64,
|
||||
blockchainPrivatePkcs8B64: signingMaterial.blockchainPrivatePkcs8B64,
|
||||
clientPrivatePkcs8B64: signingMaterial.clientPrivatePkcs8B64,
|
||||
accessServers: normalizedList,
|
||||
});
|
||||
await loadCurrentServers();
|
||||
target.textContent = `${String(successText || t('dialogs.modals.access_servers_view.label_025'))} Tx: ${shortenSignature(tx?.signature)}`;
|
||||
setSelectedCandidate(null);
|
||||
suggestEl.hidden = true;
|
||||
suggestEl.innerHTML = '';
|
||||
refreshAddButton();
|
||||
} catch (error) {
|
||||
if (isInsufficientFundsForRentError(error)) {
|
||||
showTopupRequiredStatus(target, signingMaterial?.payerAddress);
|
||||
} else {
|
||||
target.textContent = actionErrorText(t('dialogs.modals.access_servers_view.label_026'), error);
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
setOperationBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
addInput.addEventListener('input', () => {
|
||||
setSelectedCandidate(null);
|
||||
refreshAddButton();
|
||||
void loadSuggestions();
|
||||
});
|
||||
addInput.addEventListener('focus', () => {
|
||||
void loadSuggestions();
|
||||
});
|
||||
suggestEl.addEventListener('click', (event) => {
|
||||
const target = event.target instanceof HTMLElement ? event.target.closest('[data-login]') : null;
|
||||
if (!(target instanceof HTMLElement)) return;
|
||||
setSelectedCandidate({
|
||||
login: String(target.dataset.login || ''),
|
||||
url: String(target.dataset.url || ''),
|
||||
});
|
||||
suggestEl.hidden = true;
|
||||
suggestEl.innerHTML = '';
|
||||
});
|
||||
|
||||
addButton.addEventListener('click', async () => {
|
||||
if (operationBusy) return;
|
||||
const login = normalizeLogin(selectedCandidate?.login || addInput.value);
|
||||
if (!login) {
|
||||
setSelectedCandidate(null);
|
||||
addStatus.textContent = t('dialogs.modals.access_servers_view.label_027');
|
||||
return;
|
||||
}
|
||||
if (currentAccessServers.some((item) => item.login === login)) {
|
||||
addStatus.textContent = t('screens.access_servers_view.text_019', { value1: login });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const resolved = await resolveShineServerByServerLogin({ serverLogin: login, solanaEndpoint });
|
||||
confirmModal?.open({
|
||||
title: t('dialogs.final.server.change_server_title'),
|
||||
text: t('dialogs.final.server.change_server_text', { server: resolved.serverLogin }),
|
||||
note: resolved.httpBase
|
||||
? t('dialogs.final.server.server_note_with_address', { url: resolved.httpBase })
|
||||
: t('dialogs.final.server.server_note_without_address'),
|
||||
onConfirm: async () => {
|
||||
const nextList = [resolved.serverLogin];
|
||||
try {
|
||||
await updateAccessServers(nextList, {
|
||||
statusTarget: addStatus,
|
||||
successText: t('dialogs.final.server.server_updated', { server: resolved.serverLogin }),
|
||||
inFlightText: t('dialogs.final.server.server_updating', { server: resolved.serverLogin }),
|
||||
});
|
||||
} catch {
|
||||
// Сообщение уже показано в статусе.
|
||||
}
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
addStatus.textContent = actionErrorText(t('dialogs.modals.access_servers_view.label_028'), error);
|
||||
}
|
||||
});
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.access_servers_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigate('settings-servers-view') },
|
||||
}));
|
||||
screen.append(
|
||||
introCard,
|
||||
listCard,
|
||||
changeServerToggle,
|
||||
addCard,
|
||||
);
|
||||
|
||||
void loadCurrentServers();
|
||||
|
||||
screen.cleanup = () => {
|
||||
disposed = true;
|
||||
confirmModal?.destroy();
|
||||
passwordModal?.destroy();
|
||||
};
|
||||
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import {
|
||||
normalizeChannelDisplayName,
|
||||
validateChannelDisplayName,
|
||||
} from '../services/channel-name-rules.js';
|
||||
import {
|
||||
getArweaveAttachmentAvailability,
|
||||
markArweaveAttachmentPlaced,
|
||||
} from '../components/arweave-attachment-manager.js';
|
||||
import { openChannelAttachmentManager } from '../components/channel-attachment-manager.js';
|
||||
import { renderAvatar } from '../components/avatar-image.js';
|
||||
import { makeShineChannelShortRoute } from '../services/shine-routes.js';
|
||||
|
||||
export const pageMeta = { id: 'add-channel-view', get title() { return t('screens.add_channel_view.text_001'); } };
|
||||
|
||||
const CREATE_CHANNEL_FLASH_KEY = 'shine-channels-create-success';
|
||||
const CHANNEL_TYPE_PUBLIC = 1;
|
||||
const CHANNEL_LOGIN_HINT = () => t('remaining.add_channel.channel_login_hint');
|
||||
const CHANNEL_LOGIN_DIGITS_ONLY_HINT = () => t('remaining.add_channel.channel_login_digits_only_hint');
|
||||
|
||||
function persistCreateSuccessFlash(message) {
|
||||
try {
|
||||
sessionStorage.setItem(CREATE_CHANNEL_FLASH_KEY, String(message || '').trim());
|
||||
} catch {
|
||||
// ignore storage errors
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeMetaText(value, max, label) {
|
||||
const normalized = String(value || '').trim();
|
||||
const length = Array.from(normalized).length;
|
||||
if (length > max) {
|
||||
return { ok: false, normalized, length, error: t('screens.add_channel_view.text_019', { value1: label, value2: max }) };
|
||||
}
|
||||
return { ok: true, normalized, length, error: '' };
|
||||
}
|
||||
|
||||
function renderAvatarPreview(slot, avatar, title) {
|
||||
if (!slot) return;
|
||||
const label = String(title || t('screens.add_channel_view.text_014')).trim() || t('screens.add_channel_view.text_015');
|
||||
const initials = Array.from(label)[0]?.toUpperCase() || t('screens.add_channel_view.text_016');
|
||||
// При вводе названия обновляем только текст fallback. Иначе асинхронно
|
||||
// загруженная картинка каждый раз удаляется, и на мгновение виден кружок.
|
||||
const avatarKey = `${String(avatar?.ar || '').trim()}|${String(avatar?.pr || '').trim()}`;
|
||||
const current = slot.firstElementChild;
|
||||
if (current?.dataset.avatarPreviewKey === avatarKey) {
|
||||
current.title = label;
|
||||
const fallback = current.querySelector('.avatar-fallback');
|
||||
if (fallback) fallback.textContent = initials;
|
||||
return;
|
||||
}
|
||||
const wrap = renderAvatar({
|
||||
initials,
|
||||
avatar,
|
||||
authorLogin: state.session.login,
|
||||
size: 'xl',
|
||||
className: 'channel-profile-avatar avatar-plain',
|
||||
title: label,
|
||||
alt: t('screens.add_channel_view.text_002'),
|
||||
});
|
||||
wrap.dataset.avatarPreviewKey = avatarKey;
|
||||
wrap.style.setProperty('--channel-avatar-size', '96px');
|
||||
slot.replaceChildren(wrap);
|
||||
}
|
||||
|
||||
function buildAbsoluteChannelUrl({ ownerBlockchainName = '', channelName = '' } = {}) {
|
||||
const route = makeShineChannelShortRoute({ ownerLogin: state.session.login, ownerBlockchainName, channelName });
|
||||
if (!route) return '';
|
||||
try {
|
||||
return new URL(`/${route}`, window.location.origin).toString();
|
||||
} catch {
|
||||
return `${window.location.origin}/${route}`;
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizeChannelLoginInput(value) {
|
||||
const source = String(value || '');
|
||||
let result = '';
|
||||
for (const ch of source) {
|
||||
if (/[A-Za-z0-9_-]/.test(ch)) result += ch;
|
||||
}
|
||||
return result.slice(0, 32);
|
||||
}
|
||||
|
||||
function shortAvatarBlockchainAddress(value) {
|
||||
const raw = String(value || '').trim();
|
||||
if (raw.length <= 24) return raw;
|
||||
return raw.slice(-24);
|
||||
}
|
||||
|
||||
const TRANSLIT = {
|
||||
а: 'a', б: 'b', в: 'v', г: 'g', д: 'd', е: 'e', ё: 'e', ж: 'zh', з: 'z', и: 'i', й: 'y', к: 'k', л: 'l', м: 'm',
|
||||
н: 'n', о: 'o', п: 'p', р: 'r', с: 's', т: 't', у: 'u', ф: 'f', х: 'h', ц: 'ts', ч: 'ch', ш: 'sh', щ: 'sch',
|
||||
ъ: '', ы: 'y', ь: '', э: 'e', ю: 'yu', я: 'ya',
|
||||
};
|
||||
|
||||
function suggestChannelLogin(title) {
|
||||
const latin = Array.from(String(title || '').toLowerCase()).map((ch) => TRANSLIT[ch] ?? ch).join('');
|
||||
return latin.replace(/[^a-z0-9_-]+/g, '-').replace(/-{2,}/g, '-').replace(/^[-_]+|[-_]+$/g, '').slice(0, 32);
|
||||
}
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack channels-screen channels-screen--add';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.add_channel_view.text_003'),
|
||||
back: { label: '<', onClick: () => navigate('channels-list') },
|
||||
}));
|
||||
|
||||
const form = document.createElement('form');
|
||||
form.className = 'card stack';
|
||||
form.innerHTML = `
|
||||
<div class="channel-create-avatar-head">
|
||||
<div id="channel-avatar-preview"></div>
|
||||
<div class="channel-create-avatar-side">
|
||||
<div class="channel-create-avatar-status-row">
|
||||
<div class="channel-create-avatar-status" id="channel-avatar-status"></div>
|
||||
<button type="button" class="ui-button channel-avatar-remove-btn" id="channel-avatar-remove" title="${th('screens.add_channel_view.text_021')}" aria-label="${th('screens.add_channel_view.text_022')}">✕</button>
|
||||
</div>
|
||||
<button type="button" class="secondary-btn" id="channel-avatar-btn">${th('screens.add_channel_view.text_023')}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-field">
|
||||
<label for="channel-title">${th('screens.add_channel_view.text_024')}</label>
|
||||
<input id="channel-title" class="input" maxlength="50" placeholder="${th('screens.add_channel_view.text_025')}" autocomplete="off" />
|
||||
<div class="form-field__meta">
|
||||
<div id="channel-title-error" class="inline-error"></div>
|
||||
<div class="form-field__counter" id="channel-title-counter">0 / 50</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-field">
|
||||
<label for="channel-name">${th('screens.add_channel_view.text_026')}</label>
|
||||
<input id="channel-name" class="input" maxlength="32" placeholder="my-channel" required autocomplete="off" autocapitalize="off" spellcheck="false" />
|
||||
<div class="form-field__hint channel-create-login-hint">${CHANNEL_LOGIN_HINT()}${th('remaining.html_add_channel_view.auto_filled_from_the_title_you_can_edit_it')}</div>
|
||||
<div class="form-field__hint channel-link-preview" id="channel-link-preview" hidden></div>
|
||||
<div id="channel-name-error" class="inline-error"></div>
|
||||
</div>
|
||||
|
||||
<div class="form-field">
|
||||
<label for="channel-description">${th('screens.add_channel_view.text_027')} <span class="form-field__optional">${th('screens.add_channel_view.text_028')}</span></label>
|
||||
<textarea id="channel-description" class="input" rows="3" maxlength="250" placeholder="${th('screens.add_channel_view.text_029')}"></textarea>
|
||||
<div class="form-field__meta">
|
||||
<div id="channel-description-error" class="inline-error"></div>
|
||||
<div class="form-field__counter" id="channel-description-counter">0 / 250</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="channel-create-error" class="meta-muted inline-error"></div>
|
||||
<div class="form-actions-grid">
|
||||
<button type="button" class="secondary-btn" id="cancel-create-channel">${th('screens.add_channel_view.text_030')}</button>
|
||||
<button type="submit" class="primary-btn" id="submit-create-channel">${th('screens.add_channel_view.text_031')}</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const nameEl = form.querySelector('#channel-name');
|
||||
const titleEl = form.querySelector('#channel-title');
|
||||
const descriptionEl = form.querySelector('#channel-description');
|
||||
const avatarPreviewEl = form.querySelector('#channel-avatar-preview');
|
||||
const avatarStatusEl = form.querySelector('#channel-avatar-status');
|
||||
const avatarBtn = form.querySelector('#channel-avatar-btn');
|
||||
const avatarRemoveBtn = form.querySelector('#channel-avatar-remove');
|
||||
const linkPreviewEl = form.querySelector('#channel-link-preview');
|
||||
const nameErrorEl = form.querySelector('#channel-name-error');
|
||||
const titleErrorEl = form.querySelector('#channel-title-error');
|
||||
const titleCounterEl = form.querySelector('#channel-title-counter');
|
||||
const descriptionErrorEl = form.querySelector('#channel-description-error');
|
||||
const descriptionCounterEl = form.querySelector('#channel-description-counter');
|
||||
const errorEl = form.querySelector('#channel-create-error');
|
||||
const submitEl = form.querySelector('#submit-create-channel');
|
||||
const cancelEl = form.querySelector('#cancel-create-channel');
|
||||
|
||||
let submitInFlight = false;
|
||||
let selectedAvatar = null;
|
||||
let ownerBlockchainName = '';
|
||||
let avatarAvailabilityLabel = '';
|
||||
let avatarAvailabilityTxId = '';
|
||||
|
||||
const renderAvatarStatus = (nameValue, titleValue) => {
|
||||
renderAvatarPreview(avatarPreviewEl, selectedAvatar, titleValue || nameValue);
|
||||
avatarRemoveBtn.hidden = !selectedAvatar?.pr;
|
||||
if (!selectedAvatar?.pr) {
|
||||
avatarStatusEl.innerHTML = t('screens.add_channel_view.text_017');
|
||||
return;
|
||||
}
|
||||
const txId = String(selectedAvatar.ar || '').trim();
|
||||
if (!txId) {
|
||||
avatarStatusEl.innerHTML = t('screens.add_channel_view.text_018');
|
||||
return;
|
||||
}
|
||||
const shortTxId = shortAvatarBlockchainAddress(txId);
|
||||
const isPending = avatarAvailabilityLabel === 'pending' || avatarAvailabilityTxId !== txId;
|
||||
avatarStatusEl.innerHTML = `
|
||||
<p class="channel-avatar-status-text">${th('screens.add_channel_view.text_032')}</p>
|
||||
<p class="channel-avatar-status-line">${th('screens.add_channel_view.text_033')} <span class="channel-avatar-txid">${shortTxId}</span><span class="channel-avatar-status-pending">${isPending ? t('screens.add_channel_view.text_010') : ''}</span></p>
|
||||
`;
|
||||
};
|
||||
|
||||
const renderChannelLinkPreview = (nameValue) => {
|
||||
const normalizedChannelName = normalizeChannelDisplayName(nameValue);
|
||||
if (!ownerBlockchainName || !normalizedChannelName) {
|
||||
linkPreviewEl.hidden = true;
|
||||
linkPreviewEl.textContent = '';
|
||||
return;
|
||||
}
|
||||
linkPreviewEl.hidden = false;
|
||||
const directUrl = buildAbsoluteChannelUrl({
|
||||
ownerBlockchainName,
|
||||
channelName: normalizedChannelName,
|
||||
});
|
||||
linkPreviewEl.innerHTML = `${th('remaining.html_add_channel_view.direct_link')}<a href="${directUrl}" target="_blank" rel="noopener noreferrer">${directUrl}</a>`;
|
||||
};
|
||||
|
||||
const refreshAvatarAvailability = async () => {
|
||||
const txId = String(selectedAvatar?.ar || '').trim();
|
||||
avatarAvailabilityTxId = txId;
|
||||
avatarAvailabilityLabel = txId ? 'pending' : '';
|
||||
renderAvatarStatus(nameEl.value, titleEl.value);
|
||||
if (!txId) return;
|
||||
try {
|
||||
const availability = await getArweaveAttachmentAvailability({
|
||||
gateway: state.entrySettings.arweaveServer,
|
||||
attachment: selectedAvatar,
|
||||
});
|
||||
if (avatarAvailabilityTxId !== txId) return;
|
||||
avatarAvailabilityLabel = String(availability?.status || '').trim().toLowerCase();
|
||||
} catch {
|
||||
if (avatarAvailabilityTxId !== txId) return;
|
||||
avatarAvailabilityLabel = 'pending';
|
||||
}
|
||||
renderAvatarStatus(nameEl.value, titleEl.value);
|
||||
};
|
||||
|
||||
const setBusy = (busy) => {
|
||||
submitInFlight = !!busy;
|
||||
submitEl.disabled = submitInFlight;
|
||||
cancelEl.disabled = submitInFlight;
|
||||
nameEl.disabled = submitInFlight;
|
||||
titleEl.disabled = submitInFlight;
|
||||
descriptionEl.disabled = submitInFlight;
|
||||
avatarBtn.disabled = submitInFlight;
|
||||
submitEl.textContent = submitInFlight ? t('screens.add_channel_view.text_011') : t('screens.add_channel_view.text_012');
|
||||
};
|
||||
|
||||
const updateValidation = () => {
|
||||
const nameCheck = validateChannelDisplayName(nameEl.value);
|
||||
const titleCheck = normalizeMetaText(titleEl.value, 50, t('screens.add_channel_view.text_034'));
|
||||
const descriptionCheck = normalizeMetaText(descriptionEl.value, 250, t('screens.add_channel_view.text_035'));
|
||||
|
||||
nameErrorEl.textContent = '';
|
||||
titleErrorEl.textContent = titleCheck.error;
|
||||
descriptionErrorEl.textContent = descriptionCheck.error;
|
||||
|
||||
titleCounterEl.textContent = `${Number(titleCheck.length || 0)} / 50`;
|
||||
descriptionCounterEl.textContent = `${Number(descriptionCheck.length || 0)} / 250`;
|
||||
|
||||
const ok = nameCheck.ok && titleCheck.ok && descriptionCheck.ok;
|
||||
submitEl.disabled = submitInFlight || !ok;
|
||||
renderAvatarStatus(nameCheck.normalized, titleCheck.normalized);
|
||||
renderChannelLinkPreview(nameCheck.normalized);
|
||||
|
||||
return {
|
||||
ok,
|
||||
name: nameCheck.normalized,
|
||||
title: titleCheck.normalized,
|
||||
description: descriptionCheck.normalized,
|
||||
};
|
||||
};
|
||||
|
||||
let nameEditedByHand = false;
|
||||
nameEl.addEventListener('input', () => {
|
||||
nameEditedByHand = nameEl.value.trim() !== '';
|
||||
const raw = String(nameEl.value || '');
|
||||
const sanitized = sanitizeChannelLoginInput(raw);
|
||||
if (raw !== sanitized) nameEl.value = sanitized;
|
||||
updateValidation();
|
||||
if (raw !== sanitized) nameErrorEl.textContent = t('screens.add_channel_view.text_004');
|
||||
});
|
||||
titleEl.addEventListener('input', () => {
|
||||
if (!nameEditedByHand) nameEl.value = suggestChannelLogin(titleEl.value);
|
||||
updateValidation();
|
||||
});
|
||||
descriptionEl.addEventListener('input', updateValidation);
|
||||
avatarBtn.addEventListener('click', async () => {
|
||||
try {
|
||||
const nextAvatar = await openChannelAttachmentManager({
|
||||
login: state.session.login,
|
||||
storagePwd: state.session.storagePwdInMemory,
|
||||
gateway: state.entrySettings.arweaveServer,
|
||||
mode: 'avatar',
|
||||
});
|
||||
if (nextAvatar?.pr) {
|
||||
selectedAvatar = nextAvatar;
|
||||
void refreshAvatarAvailability();
|
||||
}
|
||||
updateValidation();
|
||||
} catch (error) {
|
||||
errorEl.textContent = toUserMessage(error, t('screens.add_channel_view.text_008'));
|
||||
}
|
||||
});
|
||||
|
||||
avatarRemoveBtn.addEventListener('click', async () => {
|
||||
if (!selectedAvatar?.pr) return;
|
||||
const confirmed = await confirmDialog({ title: t('screens.add_channel_view.text_005'), text: t('screens.add_channel_view.text_013'), confirmLabel: t('screens.add_channel_view.text_006') });
|
||||
if (!confirmed) return;
|
||||
selectedAvatar = null;
|
||||
avatarAvailabilityLabel = '';
|
||||
avatarAvailabilityTxId = '';
|
||||
updateValidation();
|
||||
});
|
||||
|
||||
form.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
if (submitInFlight) return;
|
||||
|
||||
const login = state.session.login;
|
||||
const storagePwd = state.session.storagePwdInMemory;
|
||||
if (!login || !storagePwd) {
|
||||
errorEl.textContent = t('screens.add_channel_view.text_007');
|
||||
return;
|
||||
}
|
||||
|
||||
const check = updateValidation();
|
||||
if (check.name && /^[0-9]+$/.test(check.name)) {
|
||||
nameErrorEl.textContent = CHANNEL_LOGIN_DIGITS_ONLY_HINT();
|
||||
nameEl.focus();
|
||||
return;
|
||||
}
|
||||
if (!check.ok) return;
|
||||
|
||||
setBusy(true);
|
||||
errorEl.textContent = '';
|
||||
|
||||
try {
|
||||
await authService.addBlockCreateChannel({
|
||||
login,
|
||||
storagePwd,
|
||||
channelName: normalizeChannelDisplayName(check.name),
|
||||
channelDescription: check.description,
|
||||
channelProfileTitle: check.title,
|
||||
channelAvatar: selectedAvatar,
|
||||
channelType: CHANNEL_TYPE_PUBLIC,
|
||||
channelTypeVersion: 1,
|
||||
});
|
||||
if (selectedAvatar?.ar) markArweaveAttachmentPlaced(login, selectedAvatar);
|
||||
|
||||
persistCreateSuccessFlash(t('screens.add_channel_view.text_020', { value1: normalizeChannelDisplayName(check.name) }));
|
||||
navigate('channels-list');
|
||||
} catch (error) {
|
||||
errorEl.textContent = toUserMessage(error, t('screens.add_channel_view.text_009'));
|
||||
setBusy(false);
|
||||
updateValidation();
|
||||
}
|
||||
});
|
||||
|
||||
cancelEl.addEventListener('click', () => navigate('channels-list'));
|
||||
|
||||
screen.append(form);
|
||||
nameEl.focus();
|
||||
updateValidation();
|
||||
void authService.getUser(String(state.session.login || '').trim())
|
||||
.then((user) => {
|
||||
ownerBlockchainName = String(user?.blockchainName || '').trim();
|
||||
renderChannelLinkPreview(nameEl.value);
|
||||
})
|
||||
.catch(() => {
|
||||
ownerBlockchainName = '';
|
||||
renderChannelLinkPreview(nameEl.value);
|
||||
});
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { normalizeChannelDescription } from '../services/channel-name-rules.js';
|
||||
|
||||
export const pageMeta = { id: 'add-personal-public-chat-view', get title() { return t('screens.add_personal_public_chat_view.text_001'); } };
|
||||
|
||||
const CREATE_CHANNEL_FLASH_KEY = 'shine-channels-create-success';
|
||||
const CHANNEL_TYPE_PERSONAL = 100;
|
||||
|
||||
function persistCreateSuccessFlash(message) {
|
||||
try {
|
||||
sessionStorage.setItem(CREATE_CHANNEL_FLASH_KEY, String(message || '').trim());
|
||||
} catch {
|
||||
// ignore storage errors
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeLoginInput(value) {
|
||||
return String(value || '').trim().replace(/^@+/, '');
|
||||
}
|
||||
|
||||
function isValidLogin(value) {
|
||||
const clean = normalizeLoginInput(value);
|
||||
if (!clean) return false;
|
||||
if (clean.length < 1 || clean.length > 20) return false;
|
||||
return /^[A-Za-z0-9_]+$/.test(clean);
|
||||
}
|
||||
|
||||
function validateDescription(value) {
|
||||
const normalized = normalizeChannelDescription(value);
|
||||
const bytes = new TextEncoder().encode(normalized).length;
|
||||
if (bytes > 200) {
|
||||
return { ok: false, normalized, bytes, error: t('screens.add_personal_public_chat_view.text_005') };
|
||||
}
|
||||
return { ok: true, normalized, bytes, error: '' };
|
||||
}
|
||||
|
||||
function createDebounced(fn, delayMs = 240) {
|
||||
let timer = null;
|
||||
return (...args) => {
|
||||
if (timer) clearTimeout(timer);
|
||||
timer = setTimeout(() => {
|
||||
timer = null;
|
||||
fn(...args);
|
||||
}, delayMs);
|
||||
};
|
||||
}
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack channels-screen channels-screen--add';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.add_personal_public_chat_view.text_002'),
|
||||
back: { label: '<', onClick: () => navigate('channels-list/dialogs') },
|
||||
}));
|
||||
|
||||
const form = document.createElement('form');
|
||||
form.className = 'card stack';
|
||||
form.innerHTML = `
|
||||
<strong class="channel-head-title">${th('screens.add_personal_public_chat_view.text_013')}</strong>
|
||||
<p class="channel-head-meta">${th('screens.add_personal_public_chat_view.text_014')}</p>
|
||||
|
||||
<label for="chat-login">${th('screens.add_personal_public_chat_view.text_015')}</label>
|
||||
<input id="chat-login" class="input" maxlength="20" placeholder="${th('screens.add_personal_public_chat_view.text_016')}" autocomplete="off" required />
|
||||
<div id="chat-login-suggest" class="channels-search-suggest" style="display:none"></div>
|
||||
<div id="chat-login-error" class="meta-muted inline-error"></div>
|
||||
|
||||
<label for="chat-description">${th('screens.add_personal_public_chat_view.text_017')}</label>
|
||||
<textarea id="chat-description" class="input" rows="4" maxlength="400" placeholder="${th('screens.add_personal_public_chat_view.text_018')}"></textarea>
|
||||
<div class="meta-muted" id="chat-description-counter">${th('screens.add_personal_public_chat_view.text_019')}</div>
|
||||
<div id="chat-description-error" class="meta-muted inline-error"></div>
|
||||
|
||||
<div class="card meta-muted">
|
||||
${th('screens.add_personal_public_chat_view.text_020')}
|
||||
</div>
|
||||
|
||||
<div id="chat-create-error" class="meta-muted inline-error"></div>
|
||||
<div class="form-actions-grid">
|
||||
<button type="button" class="secondary-btn" id="cancel-create-chat">${th('screens.add_personal_public_chat_view.text_021')}</button>
|
||||
<button type="submit" class="primary-btn" id="submit-create-chat">${th('screens.add_personal_public_chat_view.text_022')}</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const loginEl = form.querySelector('#chat-login');
|
||||
const suggestEl = form.querySelector('#chat-login-suggest');
|
||||
const loginErrorEl = form.querySelector('#chat-login-error');
|
||||
const descriptionEl = form.querySelector('#chat-description');
|
||||
const descriptionErrorEl = form.querySelector('#chat-description-error');
|
||||
const descriptionCounterEl = form.querySelector('#chat-description-counter');
|
||||
const errorEl = form.querySelector('#chat-create-error');
|
||||
const submitEl = form.querySelector('#submit-create-chat');
|
||||
const cancelEl = form.querySelector('#cancel-create-chat');
|
||||
|
||||
let submitInFlight = false;
|
||||
let selectedCanonicalLogin = '';
|
||||
|
||||
const setBusy = (busy) => {
|
||||
submitInFlight = !!busy;
|
||||
submitEl.disabled = submitInFlight;
|
||||
cancelEl.disabled = submitInFlight;
|
||||
loginEl.disabled = submitInFlight;
|
||||
descriptionEl.disabled = submitInFlight;
|
||||
submitEl.textContent = submitInFlight ? t('screens.add_personal_public_chat_view.text_006') : t('screens.add_personal_public_chat_view.text_007');
|
||||
};
|
||||
|
||||
const renderLoginSuggestions = (logins) => {
|
||||
suggestEl.innerHTML = '';
|
||||
const rows = Array.isArray(logins) ? logins.filter(Boolean) : [];
|
||||
if (!rows.length) {
|
||||
suggestEl.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
suggestEl.style.display = '';
|
||||
rows.slice(0, 8).forEach((login) => {
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'ui-button channel-search-item';
|
||||
btn.textContent = String(login);
|
||||
btn.addEventListener('click', () => {
|
||||
selectedCanonicalLogin = String(login);
|
||||
loginEl.value = selectedCanonicalLogin;
|
||||
suggestEl.style.display = 'none';
|
||||
});
|
||||
suggestEl.append(btn);
|
||||
});
|
||||
};
|
||||
|
||||
const updateValidation = () => {
|
||||
const loginRaw = String(loginEl.value || '').trim();
|
||||
const loginOk = isValidLogin(loginRaw);
|
||||
const descriptionCheck = validateDescription(descriptionEl.value);
|
||||
|
||||
loginErrorEl.textContent = loginOk ? '' : t('screens.add_personal_public_chat_view.text_008');
|
||||
descriptionErrorEl.textContent = descriptionCheck.error;
|
||||
descriptionCounterEl.textContent = t('screens.add_personal_public_chat_view.text_011', { value1: Number(descriptionCheck.bytes || 0) });
|
||||
|
||||
const ok = loginOk && descriptionCheck.ok;
|
||||
submitEl.disabled = submitInFlight || !ok;
|
||||
return { ok, description: descriptionCheck.normalized };
|
||||
};
|
||||
|
||||
const refreshSuggestions = createDebounced(async () => {
|
||||
if (submitInFlight) return;
|
||||
const loginRaw = normalizeLoginInput(loginEl.value);
|
||||
if (loginRaw.length < 1) {
|
||||
suggestEl.style.display = 'none';
|
||||
suggestEl.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const logins = await authService.searchUsers(loginRaw);
|
||||
renderLoginSuggestions(logins);
|
||||
} catch {
|
||||
suggestEl.style.display = 'none';
|
||||
suggestEl.innerHTML = '';
|
||||
}
|
||||
}, 220);
|
||||
|
||||
loginEl.addEventListener('input', () => {
|
||||
selectedCanonicalLogin = '';
|
||||
errorEl.textContent = '';
|
||||
updateValidation();
|
||||
refreshSuggestions();
|
||||
});
|
||||
descriptionEl.addEventListener('input', updateValidation);
|
||||
|
||||
form.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
if (submitInFlight) return;
|
||||
|
||||
const login = state.session.login;
|
||||
const storagePwd = state.session.storagePwdInMemory;
|
||||
if (!login || !storagePwd) {
|
||||
errorEl.textContent = t('screens.add_personal_public_chat_view.text_003');
|
||||
return;
|
||||
}
|
||||
|
||||
const validation = updateValidation();
|
||||
if (!validation.ok) return;
|
||||
|
||||
setBusy(true);
|
||||
errorEl.textContent = '';
|
||||
loginErrorEl.textContent = '';
|
||||
|
||||
try {
|
||||
const inputLogin = normalizeLoginInput(loginEl.value);
|
||||
const foundUser = await authService.getUser(inputLogin);
|
||||
if (!foundUser?.exists) {
|
||||
throw new Error(t('screens.add_personal_public_chat_view.text_009'));
|
||||
}
|
||||
const canonicalLogin = String(foundUser?.login || inputLogin).trim();
|
||||
if (!canonicalLogin) throw new Error(t('screens.add_personal_public_chat_view.text_010'));
|
||||
|
||||
await authService.addBlockCreateChannel({
|
||||
login,
|
||||
storagePwd,
|
||||
channelName: canonicalLogin,
|
||||
channelDescription: validation.description,
|
||||
channelType: CHANNEL_TYPE_PERSONAL,
|
||||
channelTypeVersion: 1,
|
||||
});
|
||||
|
||||
persistCreateSuccessFlash(t('screens.add_personal_public_chat_view.text_012', { value1: canonicalLogin }));
|
||||
navigate('channels-list/dialogs');
|
||||
} catch (error) {
|
||||
errorEl.textContent = toUserMessage(error, t('screens.add_personal_public_chat_view.text_004'));
|
||||
setBusy(false);
|
||||
updateValidation();
|
||||
}
|
||||
});
|
||||
|
||||
cancelEl.addEventListener('click', () => navigate('channels-list/dialogs'));
|
||||
|
||||
screen.append(form);
|
||||
loginEl.focus();
|
||||
updateValidation();
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import {
|
||||
isDeveloperToolsEnabled,
|
||||
isDmFileTransferEnabled,
|
||||
setDeveloperToolsEnabled,
|
||||
setDmFileTransferEnabled,
|
||||
} from '../services/feature-settings.js';
|
||||
|
||||
export const pageMeta = { id: 'advanced-settings-view', get title() { return t('screens.advanced_settings_view.text_001'); } };
|
||||
|
||||
function createToggleRow({ id, title, hint, checked }) {
|
||||
const label = document.createElement('label');
|
||||
label.className = 'card settings-feature-toggle-row';
|
||||
label.htmlFor = id;
|
||||
label.innerHTML = `
|
||||
<span class="settings-feature-toggle-copy">
|
||||
<strong class="settings-feature-toggle-title">${title}</strong>
|
||||
<span class="settings-feature-toggle-hint">${hint}</span>
|
||||
</span>
|
||||
<input class="switch" id="${id}" type="checkbox" ${checked ? 'checked' : ''} />
|
||||
`;
|
||||
return label;
|
||||
}
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack advanced-settings-screen';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.advanced_settings_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigate('settings-view') },
|
||||
}));
|
||||
|
||||
const intro = document.createElement('div');
|
||||
intro.className = 'settings-intro';
|
||||
intro.innerHTML = `
|
||||
<p class="meta-muted">${th('screens.advanced_settings_view.text_007')}</p>
|
||||
`;
|
||||
|
||||
const developerRow = createToggleRow({
|
||||
id: 'advanced-developer-tools',
|
||||
title: t('screens.advanced_settings_view.text_003'),
|
||||
hint: t('screens.advanced_settings_view.text_005'),
|
||||
checked: isDeveloperToolsEnabled(),
|
||||
});
|
||||
|
||||
const filesRow = createToggleRow({
|
||||
id: 'advanced-dm-files',
|
||||
title: t('screens.advanced_settings_view.text_004'),
|
||||
hint: t('screens.advanced_settings_view.text_006'),
|
||||
checked: isDmFileTransferEnabled(),
|
||||
});
|
||||
|
||||
const developerInput = developerRow.querySelector('#advanced-developer-tools');
|
||||
const filesInput = filesRow.querySelector('#advanced-dm-files');
|
||||
developerInput?.addEventListener('change', () => setDeveloperToolsEnabled(developerInput.checked));
|
||||
filesInput?.addEventListener('change', () => setDmFileTransferEnabled(filesInput.checked));
|
||||
|
||||
screen.append(intro, developerRow, filesRow);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import { formatTime } from '../i18n/format.js';
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { clearAppLogEntries, getAppLogEntries } from '../state.js';
|
||||
|
||||
export const pageMeta = { id: 'app-log-view', get title() { return t('screens.app_log_view.text_001'); } };
|
||||
|
||||
function formatLogTime(ts) {
|
||||
try {
|
||||
return formatTime(new Date(ts));
|
||||
} catch {
|
||||
return String(ts || '');
|
||||
}
|
||||
}
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.app_log_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigate('developer-settings-view') },
|
||||
actions: [{ icon: 'refresh', title: t('screens.app_log_view.text_003'), ariaLabel: t('screens.app_log_view.text_004'), onClick: () => renderEntries() }],
|
||||
}));
|
||||
|
||||
const controls = document.createElement('div');
|
||||
controls.className = 'action-pair';
|
||||
controls.innerHTML = `
|
||||
<button class="secondary-btn" type="button" data-action="copy-all">${th('screens.app_log_view.text_012')}</button>
|
||||
<button class="destructive-btn" type="button" data-action="clear">${th('screens.app_log_view.text_013')}</button>
|
||||
`;
|
||||
|
||||
const status = document.createElement('div');
|
||||
status.className = 'status-line';
|
||||
status.textContent = t('screens.app_log_view.text_005');
|
||||
|
||||
const list = document.createElement('div');
|
||||
list.className = 'stack';
|
||||
|
||||
function entriesToClipboardText(entries) {
|
||||
return entries
|
||||
.slice()
|
||||
.reverse()
|
||||
.map((entry) => {
|
||||
const level = String(entry.level || 'info').toUpperCase();
|
||||
const source = String(entry.source || 'ui');
|
||||
const header = `[${formatLogTime(entry.ts)}] ${level} ${source}`;
|
||||
const message = String(entry.message || '');
|
||||
const details = String(entry.details || '').trim();
|
||||
return details ? `${header}\n${message}\n${details}` : `${header}\n${message}`;
|
||||
})
|
||||
.join('\n\n');
|
||||
}
|
||||
|
||||
async function copyTextToClipboard(text) {
|
||||
if (navigator?.clipboard?.writeText) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
return true;
|
||||
}
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = text;
|
||||
ta.setAttribute('readonly', '');
|
||||
ta.style.position = 'fixed';
|
||||
ta.style.opacity = '0';
|
||||
ta.style.pointerEvents = 'none';
|
||||
document.body.append(ta);
|
||||
ta.select();
|
||||
const ok = document.execCommand('copy');
|
||||
ta.remove();
|
||||
return !!ok;
|
||||
}
|
||||
|
||||
function renderEntries() {
|
||||
const entries = getAppLogEntries();
|
||||
list.innerHTML = '';
|
||||
|
||||
if (!entries.length) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'empty-note';
|
||||
empty.textContent = t('screens.app_log_view.text_006');
|
||||
list.append(empty);
|
||||
status.className = 'status-line is-available';
|
||||
status.textContent = t('screens.app_log_view.text_007');
|
||||
return;
|
||||
}
|
||||
|
||||
entries.slice().reverse().forEach((entry) => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'card stack';
|
||||
const level = String(entry.level || 'info').toUpperCase();
|
||||
const source = String(entry.source || 'ui');
|
||||
const details = String(entry.details || '').trim();
|
||||
|
||||
const head = document.createElement('div');
|
||||
head.className = 'meta-muted';
|
||||
head.textContent = `[${formatLogTime(entry.ts)}] ${level} ${source}`;
|
||||
|
||||
const message = document.createElement('div');
|
||||
message.textContent = entry.message || '';
|
||||
|
||||
row.append(head, message);
|
||||
|
||||
if (details) {
|
||||
const detailsNode = document.createElement('pre');
|
||||
detailsNode.className = 'meta-muted';
|
||||
detailsNode.style.whiteSpace = 'pre-wrap';
|
||||
detailsNode.style.margin = '0';
|
||||
detailsNode.textContent = details;
|
||||
row.append(detailsNode);
|
||||
}
|
||||
|
||||
list.append(row);
|
||||
});
|
||||
|
||||
status.className = 'status-line is-available';
|
||||
status.textContent = t('screens.app_log_view.text_010', { value1: entries.length });
|
||||
}
|
||||
|
||||
controls.querySelector('[data-action="copy-all"]').addEventListener('click', async () => {
|
||||
const entries = getAppLogEntries();
|
||||
if (!entries.length) {
|
||||
status.className = 'status-line';
|
||||
status.textContent = t('screens.app_log_view.text_008');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const text = entriesToClipboardText(entries);
|
||||
await copyTextToClipboard(text);
|
||||
status.className = 'status-line is-available';
|
||||
status.textContent = t('screens.app_log_view.text_011', { value1: entries.length });
|
||||
} catch (e) {
|
||||
status.className = 'status-line';
|
||||
status.textContent = t('screens.app_log_view.text_009');
|
||||
}
|
||||
});
|
||||
controls.querySelector('[data-action="clear"]').addEventListener('click', () => {
|
||||
clearAppLogEntries();
|
||||
renderEntries();
|
||||
});
|
||||
|
||||
screen.append(controls, status, list);
|
||||
renderEntries();
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
// «Оформление»: тема (Авто / Светлая / Тёмная) и палитра – образцами, применяются сразу.
|
||||
// Тонкая ручная настройка цветов – прежний редактор палитры.
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { openPaletteEditor } from '../components/palette-editor.js';
|
||||
import {
|
||||
PALETTE_PRESETS, getPaletteSettings, getThemeMode, resolvePalette, resolveThemeMode, setPaletteSettings, setThemeMode,
|
||||
} from '../services/theme-service.js';
|
||||
|
||||
export const pageMeta = { id: 'appearance-view', get title() { return t('screens.appearance_view.text_001'); } };
|
||||
|
||||
const THEME_MODES = () => [
|
||||
['system', t('screens.appearance_view.text_012')],
|
||||
['light', t('screens.appearance_view.text_013')],
|
||||
['dark', t('screens.appearance_view.text_014')],
|
||||
];
|
||||
|
||||
export function render({ navigate, chrome } = {}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack appearance-screen';
|
||||
let closeEditor = null; // openPaletteEditor возвращает функцию закрытия
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.appearance_view.text_002'),
|
||||
back: { onClick: () => navigate('settings-view') },
|
||||
}));
|
||||
|
||||
// --- тема ---
|
||||
const themeTitle = document.createElement('p');
|
||||
themeTitle.className = 'nav-list__title';
|
||||
themeTitle.textContent = t('screens.appearance_view.text_003');
|
||||
const themeTabs = document.createElement('div');
|
||||
themeTabs.className = 'tabs tabs--three appearance-theme';
|
||||
themeTabs.setAttribute('role', 'radiogroup');
|
||||
themeTabs.setAttribute('aria-label', t('screens.appearance_view.text_015'));
|
||||
const themeHint = document.createElement('p');
|
||||
themeHint.className = 'meta-muted appearance-hint';
|
||||
for (const [mode, label] of THEME_MODES()) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'tab-btn';
|
||||
button.dataset.mode = mode;
|
||||
button.setAttribute('role', 'radio');
|
||||
button.textContent = label;
|
||||
button.addEventListener('click', () => {
|
||||
setThemeMode(mode);
|
||||
sync();
|
||||
});
|
||||
themeTabs.append(button);
|
||||
}
|
||||
|
||||
// --- палитра ---
|
||||
const paletteTitle = document.createElement('p');
|
||||
paletteTitle.className = 'nav-list__title';
|
||||
paletteTitle.textContent = t('screens.appearance_view.text_004');
|
||||
const grid = document.createElement('div');
|
||||
grid.className = 'palette-grid';
|
||||
grid.setAttribute('role', 'radiogroup');
|
||||
grid.setAttribute('aria-label', t('screens.appearance_view.text_016'));
|
||||
const swatches = new Map();
|
||||
for (const [id, preset] of Object.entries(PALETTE_PRESETS)) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'palette-swatch';
|
||||
button.setAttribute('role', 'radio');
|
||||
button.setAttribute('aria-label', preset.label);
|
||||
button.innerHTML = `
|
||||
<span class="palette-swatch__sample" aria-hidden="true">
|
||||
<span class="palette-swatch__bar"></span>
|
||||
<span class="palette-swatch__bubble"></span>
|
||||
<span class="palette-swatch__dot"></span>
|
||||
<span class="palette-swatch__check">${iconHtml('check')}</span>
|
||||
</span>
|
||||
<span class="palette-swatch__label"></span>
|
||||
`;
|
||||
button.querySelector('.palette-swatch__label').textContent = preset.label;
|
||||
button.addEventListener('click', () => {
|
||||
// Выбор готовой палитры сбрасывает ручные правки – иначе выбор выглядел бы «не тем».
|
||||
setPaletteSettings({ preset: id, custom: { dark: {}, light: {} } });
|
||||
sync();
|
||||
});
|
||||
swatches.set(id, button);
|
||||
grid.append(button);
|
||||
}
|
||||
|
||||
const more = document.createElement('div');
|
||||
more.className = 'nav-list';
|
||||
const customRow = document.createElement('button');
|
||||
customRow.type = 'button';
|
||||
customRow.className = 'nav-row';
|
||||
customRow.innerHTML = t('screens.appearance_view.text_009');
|
||||
customRow.addEventListener('click', () => {
|
||||
closeEditor?.();
|
||||
closeEditor = openPaletteEditor({ onClose: () => { closeEditor = null; sync(); } });
|
||||
});
|
||||
more.append(customRow);
|
||||
|
||||
function sync() {
|
||||
const mode = getThemeMode();
|
||||
const resolved = resolveThemeMode(mode);
|
||||
themeTabs.querySelectorAll('.tab-btn').forEach((button) => {
|
||||
button.setAttribute('aria-checked', String(button.dataset.mode === mode));
|
||||
});
|
||||
themeHint.textContent = mode === 'system'
|
||||
? t('screens.appearance_view.text_010', { value1: resolved === 'light' ? t('screens.appearance_view.text_005') : t('screens.appearance_view.text_006') })
|
||||
: t('screens.appearance_view.text_007');
|
||||
const settings = getPaletteSettings();
|
||||
const customized = Object.keys(settings.custom.dark).length + Object.keys(settings.custom.light).length > 0;
|
||||
swatches.forEach((button, id) => {
|
||||
// Образцы показывают ту тему, что сейчас на экране.
|
||||
const colors = resolvePalette(resolved, { preset: id, custom: { dark: {}, light: {} } });
|
||||
const sample = button.querySelector('.palette-swatch__sample');
|
||||
sample.style.setProperty('--swatch-bg', colors.background);
|
||||
sample.style.setProperty('--swatch-surface', colors.surface);
|
||||
sample.style.setProperty('--swatch-accent', colors.accent);
|
||||
sample.style.setProperty('--swatch-bubble', colors['bubble-out']);
|
||||
sample.style.setProperty('--swatch-on-accent', colors['on-accent']);
|
||||
button.setAttribute('aria-checked', String(settings.preset === id && !customized));
|
||||
});
|
||||
customRow.querySelector('.nav-row__hint').textContent = customized
|
||||
? t('screens.appearance_view.text_011', { value1: PALETTE_PRESETS[settings.preset]?.label || settings.preset })
|
||||
: t('screens.appearance_view.text_008');
|
||||
}
|
||||
|
||||
sync();
|
||||
screen.append(themeTitle, themeTabs, themeHint, paletteTitle, grid, more);
|
||||
screen.cleanup = () => {
|
||||
const close = closeEditor;
|
||||
closeEditor = null;
|
||||
close?.();
|
||||
};
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { getShowPublicHistoryWarning, setShowPublicHistoryWarning } from '../services/public-history-consent.js';
|
||||
|
||||
export const pageMeta = { id: 'application-settings-view', get title() { return t('screens.application_settings_view.text_001'); } };
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.application_settings_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigate('settings-view') },
|
||||
}));
|
||||
const section = document.createElement('div');
|
||||
section.className = 'nav-list';
|
||||
const row = document.createElement('label');
|
||||
row.className = 'nav-row nav-row--switch';
|
||||
row.innerHTML = `
|
||||
<span class="nav-row__text">
|
||||
<span class="nav-row__label">${th('screens.application_settings_view.text_003')}</span>
|
||||
<span class="nav-row__hint">${th('screens.application_settings_view.text_004')}</span>
|
||||
</span>
|
||||
<input class="switch" type="checkbox" />
|
||||
`;
|
||||
const input = row.querySelector('input');
|
||||
input.checked = getShowPublicHistoryWarning();
|
||||
input.addEventListener('change', () => setShowPublicHistoryWarning(input.checked));
|
||||
section.append(row);
|
||||
screen.append(section);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import {
|
||||
clearArweaveAttachmentHistory,
|
||||
formatArweaveHistoryTime,
|
||||
getArweaveAttachmentAvailability,
|
||||
openArweaveAttachmentManager,
|
||||
readArweaveAttachmentHistory,
|
||||
} from '../components/arweave-attachment-manager.js';
|
||||
import { formatBytes } from '../services/attachment-format.js';
|
||||
import { createOverflowDots } from '../components/overflow-dots.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { state } from '../state.js';
|
||||
|
||||
export const pageMeta = { id: 'arweave-uploads-view', get title() { return t('screens.arweave_uploads_view.text_001'); } };
|
||||
|
||||
function setStatusBadge(node, status, label) {
|
||||
if (!node) return;
|
||||
node.className = `ar-attachment-status ar-attachment-status--${status || 'pending'}`;
|
||||
node.textContent = label || t('screens.arweave_uploads_view.text_014');
|
||||
}
|
||||
|
||||
function renderTile(item, index) {
|
||||
const tile = document.createElement('article');
|
||||
tile.className = 'ar-attachment-history-tile ar-attachment-history-tile--page';
|
||||
|
||||
const name = document.createElement('strong');
|
||||
name.className = 'ar-attachment-history-name';
|
||||
name.textContent = item.name;
|
||||
|
||||
const status = document.createElement('span');
|
||||
status.className = 'ar-attachment-status ar-attachment-status--pending';
|
||||
status.dataset.statusIndex = String(index);
|
||||
status.textContent = t('screens.arweave_uploads_view.text_002');
|
||||
|
||||
const meta = document.createElement('div');
|
||||
meta.className = 'ar-attachment-history-meta-row';
|
||||
const size = document.createElement('span');
|
||||
size.textContent = formatBytes(item.size);
|
||||
const time = document.createElement('span');
|
||||
time.textContent = formatArweaveHistoryTime(item.uploadedAtMs);
|
||||
meta.append(status, size, time);
|
||||
if (item.pendingPlacement) {
|
||||
const flag = document.createElement('span');
|
||||
flag.className = 'ar-attachment-placement-flag';
|
||||
flag.textContent = t('screens.arweave_uploads_view.text_003');
|
||||
meta.append(flag);
|
||||
}
|
||||
|
||||
const txId = document.createElement('div');
|
||||
txId.className = 'mono-cell ar-attachment-history-txid';
|
||||
txId.textContent = item.ar;
|
||||
|
||||
tile.append(name, meta, txId);
|
||||
return tile;
|
||||
}
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack arweave-uploads-screen';
|
||||
|
||||
const statusLine = document.createElement('p');
|
||||
statusLine.className = 'meta-muted inline-error';
|
||||
|
||||
const list = document.createElement('div');
|
||||
list.className = 'ar-attachment-history-tiles arweave-uploads-list';
|
||||
|
||||
const uploadFile = async () => {
|
||||
statusLine.textContent = '';
|
||||
try {
|
||||
await openArweaveAttachmentManager({
|
||||
login: state.session.login,
|
||||
storagePwd: state.session.storagePwdInMemory,
|
||||
gateway: state.entrySettings.arweaveServer,
|
||||
historyOnly: true,
|
||||
});
|
||||
renderHistory();
|
||||
} catch (error) {
|
||||
statusLine.textContent = toUserMessage(error, t('screens.arweave_uploads_view.text_013'));
|
||||
}
|
||||
};
|
||||
|
||||
function renderHistory() {
|
||||
const rows = readArweaveAttachmentHistory(state.session.login).slice().reverse();
|
||||
list.innerHTML = '';
|
||||
statusLine.textContent = '';
|
||||
|
||||
if (!rows.length) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'empty-note';
|
||||
empty.textContent = t('screens.arweave_uploads_view.text_004');
|
||||
list.append(empty);
|
||||
return;
|
||||
}
|
||||
|
||||
rows.forEach((item, index) => {
|
||||
list.append(renderTile(item, index));
|
||||
const statusEl = list.querySelector(`[data-status-index="${index}"]`);
|
||||
void getArweaveAttachmentAvailability({
|
||||
gateway: state.entrySettings.arweaveServer,
|
||||
attachment: item,
|
||||
})
|
||||
.then((result) => setStatusBadge(statusEl, result.status, result.label))
|
||||
.catch(() => setStatusBadge(statusEl, 'unavailable', t('screens.arweave_uploads_view.text_015')));
|
||||
});
|
||||
|
||||
window.setTimeout(() => {
|
||||
list.scrollTop = list.scrollHeight;
|
||||
}, 0);
|
||||
}
|
||||
|
||||
const topbar = createTopBar({
|
||||
title: t('screens.arweave_uploads_view.text_005'),
|
||||
back: { onClick: () => navigate('my-blockchain-view') },
|
||||
actions: [
|
||||
{
|
||||
icon: 'plus',
|
||||
title: t('screens.arweave_uploads_view.text_006'),
|
||||
ariaLabel: t('screens.arweave_uploads_view.text_007'),
|
||||
className: 'arweave-uploads-add',
|
||||
onClick: () => { void uploadFile(); },
|
||||
},
|
||||
{
|
||||
iconNode: createOverflowDots(),
|
||||
title: t('screens.arweave_uploads_view.text_008'),
|
||||
ariaLabel: t('screens.arweave_uploads_view.text_009'),
|
||||
className: 'arweave-uploads-menu-btn',
|
||||
menu: {
|
||||
minWidth: 220,
|
||||
items: [
|
||||
{ label: t('screens.arweave_uploads_view.text_010'), action: () => uploadFile() },
|
||||
{
|
||||
label: t('screens.arweave_uploads_view.text_011'),
|
||||
action: async () => {
|
||||
const confirmed = await confirmDialog({ title: t('dialogs.pages.arweave_uploads_view.title_001'), text: t('dialogs.pages.arweave_uploads_view.text_002'), confirmLabel: t('dialogs.pages.arweave_uploads_view.confirmLabel_003'), danger: true });
|
||||
if (!confirmed) return;
|
||||
clearArweaveAttachmentHistory(state.session.login);
|
||||
renderHistory();
|
||||
},
|
||||
},
|
||||
{
|
||||
label: t('screens.arweave_uploads_view.text_012'),
|
||||
action: () => window.alert(
|
||||
t('dialogs.final.uploads.help')
|
||||
),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
chrome?.setTopbar(topbar);
|
||||
screen.append(statusLine, list);
|
||||
renderHistory();
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,791 @@
|
||||
import { formatDate } from '../i18n/format.js';
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { renderAvatar } from '../components/avatar-image.js';
|
||||
import { markArweaveAttachmentPlaced, openArweaveAttachmentManager } from '../components/arweave-attachment-manager.js';
|
||||
import { openChannelAttachmentManager } from '../components/channel-attachment-manager.js';
|
||||
import { authService, setChannelsFeed, state } from '../state.js';
|
||||
import { navigateBack, getPreviousTrackedPath } from '../router.js';
|
||||
import {
|
||||
extractLoginFromBlockchainName,
|
||||
makeProfileRoute,
|
||||
makeShineChannelShortRoute,
|
||||
makeShineChannelDonateRoute,
|
||||
formatChannelAddress,
|
||||
} from '../services/shine-routes.js';
|
||||
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||||
import {
|
||||
formatSol,
|
||||
getBalanceSol,
|
||||
getSolanaWalletFromStoredSecret,
|
||||
getWalletFromStoredBlockchainKey,
|
||||
solanaAddressFromPublicKeyBase64,
|
||||
transferSol,
|
||||
} from '../services/solana-wallet-service.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'channel-about-view', get title() { return t('screens.channel_about_view.text_001'); } };
|
||||
|
||||
function escapeHtml(text) {
|
||||
return String(text || '')
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
|
||||
function normalizeHash(hash) {
|
||||
const normalized = String(hash || '').trim().toLowerCase();
|
||||
return normalized || '0';
|
||||
}
|
||||
|
||||
function toSafeInt(value) {
|
||||
if (value === '' || value == null) return null;
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
function buildChannelLink(route) {
|
||||
if (!route) return '';
|
||||
try {
|
||||
return new URL(`/${String(route).replace(/^\/+/, '')}`, window.location.origin).toString();
|
||||
} catch {
|
||||
return `${window.location.origin}/${String(route).replace(/^\/+/, '')}`;
|
||||
}
|
||||
}
|
||||
|
||||
function statsText(value) {
|
||||
return Number.isFinite(Number(value)) ? String(Math.max(0, Number(value))) : '0';
|
||||
}
|
||||
|
||||
function profileField(snapshot, key) {
|
||||
const row = Array.isArray(snapshot?.fields)
|
||||
? snapshot.fields.find((item) => String(item?.key || '') === key)
|
||||
: null;
|
||||
return String(row?.value || '').trim();
|
||||
}
|
||||
|
||||
function ownerDisplayName(snapshot, ownerLogin) {
|
||||
const firstName = profileField(snapshot, 'first_name');
|
||||
const lastName = profileField(snapshot, 'last_name');
|
||||
return [firstName, lastName].filter(Boolean).join(' ').trim() || String(ownerLogin || '').trim() || t('screens.channel_about_view.text_023');
|
||||
}
|
||||
|
||||
function formatChannelCreatedAt(value) {
|
||||
const time = Number(value || 0);
|
||||
if (!Number.isFinite(time) || time <= 0) return t('screens.channel_about_view.text_011');
|
||||
try {
|
||||
return formatDate(new Date(time), { day: '2-digit', month: 'long', year: 'numeric' });
|
||||
} catch {
|
||||
return formatDate(new Date(time));
|
||||
}
|
||||
}
|
||||
|
||||
function openChannelProfileEditor({ channel, selector, onSaved }) {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!root) return;
|
||||
let selectedAvatar = String(channel?.avaPr || '').trim() ? {
|
||||
name: t('dialogs.remaining.pages.channel_about_view.openchannelprofileeditor.avatar'),
|
||||
ar: String(channel.avaAr || '').trim(),
|
||||
pr: String(channel?.avaPr || '').trim(),
|
||||
size: Number(channel?.avaSize || 0),
|
||||
purpose: 'avatar',
|
||||
} : null;
|
||||
|
||||
const cleanTitle = String(channel?.displayName || channel?.displayTitle || channel?.channelName || '').trim();
|
||||
const cleanDescription = String(channel?.channelDescription || channel?.description || '').trim();
|
||||
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="channel-profile-edit-modal">
|
||||
<div class="modal-card stack channel-profile-card">
|
||||
<h3 class="modal-title">${t('dialogs.modals.channel_about_view.label_001')}</h3>
|
||||
<div id="channel-profile-edit-avatar-preview"></div>
|
||||
<button class="secondary-btn" id="channel-profile-edit-avatar" type="button">${t('dialogs.modals.channel_about_view.label_002')}</button>
|
||||
<label class="meta-muted" for="channel-profile-edit-title">${t('dialogs.modals.channel_about_view.label_003')}</label>
|
||||
<input class="input" id="channel-profile-edit-title" type="text" maxlength="50" value="${escapeHtml(cleanTitle)}" />
|
||||
<label class="meta-muted" for="channel-profile-edit-description">${t('dialogs.modals.channel_about_view.label_004')}</label>
|
||||
<textarea class="input" id="channel-profile-edit-description" rows="4" maxlength="250">${escapeHtml(cleanDescription)}</textarea>
|
||||
<p class="meta-muted inline-error" id="channel-profile-edit-error"></p>
|
||||
<div class="form-actions-grid">
|
||||
<button class="secondary-btn" id="channel-profile-edit-cancel" type="button">${t('dialogs.modals.channel_about_view.label_005')}</button>
|
||||
<button class="primary-btn" id="channel-profile-edit-save" type="button">${t('dialogs.modals.channel_about_view.label_006')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const renderPreview = () => {
|
||||
const slot = root.querySelector('#channel-profile-edit-avatar-preview');
|
||||
if (!slot) return;
|
||||
const title = String(root.querySelector('#channel-profile-edit-title')?.value || cleanTitle).trim();
|
||||
slot.innerHTML = '';
|
||||
slot.append(renderAvatar({
|
||||
initials: (title || t('dialogs.remaining.pages.channel_about_view.renderpreview.k')).slice(0, 1).toUpperCase(),
|
||||
avatar: selectedAvatar?.pr ? { ar: String(selectedAvatar.ar || ''), pr: selectedAvatar.pr } : null,
|
||||
authorLogin: String(channel?.ownerLogin || state.session.login || '').trim(),
|
||||
size: 'xl',
|
||||
className: 'channel-about-avatar channel-profile-avatar avatar-plain',
|
||||
title: title || t('dialogs.modals.channel_about_view.channel_fallback'),
|
||||
alt: t('dialogs.remaining.pages.channel_about_view.renderpreview.avatar_kanala'),
|
||||
}));
|
||||
};
|
||||
renderPreview();
|
||||
|
||||
root.querySelector('#channel-profile-edit-cancel')?.addEventListener('click', () => { root.innerHTML = ''; });
|
||||
root.querySelector('#channel-profile-edit-title')?.addEventListener('input', renderPreview);
|
||||
root.querySelector('#channel-profile-edit-avatar')?.addEventListener('click', async () => {
|
||||
const errorEl = root.querySelector('#channel-profile-edit-error');
|
||||
try {
|
||||
const item = await openChannelAttachmentManager({
|
||||
login: state.session.login,
|
||||
storagePwd: state.session.storagePwdInMemory,
|
||||
gateway: state.entrySettings.arweaveServer,
|
||||
mode: 'avatar',
|
||||
});
|
||||
if (!item) return;
|
||||
selectedAvatar = item;
|
||||
renderPreview();
|
||||
} catch (error) {
|
||||
if (errorEl) errorEl.textContent = toUserMessage(error, t('dialogs.modals.channel_about_view.label_014'));
|
||||
}
|
||||
});
|
||||
|
||||
root.querySelector('#channel-profile-edit-save')?.addEventListener('click', async () => {
|
||||
const save = root.querySelector('#channel-profile-edit-save');
|
||||
const errorEl = root.querySelector('#channel-profile-edit-error');
|
||||
const title = String(root.querySelector('#channel-profile-edit-title')?.value || '').trim();
|
||||
const description = String(root.querySelector('#channel-profile-edit-description')?.value || '').trim();
|
||||
if (Array.from(title).length > 50 || Array.from(description).length > 250) {
|
||||
if (errorEl) errorEl.textContent = t('dialogs.modals.channel_about_view.label_015');
|
||||
return;
|
||||
}
|
||||
save.disabled = true;
|
||||
if (errorEl) errorEl.textContent = '';
|
||||
try {
|
||||
const login = String(state.session.login || '').trim();
|
||||
const storagePwd = String(state.session.storagePwdInMemory || '').trim();
|
||||
if (!login || !storagePwd) throw new Error(t('dialogs.remaining.pages.channel_about_view.openchannelprofileeditor.dlya_izmeneniya_profilya_nuzhno_voyti_zanovo'));
|
||||
await authService.addBlockChannelMeta({ login, storagePwd, channel: selector, title, description, avatar: selectedAvatar });
|
||||
if (selectedAvatar?.ar) markArweaveAttachmentPlaced(login, selectedAvatar);
|
||||
root.innerHTML = '';
|
||||
showToast(t('dialogs.remaining.pages.channel_about_view.openchannelprofileeditor.profil_kanala_obnovlyon'));
|
||||
onSaved?.();
|
||||
} catch (error) {
|
||||
save.disabled = false;
|
||||
if (errorEl) errorEl.textContent = toUserMessage(error, t('dialogs.modals.channel_about_view.label_016'));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function isSelectorMatch(row, selector) {
|
||||
return Boolean(
|
||||
row?.channel
|
||||
&& String(row.channel.ownerBlockchainName || '') === String(selector?.ownerBlockchainName || '')
|
||||
&& Number(row.channel.channelRoot?.blockNumber) === Number(selector?.channelRootBlockNumber)
|
||||
&& normalizeHash(row.channel.channelRoot?.blockHash) === normalizeHash(selector?.channelRootBlockHash)
|
||||
);
|
||||
}
|
||||
|
||||
async function resolveChannelSelector(route) {
|
||||
const ownerRef = String(route?.params?.ownerBlockchainName || '').trim();
|
||||
const rootNo = toSafeInt(route?.params?.channelRootBlockNumber);
|
||||
const rootHash = normalizeHash(route?.params?.channelRootBlockHash);
|
||||
const channelName = String(route?.params?.channelName || '').trim();
|
||||
|
||||
if (ownerRef && rootNo != null) {
|
||||
return {
|
||||
ownerBlockchainName: ownerRef,
|
||||
channelRootBlockNumber: rootNo,
|
||||
channelRootBlockHash: rootHash,
|
||||
channelName,
|
||||
};
|
||||
}
|
||||
|
||||
if (!ownerRef || !channelName) {
|
||||
throw new Error(t('screens.channel_about_view.text_024'));
|
||||
}
|
||||
|
||||
const ownerLogin = extractLoginFromBlockchainName(ownerRef);
|
||||
const ownerUser = await authService.getUser(ownerLogin);
|
||||
if (!ownerUser?.exists) throw new Error(t('screens.channel_about_view.text_025'));
|
||||
|
||||
const ownerFeed = await authService.listSubscriptionsFeed(ownerLogin, 500);
|
||||
const ownedRows = Array.isArray(ownerFeed?.ownedChannels) ? ownerFeed.ownedChannels : [];
|
||||
const ownerLoginNormalized = ownerLogin.toLowerCase();
|
||||
const row = ownedRows.find((item) => (
|
||||
String(item?.channel?.channelName || '').trim().toLowerCase() === channelName.toLowerCase()
|
||||
&& String(item?.channel?.ownerLogin || '').trim().toLowerCase() === ownerLoginNormalized
|
||||
));
|
||||
if (row?.channel?.channelRoot) {
|
||||
const rootBlockchainName = String(row.channel.ownerBlockchainName || ownerRef).trim();
|
||||
return {
|
||||
ownerBlockchainName: rootBlockchainName,
|
||||
channelRootBlockNumber: Number(row.channel.channelRoot.blockNumber),
|
||||
channelRootBlockHash: normalizeHash(row.channel.channelRoot.blockHash),
|
||||
channelName,
|
||||
};
|
||||
}
|
||||
|
||||
const profileChannels = await authService.listUserProfileChannels(ownerLogin, 'owned', 500, 0, true);
|
||||
const deletedRow = (Array.isArray(profileChannels?.channels) ? profileChannels.channels : []).find((item) => (
|
||||
String(item?.slug || '').trim().toLowerCase() === channelName.toLowerCase()
|
||||
&& String(item?.ownerLogin || '').trim().toLowerCase() === ownerLoginNormalized
|
||||
));
|
||||
if (!deletedRow) throw new Error(t('screens.channel_about_view.text_026'));
|
||||
return {
|
||||
ownerBlockchainName: String(deletedRow.ownerBlockchainName || ownerRef).trim(),
|
||||
channelRootBlockNumber: Number(deletedRow.rootBlockNumber),
|
||||
channelRootBlockHash: normalizeHash(deletedRow.rootBlockHashHex),
|
||||
channelName,
|
||||
};
|
||||
}
|
||||
|
||||
function publicKeyChoice(ownerUser, field, id, label) {
|
||||
const publicKeyB64 = String(ownerUser?.[field] || '').trim();
|
||||
if (!publicKeyB64) return null;
|
||||
try {
|
||||
return {
|
||||
id,
|
||||
label,
|
||||
address: solanaAddressFromPublicKeyBase64(publicKeyB64),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function openSupportChannelModal({ ownerLogin, ownerUser, channelTitle }) {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!root) return;
|
||||
|
||||
const recipientChoices = [
|
||||
publicKeyChoice(ownerUser, 'blockchainKey', 'blockchain-key', 'Blockchain key'),
|
||||
].filter(Boolean);
|
||||
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="channel-support-modal">
|
||||
<div class="modal-card stack channel-support-modal-card">
|
||||
<div class="channel-support-modal-head">
|
||||
<div>
|
||||
<h3 class="modal-title">${t('dialogs.modals.channel_about_view.label_008')}</h3>
|
||||
<p class="meta-muted channel-support-subtitle">${escapeHtml(channelTitle || t('dialogs.modals.channel_about_view.channel_fallback'))} · ${escapeHtml(ownerLogin)}</p>
|
||||
</div>
|
||||
<button class="icon-btn channel-support-close" id="channel-support-close" type="button" aria-label="${t('dialogs.modals.channel_about_view.label_007')}" title="${t('dialogs.modals.channel_about_view.label_007')}">×</button>
|
||||
</div>
|
||||
|
||||
<label class="field-label" for="channel-support-blockchain">${t('dialogs.modals.channel_about_view.label_009')}</label>
|
||||
<select class="select" id="channel-support-blockchain">
|
||||
<option value="solana">Solana</option>
|
||||
</select>
|
||||
|
||||
<label class="field-label" for="channel-support-recipient-key">${t('dialogs.modals.channel_about_view.label_010')}</label>
|
||||
<select class="select" id="channel-support-recipient-key" ${recipientChoices.length ? '' : 'disabled'}>
|
||||
${recipientChoices.map((choice) => `<option value="${escapeHtml(choice.id)}">${escapeHtml(choice.label)}</option>`).join('')}
|
||||
</select>
|
||||
<div class="channel-support-address" id="channel-support-recipient-address">–</div>
|
||||
|
||||
<label class="field-label" for="channel-support-sender-key">${t('dialogs.remaining.pages.channel_about_view.markup.perevesti_s_moego_schyota')}</label>
|
||||
<div class="channel-support-address" id="channel-support-sender-key">Blockchain key</div>
|
||||
<div class="channel-support-address" id="channel-support-sender-address">—</div>
|
||||
|
||||
<div class="channel-support-balance-row">
|
||||
<span class="meta-muted">${t('dialogs.remaining.pages.channel_about_view.markup.balans')}</span>
|
||||
<strong id="channel-support-balance">–</strong>
|
||||
<button class="secondary-btn channel-support-refresh" id="channel-support-refresh" type="button">${t('dialogs.remaining.pages.channel_about_view.markup.obnovit')}</button>
|
||||
</div>
|
||||
|
||||
<label class="field-label" for="channel-support-amount">${t('dialogs.remaining.pages.channel_about_view.markup.summa')}</label>
|
||||
<div class="channel-support-amount-row">
|
||||
<input class="input" id="channel-support-amount" type="number" min="0" step="0.000001" inputmode="decimal" placeholder="0.1" />
|
||||
<span>SOL</span>
|
||||
</div>
|
||||
|
||||
<p class="meta-muted inline-error channel-support-status" id="channel-support-status"></p>
|
||||
<div class="channel-support-result" id="channel-support-result" hidden></div>
|
||||
<button class="primary-btn channel-support-submit" id="channel-support-submit" type="button" ${recipientChoices.length ? '' : 'disabled'}>${t('dialogs.remaining.pages.channel_about_view.markup.perevesti')}</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const modal = root.querySelector('#channel-support-modal');
|
||||
const recipientSelect = root.querySelector('#channel-support-recipient-key');
|
||||
const senderSelect = root.querySelector('#channel-support-sender-key');
|
||||
const recipientAddressEl = root.querySelector('#channel-support-recipient-address');
|
||||
const senderAddressEl = root.querySelector('#channel-support-sender-address');
|
||||
const balanceEl = root.querySelector('#channel-support-balance');
|
||||
const amountEl = root.querySelector('#channel-support-amount');
|
||||
const statusEl = root.querySelector('#channel-support-status');
|
||||
const resultEl = root.querySelector('#channel-support-result');
|
||||
const submitEl = root.querySelector('#channel-support-submit');
|
||||
const refreshEl = root.querySelector('#channel-support-refresh');
|
||||
const walletCache = new Map();
|
||||
let closed = false;
|
||||
let busy = false;
|
||||
|
||||
const cleanupWallets = () => {
|
||||
for (const wallet of walletCache.values()) {
|
||||
try {
|
||||
wallet?.keypair?.secretKey?.fill?.(0);
|
||||
} catch {
|
||||
// best effort: секрет существует только в памяти модального окна
|
||||
}
|
||||
}
|
||||
walletCache.clear();
|
||||
};
|
||||
|
||||
const close = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
cleanupWallets();
|
||||
if (root.querySelector('#channel-support-modal') === modal) root.innerHTML = '';
|
||||
};
|
||||
|
||||
const setBusy = (nextBusy) => {
|
||||
busy = Boolean(nextBusy);
|
||||
if (submitEl) submitEl.disabled = busy || recipientChoices.length === 0;
|
||||
if (refreshEl) refreshEl.disabled = busy;
|
||||
if (recipientSelect) recipientSelect.disabled = busy || recipientChoices.length === 0;
|
||||
if (senderSelect) senderSelect.disabled = busy;
|
||||
if (amountEl) amountEl.disabled = busy;
|
||||
};
|
||||
|
||||
const setStatus = (message, kind = '') => {
|
||||
if (!statusEl) return;
|
||||
statusEl.textContent = String(message || '');
|
||||
statusEl.classList.toggle('is-error', kind === 'error');
|
||||
};
|
||||
|
||||
const selectedRecipient = () => recipientChoices.find((choice) => choice.id === String(recipientSelect?.value || '')) || recipientChoices[0] || null;
|
||||
|
||||
const updateRecipientAddress = () => {
|
||||
const choice = selectedRecipient();
|
||||
if (recipientAddressEl) recipientAddressEl.textContent = choice?.address || t('dialogs.modals.channel_about_view.label_017');
|
||||
};
|
||||
|
||||
const resolveSenderWallet = async () => {
|
||||
const keyId = 'blockchain-key';
|
||||
if (walletCache.has(keyId)) return walletCache.get(keyId);
|
||||
|
||||
const login = String(state.session.login || '').trim();
|
||||
const storagePwd = String(state.session.storagePwdInMemory || '').trim();
|
||||
if (!login || !storagePwd) throw new Error(t('dialogs.remaining.pages.channel_about_view.opensupportchannelmodal.dlya_perevoda_nuzhno_voyti_v_siyanii'));
|
||||
const wallet = await getWalletFromStoredBlockchainKey({ login, storagePwd });
|
||||
|
||||
walletCache.set(keyId, wallet);
|
||||
return wallet;
|
||||
};
|
||||
|
||||
const refreshBalance = async () => {
|
||||
if (busy || closed) return;
|
||||
setBusy(true);
|
||||
setStatus(t('dialogs.remaining.pages.channel_about_view.opensupportchannelmodal.zagruzka_balansa'));
|
||||
if (balanceEl) balanceEl.textContent = '–';
|
||||
try {
|
||||
const wallet = await resolveSenderWallet();
|
||||
if (closed) return;
|
||||
if (senderAddressEl) senderAddressEl.textContent = wallet.address;
|
||||
const balance = await getBalanceSol({
|
||||
endpoint: state.entrySettings.solanaServer,
|
||||
address: wallet.address,
|
||||
});
|
||||
if (closed) return;
|
||||
if (balanceEl) balanceEl.textContent = `${formatSol(balance.sol)} SOL`;
|
||||
setStatus('');
|
||||
} catch (error) {
|
||||
if (closed) return;
|
||||
if (senderAddressEl) senderAddressEl.textContent = '–';
|
||||
setStatus(toUserMessage(error, t('dialogs.remaining.pages.channel_about_view.opensupportchannelmodal.ne_udalos_poluchit_balans')), 'error');
|
||||
} finally {
|
||||
if (!closed) setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
recipientSelect?.addEventListener('change', updateRecipientAddress);
|
||||
senderSelect?.addEventListener('change', () => {
|
||||
if (senderAddressEl) senderAddressEl.textContent = '–';
|
||||
if (balanceEl) balanceEl.textContent = '–';
|
||||
setStatus('');
|
||||
void refreshBalance();
|
||||
});
|
||||
refreshEl?.addEventListener('click', () => void refreshBalance());
|
||||
root.querySelector('#channel-support-close')?.addEventListener('click', close);
|
||||
modal?.addEventListener('pointerdown', (event) => {
|
||||
if (event.target === modal) close();
|
||||
});
|
||||
|
||||
submitEl?.addEventListener('click', async () => {
|
||||
if (busy || closed) return;
|
||||
const recipient = selectedRecipient();
|
||||
if (!recipient?.address) {
|
||||
setStatus(t('dialogs.remaining.pages.channel_about_view.opensupportchannelmodal.ne_udalos_opredelit_schyot_poluchatelya'), 'error');
|
||||
return;
|
||||
}
|
||||
const amount = Number(String(amountEl?.value || '').replace(',', '.'));
|
||||
if (!Number.isFinite(amount) || amount <= 0) {
|
||||
setStatus(t('dialogs.remaining.pages.channel_about_view.opensupportchannelmodal.vvedite_summu_perevoda_bolshe_0'), 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
setBusy(true);
|
||||
setStatus(t('dialogs.remaining.pages.channel_about_view.opensupportchannelmodal.otpravlyaem_perevod'));
|
||||
if (resultEl) {
|
||||
resultEl.hidden = true;
|
||||
resultEl.innerHTML = '';
|
||||
}
|
||||
try {
|
||||
const wallet = await resolveSenderWallet();
|
||||
const result = await transferSol({
|
||||
endpoint: state.entrySettings.solanaServer,
|
||||
fromKeypair: wallet.keypair,
|
||||
toAddress: recipient.address,
|
||||
amountSol: amount,
|
||||
});
|
||||
if (closed) return;
|
||||
setStatus('');
|
||||
if (resultEl) {
|
||||
resultEl.hidden = false;
|
||||
resultEl.innerHTML = `
|
||||
<strong>${t('dialogs.remaining.pages.channel_about_view.markup.perevod_vypolnen')}</strong>
|
||||
<span>${escapeHtml(formatSol(amount))} SOL → ${escapeHtml(recipient.label)}</span>
|
||||
<code>${escapeHtml(String(result.signature || ''))}</code>
|
||||
`;
|
||||
}
|
||||
showToast(t('dialogs.remaining.pages.channel_about_view.opensupportchannelmodal.perevod_otpravlen'));
|
||||
const balance = await getBalanceSol({
|
||||
endpoint: state.entrySettings.solanaServer,
|
||||
address: wallet.address,
|
||||
});
|
||||
if (!closed && balanceEl) balanceEl.textContent = `${formatSol(balance.sol)} SOL`;
|
||||
} catch (error) {
|
||||
if (!closed) setStatus(toUserMessage(error, t('dialogs.remaining.pages.channel_about_view.opensupportchannelmodal.ne_udalos_vypolnit_perevod')), 'error');
|
||||
} finally {
|
||||
if (!closed) setBusy(false);
|
||||
}
|
||||
});
|
||||
|
||||
updateRecipientAddress();
|
||||
if (!recipientChoices.length) {
|
||||
setStatus(t('dialogs.remaining.pages.channel_about_view.opensupportchannelmodal.u_vladeltsa_kanala_net_dostupnyh_publichnyh_klyuchey_d'), 'error');
|
||||
} else {
|
||||
void refreshBalance();
|
||||
}
|
||||
return close;
|
||||
}
|
||||
|
||||
function confirmUnsubscribeModal({ channelTitle }) {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!root) return Promise.resolve(window.confirm(t('dialogs.pages.channel_about_view.confirm_001')));
|
||||
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const finish = (value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (root.querySelector('#channel-unsubscribe-confirm-modal')) root.innerHTML = '';
|
||||
resolve(Boolean(value));
|
||||
};
|
||||
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="channel-unsubscribe-confirm-modal">
|
||||
<div class="modal-card stack channel-unsubscribe-confirm-card">
|
||||
<h3 class="modal-title">${t('dialogs.modals.channel_about_view.label_011')}</h3>
|
||||
<p class="meta-muted channel-unsubscribe-confirm-text">
|
||||
${escapeHtml(t('dialogs.final.channel.unsubscribe_prompt', { channel: channelTitle || t('dialogs.modals.channel_about_view.this_channel') }))}
|
||||
</p>
|
||||
<div class="channel-unsubscribe-confirm-actions">
|
||||
<button class="secondary-btn" id="channel-unsubscribe-no" type="button">${t('dialogs.modals.channel_about_view.label_012')}</button>
|
||||
<button class="destructive-btn channel-unsubscribe-confirm-yes" id="channel-unsubscribe-yes" type="button">${t('dialogs.modals.channel_about_view.label_013')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const modal = root.querySelector('#channel-unsubscribe-confirm-modal');
|
||||
root.querySelector('#channel-unsubscribe-no')?.addEventListener('click', () => finish(false));
|
||||
root.querySelector('#channel-unsubscribe-yes')?.addEventListener('click', () => finish(true));
|
||||
modal?.addEventListener('pointerdown', (event) => {
|
||||
if (event.target === modal) finish(false);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function subscribersWord(count) {
|
||||
const n = Math.abs(Number(count) || 0) % 100;
|
||||
const last = n % 10;
|
||||
if (n > 10 && n < 20) return t('screens.channel_about_view.text_012');
|
||||
if (last === 1) return t('screens.channel_about_view.text_013');
|
||||
if (last >= 2 && last <= 4) return t('screens.channel_about_view.text_014');
|
||||
return t('screens.channel_about_view.text_015');
|
||||
}
|
||||
|
||||
export function render({ navigate, route, chrome }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack channels-screen channels-screen--channel-about';
|
||||
|
||||
const topbar = createTopBar({
|
||||
title: t('screens.channel_about_view.text_002'),
|
||||
back: {
|
||||
label: '←',
|
||||
onClick: () => {
|
||||
if (window.history.length > 1) {
|
||||
navigateBack();
|
||||
return;
|
||||
}
|
||||
navigate('channels-list');
|
||||
},
|
||||
ariaLabel: t('screens.channel_about_view.text_003'),
|
||||
title: t('screens.channel_about_view.text_004'),
|
||||
},
|
||||
});
|
||||
chrome?.setTopbar(topbar);
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack channel-about-card';
|
||||
const content = document.createElement('div');
|
||||
content.className = 'stack channel-about-content';
|
||||
content.innerHTML = t('screens.channel_about_view.text_027');
|
||||
card.append(content);
|
||||
screen.append(card);
|
||||
|
||||
let disposed = false;
|
||||
let refreshSeq = 0;
|
||||
let closeSupportModal = null;
|
||||
|
||||
const requireSigningSession = () => {
|
||||
const login = String(state.session.login || '').trim();
|
||||
const storagePwd = String(state.session.storagePwdInMemory || '').trim();
|
||||
if (!login || !storagePwd) {
|
||||
state.authReturnHash = window.location.pathname || '/channels';
|
||||
navigate('login-view');
|
||||
throw new Error(t('screens.channel_about_view.text_028'));
|
||||
}
|
||||
return { login, storagePwd };
|
||||
};
|
||||
|
||||
const renderContent = ({ channel, selector, ownerUser, ownerProfile, isOwnChannel, isSubscribed }) => {
|
||||
const cleanName = String(channel?.displayTitle || channel?.displayName || channel?.channelName || t('dialogs.modals.channel_about_view.channel_fallback')).trim();
|
||||
const ownerLogin = String(channel?.ownerLogin || extractLoginFromBlockchainName(selector?.ownerBlockchainName) || '').trim();
|
||||
const channelName = String(channel?.channelName || '').trim();
|
||||
const description = String(channel?.channelDescription || channel?.description || '').trim();
|
||||
const subscribersCount = Number(channel?.subscribersCount || 0);
|
||||
const isDeleted = !!channel?.deleted;
|
||||
const shortRoute = makeShineChannelShortRoute({
|
||||
ownerLogin,
|
||||
ownerBlockchainName: selector?.ownerBlockchainName,
|
||||
channelName,
|
||||
});
|
||||
const donateRoute = makeShineChannelDonateRoute({
|
||||
ownerBlockchainName: selector?.ownerBlockchainName,
|
||||
channelRootBlockNumber: selector?.channelRootBlockNumber,
|
||||
channelRootBlockHash: selector?.channelRootBlockHash,
|
||||
});
|
||||
const serverLink = buildChannelLink(shortRoute);
|
||||
const shortLink = String(serverLink || '').replace(/^https?:\/\//, '');
|
||||
const cameFromChannel = !!shortRoute && (getPreviousTrackedPath() || '').replace(/^\//, '') === String(shortRoute).replace(/^\//, '');
|
||||
const ownerName = ownerDisplayName(ownerProfile, ownerLogin);
|
||||
|
||||
const subscriptionTile = isOwnChannel ? '' : `
|
||||
<button class="channel-about-tile${isSubscribed ? ' is-active' : ''}" id="channel-about-subscription" type="button">
|
||||
${iconHtml(isSubscribed ? 'check' : 'plus')}<span>${isSubscribed ? t('screens.channel_about_view.text_016') : t('screens.channel_about_view.text_017')}</span>
|
||||
</button>`;
|
||||
|
||||
content.innerHTML = `
|
||||
<div class="channel-about-hero">
|
||||
<div class="channel-about-avatar-slot" id="channel-about-avatar-slot"></div>
|
||||
<h2 class="channel-about-title">${escapeHtml(cleanName)}</h2>
|
||||
<div class="channel-about-subline">${escapeHtml(formatChannelAddress({ ownerLogin, channelName }))} · ${escapeHtml(statsText(subscribersCount))} ${escapeHtml(subscribersWord(subscribersCount))}</div>
|
||||
${isDeleted ? t('screens.channel_about_view.text_018') : ''}
|
||||
</div>
|
||||
|
||||
<div class="channel-about-tiles">
|
||||
${cameFromChannel ? '' : `<button class="channel-about-tile" id="channel-about-open" type="button">${iconHtml('open')}<span>${th('screens.channel_about_view.text_035')}</span></button>`}
|
||||
${isOwnChannel ? `<button class="channel-about-tile" id="channel-about-edit" type="button">${iconHtml('edit')}<span>${th('screens.channel_about_view.text_036')}</span></button>` : ''}
|
||||
${subscriptionTile}
|
||||
${isOwnChannel ? '' : `<button class="channel-about-tile" id="channel-about-support" type="button">${iconHtml('gift')}<span>${th('screens.channel_about_view.text_037')}</span></button>`}
|
||||
</div>
|
||||
|
||||
<div class="channel-about-list">
|
||||
<div class="channel-about-row channel-about-row--static">
|
||||
<span class="channel-about-row-label">${th('screens.channel_about_view.text_032')}</span>
|
||||
<p class="channel-about-description">${escapeHtml(description || t('screens.channel_about_view.text_029'))}</p>
|
||||
</div>
|
||||
<div class="channel-about-row channel-about-row--static">
|
||||
<span class="channel-about-row-main"><span class="channel-about-row-label">${th('screens.channel_about_view.text_033')}</span><strong>${escapeHtml(formatChannelCreatedAt(channel?.createdAtMs))}</strong></span>
|
||||
</div>
|
||||
<button class="channel-about-row" id="channel-about-owner" type="button">
|
||||
<span class="channel-about-owner-avatar" id="channel-about-owner-avatar"></span>
|
||||
<span class="channel-about-row-main">
|
||||
<strong>${escapeHtml(ownerName)}</strong>
|
||||
<span class="channel-about-row-label">${th('remaining.html_channel_about_view.owner')}${escapeHtml(ownerLogin)}</span>
|
||||
</span>
|
||||
<span class="channel-about-row-chevron">${iconHtml('chevron')}</span>
|
||||
</button>
|
||||
${isOwnChannel && !isDeleted ? `<button class="channel-about-row" id="channel-about-delete" type="button">
|
||||
<span class="channel-about-row-main"><span class="channel-about-row-label">${th('screens.channel_about_view.text_038')}</span><span class="meta-muted">${th('screens.channel_about_view.text_039')}</span></span>
|
||||
<span class="channel-about-row-chevron" aria-hidden="true">${iconHtml('trash')}</span>
|
||||
</button>` : ''}
|
||||
<button class="channel-about-row" id="channel-about-copy-row" type="button">
|
||||
<span class="channel-about-row-main">
|
||||
<span class="channel-about-row-label">${th('screens.channel_about_view.text_034')}</span>
|
||||
<span class="channel-about-link">${escapeHtml(shortLink)}</span>
|
||||
</span>
|
||||
<span class="channel-about-row-chevron" aria-hidden="true">${iconHtml('copy')}</span>
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const channelAvatar = renderAvatar({
|
||||
initials: cleanName.slice(0, 1).toUpperCase() || t('screens.channel_about_view.text_030'),
|
||||
avatar: String(channel?.avaAr || channel?.avaPr || '').trim() ? { ar: String(channel.avaAr || '').trim(), pr: String(channel?.avaPr || '').trim() } : null,
|
||||
authorLogin: ownerLogin,
|
||||
size: 'xl',
|
||||
className: 'channel-about-avatar channel-profile-avatar avatar-plain',
|
||||
title: cleanName,
|
||||
alt: t('screens.channel_about_view.text_005'),
|
||||
});
|
||||
content.querySelector('#channel-about-avatar-slot')?.append(channelAvatar);
|
||||
content.querySelector('#channel-about-owner-avatar')?.append(renderAvatar({
|
||||
initials: ownerName.slice(0, 1).toUpperCase() || '?',
|
||||
size: 'md',
|
||||
className: 'channel-about-owner-avatar-img avatar-plain',
|
||||
alt: '',
|
||||
}));
|
||||
|
||||
content.querySelector('#channel-about-edit')?.addEventListener('click', () => {
|
||||
requireSigningSession();
|
||||
openChannelProfileEditor({ channel, selector, onSaved: () => void refresh() });
|
||||
});
|
||||
content.querySelector('#channel-about-owner')?.addEventListener('click', () => {
|
||||
const profileRoute = makeProfileRoute(ownerLogin);
|
||||
if (profileRoute) navigate(profileRoute);
|
||||
});
|
||||
content.querySelector('#channel-about-support')?.addEventListener('click', () => {
|
||||
if (donateRoute) navigate(donateRoute);
|
||||
});
|
||||
content.querySelector('#channel-about-open')?.addEventListener('click', () => {
|
||||
if (shortRoute) navigate(shortRoute);
|
||||
});
|
||||
const copyLink = async () => {
|
||||
if (!serverLink) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(serverLink);
|
||||
showToast(t('screens.channel_about_view.text_006'));
|
||||
} catch (error) {
|
||||
showToast(toUserMessage(error, t('screens.channel_about_view.text_007')), { kind: 'error' });
|
||||
}
|
||||
};
|
||||
content.querySelector('#channel-about-copy-row')?.addEventListener('click', copyLink);
|
||||
content.querySelector('#channel-about-delete')?.addEventListener('click', async () => {
|
||||
if (!await confirmDialog({
|
||||
title: t('dialogs.pages.channel_about_view.title_002'),
|
||||
text: t('dialogs.pages.channel_about_view.text_003'),
|
||||
confirmLabel: t('dialogs.pages.channel_about_view.confirmLabel_004'),
|
||||
danger: true,
|
||||
})) return;
|
||||
try {
|
||||
const { login, storagePwd } = requireSigningSession();
|
||||
await authService.addBlockChannelDelete({ login, storagePwd, channel: selector });
|
||||
showToast(t('screens.channel_about_view.text_008'));
|
||||
void refresh();
|
||||
} catch (error) {
|
||||
showToast(toUserMessage(error, t('screens.channel_about_view.text_009')), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
const subscriptionButton = content.querySelector('#channel-about-subscription');
|
||||
subscriptionButton?.addEventListener('click', async () => {
|
||||
if (subscriptionButton.disabled) return;
|
||||
try {
|
||||
const { login, storagePwd } = requireSigningSession();
|
||||
if (isSubscribed) {
|
||||
const confirmed = await confirmUnsubscribeModal({ channelTitle: cleanName });
|
||||
if (!confirmed) return;
|
||||
}
|
||||
subscriptionButton.disabled = true;
|
||||
await authService.addBlockFollowChannel({
|
||||
login,
|
||||
storagePwd,
|
||||
targetBlockchainName: selector.ownerBlockchainName,
|
||||
targetBlockNumber: selector.channelRootBlockNumber,
|
||||
targetBlockHashHex: selector.channelRootBlockHash,
|
||||
unfollow: isSubscribed,
|
||||
});
|
||||
if (disposed) return;
|
||||
const feed = await authService.listSubscriptionsFeed(login, 1000);
|
||||
if (disposed) return;
|
||||
setChannelsFeed(feed, state.channelsIndex);
|
||||
showToast(isSubscribed ? t('screens.channel_about_view.text_019') : t('screens.channel_about_view.text_020'));
|
||||
void refresh();
|
||||
} catch (error) {
|
||||
if (!disposed) {
|
||||
showToast(toUserMessage(error, isSubscribed ? t('screens.channel_about_view.text_021') : t('screens.channel_about_view.text_022')), { kind: 'error' });
|
||||
subscriptionButton.disabled = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const refresh = async () => {
|
||||
const seq = ++refreshSeq;
|
||||
content.innerHTML = t('screens.channel_about_view.text_031');
|
||||
try {
|
||||
const selector = await resolveChannelSelector(route);
|
||||
const payload = await authService.getChannelMessages(selector, 1, 'asc', String(state.session.login || '').trim());
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
|
||||
const channel = payload?.channel || {};
|
||||
const ownerLogin = String(channel?.ownerLogin || extractLoginFromBlockchainName(selector.ownerBlockchainName) || '').trim();
|
||||
const currentLogin = String(state.session.login || '').trim();
|
||||
const isOwnChannel = Boolean(ownerLogin && currentLogin && ownerLogin.toLowerCase() === currentLogin.toLowerCase());
|
||||
|
||||
const [ownerUserResult, ownerProfileResult, feedResult] = await Promise.allSettled([
|
||||
authService.getUser(ownerLogin),
|
||||
loadProfileSnapshot(ownerLogin),
|
||||
currentLogin && !isOwnChannel ? authService.listSubscriptionsFeed(currentLogin, 1000) : Promise.resolve(null),
|
||||
]);
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
|
||||
const ownerUser = ownerUserResult.status === 'fulfilled' ? ownerUserResult.value : {};
|
||||
const ownerProfile = ownerProfileResult.status === 'fulfilled' ? ownerProfileResult.value : null;
|
||||
const feed = feedResult.status === 'fulfilled' ? feedResult.value : null;
|
||||
if (feed) setChannelsFeed(feed, state.channelsIndex);
|
||||
const followedRows = Array.isArray(feed?.followedChannels)
|
||||
? feed.followedChannels
|
||||
: (Array.isArray(state.channelsFeed?.followedChannels) ? state.channelsFeed.followedChannels : []);
|
||||
const isSubscribed = !isOwnChannel && followedRows.some((row) => isSelectorMatch(row, selector));
|
||||
|
||||
renderContent({
|
||||
channel,
|
||||
selector,
|
||||
ownerUser,
|
||||
ownerProfile,
|
||||
isOwnChannel,
|
||||
isSubscribed,
|
||||
});
|
||||
} catch (error) {
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
content.innerHTML = `
|
||||
<div class="meta-muted">${th('screens.channel_about_view.text_040')}</div>
|
||||
<div class="meta-muted">${escapeHtml(toUserMessage(error, t('screens.channel_about_view.text_010')))}</div>
|
||||
<button class="secondary-btn" id="channel-about-retry" type="button">${th('screens.channel_about_view.text_041')}</button>
|
||||
`;
|
||||
content.querySelector('#channel-about-retry')?.addEventListener('click', () => void refresh());
|
||||
}
|
||||
};
|
||||
|
||||
screen.refresh = refresh;
|
||||
screen.cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
refreshSeq += 1;
|
||||
closeSupportModal?.();
|
||||
closeSupportModal = null;
|
||||
};
|
||||
|
||||
void refresh();
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,427 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { navigateBack } from '../router.js';
|
||||
import { extractLoginFromBlockchainName, formatChannelAddress } from '../services/shine-routes.js';
|
||||
import {
|
||||
formatSol,
|
||||
getBalanceSol,
|
||||
getSolanaWalletFromStoredSecret,
|
||||
getWalletFromStoredBlockchainKey,
|
||||
solanaAddressFromPublicKeyBase64,
|
||||
} from '../services/solana-wallet-service.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { bytesToBase58 } from '../services/crypto-utils.js';
|
||||
import { loadEncryptedUserSecrets } from '../services/key-vault.js';
|
||||
import { readShineUserPda, supportShineUserOnSolana } from '../services/shine-user-pda-service.js';
|
||||
import { parseStarCents, splitStarCents, formatStars, starCentsToLamports, formatLamportsSol, hexHash32 } from '../services/shine-support-amount.js';
|
||||
import { transferSolLamports } from '../services/solana-wallet-service.js';
|
||||
import { getStarsQuoteFromRpc } from '../services/shine-stars-pyth.js';
|
||||
import { loadVerifiedSupportTotals, formatVerifiedSupportStars } from '../services/support-totals-service.js';
|
||||
|
||||
export const pageMeta = { id: 'channel-donate-view', get title() { return t('screens.channel_donate_view.text_001'); } };
|
||||
|
||||
function escapeHtml(text) {
|
||||
return String(text || '')
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
|
||||
function normalizeHash(hash) {
|
||||
const normalized = String(hash || '').trim().toLowerCase();
|
||||
return normalized || '0';
|
||||
}
|
||||
|
||||
function toSafeInt(value) {
|
||||
if (value === '' || value == null) return null;
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
async function resolveChannelSelector(route) {
|
||||
const ownerRef = String(route?.params?.ownerBlockchainName || '').trim();
|
||||
const rootNo = toSafeInt(route?.params?.channelRootBlockNumber);
|
||||
const rootHash = normalizeHash(route?.params?.channelRootBlockHash);
|
||||
const channelName = String(route?.params?.channelName || '').trim();
|
||||
|
||||
if (ownerRef && rootNo != null) {
|
||||
return {
|
||||
ownerBlockchainName: ownerRef,
|
||||
channelRootBlockNumber: rootNo,
|
||||
channelRootBlockHash: rootHash,
|
||||
channelName,
|
||||
};
|
||||
}
|
||||
|
||||
if (!ownerRef || !channelName) {
|
||||
throw new Error(t('screens.channel_donate_view.text_014'));
|
||||
}
|
||||
|
||||
const ownerLogin = extractLoginFromBlockchainName(ownerRef);
|
||||
const ownerUser = await authService.getUser(ownerLogin);
|
||||
if (!ownerUser?.exists) throw new Error(t('screens.channel_donate_view.text_015'));
|
||||
|
||||
const ownerBlockchainName = String(ownerUser.blockchainName || ownerRef).trim();
|
||||
const ownerFeed = await authService.listSubscriptionsFeed(ownerLogin, 500);
|
||||
const ownedRows = Array.isArray(ownerFeed?.ownedChannels) ? ownerFeed.ownedChannels : [];
|
||||
const row = ownedRows.find((item) => (
|
||||
String(item?.channel?.channelName || '').trim().toLowerCase() === channelName.toLowerCase()
|
||||
&& String(item?.channel?.ownerBlockchainName || '').trim().toLowerCase() === ownerBlockchainName.toLowerCase()
|
||||
));
|
||||
if (!row?.channel?.channelRoot) throw new Error(t('screens.channel_donate_view.text_016'));
|
||||
|
||||
return {
|
||||
ownerBlockchainName,
|
||||
channelRootBlockNumber: Number(row.channel.channelRoot.blockNumber),
|
||||
channelRootBlockHash: normalizeHash(row.channel.channelRoot.blockHash),
|
||||
channelName,
|
||||
};
|
||||
}
|
||||
|
||||
function publicKeyChoice(ownerUser, field, id, label) {
|
||||
const publicKeyB64 = String(ownerUser?.[field] || '').trim();
|
||||
if (!publicKeyB64) return null;
|
||||
try {
|
||||
return {
|
||||
id,
|
||||
label,
|
||||
address: solanaAddressFromPublicKeyBase64(publicKeyB64),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function render({ navigate, route, chrome }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack channels-screen channels-screen--channel-donate';
|
||||
|
||||
const topbar = createTopBar({
|
||||
title: t('screens.channel_donate_view.text_002'),
|
||||
back: {
|
||||
label: '←',
|
||||
onClick: () => {
|
||||
if (window.history.length > 1) {
|
||||
navigateBack();
|
||||
return;
|
||||
}
|
||||
navigate('channels-list');
|
||||
},
|
||||
ariaLabel: t('screens.channel_donate_view.text_003'),
|
||||
title: t('screens.channel_donate_view.text_004'),
|
||||
},
|
||||
});
|
||||
chrome?.setTopbar(topbar);
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack channel-donate-card';
|
||||
const content = document.createElement('div');
|
||||
content.className = 'stack channel-donate-content';
|
||||
content.innerHTML = t('screens.channel_donate_view.text_017');
|
||||
card.append(content);
|
||||
screen.append(card);
|
||||
|
||||
let disposed = false;
|
||||
let refreshSeq = 0;
|
||||
let busy = false;
|
||||
const walletCache = new Map();
|
||||
|
||||
const cleanupWallets = () => {
|
||||
for (const wallet of walletCache.values()) {
|
||||
try {
|
||||
wallet?.keypair?.secretKey?.fill?.(0);
|
||||
} catch {
|
||||
// Секретные ключи живут только в памяти этой страницы.
|
||||
}
|
||||
}
|
||||
walletCache.clear();
|
||||
};
|
||||
|
||||
const renderDonationForm = ({ channel, selector, ownerUser, recipientPda }) => {
|
||||
const ownerLogin = String(channel?.ownerLogin || extractLoginFromBlockchainName(selector?.ownerBlockchainName) || '').trim();
|
||||
const channelTitle = String(channel?.displayTitle || channel?.displayName || channel?.channelName || t('screens.channel_donate_view.text_018')).trim();
|
||||
const channelName = String(channel?.channelName || selector?.channelName || '').trim();
|
||||
const recipientChoices = [
|
||||
recipientPda?.forks?.length
|
||||
? { id: 'blockchain-key', label: 'Blockchain key', address: bytesToBase58(recipientPda.forks.at(-1).blockchainKey) }
|
||||
: publicKeyChoice(ownerUser, 'blockchainKey', 'blockchain-key', 'Blockchain key'),
|
||||
].filter(Boolean);
|
||||
|
||||
content.innerHTML = `
|
||||
<div class="channel-donate-hero">
|
||||
<h2>${th('screens.channel_donate_view.text_023')}</h2>
|
||||
<strong>${escapeHtml(channelTitle)}</strong>
|
||||
<span>${escapeHtml(formatChannelAddress({ ownerLogin, channelName }))}</span>
|
||||
</div>
|
||||
<div class="meta-muted" id="channel-donate-verified-total"></div>
|
||||
|
||||
<section class="channel-donate-section">
|
||||
<label class="field-label" for="channel-donate-blockchain">${th('screens.channel_donate_view.text_024')}</label>
|
||||
<select class="select" id="channel-donate-blockchain">
|
||||
<option value="solana">Solana</option>
|
||||
</select>
|
||||
</section>
|
||||
|
||||
<section class="channel-donate-section">
|
||||
<label class="field-label" for="channel-donate-recipient-key">${th('screens.channel_donate_view.text_025')}</label>
|
||||
<select class="select" id="channel-donate-recipient-key" ${recipientChoices.length ? '' : 'disabled'}>
|
||||
${recipientChoices.map((choice) => `<option value="${escapeHtml(choice.id)}">${escapeHtml(choice.label)}</option>`).join('')}
|
||||
</select>
|
||||
<div class="channel-donate-address" id="channel-donate-recipient-address">–</div>
|
||||
</section>
|
||||
|
||||
<section class="channel-donate-section">
|
||||
<label class="field-label" for="channel-donate-sender-key">${th('screens.channel_donate_view.text_026')}</label>
|
||||
<div class="channel-donate-address" id="channel-donate-sender-key">Blockchain key</div>
|
||||
<div class="channel-donate-address" id="channel-donate-sender-address">—</div>
|
||||
|
||||
<div class="channel-donate-balance-row">
|
||||
<span class="meta-muted">${th('screens.channel_donate_view.text_027')}</span>
|
||||
<strong id="channel-donate-balance">–</strong>
|
||||
<button class="secondary-btn channel-donate-refresh" id="channel-donate-refresh" type="button">${th('screens.channel_donate_view.text_028')}</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="channel-donate-section">
|
||||
<label class="field-label" for="channel-donate-amount">${th('screens.channel_donate_view.text_029')}</label>
|
||||
<div class="channel-donate-amount-row">
|
||||
<input class="input" id="channel-donate-amount" type="text" inputmode="decimal" placeholder="0.1" autocomplete="off" />
|
||||
<span>⭐</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<p class="meta-muted" id="channel-donate-split"></p>
|
||||
<p class="meta-muted" id="channel-donate-explanation"></p>
|
||||
<p class="meta-muted inline-error channel-donate-status" id="channel-donate-status"></p>
|
||||
<div class="channel-donate-result" id="channel-donate-result" hidden></div>
|
||||
<button class="primary-btn channel-donate-submit" id="channel-donate-submit" type="button" ${recipientChoices.length && recipientPda ? '' : 'disabled'}>${th('screens.support_flow.donate')}</button>
|
||||
|
||||
`;
|
||||
|
||||
const recipientSelect = content.querySelector('#channel-donate-recipient-key');
|
||||
const senderSelect = content.querySelector('#channel-donate-sender-key');
|
||||
const recipientAddressEl = content.querySelector('#channel-donate-recipient-address');
|
||||
const senderAddressEl = content.querySelector('#channel-donate-sender-address');
|
||||
const balanceEl = content.querySelector('#channel-donate-balance');
|
||||
const amountEl = content.querySelector('#channel-donate-amount');
|
||||
const statusEl = content.querySelector('#channel-donate-status');
|
||||
const resultEl = content.querySelector('#channel-donate-result');
|
||||
const submitEl = content.querySelector('#channel-donate-submit');
|
||||
const refreshEl = content.querySelector('#channel-donate-refresh');
|
||||
const directEl = content.querySelector('#channel-donate-direct');
|
||||
const splitEl = content.querySelector('#channel-donate-split');
|
||||
const explanationEl = content.querySelector('#channel-donate-explanation');
|
||||
|
||||
const setBusy = (nextBusy) => {
|
||||
busy = Boolean(nextBusy);
|
||||
if (submitEl) submitEl.disabled = busy || recipientChoices.length === 0 || !recipientPda;
|
||||
if (directEl) directEl.disabled = busy || recipientChoices.length === 0;
|
||||
if (refreshEl) refreshEl.disabled = busy;
|
||||
if (recipientSelect) recipientSelect.disabled = busy || recipientChoices.length === 0;
|
||||
if (senderSelect) senderSelect.disabled = busy;
|
||||
if (amountEl) amountEl.disabled = busy;
|
||||
};
|
||||
|
||||
const setStatus = (message, kind = '') => {
|
||||
if (!statusEl) return;
|
||||
statusEl.textContent = String(message || '');
|
||||
statusEl.classList.toggle('is-error', kind === 'error');
|
||||
};
|
||||
|
||||
const selectedRecipient = () => (
|
||||
recipientChoices.find((choice) => choice.id === String(recipientSelect?.value || ''))
|
||||
|| recipientChoices[0]
|
||||
|| null
|
||||
);
|
||||
|
||||
const updateRecipientAddress = () => {
|
||||
const choice = selectedRecipient();
|
||||
if (recipientAddressEl) recipientAddressEl.textContent = choice?.address || t('screens.channel_donate_view.text_019');
|
||||
};
|
||||
|
||||
const resolveSenderWallet = async () => {
|
||||
const keyId = 'blockchain-key';
|
||||
if (walletCache.has(keyId)) return walletCache.get(keyId);
|
||||
|
||||
const login = String(state.session.login || '').trim();
|
||||
const storagePwd = String(state.session.storagePwdInMemory || '').trim();
|
||||
if (!login || !storagePwd) throw new Error(t('screens.channel_donate_view.text_020'));
|
||||
const wallet = await getWalletFromStoredBlockchainKey({ login, storagePwd });
|
||||
|
||||
walletCache.set(keyId, wallet);
|
||||
return wallet;
|
||||
};
|
||||
|
||||
const refreshBalance = async () => {
|
||||
if (busy || disposed) return;
|
||||
setBusy(true);
|
||||
setStatus(t('screens.channel_donate_view.text_005'));
|
||||
if (balanceEl) balanceEl.textContent = '–';
|
||||
try {
|
||||
const wallet = await resolveSenderWallet();
|
||||
if (disposed) return;
|
||||
if (senderAddressEl) senderAddressEl.textContent = wallet.address;
|
||||
const balance = await getBalanceSol({
|
||||
endpoint: state.entrySettings.solanaServer,
|
||||
address: wallet.address,
|
||||
});
|
||||
if (disposed) return;
|
||||
if (balanceEl) balanceEl.textContent = `${formatSol(balance.sol)} SOL`;
|
||||
setStatus('');
|
||||
} catch (error) {
|
||||
if (disposed) return;
|
||||
if (senderAddressEl) senderAddressEl.textContent = '–';
|
||||
setStatus(toUserMessage(error, t('screens.channel_donate_view.text_006')), 'error');
|
||||
} finally {
|
||||
if (!disposed) setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
recipientSelect?.addEventListener('change', updateRecipientAddress);
|
||||
senderSelect?.addEventListener('change', () => {
|
||||
if (senderAddressEl) senderAddressEl.textContent = '–';
|
||||
if (balanceEl) balanceEl.textContent = '–';
|
||||
setStatus('');
|
||||
void refreshBalance();
|
||||
});
|
||||
refreshEl?.addEventListener('click', () => void refreshBalance());
|
||||
|
||||
let starsQuote = null;
|
||||
const renderSplit = () => {
|
||||
try {
|
||||
const cents = parseStarCents(amountEl?.value || '');
|
||||
const parts = splitStarCents(cents);
|
||||
const sol = starsQuote ? ` · ≈ ${formatLamportsSol(starCentsToLamports(cents, starsQuote.solUsdE8, starsQuote.usdtUsdE8))} SOL` : '';
|
||||
if (splitEl) splitEl.textContent = `${t('screens.support_flow.recipient')}: ${formatStars(parts.author)} · ${t('screens.support_flow.fund')}: ${formatStars(parts.dao)}${sol}`;
|
||||
} catch { if (splitEl) splitEl.textContent = 'Минимальная поддержка 0,10 ⭐'; }
|
||||
};
|
||||
void getStarsQuoteFromRpc({ solanaEndpoint: state.entrySettings.solanaServer }).then(v => { starsQuote = v; if (!disposed) renderSplit(); })
|
||||
.catch(() => { if (splitEl && !disposed) splitEl.textContent = 'Курс временно недоступен'; });
|
||||
if (explanationEl) explanationEl.textContent = recipientPda
|
||||
? t('screens.support_flow.explanation')
|
||||
: t('screens.support_flow.paid_required');
|
||||
amountEl?.addEventListener('input', renderSplit);
|
||||
|
||||
const submitTransfer = async (direct) => {
|
||||
if (busy || disposed) return;
|
||||
const recipient = selectedRecipient();
|
||||
if (!recipient?.address) { setStatus(t('screens.channel_donate_view.text_007'), 'error'); return; }
|
||||
let amount, cents;
|
||||
try {
|
||||
cents = parseStarCents(amountEl?.value || '');
|
||||
if (direct) throw new Error('Прямой перевод отключён в системе Stars');
|
||||
} catch (error) { setStatus(error.message || t('screens.channel_donate_view.text_008'), 'error'); return; }
|
||||
if (direct && !window.confirm(t('screens.support_flow.direct_warning'))) return;
|
||||
|
||||
setBusy(true);
|
||||
setStatus(t('screens.channel_donate_view.text_009'));
|
||||
if (resultEl) { resultEl.hidden = true; resultEl.innerHTML = ''; }
|
||||
try {
|
||||
starsQuote = await getStarsQuoteFromRpc({ solanaEndpoint: state.entrySettings.solanaServer });
|
||||
amount = starCentsToLamports(cents, starsQuote.solUsdE8, starsQuote.usdtUsdE8);
|
||||
const wallet = await resolveSenderWallet();
|
||||
let result;
|
||||
if (direct) {
|
||||
// Свежий ключ читается перед отправкой; если PDA есть, он приоритетнее серверного профиля.
|
||||
let address = recipient.address;
|
||||
if (recipientPda) {
|
||||
const fresh = await readShineUserPda({ login: ownerLogin, solanaEndpoint: state.entrySettings.solanaServer });
|
||||
const key = fresh.forks.at(-1).blockchainKey;
|
||||
address = bytesToBase58(key);
|
||||
} else {
|
||||
const latest = await authService.getUser(ownerLogin);
|
||||
address = publicKeyChoice(latest, 'blockchainKey', 'blockchain-key', 'Blockchain key')?.address || '';
|
||||
if (!address) throw new Error(t('screens.channel_donate_view.text_007'));
|
||||
}
|
||||
result = await transferSolLamports({ endpoint: state.entrySettings.solanaServer, fromKeypair: wallet.keypair, toAddress: address, amountLamports: amount });
|
||||
} else {
|
||||
if (!recipientPda) throw new Error(t('screens.support_flow.paid_required'));
|
||||
const { login, storagePwdInMemory: storagePwd } = state.session;
|
||||
const secrets = await loadEncryptedUserSecrets(login, storagePwd);
|
||||
if (!secrets?.blockchainKey || !secrets?.clientKey) throw new Error(t('screens.support_flow.keys_required'));
|
||||
result = await supportShineUserOnSolana({
|
||||
senderLogin: login, recipientLogin: ownerLogin, amountLamports: amount,
|
||||
starCents: cents, oracleAccounts: { solUsd: starsQuote.solOracleAccount, usdtUsd: starsQuote.usdtOracleAccount },
|
||||
target: { type: 1, channelBlockNumber: BigInt(selector.channelRootBlockNumber), channelBlockHash: hexHash32(selector.channelRootBlockHash) },
|
||||
solanaEndpoint: state.entrySettings.solanaServer,
|
||||
blockchainPrivatePkcs8B64: secrets.blockchainKey,
|
||||
clientPrivatePkcs8B64: secrets.clientKey,
|
||||
});
|
||||
}
|
||||
if (disposed) return;
|
||||
setStatus('');
|
||||
if (resultEl) {
|
||||
resultEl.hidden = false;
|
||||
resultEl.innerHTML = `<strong>${th('screens.channel_donate_view.text_031')}</strong><span>${escapeHtml(formatStars(cents))} → ${escapeHtml(recipient.label)}</span><code>${escapeHtml(String(result.signature || ''))}</code>`;
|
||||
}
|
||||
showToast(t('screens.channel_donate_view.text_010'));
|
||||
const balance = await getBalanceSol({ endpoint: state.entrySettings.solanaServer, address: wallet.address });
|
||||
if (!disposed && balanceEl) balanceEl.textContent = `${formatSol(balance.sol)} SOL`;
|
||||
} catch (error) {
|
||||
if (!disposed) setStatus(toUserMessage(error, t('screens.channel_donate_view.text_011')), 'error');
|
||||
} finally { if (!disposed) setBusy(false); }
|
||||
};
|
||||
submitEl?.addEventListener('click', () => void submitTransfer(false));
|
||||
directEl?.addEventListener('click', () => void submitTransfer(true));
|
||||
renderSplit();
|
||||
|
||||
void loadVerifiedSupportTotals(selector).then((totals) => {
|
||||
if (disposed) return;
|
||||
const label = content.querySelector('#channel-donate-verified-total');
|
||||
const total = totals && formatVerifiedSupportStars(totals.channelReceivedStarCents);
|
||||
if (label && total) label.textContent = `${t('screens.support_phase3.channel_total')}: ${total}`;
|
||||
});
|
||||
updateRecipientAddress();
|
||||
if (!recipientChoices.length) {
|
||||
setStatus(t('screens.channel_donate_view.text_012'), 'error');
|
||||
} else {
|
||||
void refreshBalance();
|
||||
}
|
||||
};
|
||||
|
||||
const refresh = async () => {
|
||||
const seq = ++refreshSeq;
|
||||
cleanupWallets();
|
||||
content.innerHTML = t('screens.channel_donate_view.text_021');
|
||||
try {
|
||||
const selector = await resolveChannelSelector(route);
|
||||
const payload = await authService.getChannelMessages(selector, 1, 'asc', String(state.session.login || '').trim());
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
|
||||
const channel = payload?.channel || {};
|
||||
const ownerLogin = String(channel?.ownerLogin || extractLoginFromBlockchainName(selector.ownerBlockchainName) || '').trim();
|
||||
const ownerUser = await authService.getUser(ownerLogin);
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
if (!ownerUser?.exists) throw new Error(t('screens.channel_donate_view.text_022'));
|
||||
|
||||
let recipientPda = null;
|
||||
try { recipientPda = await readShineUserPda({ login: ownerLogin, solanaEndpoint: state.entrySettings.solanaServer }); }
|
||||
catch { /* Free пользователь: доступен только прямой перевод. */ }
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
renderDonationForm({ channel, selector, ownerUser, recipientPda });
|
||||
} catch (error) {
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
content.innerHTML = `
|
||||
<div class="meta-muted">${th('screens.channel_donate_view.text_032')}</div>
|
||||
<div class="meta-muted">${escapeHtml(toUserMessage(error, t('screens.channel_donate_view.text_013')))}</div>
|
||||
<button class="secondary-btn" id="channel-donate-retry" type="button">${th('screens.channel_donate_view.text_033')}</button>
|
||||
`;
|
||||
content.querySelector('#channel-donate-retry')?.addEventListener('click', () => void refresh());
|
||||
}
|
||||
};
|
||||
|
||||
screen.refresh = refresh;
|
||||
screen.cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
refreshSeq += 1;
|
||||
cleanupWallets();
|
||||
};
|
||||
|
||||
void refresh();
|
||||
return screen;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,253 @@
|
||||
import { formatDate } from '../i18n/format.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
// «Медиа и файлы» личной переписки: сетка фото и видео и список документов по месяцам.
|
||||
// История догружается с сервера целиком; превью расшифровываются, только когда плитка видна.
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { openMediaViewer } from '../components/media-viewer.js';
|
||||
import { createDmFileAttachmentCard, isDmInlineMedia, resolveDmMediaUrl } from '../components/dm-attachments.js';
|
||||
import { getAttachmentKind } from '../services/attachment-format.js';
|
||||
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
||||
import { loadFullDmHistory, resolveMessageTimeMs } from '../services/dm-history.js';
|
||||
import { formatClockTime, formatDayLabel } from '../services/channels-ux.js';
|
||||
import { getChatMessages, getRememberedDmPeer, normalizeDmChatId, state } from '../state.js';
|
||||
import { navigateUp } from '../router.js';
|
||||
|
||||
export const pageMeta = { id: 'chat-media-view', get title() { return t('screens.chat_media_view.text_001'); } };
|
||||
|
||||
const monthTitle = (date) => formatDate(date, { month: 'long', year: 'numeric' });
|
||||
|
||||
// Все вложения переписки, от новых к старым.
|
||||
function collectAttachments(chatId, currentLogin) {
|
||||
const media = [];
|
||||
const files = [];
|
||||
for (const msg of getChatMessages(chatId)) {
|
||||
if (msg?.deleted) continue;
|
||||
const parsed = parseDmTechBlocks(String(msg?.text || ''));
|
||||
const list = Array.isArray(parsed.fileAttachments) ? parsed.fileAttachments : (parsed.fileAttachment ? [parsed.fileAttachment] : []);
|
||||
for (const item of list) {
|
||||
if (item?.kind === 'voice') continue;
|
||||
const timeMs = resolveMessageTimeMs(msg);
|
||||
const attachment = { ...item,
|
||||
senderLogin: msg?.from === 'out' ? currentLogin : chatId,
|
||||
messageTimestampMs: timeMs,
|
||||
};
|
||||
const entry = { attachment, timeMs, from: msg?.from };
|
||||
(isDmInlineMedia(attachment) ? media : files).push(entry);
|
||||
}
|
||||
}
|
||||
const newestFirst = (a, b) => b.timeMs - a.timeMs;
|
||||
return { media: media.sort(newestFirst), files: files.sort(newestFirst) };
|
||||
}
|
||||
|
||||
function groupByMonth(entries) {
|
||||
const groups = [];
|
||||
for (const entry of entries) {
|
||||
const date = entry.timeMs ? new Date(entry.timeMs) : null;
|
||||
const key = date ? `${date.getFullYear()}-${date.getMonth()}` : 'unknown';
|
||||
const raw = date ? monthTitle(date) : t('screens.chat_media_view.text_003');
|
||||
const label = raw.charAt(0).toUpperCase() + raw.slice(1);
|
||||
const last = groups[groups.length - 1];
|
||||
if (last?.key === key) last.items.push(entry);
|
||||
else groups.push({ key, label, items: [entry] });
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
export function render({ navigate, route, chrome }) {
|
||||
const chatId = normalizeDmChatId(route?.params?.chatId);
|
||||
const peer = getRememberedDmPeer(chatId);
|
||||
const peerName = [peer?.firstName, peer?.lastName].map((x) => String(x || '').trim()).filter(Boolean).join(' ') || chatId;
|
||||
const chatPath = `chat/${encodeURIComponent(chatId)}`;
|
||||
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack chat-media-screen';
|
||||
let disposed = false;
|
||||
let activeTab = 'media';
|
||||
let loading = true;
|
||||
let loadFailed = false;
|
||||
const objectUrls = new Set();
|
||||
const tileUrls = new Map(); // id файла → url для просмотрщика
|
||||
const fileKey = (attachment) => String(attachment?.id || attachment?.url || '');
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.chat_media_view.text_002'),
|
||||
back: {
|
||||
onClick: () => navigateUp((r) => r.pageId === 'chat-view' && normalizeDmChatId(r.params?.chatId) === chatId, chatPath),
|
||||
},
|
||||
}));
|
||||
|
||||
const subtitle = document.createElement('p');
|
||||
subtitle.className = 'meta-muted chat-media-peer';
|
||||
subtitle.textContent = t('screens.chat_media_view.text_013', { value1: peerName });
|
||||
|
||||
const tabs = document.createElement('div');
|
||||
tabs.className = 'tabs tabs--auto tabs--dense chat-media-tabs';
|
||||
tabs.setAttribute('role', 'radiogroup');
|
||||
tabs.setAttribute('aria-label', t('screens.chat_media_view.text_014'));
|
||||
const tabButtons = new Map();
|
||||
for (const [value, label] of [['media', t('screens.chat_media_view.text_004')], ['files', t('screens.chat_media_view.text_005')]]) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'tab-btn';
|
||||
button.dataset.tab = value;
|
||||
button.setAttribute('role', 'radio');
|
||||
button.addEventListener('click', () => {
|
||||
if (activeTab === value) return;
|
||||
activeTab = value;
|
||||
renderBody();
|
||||
});
|
||||
tabButtons.set(value, { button, label });
|
||||
tabs.append(button);
|
||||
}
|
||||
|
||||
const status = document.createElement('div');
|
||||
status.className = 'chat-media-status';
|
||||
const body = document.createElement('div');
|
||||
body.className = 'stack chat-media-body';
|
||||
screen.append(subtitle, tabs, status, body);
|
||||
|
||||
const thumbObserver = typeof IntersectionObserver === 'function'
|
||||
? new IntersectionObserver((entries) => {
|
||||
for (const entry of entries) {
|
||||
if (!entry.isIntersecting) continue;
|
||||
thumbObserver.unobserve(entry.target);
|
||||
entry.target.__loadThumb?.();
|
||||
}
|
||||
}, { rootMargin: '300px 0px' })
|
||||
: null;
|
||||
|
||||
const createTile = (entry, openAt) => {
|
||||
const { attachment } = entry;
|
||||
const kind = getAttachmentKind(attachment);
|
||||
const tile = document.createElement('button');
|
||||
tile.type = 'button';
|
||||
tile.className = `chat-media-tile is-loading${kind === 'video' ? ' chat-media-tile--video' : ''}`;
|
||||
tile.setAttribute('aria-label', `${kind === 'video' ? t('screens.chat_media_view.text_006') : t('screens.chat_media_view.text_007')} ${attachment.name || ''}, ${formatDayLabel(entry.timeMs)}`);
|
||||
tile.__loadThumb = () => {
|
||||
resolveDmMediaUrl(attachment).then(({ url }) => {
|
||||
objectUrls.add(url);
|
||||
if (disposed) return;
|
||||
tileUrls.set(fileKey(attachment), url);
|
||||
const media = document.createElement(kind === 'video' ? 'video' : 'img');
|
||||
media.className = 'chat-media-tile__media';
|
||||
if (kind === 'video') {
|
||||
media.muted = true;
|
||||
media.preload = 'metadata';
|
||||
media.playsInline = true;
|
||||
// Кадр чуть позже начала: первый часто чёрный.
|
||||
media.src = `${url}#t=0.1`;
|
||||
} else {
|
||||
media.alt = '';
|
||||
media.decoding = 'async';
|
||||
media.src = url;
|
||||
}
|
||||
tile.prepend(media);
|
||||
tile.classList.remove('is-loading');
|
||||
}).catch(() => {
|
||||
if (!disposed) tile.classList.replace('is-loading', 'is-failed');
|
||||
});
|
||||
};
|
||||
if (kind === 'video') {
|
||||
const badge = document.createElement('span');
|
||||
badge.className = 'chat-media-tile__badge';
|
||||
badge.innerHTML = iconHtml('video');
|
||||
tile.append(badge);
|
||||
}
|
||||
tile.addEventListener('click', () => openAt(attachment));
|
||||
if (thumbObserver) thumbObserver.observe(tile);
|
||||
else tile.__loadThumb();
|
||||
return tile;
|
||||
};
|
||||
|
||||
const openViewerAt = async (allMedia, attachment) => {
|
||||
if (!tileUrls.has(fileKey(attachment))) {
|
||||
try {
|
||||
const { url } = await resolveDmMediaUrl(attachment);
|
||||
objectUrls.add(url);
|
||||
tileUrls.set(fileKey(attachment), url);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (disposed) return;
|
||||
// В просмотрщик – уже расшифрованные: остальные догрузятся, когда до них долистают в сетке.
|
||||
const entries = allMedia
|
||||
.filter((entry) => tileUrls.has(fileKey(entry.attachment)))
|
||||
.map((entry) => ({ kind: getAttachmentKind(entry.attachment), url: tileUrls.get(fileKey(entry.attachment)), name: entry.attachment.name, attachment: entry.attachment }));
|
||||
openMediaViewer(entries, Math.max(0, entries.findIndex((entry) => fileKey(entry.attachment) === fileKey(attachment))));
|
||||
};
|
||||
|
||||
const renderEmpty = (text) => {
|
||||
const empty = document.createElement('p');
|
||||
empty.className = 'empty-note';
|
||||
empty.textContent = text;
|
||||
body.append(empty);
|
||||
};
|
||||
|
||||
function renderBody() {
|
||||
if (disposed) return;
|
||||
const { media, files } = collectAttachments(chatId, state.session?.login);
|
||||
for (const [value, { button, label }] of tabButtons) {
|
||||
const count = value === 'media' ? media.length : files.length;
|
||||
button.textContent = count ? `${label} · ${count}` : label;
|
||||
button.setAttribute('aria-checked', String(value === activeTab));
|
||||
}
|
||||
status.hidden = !loading && !loadFailed;
|
||||
status.classList.toggle('is-error', loadFailed);
|
||||
status.innerHTML = loadFailed
|
||||
? t('screens.chat_media_view.text_008')
|
||||
: t('screens.chat_media_view.text_009');
|
||||
thumbObserver?.disconnect();
|
||||
body.replaceChildren();
|
||||
|
||||
const entries = activeTab === 'media' ? media : files;
|
||||
if (!entries.length) {
|
||||
if (!loading) renderEmpty(activeTab === 'media' ? t('screens.chat_media_view.text_010') : t('screens.chat_media_view.text_011'));
|
||||
return;
|
||||
}
|
||||
for (const group of groupByMonth(entries)) {
|
||||
const heading = document.createElement('h2');
|
||||
heading.className = 'chat-media-month';
|
||||
heading.textContent = group.label;
|
||||
body.append(heading);
|
||||
if (activeTab === 'media') {
|
||||
const grid = document.createElement('div');
|
||||
grid.className = 'chat-media-grid';
|
||||
group.items.forEach((entry) => grid.append(createTile(entry, (attachment) => void openViewerAt(media, attachment))));
|
||||
body.append(grid);
|
||||
} else {
|
||||
const list = document.createElement('div');
|
||||
list.className = 'stack chat-media-files';
|
||||
for (const entry of group.items) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'chat-media-file';
|
||||
const meta = document.createElement('span');
|
||||
meta.className = 'meta-muted chat-media-file__meta';
|
||||
meta.textContent = `${entry.from === 'out' ? t('screens.chat_media_view.text_012') : peerName} · ${formatDayLabel(entry.timeMs)}, ${formatClockTime(entry.timeMs)}`;
|
||||
row.append(createDmFileAttachmentCard(entry.attachment), meta);
|
||||
list.append(row);
|
||||
}
|
||||
body.append(list);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
renderBody();
|
||||
loadFullDmHistory(chatId)
|
||||
.catch(() => { loadFailed = true; })
|
||||
.finally(() => {
|
||||
loading = false;
|
||||
renderBody();
|
||||
});
|
||||
|
||||
screen.cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
thumbObserver?.disconnect();
|
||||
// Просмотрщик мог остаться открытым поверх: его картинки живут, пока он не закрыт.
|
||||
window.setTimeout(() => objectUrls.forEach((url) => URL.revokeObjectURL(url)), 60000);
|
||||
};
|
||||
|
||||
return screen;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,108 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
// UNUSED FOR NOW: альтернативные способы подключения (QR/камера) скрыты из UI.
|
||||
// Файл сохранён как заготовка; активный путь идёт напрямую в device-pairing-view.
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { state } from '../state.js';
|
||||
import { loadEncryptedUserSecrets } from '../services/key-vault.js';
|
||||
|
||||
export const pageMeta = { id: 'connect-device-view', get title() { return t('screens.connect_device_view.text_001'); } };
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.connect_device_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigate('device-view') },
|
||||
}));
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack';
|
||||
card.innerHTML = `
|
||||
<div class="stack" style="gap:6px;">
|
||||
<p class="field-label">${th('screens.connect_device_view.text_007')}</p>
|
||||
<p class="meta-muted">${th('screens.connect_device_view.text_008')}</p>
|
||||
<p class="meta-muted">${th('screens.connect_device_view.text_009')}</p>
|
||||
</div>
|
||||
<p class="meta-muted" id="connect-keys-status">${th('screens.connect_device_view.text_010')}</p>
|
||||
<div class="row">
|
||||
<button class="icon-btn small-btn" type="button" id="tech-help">${th('screens.connect_device_view.text_011')}</button>
|
||||
</div>
|
||||
<div class="stack">
|
||||
<button class="primary-btn" type="button" id="open-qr">${th('screens.connect_device_view.text_012')}</button>
|
||||
<button class="ghost-btn" type="button" id="open-pairing">${th('screens.connect_device_view.text_013')}</button>
|
||||
<button class="text-btn" type="button" id="open-camera">${th('screens.connect_device_view.text_014')}</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const statusEl = card.querySelector('#connect-keys-status');
|
||||
const openQrBtn = card.querySelector('#open-qr');
|
||||
const openPairBtn = card.querySelector('#open-pairing');
|
||||
|
||||
const helpModal = document.createElement('div');
|
||||
helpModal.className = 'modal-shell';
|
||||
helpModal.hidden = true;
|
||||
helpModal.innerHTML = `
|
||||
<div class="modal-backdrop" data-close="true"></div>
|
||||
<div class="modal-dialog card" role="dialog" aria-modal="true" tabindex="-1">
|
||||
<div class="row" style="align-items:flex-start;">
|
||||
<h3 style="font-size:18px;">${th('screens.connect_device_view.text_015')}</h3>
|
||||
<button class="icon-btn" type="button" data-close="true" aria-label="${th('screens.connect_device_view.text_016')}">✕</button>
|
||||
</div>
|
||||
<div class="stack" style="gap:6px;">
|
||||
<p class="meta-muted">${th('screens.connect_device_view.text_017')}</p>
|
||||
<p class="meta-muted">${th('screens.connect_device_view.text_018')}</p>
|
||||
<p class="meta-muted">${th('screens.connect_device_view.text_019')}</p>
|
||||
<p class="meta-muted">${th('screens.connect_device_view.text_020')}</p>
|
||||
<p class="meta-muted">${th('screens.connect_device_view.text_021')}</p>
|
||||
</div>
|
||||
<button class="primary-btn" type="button" data-close="true">OK</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const openHelp = () => {
|
||||
helpModal.hidden = false;
|
||||
helpModal.querySelector('.modal-dialog')?.focus();
|
||||
};
|
||||
const closeHelp = () => { helpModal.hidden = true; };
|
||||
|
||||
card.querySelector('#tech-help').addEventListener('click', openHelp);
|
||||
card.querySelector('#open-qr').addEventListener('click', () => navigate('device-qr-view'));
|
||||
card.querySelector('#open-pairing').addEventListener('click', () => navigate('device-pairing-view'));
|
||||
card.querySelector('#open-camera').addEventListener('click', () => navigate('device-camera-view'));
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
if (!state.session.login || !state.session.storagePwdInMemory) {
|
||||
throw new Error(t('screens.connect_device_view.text_006'));
|
||||
}
|
||||
const savedKeys = await loadEncryptedUserSecrets(state.session.login, state.session.storagePwdInMemory);
|
||||
const hasBlockchain = Boolean(savedKeys.blockchainKey);
|
||||
const hasClient = Boolean(savedKeys.clientKey);
|
||||
const ready = hasBlockchain && hasClient;
|
||||
openQrBtn.disabled = !ready;
|
||||
openPairBtn.disabled = !ready;
|
||||
statusEl.textContent = ready
|
||||
? t('screens.connect_device_view.text_004')
|
||||
: t('screens.connect_device_view.text_005');
|
||||
} catch {
|
||||
openQrBtn.disabled = true;
|
||||
openPairBtn.disabled = true;
|
||||
statusEl.textContent = t('screens.connect_device_view.text_003');
|
||||
}
|
||||
})();
|
||||
|
||||
helpModal.addEventListener('click', (event) => {
|
||||
const target = event.target;
|
||||
if (target instanceof HTMLElement && target.dataset.close === 'true') closeHelp();
|
||||
});
|
||||
helpModal.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Escape') closeHelp();
|
||||
});
|
||||
|
||||
screen.append(card);
|
||||
const modalRoot = document.getElementById('modal-root');
|
||||
modalRoot?.append(helpModal);
|
||||
screen.cleanup = () => { helpModal.remove(); };
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
// «Новый чат»: выбрать, кому написать. Пока поле пустое – свои близкие и друзья; при вводе –
|
||||
// сначала свои (мгновенно, на устройстве), затем вся сеть (по имени и логину). Нажатие
|
||||
// открывает переписку, профиль – кнопкой справа.
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createListSection, createPersonRow } from '../components/person-row.js';
|
||||
import { createLoadingState, createStateMessage } from '../components/feedback.js';
|
||||
import { authService, normalizeDmChatId } from '../state.js';
|
||||
import { makeProfileRoute } from '../services/shine-routes.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { matchesPeopleQuery } from '../services/people-search.js';
|
||||
|
||||
export const pageMeta = { id: 'contact-search-view', get title() { return t('screens.contact_search_view.text_001'); } };
|
||||
|
||||
const RELATION_TEXT = { get close_friend() { return t('screens.contact_search_view.text_016'); }, get friend() { return t('screens.contact_search_view.text_017'); }, get contact() { return t('screens.contact_search_view.text_018'); } };
|
||||
const RELATION_ORDER = { close_friend: 0, friend: 1, contact: 2 };
|
||||
|
||||
function searchText(value) {
|
||||
return String(value || '').toLowerCase().replaceAll('ё', 'е').trim();
|
||||
}
|
||||
|
||||
function displayName(person) {
|
||||
const full = [person.firstName, person.lastName].map((part) => String(part || '').trim()).filter(Boolean).join(' ');
|
||||
return full || String(person.displayName || '').trim() || person.login;
|
||||
}
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack dm-screen dm-search-screen';
|
||||
let disposed = false;
|
||||
let searchTimer = 0;
|
||||
let searchSeq = 0;
|
||||
let mine = []; // свои связи из списка чатов
|
||||
let remote = { query: '', items: [], loading: false, error: null };
|
||||
|
||||
const field = document.createElement('label');
|
||||
field.className = 'search-field contact-search-field';
|
||||
field.innerHTML = `<span class="search-field__icon" aria-hidden="true">${iconHtml('search')}</span>`;
|
||||
const input = document.createElement('input');
|
||||
input.className = 'search-field__input contact-search-input';
|
||||
input.type = 'search';
|
||||
input.placeholder = t('screens.contact_search_view.text_002');
|
||||
input.setAttribute('aria-label', t('screens.contact_search_view.text_019'));
|
||||
input.enterKeyHint = 'search';
|
||||
input.autocomplete = 'off';
|
||||
input.maxLength = 80;
|
||||
field.append(input);
|
||||
|
||||
const results = document.createElement('div');
|
||||
results.className = 'contact-search-results';
|
||||
|
||||
const openChat = (login) => navigate(`chat/${encodeURIComponent(normalizeDmChatId(login))}`);
|
||||
|
||||
function personRow(person, sub) {
|
||||
return createPersonRow({
|
||||
login: person.login,
|
||||
name: displayName(person),
|
||||
firstName: person.firstName,
|
||||
lastName: person.lastName,
|
||||
avatar: person.avatar || ((person.avatarAr || person.avatarPr) ? { ar: person.avatarAr, pr: person.avatarPr } : null),
|
||||
ring: person.relationFlag === 'close_friend' ? 'close' : '',
|
||||
sub,
|
||||
onClick: () => openChat(person.login),
|
||||
actions: [{ icon: 'profile', label: t('screens.contact_search_view.text_003'), onClick: () => navigate(makeProfileRoute(person.login)) }],
|
||||
});
|
||||
}
|
||||
|
||||
function renderResults() {
|
||||
if (disposed) return;
|
||||
const query = searchText(input.value).replace(/^@/, '');
|
||||
results.replaceChildren();
|
||||
const frag = document.createDocumentFragment();
|
||||
const ownMatches = mine.filter((person) => !query
|
||||
|| matchesPeopleQuery(`${displayName(person)} ${person.login} ${person.firstName} ${person.lastName}`, query));
|
||||
const ownShown = query ? ownMatches : ownMatches.filter((person) => person.relationFlag !== 'contact');
|
||||
if (ownShown.length) {
|
||||
frag.append(createListSection(query ? t('screens.contact_search_view.text_015', { value1: ownShown.length }) : t('screens.contact_search_view.text_010')));
|
||||
ownShown.slice(0, query ? 50 : 40).forEach((person) => {
|
||||
const sub = [displayName(person) !== person.login ? `${person.login}` : '', RELATION_TEXT[person.relationFlag] || ''].filter(Boolean).join(' · ');
|
||||
frag.append(personRow(person, sub));
|
||||
});
|
||||
}
|
||||
if (query.length >= 2) {
|
||||
const own = new Set(ownMatches.map((person) => person.login.toLowerCase()));
|
||||
const others = remote.items.filter((user) => !own.has(String(user.login || '').toLowerCase()));
|
||||
if (remote.loading || remote.error || others.length) frag.append(createListSection(t('screens.contact_search_view.text_008')));
|
||||
if (remote.loading) frag.append(createLoadingState({ label: t('screens.contact_search_view.text_004'), delayMs: 150 }));
|
||||
else if (remote.error) {
|
||||
const note = document.createElement('p');
|
||||
note.className = 'empty-note';
|
||||
note.textContent = toUserMessage(remote.error, t('screens.contact_search_view.text_009'));
|
||||
frag.append(note);
|
||||
} else {
|
||||
others.forEach((user) => {
|
||||
const person = { login: String(user.login || ''), displayName: user.displayName, avatarAr: user.avatarAr, avatarPr: user.avatarPr };
|
||||
frag.append(personRow(person, displayName(person) !== person.login ? `${person.login}` : ''));
|
||||
});
|
||||
}
|
||||
if (!ownShown.length && !remote.loading && !remote.error && !others.length) {
|
||||
frag.append(createStateMessage({ icon: 'search', title: t('screens.contact_search_view.text_005'), text: t('screens.contact_search_view.text_011') }));
|
||||
}
|
||||
} else if (!ownShown.length) {
|
||||
frag.append(createStateMessage({
|
||||
icon: 'message',
|
||||
title: query ? t('screens.contact_search_view.text_012') : t('screens.contact_search_view.text_013'),
|
||||
text: t('screens.contact_search_view.text_014'),
|
||||
}));
|
||||
}
|
||||
results.append(frag);
|
||||
}
|
||||
|
||||
async function runRemote() {
|
||||
const query = searchText(input.value).replace(/^@/, '');
|
||||
const seq = ++searchSeq;
|
||||
if (query.length < 2) {
|
||||
remote = { query: '', items: [], loading: false, error: null };
|
||||
renderResults();
|
||||
return;
|
||||
}
|
||||
remote = { query, items: [], loading: true, error: null };
|
||||
renderResults();
|
||||
try {
|
||||
const users = await authService.searchPeople(query, { limit: 20 });
|
||||
if (disposed || seq !== searchSeq) return;
|
||||
remote = { query, items: Array.isArray(users) ? users : [], loading: false, error: null };
|
||||
} catch (error) {
|
||||
if (disposed || seq !== searchSeq) return;
|
||||
remote = { query, items: [], loading: false, error };
|
||||
}
|
||||
renderResults();
|
||||
}
|
||||
|
||||
input.addEventListener('input', () => {
|
||||
renderResults();
|
||||
if (searchTimer) window.clearTimeout(searchTimer);
|
||||
searchTimer = window.setTimeout(() => { searchTimer = 0; void runRemote(); }, 300);
|
||||
});
|
||||
input.addEventListener('keydown', (event) => {
|
||||
if (event.key !== 'Enter') return;
|
||||
event.preventDefault();
|
||||
results.querySelector('.person-row__main')?.click();
|
||||
});
|
||||
|
||||
// Свои связи – из того же ответа, что и список чатов.
|
||||
async function loadMine() {
|
||||
try {
|
||||
const payload = await authService.listContacts();
|
||||
if (disposed) return;
|
||||
const byLogin = new Map();
|
||||
for (const dialog of Array.isArray(payload?.dialogs) ? payload.dialogs : []) {
|
||||
const login = String(dialog?.peerLogin || '').trim();
|
||||
const relationFlag = String(dialog?.relationFlag || '').trim().toLowerCase();
|
||||
if (!login || !RELATION_TEXT[relationFlag] || byLogin.has(login.toLowerCase())) continue;
|
||||
byLogin.set(login.toLowerCase(), {
|
||||
login,
|
||||
relationFlag,
|
||||
firstName: String(dialog?.firstName || '').trim(),
|
||||
lastName: String(dialog?.lastName || '').trim(),
|
||||
avatar: dialog?.avatar && typeof dialog.avatar === 'object' ? dialog.avatar : null,
|
||||
});
|
||||
}
|
||||
mine = [...byLogin.values()].sort((a, b) => (RELATION_ORDER[a.relationFlag] - RELATION_ORDER[b.relationFlag])
|
||||
|| displayName(a).localeCompare(displayName(b), 'ru'));
|
||||
} catch {
|
||||
mine = [];
|
||||
}
|
||||
renderResults();
|
||||
}
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.contact_search_view.text_006'),
|
||||
back: { onClick: () => navigate('messages-list') },
|
||||
}));
|
||||
screen.append(field, results);
|
||||
results.append(createLoadingState({ label: t('screens.contact_search_view.text_007') }));
|
||||
void loadMine();
|
||||
window.requestAnimationFrame(() => { if (!disposed) input.focus(); });
|
||||
|
||||
screen.cleanup = () => {
|
||||
disposed = true;
|
||||
searchSeq += 1;
|
||||
if (searchTimer) window.clearTimeout(searchTimer);
|
||||
};
|
||||
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { openPaletteEditor } from '../components/palette-editor.js';
|
||||
import { resolveThemeMode } from '../services/theme-service.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { addAppLogEntry, authService, state } from '../state.js';
|
||||
import {
|
||||
canInstallPwa,
|
||||
isStandalonePwaMode,
|
||||
onPwaInstallAvailabilityChange,
|
||||
promptPwaInstall,
|
||||
} from '../services/pwa-install-service.js';
|
||||
import { initPwaPush } from '../services/pwa-push-service.js';
|
||||
import { getArweaveWalletFromStoredBlockchainKey } from '../services/arweave-wallet-service.js';
|
||||
import {
|
||||
prepareAvatarImageFile,
|
||||
uploadArweaveFile,
|
||||
validateAvatarSourceFile,
|
||||
} from '../services/arweave-file-service.js';
|
||||
import { defaultServerAddress, defaultServerHttp } from '../deploy-config.js';
|
||||
|
||||
export const pageMeta = { id: 'developer-settings-view', get title() { return t('screens.developer_settings_view.text_001'); } };
|
||||
|
||||
function clearArweaveJwk(walletCtx) {
|
||||
if (!walletCtx?.jwk || typeof walletCtx.jwk !== 'object') return;
|
||||
Object.keys(walletCtx.jwk).forEach((key) => {
|
||||
walletCtx.jwk[key] = '';
|
||||
});
|
||||
walletCtx.jwk = null;
|
||||
}
|
||||
|
||||
function formatBytes(bytes) {
|
||||
const value = Number(bytes || 0);
|
||||
if (!Number.isFinite(value) || value <= 0) return '0 B';
|
||||
if (value < 1024) return `${value} B`;
|
||||
if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`;
|
||||
return `${(value / (1024 * 1024)).toFixed(2)} MB`;
|
||||
}
|
||||
|
||||
function openDeveloperAvatarUploadModal({ walletLogin, storagePwd, gateway } = {}) {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!root) return;
|
||||
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="settings-dev-avatar-modal">
|
||||
<div class="modal-card stack settings-dev-avatar-modal-card">
|
||||
<h3 class="modal-title">${t('dialogs.modals.developer_settings_view.label_002')}</h3>
|
||||
<label class="field-label" for="settings-dev-avatar-login">${t('dialogs.modals.developer_settings_view.label_003')}</label>
|
||||
<input class="input" id="settings-dev-avatar-login" type="text" maxlength="60" placeholder="${t('dialogs.modals.developer_settings_view.label_001')}" value="" />
|
||||
<label class="field-label" for="settings-dev-avatar-file">${t('dialogs.modals.developer_settings_view.label_004')}</label>
|
||||
<input class="input" id="settings-dev-avatar-file" type="file" accept="image/jpeg,image/png,image/webp" />
|
||||
<p class="meta-muted">${t('dialogs.modals.developer_settings_view.label_005')}</p>
|
||||
<div class="settings-dev-avatar-meta" id="settings-dev-avatar-meta"></div>
|
||||
<p class="inline-error settings-dev-avatar-error" id="settings-dev-avatar-error"></p>
|
||||
<div class="form-actions-grid">
|
||||
<button class="secondary-btn" id="settings-dev-avatar-cancel" type="button">${t('dialogs.modals.developer_settings_view.label_006')}</button>
|
||||
<button class="primary-btn" id="settings-dev-avatar-upload" type="button">${t('dialogs.modals.developer_settings_view.label_007')}</button>
|
||||
</div>
|
||||
<div class="card stack settings-dev-avatar-result" id="settings-dev-avatar-result" hidden>
|
||||
<p class="meta-muted">Transaction ID:</p>
|
||||
<p class="key-value" id="settings-dev-avatar-txid"></p>
|
||||
<button class="ghost-btn" id="settings-dev-avatar-copy" type="button">${t('dialogs.modals.developer_settings_view.label_008')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const modal = root.querySelector('#settings-dev-avatar-modal');
|
||||
const loginInput = root.querySelector('#settings-dev-avatar-login');
|
||||
const fileInput = root.querySelector('#settings-dev-avatar-file');
|
||||
const metaEl = root.querySelector('#settings-dev-avatar-meta');
|
||||
const errorEl = root.querySelector('#settings-dev-avatar-error');
|
||||
const cancelBtn = root.querySelector('#settings-dev-avatar-cancel');
|
||||
const uploadBtn = root.querySelector('#settings-dev-avatar-upload');
|
||||
const resultCard = root.querySelector('#settings-dev-avatar-result');
|
||||
const txidEl = root.querySelector('#settings-dev-avatar-txid');
|
||||
const copyBtn = root.querySelector('#settings-dev-avatar-copy');
|
||||
|
||||
if (loginInput instanceof HTMLInputElement) {
|
||||
loginInput.value = String(walletLogin || '').trim();
|
||||
}
|
||||
|
||||
let isClosed = false;
|
||||
const closeModal = () => {
|
||||
if (isClosed) return;
|
||||
isClosed = true;
|
||||
root.innerHTML = '';
|
||||
};
|
||||
|
||||
const setError = (text) => {
|
||||
if (errorEl) errorEl.textContent = String(text || '');
|
||||
};
|
||||
const setMeta = (text) => {
|
||||
if (metaEl) metaEl.textContent = String(text || '');
|
||||
};
|
||||
const setTxId = (txId) => {
|
||||
if (!(resultCard instanceof HTMLElement) || !(txidEl instanceof HTMLElement)) return;
|
||||
const value = String(txId || '').trim();
|
||||
txidEl.textContent = value;
|
||||
resultCard.hidden = !value;
|
||||
};
|
||||
|
||||
modal?.addEventListener('click', (event) => {
|
||||
if (event.target === modal) closeModal();
|
||||
});
|
||||
cancelBtn?.addEventListener('click', closeModal);
|
||||
copyBtn?.addEventListener('click', async () => {
|
||||
const txId = String(txidEl?.textContent || '').trim();
|
||||
if (!txId) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(txId);
|
||||
setError('');
|
||||
} catch {
|
||||
setError(t('dialogs.remaining.pages.developer_settings_view.opendeveloperavataruploadmodal.ne_udalos_skopirovat_tx_id'));
|
||||
}
|
||||
});
|
||||
|
||||
uploadBtn?.addEventListener('click', async () => {
|
||||
setError('');
|
||||
setTxId('');
|
||||
const targetLogin = String(loginInput?.value || '').trim();
|
||||
const file = fileInput?.files?.[0] || null;
|
||||
if (!targetLogin) {
|
||||
setError(t('dialogs.remaining.pages.developer_settings_view.opendeveloperavataruploadmodal.vvedite_login_polzovatelya'));
|
||||
return;
|
||||
}
|
||||
if (!file) {
|
||||
setError(t('dialogs.remaining.pages.developer_settings_view.opendeveloperavataruploadmodal.vyberite_fayl_izobrazheniya'));
|
||||
return;
|
||||
}
|
||||
if (!String(walletLogin || '').trim() || !String(storagePwd || '').trim()) {
|
||||
setError(t('dialogs.remaining.pages.developer_settings_view.opendeveloperavataruploadmodal.net_aktivnoy_sessii_voydite_zanovo_i_povtorite'));
|
||||
return;
|
||||
}
|
||||
|
||||
uploadBtn.disabled = true;
|
||||
let walletCtx = null;
|
||||
try {
|
||||
validateAvatarSourceFile(file);
|
||||
setMeta(t('dialogs.remaining.pages.developer_settings_view.opendeveloperavataruploadmodal.podgotovka_izobrazheniya'));
|
||||
const optimized = await prepareAvatarImageFile(file);
|
||||
setMeta(
|
||||
t('dialogs.remaining.pages.developer_settings_view.opendeveloperavataruploadmodal.fayl_podgotovlen_value1_value2', { value1: formatBytes(optimized.originalSizeBytes), value2: formatBytes(optimized.optimizedSizeBytes) })
|
||||
+ `(${optimized.width}x${optimized.height}, ${optimized.contentType})`,
|
||||
);
|
||||
|
||||
walletCtx = await getArweaveWalletFromStoredBlockchainKey({
|
||||
login: walletLogin,
|
||||
storagePwd,
|
||||
onStatus: (message) => setMeta(message),
|
||||
});
|
||||
setMeta(t('dialogs.remaining.pages.developer_settings_view.opendeveloperavataruploadmodal.zagruzka_v_arweave'));
|
||||
|
||||
const uploaded = await uploadArweaveFile({
|
||||
gateway,
|
||||
jwk: walletCtx?.jwk,
|
||||
file: optimized.file,
|
||||
tags: [
|
||||
{ name: 'SHiNE-Profile-Login', value: targetLogin },
|
||||
],
|
||||
});
|
||||
const txId = String(uploaded?.id || '').trim();
|
||||
if (!txId) throw new Error(t('dialogs.remaining.pages.developer_settings_view.opendeveloperavataruploadmodal.pustoy_transaction_id'));
|
||||
|
||||
setMeta(t('dialogs.remaining.pages.developer_settings_view.opendeveloperavataruploadmodal.zagruzka_zavershena'));
|
||||
setTxId(txId);
|
||||
} catch (error) {
|
||||
const message = String(error?.message || '');
|
||||
// Сообщения валидатора — идентификаторы для сопоставления; отображаемый
|
||||
// пользователю текст всегда берём из словаря текущего языка.
|
||||
const fileErrors = new Map([
|
||||
[t('screens.developer_settings_view.text_008'), t('dialogs.final.developer.avatar_choose_file')],
|
||||
[t('screens.developer_settings_view.text_009'), t('dialogs.final.developer.avatar_supported_formats')],
|
||||
[t('screens.developer_settings_view.text_010'), t('dialogs.final.developer.avatar_file_too_large')],
|
||||
[t('screens.developer_settings_view.text_011'), t('dialogs.final.developer.avatar_prepare_failed')],
|
||||
]);
|
||||
setError(fileErrors.get(message)
|
||||
|| t('dialogs.remaining.pages.developer_settings_view.opendeveloperavataruploadmodal.ne_udalos_zagruzit_avatar_v_arweave'));
|
||||
} finally {
|
||||
clearArweaveJwk(walletCtx);
|
||||
uploadBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function forceUiUpdateNow() {
|
||||
try {
|
||||
window.history.replaceState({}, '', '/settings');
|
||||
window.dispatchEvent(new PopStateEvent('popstate'));
|
||||
} catch {}
|
||||
if (!('serviceWorker' in navigator)) {
|
||||
window.location.reload();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const registrations = await navigator.serviceWorker.getRegistrations();
|
||||
await Promise.all(registrations.map(async (registration) => {
|
||||
try { await registration.update(); } catch {}
|
||||
if (registration.waiting) {
|
||||
try { registration.waiting.postMessage({ type: 'SKIP_WAITING' }); } catch {}
|
||||
}
|
||||
}));
|
||||
} catch {}
|
||||
window.setTimeout(() => window.location.reload(), 450);
|
||||
}
|
||||
|
||||
function showClientUpdateHelp() {
|
||||
window.alert(
|
||||
t('dialogs.final.developer.pwa_refresh_help', { serverAddress: defaultServerAddress, serverUrl: defaultServerHttp })
|
||||
);
|
||||
}
|
||||
|
||||
function openUiErrorReportingModal() {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!root) return;
|
||||
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="settings-ui-error-reporting-modal">
|
||||
<div class="modal-card stack">
|
||||
<h3 class="modal-title">${t('dialogs.modals.developer_settings_view.label_009')}</h3>
|
||||
<p class="meta-muted">${t('dialogs.modals.developer_settings_view.label_010')}</p>
|
||||
<div class="form-actions-grid">
|
||||
<button class="primary-btn" id="ui-error-reporting-cancel" type="button">${t('dialogs.modals.developer_settings_view.label_006')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const close = () => { root.innerHTML = ''; };
|
||||
root.querySelector('#ui-error-reporting-cancel')?.addEventListener('click', close);
|
||||
}
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.developer_settings_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigate('settings-view') },
|
||||
}));
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'nav-list settings-developer-card';
|
||||
card.innerHTML = `
|
||||
<button class="nav-row" type="button" id="settings-theme-editor"><span class="nav-row__label">${th('screens.developer_settings_view.text_014')}</span></button>
|
||||
<button class="nav-row" type="button" id="settings-force-ui-update"><span class="nav-row__label">${th('screens.developer_settings_view.text_015')}</span></button>
|
||||
<button class="nav-row" type="button" id="settings-force-update-help"><span class="nav-row__label">${th('screens.developer_settings_view.text_016')}</span></button>
|
||||
<button class="nav-row" type="button" id="settings-ui-error-reporting"><span class="nav-row__label">${th('screens.developer_settings_view.text_017')}</span></button>
|
||||
<button class="nav-row" type="button" id="settings-solana-users-init"><span class="nav-row__label">${th('screens.developer_settings_view.text_018')}</span></button>
|
||||
<button class="nav-row" type="button" id="settings-solana-rpc-check"><span class="nav-row__label">${th('screens.developer_settings_view.text_019')}</span></button>
|
||||
<button class="nav-row" type="button" id="settings-app-log"><span class="nav-row__label">${th('screens.developer_settings_view.text_020')}</span></button>
|
||||
<button class="nav-row" type="button" id="settings-pwa-diagnostics"><span class="nav-row__label">${th('screens.developer_settings_view.text_021')}</span></button>
|
||||
<button class="nav-row" type="button" id="settings-pwa-install"><span class="nav-row__label">${th('screens.developer_settings_view.text_022')}</span></button>
|
||||
<button class="nav-row" type="button" id="settings-upload-avatar"><span class="nav-row__label">${th('screens.developer_settings_view.text_023')}</span></button>
|
||||
`;
|
||||
|
||||
card.querySelector('#settings-theme-editor').addEventListener('click', () => openPaletteEditor({ theme: resolveThemeMode() }));
|
||||
const appLogBtn = card.querySelector('#settings-app-log');
|
||||
const diagnosticsBtn = card.querySelector('#settings-pwa-diagnostics');
|
||||
const pwaInstallBtn = card.querySelector('#settings-pwa-install');
|
||||
const uploadAvatarBtn = card.querySelector('#settings-upload-avatar');
|
||||
const forceUpdateBtn = card.querySelector('#settings-force-ui-update');
|
||||
const forceUpdateHelpBtn = card.querySelector('#settings-force-update-help');
|
||||
const uiErrorReportingBtn = card.querySelector('#settings-ui-error-reporting');
|
||||
const solanaUsersInitBtn = card.querySelector('#settings-solana-users-init');
|
||||
const solanaRpcCheckBtn = card.querySelector('#settings-solana-rpc-check');
|
||||
|
||||
appLogBtn?.addEventListener('click', () => navigate('app-log-view'));
|
||||
solanaUsersInitBtn?.addEventListener('click', () => navigate('solana-users-init-view'));
|
||||
solanaRpcCheckBtn?.addEventListener('click', () => navigate('solana-rpc-check-view'));
|
||||
diagnosticsBtn?.addEventListener('click', () => navigate('pwa-diagnostics-view'));
|
||||
uploadAvatarBtn?.addEventListener('click', () => {
|
||||
openDeveloperAvatarUploadModal({
|
||||
walletLogin: state.session.login,
|
||||
storagePwd: state.session.storagePwdInMemory,
|
||||
gateway: state.entrySettings.arweaveServer,
|
||||
});
|
||||
});
|
||||
forceUpdateHelpBtn?.addEventListener('click', showClientUpdateHelp);
|
||||
uiErrorReportingBtn?.addEventListener('click', openUiErrorReportingModal);
|
||||
|
||||
forceUpdateBtn?.addEventListener('click', async () => {
|
||||
forceUpdateBtn.disabled = true;
|
||||
try {
|
||||
addAppLogEntry({
|
||||
level: 'info',
|
||||
source: 'ui-update',
|
||||
message: t('screens.developer_settings_view.text_003'),
|
||||
});
|
||||
await forceUiUpdateNow();
|
||||
} finally {
|
||||
forceUpdateBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
// Меняем только подпись строки: textContent на самой кнопке стирал .nav-row__label, и строка выбивалась по кеглю.
|
||||
const setPwaLabel = (text) => {
|
||||
const labelEl = pwaInstallBtn.querySelector('.nav-row__label');
|
||||
if (labelEl) labelEl.textContent = text;
|
||||
else pwaInstallBtn.textContent = text;
|
||||
};
|
||||
const syncPwaButtonLabel = () => {
|
||||
if (isStandalonePwaMode()) {
|
||||
setPwaLabel(t('screens.developer_settings_view.text_005'));
|
||||
return;
|
||||
}
|
||||
if (canInstallPwa()) {
|
||||
setPwaLabel(t('screens.developer_settings_view.text_006'));
|
||||
return;
|
||||
}
|
||||
setPwaLabel(t('screens.developer_settings_view.text_007'));
|
||||
};
|
||||
|
||||
const unsubscribeInstallAvailability = onPwaInstallAvailabilityChange(() => {
|
||||
syncPwaButtonLabel();
|
||||
});
|
||||
syncPwaButtonLabel();
|
||||
|
||||
pwaInstallBtn.addEventListener('click', async () => {
|
||||
pwaInstallBtn.disabled = true;
|
||||
try {
|
||||
await initPwaPush({
|
||||
authService,
|
||||
onLog: (entry) => addAppLogEntry(entry),
|
||||
});
|
||||
|
||||
if (canInstallPwa()) {
|
||||
const result = await promptPwaInstall();
|
||||
const accepted = result.outcome === 'accepted';
|
||||
addAppLogEntry({
|
||||
level: 'info',
|
||||
source: 'pwa-install',
|
||||
message: accepted ? t('screens.developer_settings_view.text_012') : t('screens.developer_settings_view.text_013'),
|
||||
details: { outcome: result.outcome || 'unknown' },
|
||||
});
|
||||
if (accepted) {
|
||||
window.alert(t('dialogs.pages.developer_settings_view.alert_001'));
|
||||
}
|
||||
} else if (!isStandalonePwaMode()) {
|
||||
window.alert(t('dialogs.pages.developer_settings_view.alert_002'));
|
||||
} else {
|
||||
window.alert(t('dialogs.pages.developer_settings_view.alert_003'));
|
||||
}
|
||||
} catch (error) {
|
||||
addAppLogEntry({
|
||||
level: 'warn',
|
||||
source: 'pwa-install',
|
||||
message: t('screens.developer_settings_view.text_004'),
|
||||
details: { error: error?.message || 'unknown' },
|
||||
});
|
||||
window.alert(t('dialogs.pages.developer_settings_view.alert_004', { value1: error?.message || 'unknown' }));
|
||||
} finally {
|
||||
pwaInstallBtn.disabled = false;
|
||||
syncPwaButtonLabel();
|
||||
}
|
||||
});
|
||||
|
||||
screen.cleanup = () => {
|
||||
unsubscribeInstallAvailability();
|
||||
};
|
||||
screen.append(card);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
|
||||
export const pageMeta = { id: 'device-camera-view', get title() { return t('screens.device_camera_view.text_001'); } };
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.device_camera_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigate('connect-device-view') },
|
||||
}));
|
||||
|
||||
const frame = document.createElement('div');
|
||||
frame.className = 'camera-shell';
|
||||
frame.innerHTML = `
|
||||
<div class="camera-placeholder">${th('screens.device_camera_view.text_003')}</div>
|
||||
<div class="camera-frame"></div>
|
||||
<div class="camera-hint">${th('screens.device_camera_view.text_004')}</div>
|
||||
`;
|
||||
|
||||
screen.append(frame);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,639 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import {
|
||||
authService,
|
||||
authorizeSession,
|
||||
refreshSessions,
|
||||
setAuthError,
|
||||
setAuthInfo,
|
||||
state,
|
||||
terminateCurrentSession,
|
||||
} from '../state.js';
|
||||
import { formatRelativeTime, showToast } from '../services/channels-ux.js';
|
||||
import {
|
||||
buildSecretsPayload,
|
||||
buildSessionAttachPayload,
|
||||
deriveEspPairingPasswordHash,
|
||||
encryptPairingPayloadForRequester,
|
||||
formatPairingShortCode,
|
||||
} from '../services/device-pairing-service.js';
|
||||
import { loadEncryptedUserSecrets } from '../services/key-vault.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'device-pairing-view', get title() { return t('screens.device_pairing_view.text_001'); } };
|
||||
|
||||
// UNUSED FOR NOW: дополнительный пароль pairing сохранён в коде для возможного возврата,
|
||||
// но активный UI работает только в режиме без дополнительного пароля.
|
||||
const PAIRING_PASSWORD_STATE_PREFIX = 'shine_pairing_password_state_v1';
|
||||
|
||||
function setStatus(statusEl, message, kind = 'info') {
|
||||
statusEl.classList.toggle('is-unavailable', kind === 'error');
|
||||
statusEl.classList.toggle('is-available', kind !== 'error');
|
||||
statusEl.textContent = message;
|
||||
statusEl.style.display = message ? '' : 'none';
|
||||
}
|
||||
|
||||
const SESSION_TYPE_WALLET = 50;
|
||||
|
||||
function pairingSessionKindLabel(sessionType) {
|
||||
return Number(sessionType || 0) === SESSION_TYPE_WALLET ? 'Wallet session' : 'Client session';
|
||||
}
|
||||
|
||||
function buildTransferKeys(savedKeys) {
|
||||
const keys = {
|
||||
clientKey: String(savedKeys?.clientKey || '').trim(),
|
||||
blockchainKey: String(savedKeys?.blockchainKey || '').trim(),
|
||||
};
|
||||
if (!keys.clientKey || !keys.blockchainKey) {
|
||||
throw new Error(t('screens.device_pairing_view.text_031'));
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
|
||||
function requestCardHtml(request) {
|
||||
const shortCode = formatPairingShortCode(request?.shortCode || '');
|
||||
const client = String(request?.requesterClientPlatform || 'unknown');
|
||||
const requesterSessionType = Number(request?.requesterSessionType || 0);
|
||||
const expiresText = request?.expiresAtMs ? formatRelativeTime(request.expiresAtMs) : '–';
|
||||
const sessionOnly = requesterSessionType === SESSION_TYPE_WALLET;
|
||||
const sessionKind = pairingSessionKindLabel(requesterSessionType);
|
||||
return `
|
||||
<div class="card stack" data-pairing-id="${String(request?.pairingId || '')}">
|
||||
<div class="row" style="align-items:flex-start;">
|
||||
<div class="stack" style="gap:4px;">
|
||||
<div style="font-size:28px; font-weight:700; letter-spacing:0.14em;">${shortCode}</div>
|
||||
<span class="meta-muted">Session name: ${client}</span>
|
||||
<span class="meta-muted">Session kind: ${sessionKind}</span>
|
||||
<span class="meta-muted">${th('remaining.html_device_pairing_view.expires')}${expiresText}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row pairing-request-actions" style="flex-wrap:wrap;">
|
||||
<button class="primary-btn pairing-approve-btn" type="button" data-action="approve-device">${th('screens.device_pairing_view.text_033')}</button>
|
||||
<button class="text-btn pairing-reject-btn" type="button" data-action="reject">${th('screens.device_pairing_view.text_034')}</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
async function restoreAuthorizedSessionForPairing() {
|
||||
const login = String(state.session.login || '').trim();
|
||||
const sessionId = String(state.session.sessionId || '').trim();
|
||||
if (!login || !sessionId) {
|
||||
throw new Error(t('screens.device_pairing_view.text_032'));
|
||||
}
|
||||
|
||||
const resumed = await authService.resumeSession(login, sessionId);
|
||||
authorizeSession({
|
||||
login: resumed.login || login,
|
||||
sessionId: resumed.sessionId || sessionId,
|
||||
storagePwd: resumed.storagePwd || state.session.storagePwdInMemory,
|
||||
});
|
||||
await refreshSessions().catch(() => {});
|
||||
return resumed;
|
||||
}
|
||||
|
||||
async function runPairingOpWithSessionRestore(runAction) {
|
||||
try {
|
||||
return await runAction();
|
||||
} catch (error) {
|
||||
const code = String(error?.code || '').trim().toUpperCase();
|
||||
if (code !== 'PAIRING_REQUIRES_AUTH_SESSION' && code !== 'NOT_AUTHENTICATED') {
|
||||
throw error;
|
||||
}
|
||||
|
||||
try {
|
||||
await restoreAuthorizedSessionForPairing();
|
||||
} catch (restoreError) {
|
||||
const restoreCode = String(restoreError?.code || '').trim().toUpperCase();
|
||||
if (restoreCode === 'SESSION_NOT_FOUND'
|
||||
|| restoreCode === 'SESSION_KEY_NOT_ACTUAL'
|
||||
|| restoreCode === 'SESSION_OF_ANOTHER_USER') {
|
||||
await terminateCurrentSession({
|
||||
infoMessage: t('screens.device_pairing_view.text_019'),
|
||||
});
|
||||
}
|
||||
throw restoreError;
|
||||
}
|
||||
|
||||
return runAction();
|
||||
}
|
||||
}
|
||||
|
||||
function makePasswordToggleIcons() {
|
||||
return {
|
||||
eye: iconHtml('eye', false, 'key-toggle-icon'),
|
||||
eyeOff: iconHtml('eyeOff', false, 'key-toggle-icon'),
|
||||
};
|
||||
}
|
||||
|
||||
function localPairingPasswordStateKey(login, serverUrl) {
|
||||
return `${PAIRING_PASSWORD_STATE_PREFIX}:${String(serverUrl || '').trim()}:${String(login || '').trim().toLowerCase()}`;
|
||||
}
|
||||
|
||||
function loadLocalPairingPasswordState(login, serverUrl) {
|
||||
try {
|
||||
const raw = localStorage.getItem(localPairingPasswordStateKey(login, serverUrl));
|
||||
if (!raw) return false;
|
||||
const parsed = JSON.parse(raw);
|
||||
return !!parsed?.hasPassword;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function saveLocalPairingPasswordState(login, serverUrl, hasPassword) {
|
||||
try {
|
||||
localStorage.setItem(localPairingPasswordStateKey(login, serverUrl), JSON.stringify({
|
||||
hasPassword: !!hasPassword,
|
||||
updatedAtMs: Date.now(),
|
||||
}));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
let savedKeys = null;
|
||||
let requests = [];
|
||||
let cleanupEvent = () => {};
|
||||
let disposed = false;
|
||||
let trustedDeviceLoginSettings = { enabled: true, hasPassword: false };
|
||||
let settingsBusy = false;
|
||||
let pairingPasswordConfigured = false;
|
||||
let dialogMode = '';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.device_pairing_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigate('device-view') },
|
||||
}));
|
||||
|
||||
const instructionCard = document.createElement('div');
|
||||
instructionCard.className = 'card stack pairing-guide-card';
|
||||
instructionCard.innerHTML = `
|
||||
<div class="pairing-guide__heading">
|
||||
<span class="pairing-guide__eyebrow">${th('screens.device_pairing_view.text_035')}</span>
|
||||
<p class="field-label pairing-guide__title">${th('screens.device_pairing_view.text_036')}</p>
|
||||
</div>
|
||||
<ol class="pairing-guide__steps">
|
||||
<li><span class="pairing-guide__step-number">1</span><span>${th('screens.device_pairing_view.text_037')}</span></li>
|
||||
<li><span class="pairing-guide__step-number">2</span><span>${th('screens.device_pairing_view.text_038')}</span></li>
|
||||
<li><span class="pairing-guide__step-number">3</span><span>${th('screens.device_pairing_view.text_039')}</span></li>
|
||||
</ol>
|
||||
`;
|
||||
|
||||
// UNUSED FOR NOW: UI настройки дополнительного пароля сохранён ниже в коде,
|
||||
// но карточка больше не показывается пользователю.
|
||||
const settingsCard = document.createElement('div');
|
||||
settingsCard.className = 'card stack';
|
||||
const passwordIcons = makePasswordToggleIcons();
|
||||
|
||||
const keySummaryCard = document.createElement('div');
|
||||
keySummaryCard.className = 'card stack';
|
||||
keySummaryCard.innerHTML = `
|
||||
<p class="field-label">${th('screens.device_pairing_view.text_040')}</p>
|
||||
<p class="meta-muted" id="pairing-key-summary">${th('screens.device_pairing_view.text_041')}</p>
|
||||
<p class="meta-muted">${th('screens.device_pairing_view.text_042')}</p>
|
||||
`;
|
||||
|
||||
const requestsCard = document.createElement('div');
|
||||
requestsCard.className = 'card stack';
|
||||
requestsCard.innerHTML = `
|
||||
<div class="row" style="justify-content:space-between; align-items:center; gap:10px; flex-wrap:wrap;">
|
||||
<span class="field-label">${th('screens.device_pairing_view.text_043')}</span>
|
||||
<button class="ghost-btn" type="button" id="refresh-pairing-requests">${th('screens.device_pairing_view.text_044')}</button>
|
||||
</div>
|
||||
<div class="stack" id="pairing-requests-list"></div>
|
||||
`;
|
||||
|
||||
const status = document.createElement('p');
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.style.display = 'none';
|
||||
const keySummaryEl = keySummaryCard.querySelector('#pairing-key-summary');
|
||||
const refreshBtn = requestsCard.querySelector('#refresh-pairing-requests');
|
||||
const requestsListEl = requestsCard.querySelector('#pairing-requests-list');
|
||||
|
||||
const passwordDialog = document.createElement('div');
|
||||
passwordDialog.hidden = true;
|
||||
passwordDialog.style.position = 'fixed';
|
||||
passwordDialog.style.inset = '0';
|
||||
passwordDialog.style.zIndex = '30';
|
||||
passwordDialog.innerHTML = `
|
||||
<div style="position:absolute; inset:0; background:var(--scrim); backdrop-filter:blur(4px);" data-action="close-dialog"></div>
|
||||
<div class="card stack" style="position:absolute; left:50%; top:24px; width:min(calc(100vw - 32px), 360px); transform:translateX(-50%); gap:12px; box-shadow:var(--shadow);">
|
||||
<div class="stack" style="gap:6px;">
|
||||
<p class="field-label" id="pairing-dialog-title">${t('dialogs.remaining.pages.device_pairing_view.markup.zadat_dopolnitelnyy_parol')}</p>
|
||||
<p class="meta-muted" id="pairing-dialog-text">${t('dialogs.remaining.pages.device_pairing_view.markup.dopolnitelnyy_parol_ne_dayot_prava_na_podklyuchenie_sam_po_s')}</p>
|
||||
</div>
|
||||
<label class="stack">
|
||||
<span class="field-label">${t('dialogs.remaining.pages.device_pairing_view.markup.parol')}</span>
|
||||
<div class="inline-input-row">
|
||||
<input class="input key-input" id="pairing-dialog-password" type="password" autocomplete="new-password" placeholder="${t('dialogs.remaining.pages.device_pairing_view.markup.vvedite_dopolnitelnyy_parol')}" />
|
||||
<button class="icon-btn key-toggle-btn" type="button" id="pairing-dialog-password-toggle" aria-label="${t('dialogs.remaining.pages.device_pairing_view.markup.pokazat_parol')}" title="${t('dialogs.remaining.pages.device_pairing_view.markup.pokazat_parol')}">${passwordIcons.eyeOff}</button>
|
||||
</div>
|
||||
</label>
|
||||
<label class="stack">
|
||||
<span class="field-label">${t('dialogs.remaining.pages.device_pairing_view.markup.podtverdite_parol')}</span>
|
||||
<div class="inline-input-row">
|
||||
<input class="input key-input" id="pairing-dialog-password-confirm" type="password" autocomplete="new-password" placeholder="${t('dialogs.remaining.pages.device_pairing_view.markup.povtorite_parol')}" />
|
||||
<button class="icon-btn key-toggle-btn" type="button" id="pairing-dialog-password-confirm-toggle" aria-label="${t('dialogs.remaining.pages.device_pairing_view.markup.pokazat_parol')}" title="${t('dialogs.remaining.pages.device_pairing_view.markup.pokazat_parol')}">${passwordIcons.eyeOff}</button>
|
||||
</div>
|
||||
</label>
|
||||
<div class="row" style="flex-wrap:wrap;">
|
||||
<button class="primary-btn" type="button" id="pairing-dialog-save">${t('dialogs.remaining.pages.device_pairing_view.markup.sohranit_parol')}</button>
|
||||
<button class="ghost-btn" type="button" data-action="close-dialog">${t('dialogs.remaining.pages.device_pairing_view.markup.otmena')}</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
screen.append(passwordDialog);
|
||||
|
||||
const dialogTitleEl = passwordDialog.querySelector('#pairing-dialog-title');
|
||||
const dialogTextEl = passwordDialog.querySelector('#pairing-dialog-text');
|
||||
const dialogPasswordInput = passwordDialog.querySelector('#pairing-dialog-password');
|
||||
const dialogPasswordConfirmInput = passwordDialog.querySelector('#pairing-dialog-password-confirm');
|
||||
const dialogSaveBtn = passwordDialog.querySelector('#pairing-dialog-save');
|
||||
const dialogPasswordToggleBtn = passwordDialog.querySelector('#pairing-dialog-password-toggle');
|
||||
const dialogPasswordConfirmToggleBtn = passwordDialog.querySelector('#pairing-dialog-password-confirm-toggle');
|
||||
|
||||
const dialogOverlay = document.createElement('div');
|
||||
dialogOverlay.hidden = true;
|
||||
dialogOverlay.style.position = 'absolute';
|
||||
dialogOverlay.style.inset = '0';
|
||||
dialogOverlay.style.zIndex = '2';
|
||||
dialogOverlay.innerHTML = `
|
||||
<div style="position:absolute; inset:0; background:var(--scrim);"></div>
|
||||
<div class="card stack" style="position:absolute; left:50%; top:50%; width:min(calc(100% - 32px), 320px); transform:translate(-50%, -50%); gap:12px; box-shadow:var(--shadow);">
|
||||
<p class="field-label" id="pairing-dialog-overlay-title">${t('dialogs.remaining.pages.device_pairing_view.markup.oshibka')}</p>
|
||||
<p class="meta-muted" id="pairing-dialog-overlay-text"></p>
|
||||
<div class="row" style="justify-content:flex-end; flex-wrap:wrap;">
|
||||
<button class="ghost-btn" type="button" id="pairing-dialog-overlay-cancel" hidden>${t('dialogs.remaining.pages.device_pairing_view.markup.net')}</button>
|
||||
<button class="primary-btn" type="button" id="pairing-dialog-overlay-confirm">${t('dialogs.remaining.pages.device_pairing_view.markup.ok')}</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
passwordDialog.append(dialogOverlay);
|
||||
|
||||
const dialogOverlayTitleEl = dialogOverlay.querySelector('#pairing-dialog-overlay-title');
|
||||
const dialogOverlayTextEl = dialogOverlay.querySelector('#pairing-dialog-overlay-text');
|
||||
const dialogOverlayCancelBtn = dialogOverlay.querySelector('#pairing-dialog-overlay-cancel');
|
||||
const dialogOverlayConfirmBtn = dialogOverlay.querySelector('#pairing-dialog-overlay-confirm');
|
||||
let dialogOverlayOnConfirm = null;
|
||||
let dialogOverlayOnCancel = null;
|
||||
|
||||
const closeDialogOverlay = () => {
|
||||
dialogOverlay.hidden = true;
|
||||
dialogOverlayOnConfirm = null;
|
||||
dialogOverlayOnCancel = null;
|
||||
};
|
||||
|
||||
const showDialogAlert = (message) => {
|
||||
dialogOverlayTitleEl.textContent = t('dialogs.remaining.pages.device_pairing_view.showdialogalert.oshibka');
|
||||
dialogOverlayTextEl.textContent = message;
|
||||
dialogOverlayCancelBtn.hidden = true;
|
||||
dialogOverlayConfirmBtn.textContent = t('dialogs.remaining.pages.device_pairing_view.showdialogalert.ok');
|
||||
dialogOverlay.hidden = false;
|
||||
dialogOverlayOnConfirm = () => closeDialogOverlay();
|
||||
dialogOverlayOnCancel = null;
|
||||
};
|
||||
|
||||
const showDialogConfirm = (message, { title = t('dialogs.remaining.pages.device_pairing_view.showdialogconfirm.podtverzhdenie'), confirmLabel = t('dialogs.remaining.pages.device_pairing_view.showdialogconfirm.da'), cancelLabel = t('dialogs.remaining.pages.device_pairing_view.showdialogconfirm.net'), onConfirm, onCancel } = {}) => {
|
||||
dialogOverlayTitleEl.textContent = title;
|
||||
dialogOverlayTextEl.textContent = message;
|
||||
dialogOverlayCancelBtn.hidden = false;
|
||||
dialogOverlayCancelBtn.textContent = cancelLabel;
|
||||
dialogOverlayConfirmBtn.textContent = confirmLabel;
|
||||
dialogOverlay.hidden = false;
|
||||
dialogOverlayOnConfirm = onConfirm || (() => closeDialogOverlay());
|
||||
dialogOverlayOnCancel = onCancel || (() => closeDialogOverlay());
|
||||
};
|
||||
|
||||
const bindPasswordToggle = (input, button) => {
|
||||
button.addEventListener('click', () => {
|
||||
if (input.type === 'password') {
|
||||
input.type = 'text';
|
||||
button.innerHTML = passwordIcons.eye;
|
||||
button.setAttribute('aria-label', t('screens.device_pairing_view.text_045'));
|
||||
button.title = t('screens.device_pairing_view.text_003');
|
||||
} else {
|
||||
input.type = 'password';
|
||||
button.innerHTML = passwordIcons.eyeOff;
|
||||
button.setAttribute('aria-label', t('screens.device_pairing_view.text_046'));
|
||||
button.title = t('screens.device_pairing_view.text_004');
|
||||
}
|
||||
});
|
||||
};
|
||||
bindPasswordToggle(dialogPasswordInput, dialogPasswordToggleBtn);
|
||||
bindPasswordToggle(dialogPasswordConfirmInput, dialogPasswordConfirmToggleBtn);
|
||||
|
||||
const openPasswordDialog = (mode) => {
|
||||
dialogMode = mode;
|
||||
dialogTitleEl.textContent = mode === 'change'
|
||||
? t('dialogs.remaining.pages.device_pairing_view.openpassworddialog.izmenit_dopolnitelnyy_parol')
|
||||
: t('dialogs.remaining.pages.device_pairing_view.openpassworddialog.zadat_dopolnitelnyy_parol');
|
||||
dialogTextEl.textContent =
|
||||
t('dialogs.remaining.pages.device_pairing_view.openpassworddialog.dopolnitelnyy_parol_ne_dayot_prava_na_podklyuchenie_sa');
|
||||
dialogPasswordInput.value = '';
|
||||
dialogPasswordConfirmInput.value = '';
|
||||
dialogPasswordInput.type = 'password';
|
||||
dialogPasswordConfirmInput.type = 'password';
|
||||
dialogPasswordToggleBtn.innerHTML = passwordIcons.eyeOff;
|
||||
dialogPasswordConfirmToggleBtn.innerHTML = passwordIcons.eyeOff;
|
||||
passwordDialog.hidden = false;
|
||||
};
|
||||
|
||||
const closePasswordDialog = () => {
|
||||
dialogMode = '';
|
||||
closeDialogOverlay();
|
||||
passwordDialog.hidden = true;
|
||||
};
|
||||
|
||||
const enablePairingWithoutPassword = async () => {
|
||||
const payload = await runPairingOpWithSessionRestore(() => authService.upsertTrustedDeviceLoginSettings({
|
||||
enabled: true,
|
||||
passwordHash: '',
|
||||
}));
|
||||
pairingPasswordConfigured = false;
|
||||
saveLocalPairingPasswordState(state.session.login, state.entrySettings.shineServerLogin || state.entrySettings.shineServerHttp, false);
|
||||
return payload;
|
||||
};
|
||||
|
||||
const removeAdditionalPassword = async () => {
|
||||
await enablePairingWithoutPassword();
|
||||
setAuthInfo(t('screens.device_pairing_view.text_009'));
|
||||
setStatus(status, t('screens.device_pairing_view.text_010'), 'info');
|
||||
};
|
||||
|
||||
const setSettingsBusy = (flag) => {
|
||||
settingsBusy = flag;
|
||||
renderSettingsCard();
|
||||
};
|
||||
|
||||
const formatTrustedDeviceLoginState = () => {
|
||||
if (!trustedDeviceLoginSettings.enabled) return t('screens.device_pairing_view.text_020');
|
||||
if (trustedDeviceLoginSettings.hasPassword) return t('screens.device_pairing_view.text_021');
|
||||
return t('screens.device_pairing_view.text_022');
|
||||
};
|
||||
|
||||
const reloadTrustedDeviceLoginSettings = async () => {
|
||||
trustedDeviceLoginSettings = await runPairingOpWithSessionRestore(() => authService.getTrustedDeviceLoginSettings());
|
||||
pairingPasswordConfigured = !!trustedDeviceLoginSettings.hasPassword;
|
||||
};
|
||||
|
||||
const renderSettingsCard = () => {
|
||||
settingsCard.innerHTML = '';
|
||||
|
||||
const title = document.createElement('p');
|
||||
title.className = 'field-label';
|
||||
title.textContent = t('screens.device_pairing_view.text_005');
|
||||
|
||||
const stateText = document.createElement('p');
|
||||
stateText.className = 'meta-muted';
|
||||
stateText.textContent = formatTrustedDeviceLoginState();
|
||||
|
||||
const note = document.createElement('p');
|
||||
note.className = 'meta-muted';
|
||||
note.textContent = t('screens.device_pairing_view.text_006');
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'row';
|
||||
actions.style.flexWrap = 'wrap';
|
||||
const openSettingsBtn = document.createElement('button');
|
||||
openSettingsBtn.className = 'primary-btn';
|
||||
openSettingsBtn.type = 'button';
|
||||
openSettingsBtn.textContent = t('screens.device_pairing_view.text_007');
|
||||
openSettingsBtn.disabled = settingsBusy;
|
||||
openSettingsBtn.addEventListener('click', () => navigate('trusted-device-login-settings-view'));
|
||||
actions.append(openSettingsBtn);
|
||||
|
||||
settingsCard.append(title, stateText, note, actions);
|
||||
};
|
||||
|
||||
const renderRequests = () => {
|
||||
requestsListEl.innerHTML = '';
|
||||
|
||||
if (!requests.length) {
|
||||
const empty = document.createElement('p');
|
||||
empty.className = 'meta-muted';
|
||||
empty.textContent = t('screens.device_pairing_view.text_008');
|
||||
requestsListEl.append(empty);
|
||||
return;
|
||||
}
|
||||
|
||||
requests.forEach((request) => {
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.innerHTML = requestCardHtml(request);
|
||||
requestsListEl.append(wrapper.firstElementChild);
|
||||
});
|
||||
};
|
||||
|
||||
const loadSavedKeys = async () => {
|
||||
savedKeys = await loadEncryptedUserSecrets(state.session.login, state.session.storagePwdInMemory);
|
||||
const hasClient = !!String(savedKeys?.clientKey || '').trim();
|
||||
const hasBlockchain = !!String(savedKeys?.blockchainKey || '').trim();
|
||||
keySummaryEl.textContent = hasClient && hasBlockchain
|
||||
? t('screens.device_pairing_view.text_023')
|
||||
: t('screens.device_pairing_view.text_024');
|
||||
};
|
||||
|
||||
const reloadRequests = async ({ silent = false } = {}) => {
|
||||
try {
|
||||
await reloadTrustedDeviceLoginSettings();
|
||||
renderSettingsCard();
|
||||
requests = await runPairingOpWithSessionRestore(() => authService.listTrustedDeviceLoginRequests());
|
||||
renderRequests();
|
||||
if (!silent) {
|
||||
setStatus(status, t('screens.device_pairing_view.text_011'), 'info');
|
||||
}
|
||||
} catch (error) {
|
||||
const message = toUserMessage(error, t('screens.device_pairing_view.text_012'));
|
||||
setAuthError(message);
|
||||
setStatus(status, message, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const setButtonsBusy = (flag) => {
|
||||
refreshBtn.disabled = flag;
|
||||
};
|
||||
|
||||
const approveRequest = async (request) => {
|
||||
let payload;
|
||||
if (Number(request?.requesterSessionType || 0) === SESSION_TYPE_WALLET) {
|
||||
const delegatedSession = await authService.createDelegatedSessionWithClientKey({
|
||||
login: state.session.login,
|
||||
clientPrivPkcs8: String(savedKeys?.clientKey || savedKeys?.clientKey || '').trim(),
|
||||
sessionKey: String(request?.requesterSessionKey || '').trim(),
|
||||
sessionType: Number(request?.requesterSessionType || SESSION_TYPE_WALLET) || SESSION_TYPE_WALLET,
|
||||
clientPlatform: String(request?.requesterClientPlatform || '').trim() || 'Wallet plugin',
|
||||
clientInfo: 'Wallet session approved via device pairing',
|
||||
});
|
||||
payload = buildSessionAttachPayload({
|
||||
login: state.session.login,
|
||||
session: delegatedSession,
|
||||
});
|
||||
} else {
|
||||
const keys = buildTransferKeys(savedKeys);
|
||||
payload = buildSecretsPayload({
|
||||
login: state.session.login,
|
||||
keys,
|
||||
mode: 'full-device',
|
||||
});
|
||||
}
|
||||
const encryptedPayload = await encryptPairingPayloadForRequester(request?.requesterSessionKey, payload);
|
||||
await runPairingOpWithSessionRestore(() => authService.approveTrustedDeviceLogin(request?.pairingId, encryptedPayload));
|
||||
const sessionOnly = Number(request?.requesterSessionType || 0) === SESSION_TYPE_WALLET;
|
||||
showToast(sessionOnly
|
||||
? t('screens.device_pairing_view.text_025')
|
||||
: t('screens.device_pairing_view.text_026'));
|
||||
setAuthInfo(sessionOnly
|
||||
? t('screens.device_pairing_view.text_027')
|
||||
: t('screens.device_pairing_view.text_028'));
|
||||
await refreshSessions().catch(() => {});
|
||||
await reloadRequests({ silent: true });
|
||||
};
|
||||
|
||||
passwordDialog.addEventListener('click', (event) => {
|
||||
const target = event.target;
|
||||
if (!(target instanceof HTMLElement)) return;
|
||||
if (target.dataset.action === 'close-dialog') {
|
||||
closePasswordDialog();
|
||||
}
|
||||
});
|
||||
|
||||
dialogOverlayConfirmBtn.addEventListener('click', async () => {
|
||||
const handler = dialogOverlayOnConfirm;
|
||||
if (!handler) return;
|
||||
await handler();
|
||||
});
|
||||
|
||||
dialogOverlayCancelBtn.addEventListener('click', async () => {
|
||||
const handler = dialogOverlayOnCancel;
|
||||
if (!handler) {
|
||||
closeDialogOverlay();
|
||||
return;
|
||||
}
|
||||
await handler();
|
||||
});
|
||||
|
||||
dialogSaveBtn.addEventListener('click', async () => {
|
||||
const password = String(dialogPasswordInput.value || '');
|
||||
const confirm = String(dialogPasswordConfirmInput.value || '');
|
||||
const currentMode = dialogMode;
|
||||
if (!password && !confirm) {
|
||||
showDialogConfirm(t('dialogs.final.device.password_remove_confirm'), {
|
||||
title: t('dialogs.final.device.password_not_set'),
|
||||
confirmLabel: t('dialogs.final.device.agree'),
|
||||
cancelLabel: t('dialogs.final.device.decline'),
|
||||
onConfirm: async () => {
|
||||
closeDialogOverlay();
|
||||
dialogSaveBtn.disabled = true;
|
||||
try {
|
||||
await removeAdditionalPassword();
|
||||
closePasswordDialog();
|
||||
renderSettingsCard();
|
||||
} catch (error) {
|
||||
const message = toUserMessage(error, t('dialogs.final.device.remove_extra_password_error'));
|
||||
setAuthError(message);
|
||||
showDialogAlert(message);
|
||||
} finally {
|
||||
dialogSaveBtn.disabled = false;
|
||||
}
|
||||
},
|
||||
onCancel: () => {
|
||||
closeDialogOverlay();
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!password || !confirm) {
|
||||
showDialogAlert(t('dialogs.final.device.password_fill_both'));
|
||||
return;
|
||||
}
|
||||
if (password !== confirm) {
|
||||
showDialogAlert(t('dialogs.final.device.password_mismatch'));
|
||||
return;
|
||||
}
|
||||
dialogSaveBtn.disabled = true;
|
||||
try {
|
||||
const passwordHash = await deriveEspPairingPasswordHash(state.session.login, password);
|
||||
await runPairingOpWithSessionRestore(() => authService.upsertTrustedDeviceLoginSettings({
|
||||
enabled: true,
|
||||
passwordHash,
|
||||
}));
|
||||
pairingPasswordConfigured = true;
|
||||
saveLocalPairingPasswordState(state.session.login, state.entrySettings.shineServerLogin || state.entrySettings.shineServerHttp, true);
|
||||
closePasswordDialog();
|
||||
renderSettingsCard();
|
||||
setAuthInfo(t('screens.device_pairing_view.text_013'));
|
||||
setStatus(status, currentMode === 'change'
|
||||
? t('screens.device_pairing_view.text_029')
|
||||
: t('screens.device_pairing_view.text_030'), 'info');
|
||||
} catch (error) {
|
||||
const message = toUserMessage(error, t('screens.device_pairing_view.text_014'));
|
||||
setAuthError(message);
|
||||
showDialogAlert(message);
|
||||
} finally {
|
||||
dialogSaveBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
refreshBtn.addEventListener('click', () => {
|
||||
void reloadRequests();
|
||||
});
|
||||
|
||||
requestsListEl.addEventListener('click', async (event) => {
|
||||
const target = event.target;
|
||||
if (!(target instanceof HTMLElement)) return;
|
||||
const action = String(target.dataset.action || '');
|
||||
if (!action) return;
|
||||
const card = target.closest('[data-pairing-id]');
|
||||
if (!(card instanceof HTMLElement)) return;
|
||||
const pairingId = String(card.dataset.pairingId || '');
|
||||
const request = requests.find((item) => String(item?.pairingId || '') === pairingId);
|
||||
if (!request) return;
|
||||
|
||||
const buttons = [...card.querySelectorAll('button')];
|
||||
buttons.forEach((btn) => { btn.disabled = true; });
|
||||
try {
|
||||
if (action === 'approve-device') {
|
||||
await approveRequest(request);
|
||||
} else if (action === 'reject') {
|
||||
await runPairingOpWithSessionRestore(() => authService.rejectTrustedDeviceLogin(pairingId, 'rejected_by_user'));
|
||||
showToast(t('screens.device_pairing_view.text_015'), { kind: 'error' });
|
||||
await reloadRequests({ silent: true });
|
||||
}
|
||||
} catch (error) {
|
||||
const message = toUserMessage(error, t('screens.device_pairing_view.text_016'));
|
||||
setAuthError(message);
|
||||
setStatus(status, message, 'error');
|
||||
buttons.forEach((btn) => { btn.disabled = false; });
|
||||
}
|
||||
});
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
// Активный UX временно поддерживает только вход без дополнительного пароля.
|
||||
// Если пароль был задан старой версией UI, при открытии этого экрана он сбрасывается.
|
||||
await enablePairingWithoutPassword();
|
||||
await loadSavedKeys();
|
||||
await reloadRequests({ silent: true });
|
||||
cleanupEvent = authService.onEvent('IncomingTrustedDeviceLoginRequest', () => {
|
||||
if (disposed) return;
|
||||
showToast(t('screens.device_pairing_view.text_017'), { kind: 'info' });
|
||||
void reloadRequests({ silent: true });
|
||||
});
|
||||
} catch (error) {
|
||||
const message = toUserMessage(error, t('screens.device_pairing_view.text_018'));
|
||||
setAuthError(message);
|
||||
setStatus(status, message, 'error');
|
||||
}
|
||||
})();
|
||||
|
||||
screen.cleanup = () => {
|
||||
disposed = true;
|
||||
cleanupEvent();
|
||||
};
|
||||
|
||||
screen.append(instructionCard, requestsCard, status);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { state } from '../state.js';
|
||||
import { loadEncryptedUserSecrets } from '../services/key-vault.js';
|
||||
import {
|
||||
describeTransferKeys,
|
||||
makeKeyTransferText,
|
||||
renderQrSvg,
|
||||
} from '../services/qr-key-transfer-service.js';
|
||||
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'device-qr-view', get title() { return t('screens.device_qr_view.text_001'); } };
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.device_qr_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigate('connect-device-view') },
|
||||
}));
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack qr-card';
|
||||
card.innerHTML = `
|
||||
<div class="qr-image" id="device-transfer-qr" aria-label="${th('screens.device_qr_view.text_010')}"></div>
|
||||
<p class="meta-muted" id="device-transfer-login">${th('screens.device_qr_view.text_011')}</p>
|
||||
<p class="meta-muted" id="device-transfer-keys">${th('screens.device_qr_view.text_012')}</p>
|
||||
<p class="meta-muted">${th('screens.device_qr_view.text_013')}</p>
|
||||
<p class="status-line is-unavailable" id="device-transfer-status" style="display:none;"></p>
|
||||
<button class="primary-btn" type="button" id="qr-ok">OK</button>
|
||||
`;
|
||||
|
||||
const qrEl = card.querySelector('#device-transfer-qr');
|
||||
const loginEl = card.querySelector('#device-transfer-login');
|
||||
const keysEl = card.querySelector('#device-transfer-keys');
|
||||
const statusEl = card.querySelector('#device-transfer-status');
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
if (!state.session.login || !state.session.storagePwdInMemory) {
|
||||
throw new Error(t('screens.device_qr_view.text_006'));
|
||||
}
|
||||
const savedKeys = await loadEncryptedUserSecrets(state.session.login, state.session.storagePwdInMemory);
|
||||
const keys = {
|
||||
clientKey: String(savedKeys.clientKey || '').trim(),
|
||||
blockchainKey: String(savedKeys.blockchainKey || '').trim(),
|
||||
};
|
||||
if (!keys.clientKey || !keys.blockchainKey) {
|
||||
throw new Error(t('screens.device_qr_view.text_007'));
|
||||
}
|
||||
|
||||
const qrText = makeKeyTransferText({ login: state.session.login, keys });
|
||||
qrEl.innerHTML = renderQrSvg(qrText);
|
||||
loginEl.textContent = t('screens.device_qr_view.text_008', { value1: state.session.login });
|
||||
keysEl.textContent = t('screens.device_qr_view.text_009', { value1: describeTransferKeys(keys).join(', ') });
|
||||
} catch (error) {
|
||||
qrEl.textContent = '';
|
||||
loginEl.textContent = t('screens.device_qr_view.text_003');
|
||||
keysEl.textContent = t('screens.device_qr_view.text_004');
|
||||
statusEl.textContent = actionErrorText(t('screens.device_qr_view.text_005'), error);
|
||||
statusEl.style.display = '';
|
||||
}
|
||||
})();
|
||||
|
||||
card.querySelector('#qr-ok').addEventListener('click', () => navigate('connect-device-view'));
|
||||
screen.append(card);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { formatDateTime } from '../i18n/format.js';
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import {
|
||||
authService,
|
||||
isSessionInvalidError,
|
||||
refreshSessions,
|
||||
setAuthError,
|
||||
state,
|
||||
terminateCurrentSession,
|
||||
} from '../state.js';
|
||||
|
||||
export const pageMeta = { id: 'device-session-view', get title() { return t('screens.device_session_view.text_001'); } };
|
||||
|
||||
function formatSessionType(sessionType) {
|
||||
if (Number(sessionType) === 100) return 'Homeserver';
|
||||
if (Number(sessionType) === 50) return 'Wallet';
|
||||
if (Number(sessionType) === 1) return 'Client';
|
||||
return `Type ${Number(sessionType) || 0}`;
|
||||
}
|
||||
|
||||
function formatSessionTime(ms) {
|
||||
return formatDateTime(new Date(ms), {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
});
|
||||
}
|
||||
|
||||
function formatOnlineStatus(onlineOnThisServer) {
|
||||
return onlineOnThisServer ? 'Online now on this server' : 'Offline on this server';
|
||||
}
|
||||
|
||||
export function render({navigate, route, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
const sessionId = route?.params?.sessionId || '';
|
||||
const session = (state.sessions || []).find((item) => item.sessionId === sessionId) || state.sessions[0];
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.device_session_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigate('device-view') },
|
||||
}));
|
||||
|
||||
if (!session) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'card';
|
||||
empty.textContent = t('screens.device_session_view.text_003');
|
||||
screen.append(empty);
|
||||
return screen;
|
||||
}
|
||||
|
||||
const details = document.createElement('div');
|
||||
details.className = 'card stack';
|
||||
const onlineStatusClass = session.onlineOnThisServer ? 'session-status session-status--online' : 'session-status';
|
||||
details.innerHTML = `
|
||||
<div><p class="meta-muted">sessionId</p><p>${session.sessionId}</p></div>
|
||||
<div><p class="meta-muted">sessionType</p><p>${formatSessionType(session.sessionType)}</p></div>
|
||||
<div><p class="meta-muted">clientPlatform</p><p>${session.clientPlatform || '-'}</p></div>
|
||||
<div><p class="meta-muted">onlineOnThisServer</p><p class="${onlineStatusClass}">${formatOnlineStatus(!!session.onlineOnThisServer)}</p></div>
|
||||
<div><p class="meta-muted">clientInfoFromClient</p><p>${session.clientInfoFromClient || '-'}</p></div>
|
||||
<div><p class="meta-muted">clientInfoFromRequest</p><p>${session.clientInfoFromRequest || '-'}</p></div>
|
||||
<div><p class="meta-muted">geo</p><p>${session.geo || 'unknown'}</p></div>
|
||||
<div><p class="meta-muted">${th('screens.device_session_view.text_016')}</p><p>${formatSessionTime(session.lastAuthenticatedAtMs || Date.now())}</p></div>
|
||||
`;
|
||||
|
||||
const actionBtn = document.createElement('button');
|
||||
actionBtn.className = 'shine-btn shine-btn--settings';
|
||||
actionBtn.type = 'button';
|
||||
actionBtn.textContent = t('screens.device_session_view.text_004');
|
||||
|
||||
actionBtn.addEventListener('click', async () => {
|
||||
const isCurrentSession = session.sessionId === state.session.sessionId;
|
||||
const confirmed = await confirmDialog(isCurrentSession
|
||||
? { title: t('screens.device_session_view.text_005'), text: t('screens.device_session_view.text_011'), confirmLabel: t('screens.device_session_view.text_006'), danger: true }
|
||||
: { title: t('screens.device_session_view.text_007'), text: t('screens.device_session_view.text_012'), confirmLabel: t('screens.device_session_view.text_008'), danger: true });
|
||||
if (!confirmed) return;
|
||||
|
||||
try {
|
||||
if (isCurrentSession) {
|
||||
await terminateCurrentSession({
|
||||
infoMessage: t('screens.device_session_view.text_013'),
|
||||
closeServerSession: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await authService.closeSession(session.sessionId);
|
||||
} catch (error) {
|
||||
if (!isSessionInvalidError(error)) {
|
||||
setAuthError(error.message);
|
||||
showToast(toUserMessage(error, t('screens.device_session_view.text_009')), { kind: 'error' });
|
||||
return;
|
||||
}
|
||||
if (isCurrentSession) {
|
||||
await terminateCurrentSession({
|
||||
infoMessage: t('screens.device_session_view.text_014'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await refreshSessions();
|
||||
navigate('device-view');
|
||||
} catch (error) {
|
||||
if (isSessionInvalidError(error)) {
|
||||
await terminateCurrentSession({
|
||||
infoMessage: t('screens.device_session_view.text_015'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
setAuthError(error.message);
|
||||
showToast(toUserMessage(error, t('screens.device_session_view.text_010')), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
screen.append(details, actionBtn);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import { formatDate, formatTime } from '../i18n/format.js';
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||
import {
|
||||
authService,
|
||||
isSessionInvalidError,
|
||||
refreshSessions,
|
||||
setAuthInfo,
|
||||
state,
|
||||
terminateCurrentSession,
|
||||
} from '../state.js';
|
||||
|
||||
export const pageMeta = { id: 'device-view', get title() { return t('screens.device_view.text_001'); } };
|
||||
|
||||
function formatSessionType(sessionType) {
|
||||
if (Number(sessionType) === 100) return t('screens.device_view.text_016');
|
||||
if (Number(sessionType) === 50) return t('screens.device_view.text_017');
|
||||
if (Number(sessionType) === 1) return t('screens.device_view.text_018');
|
||||
return t('screens.device_view.text_027', { value1: Number(sessionType) || 0 });
|
||||
}
|
||||
|
||||
// «Mozilla/5.0 (X11; Linux x86_64) … Chrome/139 …» → «Chrome · Linux».
|
||||
function describeClient(userAgent) {
|
||||
const ua = String(userAgent || '');
|
||||
if (!ua) return t('screens.device_view.text_019');
|
||||
const browser = /Edg\//.test(ua) ? 'Edge'
|
||||
: /OPR\/|Opera/.test(ua) ? 'Opera'
|
||||
: /Firefox\//.test(ua) ? 'Firefox'
|
||||
: /YaBrowser\//.test(ua) ? t('screens.device_view.text_020')
|
||||
: /Chrome\//.test(ua) ? 'Chrome'
|
||||
: /Safari\//.test(ua) ? 'Safari'
|
||||
: '';
|
||||
const os = /iPhone/.test(ua) ? 'iPhone'
|
||||
: /iPad/.test(ua) ? 'iPad'
|
||||
: /Android/.test(ua) ? 'Android'
|
||||
: /Windows/.test(ua) ? 'Windows'
|
||||
: /Mac OS X|Macintosh/.test(ua) ? 'macOS'
|
||||
: /Linux|X11/.test(ua) ? 'Linux'
|
||||
: '';
|
||||
const parts = [browser, os].filter(Boolean);
|
||||
return parts.length ? parts.join(' · ') : ua.slice(0, 40);
|
||||
}
|
||||
|
||||
// «сегодня, 02:20» / «вчера, 23:10» / «24 сентября, 18:05».
|
||||
function formatSessionTime(ms) {
|
||||
const date = new Date(ms);
|
||||
const time = formatTime(date, { hour: '2-digit', minute: '2-digit' });
|
||||
const startOf = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
|
||||
const days = Math.round((startOf(new Date()) - startOf(date)) / 86400000);
|
||||
if (days === 0) return t('screens.device_view.text_028', { value1: time });
|
||||
if (days === 1) return t('screens.device_view.text_029', { value1: time });
|
||||
const sameYear = date.getFullYear() === new Date().getFullYear();
|
||||
const day = formatDate(date, { day: 'numeric', month: 'long', ...(sameYear ? {} : { year: 'numeric' }) });
|
||||
return `${day}, ${time}`;
|
||||
}
|
||||
|
||||
function formatOnlineStatus(onlineOnThisServer) {
|
||||
return onlineOnThisServer ? t('screens.device_view.text_021') : t('screens.device_view.text_022');
|
||||
}
|
||||
|
||||
function sortSessionsByOnline(sessions = []) {
|
||||
return [...sessions].sort((a, b) => {
|
||||
const aOnline = a?.onlineOnThisServer ? 1 : 0;
|
||||
const bOnline = b?.onlineOnThisServer ? 1 : 0;
|
||||
if (aOnline !== bOnline) return bOnline - aOnline;
|
||||
return Number(b?.lastAuthenticatedAtMs || 0) - Number(a?.lastAuthenticatedAtMs || 0);
|
||||
});
|
||||
}
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.device_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigate('settings-view') },
|
||||
actions: [{ icon: 'refresh', title: t('screens.device_view.text_003'), ariaLabel: t('screens.device_view.text_004'), id: 'reload-sessions', onClick: () => reloadSessions() }],
|
||||
}));
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'nav-list';
|
||||
actions.innerHTML = `
|
||||
<button class="nav-row" type="button" id="pair-by-code-btn"><span class="nav-row__label">${th('screens.device_view.text_031')}</span><span class="nav-row__hint">${th('screens.device_view.text_032')}</span></button>
|
||||
`;
|
||||
|
||||
actions.querySelector('#pair-by-code-btn').addEventListener('click', () => navigate('device-pairing-view'));
|
||||
|
||||
const sessionsBlock = document.createElement('div');
|
||||
sessionsBlock.className = 'stack device-sessions';
|
||||
|
||||
const buildList = () => {
|
||||
sessionsBlock.innerHTML = '';
|
||||
const sessions = sortSessionsByOnline(state.sessions || []);
|
||||
const current = sessions.find((s) => s.sessionId === state.session.sessionId) || sessions[0];
|
||||
const others = sortSessionsByOnline(sessions.filter((s) => s.sessionId !== current?.sessionId));
|
||||
|
||||
const createSessionItem = (session, isCurrent) => {
|
||||
const item = document.createElement('button');
|
||||
item.className = 'ui-button session-item';
|
||||
item.type = 'button';
|
||||
const isWebClient = Number(session.sessionType) === 1 && /web/i.test(String(session.clientPlatform || ''));
|
||||
const sessionTypeText = isWebClient ? t('screens.device_view.text_023') : formatSessionType(session.sessionType);
|
||||
const sessionPlatformText = !isWebClient && session.clientPlatform ? ` · ${session.clientPlatform}` : '';
|
||||
const onlineStatusText = formatOnlineStatus(!!session.onlineOnThisServer);
|
||||
const onlineStatusClass = session.onlineOnThisServer ? 'session-status session-status--online' : 'session-status';
|
||||
item.innerHTML = `
|
||||
<span class="session-item__main">
|
||||
<strong class="session-item__title"></strong>
|
||||
<span class="meta-muted">${sessionTypeText}${sessionPlatformText} · <span class="${onlineStatusClass}">${onlineStatusText}</span></span>
|
||||
${session.geo && session.geo !== 'unknown' ? '<span class="meta-muted session-item__geo"></span>' : ''}
|
||||
</span>
|
||||
<span class="session-item__side">
|
||||
<span class="meta-muted">${formatSessionTime(session.lastAuthenticatedAtMs || Date.now())}</span>
|
||||
</span>
|
||||
`;
|
||||
item.querySelector('.session-item__title').textContent = describeClient(session.clientInfoFromClient);
|
||||
item.title = String(session.clientInfoFromClient || '');
|
||||
const geoEl = item.querySelector('.session-item__geo');
|
||||
if (geoEl) geoEl.textContent = session.geo;
|
||||
item.addEventListener('click', () => navigate(`device-session-view/${session.sessionId}`));
|
||||
return item;
|
||||
};
|
||||
|
||||
if (!current) {
|
||||
const empty = document.createElement('p');
|
||||
empty.className = 'meta-muted';
|
||||
empty.textContent = t('screens.device_view.text_005');
|
||||
sessionsBlock.append(empty);
|
||||
return;
|
||||
}
|
||||
|
||||
const groupTitle = (text) => {
|
||||
const title = document.createElement('p');
|
||||
title.className = 'nav-list__title';
|
||||
title.textContent = text;
|
||||
return title;
|
||||
};
|
||||
const currentList = document.createElement('div');
|
||||
currentList.className = 'nav-list';
|
||||
currentList.append(createSessionItem(current, true));
|
||||
sessionsBlock.append(groupTitle(t('screens.device_view.text_010')), currentList, groupTitle(t('screens.device_view.text_011')));
|
||||
|
||||
if (others.length === 0) {
|
||||
const empty = document.createElement('p');
|
||||
empty.className = 'empty-note';
|
||||
empty.textContent = t('screens.device_view.text_006');
|
||||
sessionsBlock.append(empty);
|
||||
} else {
|
||||
const closeAll = document.createElement('button');
|
||||
closeAll.className = 'shine-btn shine-btn--settings';
|
||||
closeAll.type = 'button';
|
||||
closeAll.textContent = t('screens.device_view.text_007');
|
||||
closeAll.addEventListener('click', async () => {
|
||||
const confirmed = await confirmDialog({
|
||||
title: t('screens.device_view.text_008'),
|
||||
text: t('screens.device_view.text_024'),
|
||||
confirmLabel: t('screens.device_view.text_009'),
|
||||
danger: true,
|
||||
});
|
||||
if (!confirmed) return;
|
||||
closeAll.disabled = true;
|
||||
try {
|
||||
const result = await authService.closeOtherSessions();
|
||||
await refreshSessions();
|
||||
buildList();
|
||||
showToast(t('screens.device_view.text_030', { value1: Number(result?.closedCount || 0) }));
|
||||
} catch (error) {
|
||||
closeAll.disabled = false;
|
||||
if (isSessionInvalidError(error)) {
|
||||
await terminateCurrentSession({ infoMessage: t('screens.device_view.text_025') });
|
||||
return;
|
||||
}
|
||||
showToast(actionErrorText(t('screens.device_view.text_012'), error), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
const othersList = document.createElement('div');
|
||||
othersList.className = 'nav-list';
|
||||
others.forEach((session) => othersList.append(createSessionItem(session, false)));
|
||||
sessionsBlock.append(closeAll, othersList);
|
||||
}
|
||||
};
|
||||
|
||||
async function reloadSessions() {
|
||||
try {
|
||||
await refreshSessions();
|
||||
buildList();
|
||||
setAuthInfo(t('screens.device_view.text_013'));
|
||||
showToast(t('screens.device_view.text_014'));
|
||||
} catch (error) {
|
||||
if (isSessionInvalidError(error)) {
|
||||
await terminateCurrentSession({
|
||||
infoMessage: t('screens.device_view.text_026'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
showToast(actionErrorText(t('screens.device_view.text_015'), error), { kind: 'error' });
|
||||
}
|
||||
}
|
||||
|
||||
buildList();
|
||||
screen.append(actions, sessionsBlock);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { formatSol, getBalanceSol } from '../services/solana-wallet-service.js';
|
||||
|
||||
export const pageMeta = {id:'devnet-topup-view', get title() { return t('screens.devnet_topup_view.text_001'); }, showAppChrome:false};
|
||||
const DEVNET_ENDPOINT='https://api.devnet.solana.com';
|
||||
function readWalletFromUrl() {
|
||||
try { return new URL(window.location.href).searchParams.get('wallet')?.trim() || ''; }
|
||||
catch { return ''; }
|
||||
}
|
||||
export function render() {
|
||||
const screen=document.createElement('section');screen.className='stack registration-screen';
|
||||
const card=document.createElement('div');card.className='card stack';
|
||||
const title=document.createElement('h3');title.textContent=t('screens.devnet_topup_view.text_002');
|
||||
const note=document.createElement('p');note.className='meta-muted';
|
||||
note.textContent=t('screens.devnet_topup_view.text_003');
|
||||
const wallet=readWalletFromUrl();
|
||||
const input=document.createElement('input');input.className='input';input.readOnly=true;input.value=wallet;
|
||||
const copy=document.createElement('button');copy.className='secondary-btn';copy.textContent=t('screens.devnet_topup_view.text_004');
|
||||
copy.addEventListener('click',()=>navigator.clipboard.writeText(input.value).catch(()=>{}));
|
||||
const balance=document.createElement('p');balance.className='meta-muted';
|
||||
balance.textContent=wallet?t('screens.devnet_topup_view.text_007'):t('screens.devnet_topup_view.text_008');
|
||||
if(wallet)void getBalanceSol({endpoint:DEVNET_ENDPOINT,address:wallet})
|
||||
.then(value=>balance.textContent=t('screens.devnet_topup_view.text_009', { value1: formatSol(value.sol,6) }))
|
||||
.catch(()=>balance.textContent=t('screens.devnet_topup_view.text_005'));
|
||||
card.append(title,note,input,copy,balance);
|
||||
screen.append(createTopBar({title:t('screens.devnet_topup_view.text_006')}),card);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import {
|
||||
authorizeLocalDemoSession,
|
||||
isLocalDemoAvailable,
|
||||
saveEntrySettings,
|
||||
state,
|
||||
} from '../state.js';
|
||||
import { checkServerAvailabilityByKey, resolveAndCheckShineServerLogin } from '../services/server-health-service.js';
|
||||
|
||||
export const pageMeta = { id: 'entry-settings-view', get title() { return t('screens.entry_settings_view.text_001'); }, showAppChrome: false };
|
||||
|
||||
const SERVER_FIELDS = [
|
||||
{ key: 'shineServerLogin', get label() { return t('screens.entry_settings_view.text_002'); } },
|
||||
{ key: 'arweaveServer', get label() { return t('screens.entry_settings_view.text_003'); } },
|
||||
];
|
||||
|
||||
export function render({ navigate }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack entry-settings';
|
||||
|
||||
const draft = {
|
||||
language: state.entrySettings.language,
|
||||
solanaServer: state.entrySettings.solanaServer,
|
||||
shineServerLogin: state.entrySettings.shineServerLogin,
|
||||
shineServerHttp: state.entrySettings.shineServerHttp,
|
||||
arweaveServer: state.entrySettings.arweaveServer,
|
||||
statuses: { ...state.entrySettings.statuses },
|
||||
};
|
||||
|
||||
const timers = new Map();
|
||||
|
||||
let disposed = false;
|
||||
const checks = [];
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'entry-servers';
|
||||
|
||||
SERVER_FIELDS.forEach((field) => {
|
||||
const block = document.createElement('div');
|
||||
block.className = 'entry-server';
|
||||
|
||||
const head = document.createElement('div');
|
||||
head.className = 'entry-server__head';
|
||||
|
||||
const title = document.createElement('label');
|
||||
title.className = 'field-label';
|
||||
title.htmlFor = `entry-${field.key}`;
|
||||
title.textContent = field.label;
|
||||
|
||||
// Статус — он же кнопка повторной проверки.
|
||||
const checkButton = document.createElement('button');
|
||||
checkButton.className = 'text-btn entry-status';
|
||||
checkButton.type = 'button';
|
||||
|
||||
const input = document.createElement('input');
|
||||
input.className = 'input';
|
||||
input.id = `entry-${field.key}`;
|
||||
input.type = 'text';
|
||||
input.autocapitalize = 'off';
|
||||
input.spellcheck = false;
|
||||
input.value = draft[field.key];
|
||||
|
||||
const hint = document.createElement('p');
|
||||
hint.className = 'entry-server__hint';
|
||||
|
||||
const applyStatus = (value, exactAddress = '') => {
|
||||
if (disposed) return;
|
||||
if (value !== 'checking') draft.statuses[field.key] = value;
|
||||
checkButton.classList.remove('is-available', 'is-unavailable', 'is-checking');
|
||||
checkButton.disabled = false;
|
||||
|
||||
if (value === 'available') {
|
||||
checkButton.textContent = t('screens.entry_settings_view.text_004');
|
||||
checkButton.classList.add('is-available');
|
||||
} else if (value === 'unavailable') {
|
||||
checkButton.textContent = t('screens.entry_settings_view.text_005');
|
||||
checkButton.classList.add('is-unavailable');
|
||||
} else if (value === 'checking') {
|
||||
checkButton.textContent = t('screens.entry_settings_view.text_006');
|
||||
checkButton.classList.add('is-checking');
|
||||
checkButton.disabled = true;
|
||||
} else {
|
||||
checkButton.textContent = t('screens.entry_settings_view.text_007');
|
||||
}
|
||||
checkButton.setAttribute('aria-label', t('screens.entry_settings_view.text_013', { value1: field.label, value2: checkButton.textContent }));
|
||||
|
||||
if (field.key === 'shineServerLogin') {
|
||||
const address = exactAddress || draft.shineServerHttp;
|
||||
hint.textContent = address || '';
|
||||
hint.hidden = !address;
|
||||
}
|
||||
};
|
||||
|
||||
let checkSeq = 0;
|
||||
const runCheck = async () => {
|
||||
draft[field.key] = input.value.trim();
|
||||
window.clearTimeout(timers.get(field.key));
|
||||
// Результат устаревшей проверки (адрес успели поменять) не должен перезаписать новый.
|
||||
const seq = ++checkSeq;
|
||||
applyStatus('checking');
|
||||
try {
|
||||
if (field.key === 'shineServerLogin') {
|
||||
const resolved = await resolveAndCheckShineServerLogin(input.value, draft.solanaServer);
|
||||
if (seq !== checkSeq) return;
|
||||
draft.shineServerHttp = resolved.httpBase;
|
||||
draft.shineServer = resolved.wsUrl;
|
||||
applyStatus(resolved.status, resolved.httpBase);
|
||||
} else {
|
||||
const next = await checkServerAvailabilityByKey(field.key, input.value, {
|
||||
solanaEndpoint: draft.solanaServer,
|
||||
});
|
||||
if (seq !== checkSeq) return;
|
||||
applyStatus(next);
|
||||
}
|
||||
} catch {
|
||||
if (seq === checkSeq) applyStatus('unavailable');
|
||||
}
|
||||
};
|
||||
|
||||
applyStatus(draft.statuses[field.key]);
|
||||
hint.hidden = field.key !== 'shineServerLogin' || !hint.textContent;
|
||||
checks.push(runCheck);
|
||||
|
||||
checkButton.addEventListener('click', runCheck);
|
||||
input.addEventListener('input', () => {
|
||||
draft[field.key] = input.value;
|
||||
checkSeq += 1;
|
||||
applyStatus('idle');
|
||||
window.clearTimeout(timers.get(field.key));
|
||||
timers.set(field.key, window.setTimeout(() => {
|
||||
void runCheck();
|
||||
}, 3000));
|
||||
});
|
||||
input.addEventListener('change', () => {
|
||||
void runCheck();
|
||||
});
|
||||
input.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
void runCheck();
|
||||
}
|
||||
});
|
||||
|
||||
head.append(title, checkButton);
|
||||
block.append(head, input, hint);
|
||||
body.append(block);
|
||||
});
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'entry-settings__actions';
|
||||
|
||||
if (isLocalDemoAvailable()) {
|
||||
const localDemoButton = document.createElement('button');
|
||||
localDemoButton.className = 'secondary-btn';
|
||||
localDemoButton.type = 'button';
|
||||
localDemoButton.textContent = t('screens.entry_settings_view.text_008');
|
||||
localDemoButton.addEventListener('click', () => {
|
||||
if (!authorizeLocalDemoSession()) return;
|
||||
navigate('messages-list');
|
||||
});
|
||||
actions.append(localDemoButton);
|
||||
}
|
||||
|
||||
const serverUiButton = document.createElement('button');
|
||||
serverUiButton.className = 'secondary-btn';
|
||||
serverUiButton.type = 'button';
|
||||
serverUiButton.textContent = t('screens.entry_settings_view.text_009');
|
||||
serverUiButton.addEventListener('click', () => {
|
||||
const url = new URL('server-ui.html', window.location.href);
|
||||
window.open(url.toString(), '_blank', 'noopener');
|
||||
});
|
||||
|
||||
const saveButton = document.createElement('button');
|
||||
saveButton.className = 'primary-btn';
|
||||
saveButton.type = 'button';
|
||||
saveButton.textContent = t('screens.entry_settings_view.text_010');
|
||||
saveButton.addEventListener('click', async () => {
|
||||
try {
|
||||
await saveEntrySettings(draft);
|
||||
navigate('start-view');
|
||||
} catch (error) {
|
||||
showToast(toUserMessage(error, t('screens.entry_settings_view.text_012')), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
actions.prepend(saveButton);
|
||||
actions.append(serverUiButton);
|
||||
|
||||
screen.append(
|
||||
createTopBar({
|
||||
title: t('screens.entry_settings_view.text_011'),
|
||||
back: { label: '←', onClick: () => navigate('start-view') },
|
||||
}),
|
||||
body,
|
||||
actions,
|
||||
);
|
||||
|
||||
screen.cleanup = () => {
|
||||
disposed = true;
|
||||
timers.forEach((timerId) => window.clearTimeout(timerId));
|
||||
};
|
||||
|
||||
// Серверы проверяются сразу — зелёный «Доступен» видно без лишних нажатий.
|
||||
checks.forEach((check) => { void check(); });
|
||||
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import { formatDateTime } from '../i18n/format.js';
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { confirmPasswordBoundarySpaces } from '../services/password-boundary-warning.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { bytesToBase64 } from '../services/crypto-utils.js';
|
||||
import { readShineUserPda } from '../services/shine-user-pda-service.js';
|
||||
import { KeyRotationClient, KEY_ROTATION_REASONS } from '../services/key-rotation-service.js';
|
||||
import { formatSol, getBalanceSol, getSolanaWalletFromStoredSecret, transferAllSol } from '../services/solana-wallet-service.js';
|
||||
|
||||
export const pageMeta = { id:'key-rotation-view', get title() { return t('screens.key_rotation_view.text_001'); }, hideToolbar:true };
|
||||
|
||||
const POLL_MS=1800;
|
||||
function h(v){return String(v??'').replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c]));}
|
||||
function short(v){const s=String(v||'');return s.length>20?`${s.slice(0,10)}…${s.slice(-8)}`:s;}
|
||||
function stageText(s){return ({COPYING_CHAIN:t('screens.key_rotation_view.text_037'),CHAIN_READY:t('screens.key_rotation_view.text_038'),ROTATING_PDA:t('screens.key_rotation_view.text_039'),PDA_ROTATED:t('screens.key_rotation_view.text_040'),REBUILDING_SERVER:t('screens.key_rotation_view.text_041'),WALLET_MIGRATION:t('screens.key_rotation_view.text_042'),MESSAGE_MIGRATION:t('screens.key_rotation_view.text_043'),FINALIZING:t('screens.key_rotation_view.text_044'),COMPLETE:t('screens.key_rotation_view.text_045'),NONE:t('screens.key_rotation_view.text_046')})[s]||s;}
|
||||
function input(label,type='password'){const wrap=document.createElement('label');wrap.className='stack';const t=document.createElement('span');t.className='field-label';t.textContent=label;const el=document.createElement('input');el.className='text-input';el.type=type;wrap.append(t,el);return {wrap,el};}
|
||||
|
||||
export function render({navigate,chrome}){
|
||||
const screen=document.createElement('section');screen.className='stack';
|
||||
// До запуска смену можно закрыть; после старта выход назад запрещён.
|
||||
function updateTopbar(status){
|
||||
const canExit=status==='NONE' || status==='COMPLETE';
|
||||
chrome?.setTopbar(createTopBar({title:t('screens.key_rotation_view.text_002'),...(canExit?{back:{label:'←',onClick:()=>navigate('access-keys-view')}}:{})}));
|
||||
window.dispatchEvent(new CustomEvent('shine-key-rotation-active',{detail:{active:!canExit}}));
|
||||
}
|
||||
// Пока статус с сервера не прочитан, не разблокируем навигацию преждевременно.
|
||||
chrome?.setTopbar(createTopBar({title:t('screens.key_rotation_view.text_003')}));
|
||||
const root=document.createElement('div');root.className='stack';screen.append(root);
|
||||
const client=new KeyRotationClient(authService);let disposed=false;let timer=null;let cachedOldBundle=null;let cachedNewBundle=null;
|
||||
const login=String(state.session.login||'').trim(); const storagePwd=String(state.session.storagePwdInMemory||'').trim();
|
||||
const solanaEndpoint=String(state.entrySettings.solanaServer||'').trim();
|
||||
|
||||
async function derive(password){return authService.derivePasswordKeyBundle(login,password,{onProgress:()=>{}});}
|
||||
async function verifyOldPassword(bundle){
|
||||
const pda=await readShineUserPda({login,solanaEndpoint});
|
||||
if(bundle.rootPair.publicKeyB64!==bytesToBase64(pda.rootKey) || bundle.blockchainPair.publicKeyB64!==bytesToBase64(pda.blockchain.blockchainPublicKey) || bundle.clientPair.publicKeyB64!==bytesToBase64(pda.clientKey)) throw new Error(t('screens.key_rotation_view.text_050'));
|
||||
}
|
||||
function setRoot(...nodes){root.replaceChildren(...nodes);}
|
||||
function exitAfterComplete(){updateTopbar('COMPLETE');navigate('access-keys-view');}
|
||||
function statusCard(s){const card=document.createElement('div');card.className='card stack';card.innerHTML=`<strong>${h(stageText(s.rotationStatus))}</strong><span class="meta-muted">${h(s.sourceBlockchainName||'')} → ${h(s.candidateBlockchainName||'')}</span><span class="meta-muted">${th('remaining.html_key_rotation_view.progress')}${Number(s.progressCurrent||0)} / ${Number(s.progressTotal||0)}</span>${s.lastError?`<span>${h(s.lastError)}</span>`:''}`;return card;}
|
||||
function note(text){const c=document.createElement('div');c.className='card';c.textContent=text;return c;}
|
||||
|
||||
async function renderNone(){
|
||||
const head=note(t('screens.key_rotation_view.text_017'));
|
||||
const oldP=input(t('screens.key_rotation_view.text_018')); const newP=input(t('screens.key_rotation_view.text_019')); const new2=input(t('screens.key_rotation_view.text_020'));
|
||||
const reason=document.createElement('select');reason.className='text-input';for(const r of KEY_ROTATION_REASONS){const o=document.createElement('option');o.value=String(r.code);o.textContent=r.label;reason.append(o);}
|
||||
const reasonWrap=document.createElement('label');reasonWrap.className='stack';reasonWrap.innerHTML=t('screens.key_rotation_view.text_051');reasonWrap.append(reason);
|
||||
const comment=document.createElement('textarea');comment.className='text-input';comment.rows=3;comment.maxLength=1024;comment.placeholder=t('screens.key_rotation_view.text_004');
|
||||
const list=document.createElement('div');list.className='stack';const more=document.createElement('button');more.className='secondary-btn';more.type='button';more.textContent=t('screens.key_rotation_view.text_005');
|
||||
let selected=null,before=null,loading=false;
|
||||
async function load(){if(loading)return;loading=true;more.disabled=true;try{const d=await client.getMyBlockchain({beforeBlock:before,limit:100});for(const b of d.blocks||[]){const btn=document.createElement('button');btn.type='button';btn.className='nav-row';btn.innerHTML=`<span class="nav-row__label">#${b.blockNumber} · ${formatDateTime(new Date(Number(b.timestampMs)||0))}</span><span class="nav-row__hint">${short(b.blockHash)}</span>`;btn.addEventListener('click',()=>{selected=b;list.querySelectorAll('button').forEach(x=>x.setAttribute('aria-pressed','false'));btn.setAttribute('aria-pressed','true');});if(selected==null && b.blockNumber===d.tipBlockNumber){selected=b;btn.setAttribute('aria-pressed','true');}list.append(btn);}before=d.nextBeforeBlock;more.hidden=before==null;}finally{loading=false;more.disabled=false;}}
|
||||
more.addEventListener('click',()=>void load());
|
||||
const start=document.createElement('button');start.className='primary-btn';start.type='button';start.textContent=t('screens.key_rotation_view.text_006');
|
||||
const error=document.createElement('div');error.className='meta-muted';
|
||||
start.addEventListener('click',async()=>{start.disabled=true;error.textContent='';try{if(!selected)throw new Error(t('screens.key_rotation_view.text_052'));if(!oldP.el.value||!newP.el.value)throw new Error(t('screens.key_rotation_view.text_053'));if(newP.el.value!==new2.el.value)throw new Error(t('screens.key_rotation_view.text_054'));if(oldP.el.value===newP.el.value)throw new Error(t('screens.key_rotation_view.text_055'));if(!await confirmPasswordBoundarySpaces(newP.el.value)){start.disabled=false;return;}if(!window.confirm(t('screens.key_rotation_view.text_074'))){start.disabled=false;return;}cachedOldBundle=await derive(oldP.el.value);await verifyOldPassword(cachedOldBundle);cachedNewBundle=await derive(newP.el.value);const stateNow=await client.start({newRootKey:cachedNewBundle.rootPair.publicKeyB64,newBlockchainKey:cachedNewBundle.blockchainPair.publicKeyB64,newClientKey:cachedNewBundle.clientPair.publicKeyB64,forkFromBlock:selected.blockNumber,forkFromHash:selected.blockHash,reasonCode:Number(reason.value),comment:comment.value});updateTopbar(stateNow.rotationStatus);await runCopy(stateNow); }catch(e){error.textContent=e?.message||String(e);start.disabled=false;}});
|
||||
setRoot(head,oldP.wrap,newP.wrap,new2.wrap,reasonWrap,comment,list,more,start,error);void load();
|
||||
}
|
||||
|
||||
async function askNewPasswordAndCopy(s){
|
||||
const card=statusCard(s), p=input(t('screens.key_rotation_view.text_021'));const go=document.createElement('button');go.className='primary-btn';go.textContent=t('screens.key_rotation_view.text_007');const err=document.createElement('div');err.className='meta-muted';go.addEventListener('click',async()=>{go.disabled=true;try{cachedNewBundle=await derive(p.el.value);if(cachedNewBundle.blockchainPair.publicKeyB64!==s.newBlockchainKey)throw new Error(t('screens.key_rotation_view.text_056'));await runCopy(s);}catch(e){err.textContent=e?.message||e;go.disabled=false;}});setRoot(card,note(t('screens.key_rotation_view.text_022')),p.wrap,go,err);
|
||||
}
|
||||
|
||||
async function runCopy(s){
|
||||
const card=statusCard(s), info=note(t('screens.key_rotation_view.text_023'));setRoot(card,info);
|
||||
try{await client.copyCandidateChain({rotation:s,newBundle:cachedNewBundle,onProgress:({current,total})=>{card.querySelectorAll('.meta-muted')[1].textContent=t('screens.key_rotation_view.text_065', { value1: current, value2: total });}});await client.waitUntilPublished({onProgress:({current,total})=>{card.querySelectorAll('.meta-muted')[1].textContent=t('screens.key_rotation_view.text_066', { value1: current, value2: total });}});await client.finishChain();await refresh();}catch(e){root.append(note(e?.message||String(e)));const retry=document.createElement('button');retry.className='primary-btn';retry.textContent=t('screens.key_rotation_view.text_008');retry.addEventListener('click',()=>void refresh());root.append(retry);}
|
||||
}
|
||||
|
||||
async function renderChainReady(s){
|
||||
if(cachedOldBundle&&cachedNewBundle){
|
||||
setRoot(statusCard(s),note(t('screens.key_rotation_view.text_024')));
|
||||
try{const next=await client.rotatePda({login,solanaEndpoint,oldBundle:cachedOldBundle,newBundle:cachedNewBundle,storagePwd});if(next?.rotationStatus==='CHAIN_READY'){pollView(next);return;}await refresh();return;}catch(e){const latest=await client.status().catch(()=>null);if(latest?.rotationStatus!==s.rotationStatus&&latest?.rotationStatus){await refresh();return;}root.append(note(e?.message||String(e)));}
|
||||
}
|
||||
const oldP=input(t('screens.key_rotation_view.text_025'));const newP=input(t('screens.key_rotation_view.text_026'));const go=document.createElement('button');go.className='primary-btn';go.textContent=t('screens.key_rotation_view.text_009');const err=document.createElement('div');err.className='meta-muted';
|
||||
go.addEventListener('click',async()=>{go.disabled=true;try{const oldCandidate=await derive(oldP.el.value);const newCandidate=await derive(newP.el.value);const next=await client.rotatePda({login,solanaEndpoint,oldBundle:oldCandidate,newBundle:newCandidate,storagePwd});cachedOldBundle=oldCandidate;cachedNewBundle=newCandidate;if(next?.rotationStatus==='CHAIN_READY'){pollView(next);return;}await refresh();}catch(e){err.textContent=e?.message||String(e);go.disabled=false;void client.status().then(latest=>{if(latest.rotationStatus!==s.rotationStatus)void refresh();}).catch(()=>{});}});setRoot(statusCard(s),note(t('screens.key_rotation_view.text_027')),oldP.wrap,newP.wrap,go,err);
|
||||
}
|
||||
|
||||
function pollView(s){setRoot(statusCard(s),note(s.rotationStatus==='REBUILDING_SERVER'?t('screens.key_rotation_view.text_047'):t('screens.key_rotation_view.text_048')));timer=setTimeout(()=>void refresh(),POLL_MS);}
|
||||
async function renderWalletMigration(s){
|
||||
const oldP=cachedOldBundle?null:input(t('screens.key_rotation_view.text_028'));
|
||||
const newP=cachedNewBundle?null:input(t('screens.key_rotation_view.text_029'));
|
||||
const info=note(t('screens.key_rotation_view.text_030'));
|
||||
const warning=note(t('screens.key_rotation_view.text_031'));
|
||||
const details=document.createElement('div');details.className='card stack';details.innerHTML=t('screens.key_rotation_view.text_057');
|
||||
const refreshBalance=document.createElement('button');refreshBalance.className='secondary-btn';refreshBalance.type='button';refreshBalance.textContent=t('screens.key_rotation_view.text_010');
|
||||
const transfer=document.createElement('button');transfer.className='primary-btn';transfer.type='button';transfer.textContent=t('screens.key_rotation_view.text_011');
|
||||
const skip=document.createElement('button');skip.className='secondary-btn';skip.type='button';skip.textContent=t('screens.key_rotation_view.text_012');
|
||||
const continueButton=document.createElement('button');continueButton.className='primary-btn';continueButton.type='button';continueButton.textContent=t('screens.key_rotation_view.text_013');continueButton.style.display='none';
|
||||
const err=document.createElement('div');err.className='meta-muted';
|
||||
let oldWallet=null,newWallet=null,oldBalance=null;
|
||||
let transferFinished=false;
|
||||
|
||||
const updateActions=()=>{
|
||||
transfer.style.display=transferFinished?'none':'';
|
||||
skip.style.display=transferFinished?'none':'';
|
||||
continueButton.style.display=transferFinished?'':'none';
|
||||
};
|
||||
|
||||
const resolveBundles=async()=>{
|
||||
const oldCandidate=cachedOldBundle||(oldP?.el.value?await derive(oldP.el.value):null);
|
||||
const newCandidate=cachedNewBundle||(newP?.el.value?await derive(newP.el.value):null);
|
||||
if(!oldCandidate||!newCandidate)throw new Error(t('screens.key_rotation_view.text_058'));
|
||||
if(String(oldCandidate.blockchainPair?.publicKeyB64||'')!==String(s.oldBlockchainKey||''))throw new Error(t('screens.key_rotation_view.text_059'));
|
||||
if(String(newCandidate.blockchainPair?.publicKeyB64||'')!==String(s.newBlockchainKey||''))throw new Error(t('screens.key_rotation_view.text_060'));
|
||||
cachedOldBundle=oldCandidate;cachedNewBundle=newCandidate;
|
||||
};
|
||||
|
||||
const prepareWallets=async()=>{
|
||||
await resolveBundles();
|
||||
oldWallet=await getSolanaWalletFromStoredSecret(cachedOldBundle.blockchainPair.privatePkcs8B64);
|
||||
newWallet=await getSolanaWalletFromStoredSecret(cachedNewBundle.blockchainPair.privatePkcs8B64);
|
||||
const [oldB,newB]=await Promise.all([
|
||||
getBalanceSol({endpoint:solanaEndpoint,address:oldWallet.address}),
|
||||
getBalanceSol({endpoint:solanaEndpoint,address:newWallet.address}),
|
||||
]);
|
||||
oldBalance=oldB;
|
||||
details.innerHTML=`<strong>${th('screens.key_rotation_view.text_072')}</strong><span class="meta-muted">${h(oldWallet.address)}</span><span>${h(formatSol(oldB.sol,9))} SOL</span><strong>${th('screens.key_rotation_view.text_073')}</strong><span class="meta-muted">${h(newWallet.address)}</span><span>${h(formatSol(newB.sol,9))} SOL</span>`;
|
||||
if(!transferFinished)transfer.disabled=false;
|
||||
};
|
||||
|
||||
refreshBalance.addEventListener('click',async()=>{refreshBalance.disabled=true;if(!transferFinished)transfer.disabled=true;err.textContent='';try{await prepareWallets();}catch(e){err.textContent=e?.message||String(e);}finally{refreshBalance.disabled=false;}});
|
||||
transfer.addEventListener('click',async()=>{transfer.disabled=true;refreshBalance.disabled=true;skip.disabled=true;err.textContent='';try{
|
||||
if(!oldWallet||!newWallet||!oldBalance)await prepareWallets();
|
||||
if(Number(oldBalance?.lamports||0)>0){
|
||||
const result=await transferAllSol({endpoint:solanaEndpoint,fromKeypair:oldWallet.keypair,toAddress:newWallet.address});
|
||||
details.insertAdjacentHTML('beforeend',`<span class="meta-muted">${result.skipped?t('screens.key_rotation_view.text_049'):t('screens.key_rotation_view.text_067', { value1: h(formatSol(Number(result.lamports)/1_000_000_000,9)), value2: h(result.signature) })}</span>`);
|
||||
}else{
|
||||
details.insertAdjacentHTML('beforeend', `<span class="meta-muted">${th('remaining.html_key_rotation_view.the_old_wallet_has_no_sol_to_transfer')}</span>`);
|
||||
}
|
||||
transferFinished=true;
|
||||
updateActions();
|
||||
}catch(e){err.textContent=e?.message||String(e);transfer.disabled=false;skip.disabled=false;}finally{refreshBalance.disabled=false;}});
|
||||
continueButton.addEventListener('click',async()=>{continueButton.disabled=true;refreshBalance.disabled=true;err.textContent='';try{
|
||||
const next=await client.continueRotation({walletMigrationStatus:'COMPLETE'});
|
||||
if(String(next?.rotationStatus||'')==='COMPLETE'){exitAfterComplete();return;}
|
||||
await refresh();
|
||||
}catch(e){err.textContent=e?.message||String(e);continueButton.disabled=false;refreshBalance.disabled=false;}});
|
||||
skip.addEventListener('click',async()=>{skip.disabled=true;transfer.disabled=true;refreshBalance.disabled=true;err.textContent='';try{
|
||||
const next=await client.continueRotation({walletMigrationStatus:'SKIPPED'});
|
||||
if(String(next?.rotationStatus||'')==='COMPLETE'){exitAfterComplete();return;}
|
||||
await refresh();
|
||||
}catch(e){err.textContent=e?.message||String(e);skip.disabled=false;transfer.disabled=!oldWallet;refreshBalance.disabled=false;}});
|
||||
|
||||
updateActions();
|
||||
const nodes=[statusCard(s),info,warning];if(oldP)nodes.push(oldP.wrap);if(newP)nodes.push(newP.wrap);nodes.push(details,refreshBalance,transfer,skip,continueButton,err);setRoot(...nodes);
|
||||
if(cachedOldBundle&&cachedNewBundle)void prepareWallets().catch(e=>{err.textContent=e?.message||String(e);});
|
||||
}
|
||||
|
||||
async function renderMessageMigration(s){
|
||||
const oldP=cachedOldBundle?null:input(t('screens.key_rotation_view.text_032'));
|
||||
const newP=cachedNewBundle?null:input(t('screens.key_rotation_view.text_033'));
|
||||
const progress=note(t('screens.key_rotation_view.text_034'));
|
||||
const go=document.createElement('button');go.className='primary-btn';go.type='button';go.textContent=t('screens.key_rotation_view.text_014');
|
||||
const err=document.createElement('div');err.className='meta-muted';
|
||||
const resolveBundles=async()=>{
|
||||
const oldCandidate=cachedOldBundle||(oldP?.el.value?await derive(oldP.el.value):null);
|
||||
const newCandidate=cachedNewBundle||(newP?.el.value?await derive(newP.el.value):null);
|
||||
if(!oldCandidate||!newCandidate)throw new Error(t('screens.key_rotation_view.text_061'));
|
||||
if(String(oldCandidate.clientPair?.publicKeyB64||'')!==String(s.oldClientKey||''))throw new Error(t('screens.key_rotation_view.text_062'));
|
||||
if(String(newCandidate.clientPair?.publicKeyB64||'')!==String(s.newClientKey||''))throw new Error(t('screens.key_rotation_view.text_063'));
|
||||
cachedOldBundle=oldCandidate;cachedNewBundle=newCandidate;
|
||||
};
|
||||
const run=async()=>{
|
||||
go.disabled=true;err.textContent='';await resolveBundles();
|
||||
const cutoff=Number(s.updatedAtMs||0);if(!cutoff)throw new Error(t('screens.key_rotation_view.text_064'));
|
||||
let processed=0;
|
||||
const contacts=await authService.listContacts();
|
||||
const items=Array.isArray(contacts?.dialogs)?contacts.dialogs:Array.isArray(contacts)?contacts:[];
|
||||
const peers=[...new Set(items.map(x=>String(x?.login||x?.peerLogin||'').trim()).filter(Boolean))];
|
||||
for(let i=0;i<peers.length;i++){
|
||||
const peer=peers[i];
|
||||
while(true){
|
||||
progress.textContent=t('screens.key_rotation_view.text_068', { value1: processed, value2: i+1, value3: peers.length, value4: peer });
|
||||
const page=await authService.getDirectMessages({peerLogin:peer,limit:100,reencryptedBeforeMs:cutoff});
|
||||
const messages=Array.isArray(page?.messages)?page.messages:[];
|
||||
if(messages.length===0)break;
|
||||
for(const m of messages){
|
||||
const blobB64=await authService.buildReencryptedLocalDm({
|
||||
blobB64:m.blobB64,login,
|
||||
oldClientPrivatePkcs8B64:cachedOldBundle.clientPair.privatePkcs8B64,
|
||||
newClientPrivatePkcs8B64:cachedNewBundle.clientPair.privatePkcs8B64,
|
||||
reencryptedAtMs:cutoff,
|
||||
});
|
||||
await authService.reencryptDirectMessage({blobB64});processed++;
|
||||
progress.textContent=t('screens.key_rotation_view.text_069', { value1: processed, value2: i+1, value3: peers.length, value4: peer });
|
||||
}
|
||||
}
|
||||
}
|
||||
const next=await client.continueRotation({});
|
||||
if(String(next?.rotationStatus||'')==='COMPLETE'){exitAfterComplete();return;}
|
||||
await refresh();
|
||||
};
|
||||
go.addEventListener('click',()=>void run().catch(e=>{err.textContent=e?.message||String(e);go.disabled=false;}));
|
||||
const nodes=[statusCard(s),note(t('screens.key_rotation_view.text_035')),progress];if(oldP)nodes.push(oldP.wrap);if(newP)nodes.push(newP.wrap);nodes.push(go,err);setRoot(...nodes);
|
||||
if(cachedOldBundle&&cachedNewBundle)void run().catch(e=>{err.textContent=e?.message||String(e);go.disabled=false;});
|
||||
}
|
||||
|
||||
async function refresh(){if(disposed)return;if(timer){clearTimeout(timer);timer=null;}try{const s=await client.status();const st=String(s.rotationStatus||'NONE');updateTopbar(st);if(st==='NONE'){await renderNone();return;}if(st==='COPYING_CHAIN'){if(cachedNewBundle)await runCopy(s);else await askNewPasswordAndCopy(s);return;}if(st==='CHAIN_READY'){await renderChainReady(s);return;}if(['ROTATING_PDA','PDA_ROTATED','REBUILDING_SERVER'].includes(st)){pollView(s);return;}if(st==='WALLET_MIGRATION'){await renderWalletMigration(s);return;}if(st==='MESSAGE_MIGRATION'){await renderMessageMigration(s);return;}if(st==='FINALIZING'){const next=await client.continueRotation({});if(String(next?.rotationStatus||'')==='COMPLETE'){exitAfterComplete();return;}await refresh();return;}if(st==='COMPLETE'){setRoot(note(t('screens.key_rotation_view.text_036')),Object.assign(document.createElement('button'),{className:'primary-btn',textContent:t('screens.key_rotation_view.text_015'),onclick:exitAfterComplete}));return;}setRoot(note(t('screens.key_rotation_view.text_070', { value1: st })));}catch(e){const retry=document.createElement('button');retry.type='button';retry.className='primary-btn';retry.textContent=t('screens.key_rotation_view.text_016');retry.addEventListener('click',()=>void refresh());setRoot(note(t('screens.key_rotation_view.text_071', { value1: e?.message||e })),retry);timer=setTimeout(()=>void refresh(),5000);}}
|
||||
void refresh();screen.cleanup=()=>{disposed=true;if(timer)clearTimeout(timer);};return screen;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { saveEntryLanguage, state } from '../state.js';
|
||||
import { getLanguage, getLanguages, t } from '../i18n/index.js';
|
||||
|
||||
export const pageMeta = { id: 'language-view', get title() { return t('screens.language_view.text_001'); } };
|
||||
|
||||
function resolveReturnPage() {
|
||||
const stored = String(sessionStorage.getItem('shine-language-return-page') || '').trim();
|
||||
return stored === 'start-view' ? 'start-view' : 'settings-view';
|
||||
}
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack language-screen';
|
||||
const returnPage = resolveReturnPage();
|
||||
let pendingLanguage = getLanguage();
|
||||
|
||||
const topbar = createTopBar({
|
||||
title: t('language.menu'),
|
||||
back: { label: '←', onClick: () => {
|
||||
sessionStorage.removeItem('shine-language-return-page');
|
||||
navigate(returnPage);
|
||||
} },
|
||||
});
|
||||
const embedTopbar = !state.session.isAuthorized;
|
||||
if (!embedTopbar) chrome?.setTopbar(topbar);
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'nav-list language-list';
|
||||
card.setAttribute('role', 'radiogroup');
|
||||
card.setAttribute('aria-label', t('language.selector'));
|
||||
getLanguages().forEach(({ code, name: label }) => {
|
||||
const row = document.createElement('button');
|
||||
row.type = 'button';
|
||||
row.className = 'nav-row language-row';
|
||||
row.setAttribute('role', 'radio');
|
||||
row.setAttribute('aria-checked', String(pendingLanguage === code));
|
||||
row.innerHTML = `<span class="nav-row__label"></span>`;
|
||||
row.querySelector('.nav-row__label').textContent = label;
|
||||
row.addEventListener('click', async () => {
|
||||
if (card.dataset.switching === 'true') return;
|
||||
card.dataset.switching = 'true';
|
||||
const applied = await saveEntryLanguage(code);
|
||||
if (!applied) {
|
||||
delete card.dataset.switching;
|
||||
return;
|
||||
}
|
||||
pendingLanguage = code;
|
||||
sessionStorage.removeItem('shine-language-return-page');
|
||||
navigate(returnPage);
|
||||
});
|
||||
card.append(row);
|
||||
});
|
||||
|
||||
if (embedTopbar) screen.append(topbar);
|
||||
screen.append(card);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import {
|
||||
authService,
|
||||
authorizeSession,
|
||||
consumeAuthReturnPage,
|
||||
isAddingProfileLogin,
|
||||
clearAuthMessages,
|
||||
clearBrowserClientData,
|
||||
refreshSessions,
|
||||
setAuthBusy,
|
||||
setAuthError,
|
||||
setAuthInfo,
|
||||
state,
|
||||
terminateCurrentSession,
|
||||
} from '../state.js';
|
||||
import { clearClientAuthData, saveEncryptedUserSecrets } from '../services/key-vault.js';
|
||||
import { clearStoredMessages } from '../services/message-store.js';
|
||||
import {
|
||||
describeTransferKeys,
|
||||
parseKeyTransferText,
|
||||
} from '../services/qr-key-transfer-service.js';
|
||||
import { actionErrorText, toUserMessage } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'login-camera-view', get title() { return t('screens.login_camera_view.text_001'); }, showAppChrome: false };
|
||||
|
||||
function canUseBarcodeDetector() {
|
||||
return typeof window.BarcodeDetector === 'function';
|
||||
}
|
||||
|
||||
async function createQrDetector() {
|
||||
if (!canUseBarcodeDetector()) return null;
|
||||
try {
|
||||
const formats = await window.BarcodeDetector.getSupportedFormats?.();
|
||||
if (Array.isArray(formats) && !formats.includes('qr_code')) return null;
|
||||
} catch {
|
||||
// Некоторые браузеры не реализуют getSupportedFormats, но сам detector работает.
|
||||
}
|
||||
return new window.BarcodeDetector({ formats: ['qr_code'] });
|
||||
}
|
||||
|
||||
function setStatus(statusEl, message, kind = 'info') {
|
||||
statusEl.classList.toggle('is-unavailable', kind === 'error');
|
||||
statusEl.classList.toggle('is-available', kind !== 'error');
|
||||
statusEl.textContent = message;
|
||||
statusEl.style.display = message ? '' : 'none';
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value || '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function renderParsedTransfer(resultEl, transfer) {
|
||||
const keys = describeTransferKeys(transfer.keys);
|
||||
resultEl.innerHTML = `
|
||||
<p class="meta-muted">${th('screens.login_camera_view.text_012')} <strong>${escapeHtml(transfer.login)}</strong></p>
|
||||
<p class="meta-muted">${th('screens.login_camera_view.text_013')} <strong>${escapeHtml(keys.join(', '))}</strong></p>
|
||||
<p class="meta-muted">${th('screens.login_camera_view.text_014')}</p>
|
||||
`;
|
||||
}
|
||||
|
||||
export function render({ navigate }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
clearAuthMessages();
|
||||
|
||||
const frame = document.createElement('div');
|
||||
frame.className = 'camera-shell';
|
||||
frame.innerHTML = `
|
||||
<video class="camera-video" autoplay playsinline muted></video>
|
||||
<div class="camera-frame"></div>
|
||||
<div class="camera-hint">${th('screens.login_camera_view.text_015')}</div>
|
||||
<div class="camera-error" id="login-camera-error" style="display:none;"></div>
|
||||
`;
|
||||
|
||||
const manualCard = document.createElement('details');
|
||||
manualCard.className = 'card stack';
|
||||
manualCard.innerHTML = `
|
||||
<summary>${th('screens.login_camera_view.text_016')}</summary>
|
||||
<textarea class="input" id="login-qr-manual" rows="4" placeholder="shine-key-transfer-v1:..."></textarea>
|
||||
<button class="ghost-btn" type="button" id="login-qr-manual-parse">${th('screens.login_camera_view.text_017')}</button>
|
||||
`;
|
||||
|
||||
const resultCard = document.createElement('div');
|
||||
resultCard.className = 'card stack';
|
||||
resultCard.style.display = 'none';
|
||||
resultCard.innerHTML = `
|
||||
<div id="login-qr-result"></div>
|
||||
<div class="row">
|
||||
<button class="ghost-btn" type="button" id="login-qr-cancel">${th('screens.login_camera_view.text_018')}</button>
|
||||
<button class="primary-btn" type="button" id="login-qr-confirm">${th('screens.login_camera_view.text_019')}</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const status = document.createElement('p');
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.style.display = 'none';
|
||||
|
||||
const backButton = document.createElement('button');
|
||||
backButton.className = 'ghost-btn';
|
||||
backButton.type = 'button';
|
||||
backButton.textContent = t('screens.login_camera_view.text_002');
|
||||
|
||||
const video = frame.querySelector('video');
|
||||
const cameraError = frame.querySelector('#login-camera-error');
|
||||
const manualInput = manualCard.querySelector('#login-qr-manual');
|
||||
const parseManualButton = manualCard.querySelector('#login-qr-manual-parse');
|
||||
const resultEl = resultCard.querySelector('#login-qr-result');
|
||||
const cancelButton = resultCard.querySelector('#login-qr-cancel');
|
||||
const confirmButton = resultCard.querySelector('#login-qr-confirm');
|
||||
|
||||
let stream = null;
|
||||
let detector = null;
|
||||
let scanTimer = 0;
|
||||
let scannedTransfer = null;
|
||||
let stopped = false;
|
||||
|
||||
const stopCamera = () => {
|
||||
stopped = true;
|
||||
if (scanTimer) {
|
||||
window.clearTimeout(scanTimer);
|
||||
scanTimer = 0;
|
||||
}
|
||||
if (stream) {
|
||||
stream.getTracks().forEach((track) => track.stop());
|
||||
stream = null;
|
||||
}
|
||||
};
|
||||
|
||||
const showTransfer = (transfer) => {
|
||||
scannedTransfer = transfer;
|
||||
stopCamera();
|
||||
renderParsedTransfer(resultEl, transfer);
|
||||
resultCard.style.display = '';
|
||||
setStatus(status, '', 'info');
|
||||
};
|
||||
|
||||
const parseTransferText = (text) => {
|
||||
try {
|
||||
const transfer = parseKeyTransferText(text);
|
||||
if (!transfer.keys.clientKey || !transfer.keys.blockchainKey) {
|
||||
throw new Error(t('screens.login_camera_view.text_007'));
|
||||
}
|
||||
showTransfer(transfer);
|
||||
} catch (error) {
|
||||
setStatus(status, error?.message || t('screens.login_camera_view.text_008'), 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const scanLoop = async () => {
|
||||
if (stopped || !detector || !video || video.readyState < 2) {
|
||||
if (!stopped) scanTimer = window.setTimeout(scanLoop, 250);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const codes = await detector.detect(video);
|
||||
const text = String(codes?.[0]?.rawValue || '').trim();
|
||||
if (text) {
|
||||
parseTransferText(text);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// Ошибки отдельных кадров игнорируем, камера продолжит сканирование.
|
||||
}
|
||||
if (!stopped) scanTimer = window.setTimeout(scanLoop, 300);
|
||||
};
|
||||
|
||||
const startCamera = async () => {
|
||||
try {
|
||||
detector = await createQrDetector();
|
||||
if (!detector) {
|
||||
throw new Error(t('screens.login_camera_view.text_009'));
|
||||
}
|
||||
if (!navigator.mediaDevices?.getUserMedia) {
|
||||
throw new Error(t('screens.login_camera_view.text_010'));
|
||||
}
|
||||
stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' }, audio: false });
|
||||
video.srcObject = stream;
|
||||
await video.play?.();
|
||||
scanLoop();
|
||||
} catch (error) {
|
||||
cameraError.textContent = actionErrorText(t('screens.login_camera_view.text_004'), error);
|
||||
cameraError.style.display = '';
|
||||
setStatus(status, cameraError.textContent, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
parseManualButton.addEventListener('click', () => parseTransferText(manualInput.value));
|
||||
cancelButton.addEventListener('click', () => {
|
||||
scannedTransfer = null;
|
||||
resultCard.style.display = 'none';
|
||||
stopped = false;
|
||||
void startCamera();
|
||||
});
|
||||
confirmButton.addEventListener('click', async () => {
|
||||
if (!scannedTransfer) return;
|
||||
confirmButton.disabled = true;
|
||||
cancelButton.disabled = true;
|
||||
setAuthBusy(true);
|
||||
setAuthError('');
|
||||
setStatus(status, t('screens.login_camera_view.text_005'), 'info');
|
||||
try {
|
||||
await authService.reconnect(state.entrySettings.shineServer);
|
||||
const session = await authService.createSessionFromImportedSecrets(scannedTransfer.login, scannedTransfer.keys);
|
||||
const addingProfile = isAddingProfileLogin();
|
||||
if (!addingProfile) {
|
||||
await terminateCurrentSession({ closeServerSession: true });
|
||||
clearBrowserClientData();
|
||||
await clearClientAuthData().catch(() => {});
|
||||
}
|
||||
await clearStoredMessages(session.login).catch(() => {});
|
||||
await saveEncryptedUserSecrets(session.login, session.storagePwd, scannedTransfer.keys);
|
||||
await authService.persistSessionMaterial(session.login, session.sessionMaterial);
|
||||
const resumed = await authService.resumeSession(session.login, session.sessionId);
|
||||
authorizeSession({
|
||||
login: resumed.login || session.login,
|
||||
sessionId: resumed.sessionId || session.sessionId,
|
||||
storagePwd: resumed.storagePwd || session.storagePwd,
|
||||
});
|
||||
state.loginDraft.login = resumed.login || session.login;
|
||||
state.loginDraft.password = '';
|
||||
await refreshSessions();
|
||||
setAuthInfo(t('screens.login_camera_view.text_011', { value1: resumed.login || session.login }));
|
||||
navigate(consumeAuthReturnPage('profile-view'));
|
||||
} catch (error) {
|
||||
const message = toUserMessage(error, t('screens.login_camera_view.text_006'));
|
||||
setAuthError(message);
|
||||
setStatus(status, message, 'error');
|
||||
} finally {
|
||||
setAuthBusy(false);
|
||||
confirmButton.disabled = false;
|
||||
cancelButton.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
backButton.addEventListener('click', () => {
|
||||
stopCamera();
|
||||
navigate('login-view');
|
||||
});
|
||||
|
||||
screen.append(
|
||||
createTopBar({
|
||||
title: t('screens.login_camera_view.text_003'),
|
||||
back: {
|
||||
label: '←',
|
||||
onClick: () => {
|
||||
stopCamera();
|
||||
navigate('login-view');
|
||||
},
|
||||
},
|
||||
}),
|
||||
frame,
|
||||
manualCard,
|
||||
resultCard,
|
||||
status,
|
||||
backButton,
|
||||
);
|
||||
|
||||
void startCamera();
|
||||
screen.cleanup = stopCamera;
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import {
|
||||
authService,
|
||||
authorizeSession,
|
||||
consumeAuthReturnPage,
|
||||
isAddingProfileLogin,
|
||||
clearAuthMessages,
|
||||
clearBrowserClientData,
|
||||
refreshSessions,
|
||||
setAuthBusy,
|
||||
setAuthError,
|
||||
setAuthInfo,
|
||||
state,
|
||||
terminateCurrentSession,
|
||||
} from '../state.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import {
|
||||
decryptPairingPayloadFromEnvelope,
|
||||
createRequesterPairingMaterial,
|
||||
formatPairingShortCode,
|
||||
} from '../services/device-pairing-service.js';
|
||||
import { clearClientAuthData, saveEncryptedUserSecrets } from '../services/key-vault.js';
|
||||
import { clearStoredMessages } from '../services/message-store.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'login-other-device-view', get title() { return t('screens.login_other_device_view.text_001'); }, showAppChrome: false };
|
||||
|
||||
function formatRemaining(ms) {
|
||||
const safe = Math.max(0, Math.ceil(Number(ms || 0) / 1000));
|
||||
return `${Math.floor(safe / 60)}:${String(safe % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
export function render({ navigate }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack pairing-login';
|
||||
let pollTimer = 0;
|
||||
let countdownTimer = 0;
|
||||
let activePairingId = '';
|
||||
let requesterMaterial = null;
|
||||
let activeExpiresAtMs = 0;
|
||||
let isDisposed = false;
|
||||
|
||||
clearAuthMessages();
|
||||
|
||||
const who = document.createElement('p');
|
||||
who.className = 'pairing-who';
|
||||
|
||||
// Код и то, что с ним делать.
|
||||
const codeBlock = document.createElement('div');
|
||||
codeBlock.className = 'pairing-code-block';
|
||||
codeBlock.innerHTML = `
|
||||
<div class="pairing-code-card">
|
||||
<p class="pairing-code-card__label">${th('screens.login_other_device_view.text_032')}</p>
|
||||
<div class="pairing-code" id="pairing-short-code"></div>
|
||||
<div class="pairing-timer" aria-live="off">
|
||||
<div class="pairing-timer__bar"><span id="pairing-timer-fill"></span></div>
|
||||
<span class="pairing-timer__text" id="pairing-timer-text"></span>
|
||||
</div>
|
||||
<p class="pairing-online" id="pairing-online"></p>
|
||||
</div>
|
||||
<ol class="pairing-steps">
|
||||
<li>${th('screens.login_other_device_view.text_033')}</li>
|
||||
<li>${th('screens.login_other_device_view.text_034')}</li>
|
||||
<li>${th('screens.login_other_device_view.text_035')}</li>
|
||||
</ol>
|
||||
<p class="pairing-waiting"><span class="pairing-spinner" aria-hidden="true"></span>${th('screens.login_other_device_view.text_036')}</p>
|
||||
`;
|
||||
|
||||
// Сообщение о ходе дела или об ошибке — вместо кода.
|
||||
const notice = document.createElement('div');
|
||||
notice.className = 'pairing-notice';
|
||||
notice.setAttribute('role', 'status');
|
||||
const noticeSpinner = document.createElement('span');
|
||||
noticeSpinner.className = 'pairing-spinner';
|
||||
noticeSpinner.setAttribute('aria-hidden', 'true');
|
||||
const noticeText = document.createElement('p');
|
||||
notice.append(noticeSpinner, noticeText);
|
||||
|
||||
// Дополнительный пароль pairing пока не используется в активном UI.
|
||||
|
||||
const startBtn = document.createElement('button');
|
||||
startBtn.className = 'primary-btn';
|
||||
startBtn.type = 'button';
|
||||
startBtn.textContent = t('screens.login_other_device_view.text_002');
|
||||
|
||||
const loginInput = { value: String(state.loginDraft.login || '').trim() };
|
||||
who.textContent = loginInput.value ? t('screens.login_other_device_view.text_026', { value1: loginInput.value }) : '';
|
||||
const shortCodeEl = codeBlock.querySelector('#pairing-short-code');
|
||||
const timerFillEl = codeBlock.querySelector('#pairing-timer-fill');
|
||||
const timerTextEl = codeBlock.querySelector('#pairing-timer-text');
|
||||
const onlineEl = codeBlock.querySelector('#pairing-online');
|
||||
let activeStartedAtMs = 0;
|
||||
|
||||
// Этапы: creating → code → approving; retry используется для истечения, отклонения и ошибок.
|
||||
const showStage = (stage, message = '', { error = false, action = '' } = {}) => {
|
||||
codeBlock.hidden = stage !== 'code';
|
||||
notice.hidden = stage === 'code';
|
||||
noticeSpinner.hidden = !(stage === 'creating' || stage === 'approving');
|
||||
noticeText.textContent = message;
|
||||
notice.classList.toggle('is-error', error);
|
||||
startBtn.hidden = stage !== 'retry';
|
||||
if (action) startBtn.textContent = action;
|
||||
};
|
||||
|
||||
const stopPolling = () => {
|
||||
if (pollTimer) {
|
||||
window.clearTimeout(pollTimer);
|
||||
pollTimer = 0;
|
||||
}
|
||||
};
|
||||
|
||||
const stopCountdown = () => {
|
||||
if (countdownTimer) {
|
||||
window.clearInterval(countdownTimer);
|
||||
countdownTimer = 0;
|
||||
}
|
||||
};
|
||||
|
||||
const updateCountdown = () => {
|
||||
const leftMs = activeExpiresAtMs - Date.now();
|
||||
if (leftMs <= 0) {
|
||||
stopPolling();
|
||||
stopCountdown();
|
||||
activePairingId = '';
|
||||
activeExpiresAtMs = 0;
|
||||
startBtn.disabled = false;
|
||||
showStage('retry', t('screens.login_other_device_view.text_004'), { error: true, action: t('screens.login_other_device_view.text_013') });
|
||||
return;
|
||||
}
|
||||
const totalMs = Math.max(1, activeExpiresAtMs - activeStartedAtMs);
|
||||
timerFillEl.style.width = `${Math.min(100, (leftMs / totalMs) * 100).toFixed(1)}%`;
|
||||
timerTextEl.textContent = formatRemaining(leftMs);
|
||||
};
|
||||
|
||||
const startCountdown = (expiresAtMs) => {
|
||||
activeExpiresAtMs = Number(expiresAtMs || 0);
|
||||
activeStartedAtMs = Date.now();
|
||||
stopCountdown();
|
||||
updateCountdown();
|
||||
countdownTimer = window.setInterval(updateCountdown, 1000);
|
||||
};
|
||||
|
||||
const clearActivePairing = () => {
|
||||
stopPolling();
|
||||
stopCountdown();
|
||||
activePairingId = '';
|
||||
activeExpiresAtMs = 0;
|
||||
};
|
||||
|
||||
const finalizeAuthorizedLogin = async (keys, login) => {
|
||||
if (!String(keys?.clientKey || '').trim() || !String(keys?.blockchainKey || '').trim()) {
|
||||
throw new Error(t('screens.login_other_device_view.text_022'));
|
||||
}
|
||||
const session = await authService.createSessionFromImportedSecrets(login, keys);
|
||||
const addingProfile = isAddingProfileLogin();
|
||||
if (!addingProfile) {
|
||||
await terminateCurrentSession({ closeServerSession: true, notifySessionReset: false });
|
||||
clearBrowserClientData();
|
||||
await clearClientAuthData().catch(() => {});
|
||||
}
|
||||
await clearStoredMessages(session.login).catch(() => {});
|
||||
await saveEncryptedUserSecrets(session.login, session.storagePwd, keys);
|
||||
await authService.persistSessionMaterial(session.login, session.sessionMaterial);
|
||||
const resumed = await authService.resumeSession(session.login, session.sessionId);
|
||||
authorizeSession({
|
||||
login: resumed.login || session.login,
|
||||
sessionId: resumed.sessionId || session.sessionId,
|
||||
storagePwd: resumed.storagePwd || session.storagePwd,
|
||||
});
|
||||
state.loginDraft.login = resumed.login || session.login;
|
||||
state.loginDraft.password = '';
|
||||
await refreshSessions();
|
||||
setAuthInfo(t('screens.login_other_device_view.text_027', { value1: resumed.login || session.login }));
|
||||
showToast(t('screens.login_other_device_view.text_028', { value1: resumed.login || session.login }));
|
||||
navigate(consumeAuthReturnPage('profile-view'));
|
||||
};
|
||||
|
||||
const finalizeAuthorizedSessionAttach = async (payloadSession, login, requesterKeys) => {
|
||||
const sessionId = String(payloadSession?.sessionId || '').trim();
|
||||
const storagePwd = String(payloadSession?.storagePwd || '').trim();
|
||||
if (!sessionId || !storagePwd) {
|
||||
throw new Error(t('screens.login_other_device_view.text_023'));
|
||||
}
|
||||
const sessionMaterial = {
|
||||
sessionId,
|
||||
sessionKey: requesterKeys.sessionKey,
|
||||
sessionPrivPkcs8: requesterKeys.sessionPrivPkcs8,
|
||||
sessionType: Number(payloadSession?.sessionType || 50) || 50,
|
||||
};
|
||||
|
||||
const addingProfile = isAddingProfileLogin();
|
||||
if (!addingProfile) {
|
||||
await terminateCurrentSession({ closeServerSession: true, notifySessionReset: false });
|
||||
clearBrowserClientData();
|
||||
await clearClientAuthData().catch(() => {});
|
||||
}
|
||||
await clearStoredMessages(login).catch(() => {});
|
||||
await authService.persistSessionMaterial(login, sessionMaterial);
|
||||
const resumed = await authService.resumeSession(login, sessionId);
|
||||
authorizeSession({
|
||||
login: resumed.login || login,
|
||||
sessionId: resumed.sessionId || sessionId,
|
||||
storagePwd: resumed.storagePwd || storagePwd,
|
||||
});
|
||||
state.loginDraft.login = resumed.login || login;
|
||||
state.loginDraft.password = '';
|
||||
await refreshSessions();
|
||||
setAuthInfo(t('screens.login_other_device_view.text_029', { value1: resumed.login || login }));
|
||||
showToast(t('screens.login_other_device_view.text_030', { value1: resumed.login || login }));
|
||||
navigate(consumeAuthReturnPage('profile-view'));
|
||||
};
|
||||
|
||||
const schedulePoll = () => {
|
||||
stopPolling();
|
||||
if (!activePairingId || isDisposed) return;
|
||||
pollTimer = window.setTimeout(async () => {
|
||||
try {
|
||||
const payload = await authService.getTrustedDeviceLoginStatus(activePairingId);
|
||||
const stateValue = String(payload?.state || '');
|
||||
if (stateValue === 'created') {
|
||||
schedulePoll();
|
||||
return;
|
||||
}
|
||||
if (stateValue === 'approved') {
|
||||
stopCountdown();
|
||||
showStage('approving', t('screens.login_other_device_view.text_005'));
|
||||
const decoded = await decryptPairingPayloadFromEnvelope(payload?.encryptedPayload, requesterMaterial);
|
||||
const decodedType = String(decoded?.type || '');
|
||||
if (decodedType === 'shine-esp-session-attach') {
|
||||
await finalizeAuthorizedSessionAttach(decoded.session, decoded.login || loginInput.value, requesterMaterial);
|
||||
return;
|
||||
}
|
||||
if (decodedType !== 'shine-esp-pairing-transfer') {
|
||||
throw new Error(t('screens.login_other_device_view.text_024'));
|
||||
}
|
||||
await finalizeAuthorizedLogin(decoded.keys, decoded.login || loginInput.value);
|
||||
return;
|
||||
}
|
||||
if (stateValue === 'rejected') {
|
||||
clearActivePairing();
|
||||
startBtn.disabled = false;
|
||||
showStage('retry', t('screens.login_other_device_view.text_006'), { error: true, action: t('screens.login_other_device_view.text_014') });
|
||||
return;
|
||||
}
|
||||
if (stateValue === 'canceled') {
|
||||
clearActivePairing();
|
||||
startBtn.disabled = false;
|
||||
showStage('retry', t('screens.login_other_device_view.text_007'), { error: true, action: t('screens.login_other_device_view.text_015') });
|
||||
return;
|
||||
}
|
||||
if (stateValue === 'expired') {
|
||||
clearActivePairing();
|
||||
startBtn.disabled = false;
|
||||
showStage('retry', t('screens.login_other_device_view.text_008'), { error: true, action: t('screens.login_other_device_view.text_016') });
|
||||
return;
|
||||
}
|
||||
schedulePoll();
|
||||
} catch (error) {
|
||||
clearActivePairing();
|
||||
startBtn.disabled = false;
|
||||
const message = toUserMessage(error, t('screens.login_other_device_view.text_009'));
|
||||
setAuthError(message);
|
||||
showStage('retry', message, { error: true, action: t('screens.login_other_device_view.text_017') });
|
||||
}
|
||||
}, 2200);
|
||||
};
|
||||
|
||||
startBtn.addEventListener('click', async () => {
|
||||
const login = String(loginInput.value || '').trim();
|
||||
if (!login) {
|
||||
navigate('login-view');
|
||||
return;
|
||||
}
|
||||
startBtn.disabled = true;
|
||||
setAuthBusy(true);
|
||||
setAuthError('');
|
||||
setAuthInfo('');
|
||||
clearActivePairing();
|
||||
showStage('creating', t('screens.login_other_device_view.text_010'));
|
||||
|
||||
try {
|
||||
await authService.reconnect(state.entrySettings.shineServer);
|
||||
const resolved = await authService.resolveLoginForAuth(login);
|
||||
if (String(resolved?.resolution || '').toUpperCase() !== 'LOCAL') {
|
||||
state.loginDraft.login = String(resolved?.login || login).trim();
|
||||
navigate('login-view');
|
||||
return;
|
||||
}
|
||||
|
||||
requesterMaterial = await createRequesterPairingMaterial();
|
||||
const payload = await authService.startTrustedDeviceLogin({
|
||||
login,
|
||||
// Активный сценарий временно всегда без дополнительного пароля.
|
||||
passwordHash: '',
|
||||
requesterSessionKey: requesterMaterial.sessionKey,
|
||||
payloadType: 2,
|
||||
});
|
||||
|
||||
activePairingId = String(payload?.pairingId || '');
|
||||
if (!activePairingId) {
|
||||
throw new Error(t('screens.login_other_device_view.text_025'));
|
||||
}
|
||||
|
||||
shortCodeEl.textContent = formatPairingShortCode(payload?.shortCode || '');
|
||||
shortCodeEl.setAttribute('aria-label', t('screens.login_other_device_view.text_031', { value1: String(payload?.shortCode || '').split('').join(' ') }));
|
||||
const online = !!payload?.trustedSessionOnline;
|
||||
onlineEl.textContent = online ? t('screens.login_other_device_view.text_018') : t('screens.login_other_device_view.text_019');
|
||||
onlineEl.classList.toggle('is-online', online);
|
||||
showStage('code');
|
||||
startCountdown(payload?.expiresAtMs);
|
||||
state.loginDraft.login = login;
|
||||
schedulePoll();
|
||||
} catch (error) {
|
||||
startBtn.disabled = false;
|
||||
if (String(error?.code || '').toUpperCase() === 'PAIRING_PASSWORD_INVALID') {
|
||||
showStage(
|
||||
'retry',
|
||||
t('screens.login_other_device_view.text_011'),
|
||||
{ error: true, action: t('screens.login_other_device_view.text_020') },
|
||||
);
|
||||
} else {
|
||||
const message = toUserMessage(error, t('screens.login_other_device_view.text_012'));
|
||||
setAuthError(message);
|
||||
showStage('retry', message, { error: true, action: t('screens.login_other_device_view.text_021') });
|
||||
}
|
||||
} finally {
|
||||
setAuthBusy(false);
|
||||
}
|
||||
});
|
||||
|
||||
const cancelActivePairingAndBack = async () => {
|
||||
const pairingId = activePairingId;
|
||||
const requesterSessionKey = requesterMaterial?.sessionKey;
|
||||
isDisposed = true;
|
||||
stopPolling();
|
||||
stopCountdown();
|
||||
if (pairingId && requesterSessionKey) {
|
||||
try {
|
||||
await authService.cancelTrustedDeviceLogin(pairingId, requesterSessionKey);
|
||||
} catch {
|
||||
// Навигацию назад не блокируем из-за ошибки отмены уже созданной заявки.
|
||||
}
|
||||
}
|
||||
navigate('login-view');
|
||||
};
|
||||
|
||||
screen.cleanup = () => {
|
||||
isDisposed = true;
|
||||
stopPolling();
|
||||
stopCountdown();
|
||||
if (activePairingId && requesterMaterial?.sessionKey) {
|
||||
void authService.cancelTrustedDeviceLogin(activePairingId, requesterMaterial.sessionKey).catch(() => {});
|
||||
}
|
||||
};
|
||||
|
||||
screen.append(
|
||||
createTopBar({
|
||||
title: t('screens.login_other_device_view.text_003'),
|
||||
back: { label: '←', onClick: () => { void cancelActivePairingAndBack(); } },
|
||||
}),
|
||||
who,
|
||||
codeBlock,
|
||||
notice,
|
||||
startBtn,
|
||||
);
|
||||
|
||||
if (!String(loginInput.value || '').trim()) {
|
||||
window.setTimeout(() => navigate('login-view'), 0);
|
||||
} else {
|
||||
// После проверки логина на предыдущем экране код создаётся сразу.
|
||||
window.setTimeout(() => startBtn.click(), 0);
|
||||
}
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import { t } 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 {
|
||||
authService,
|
||||
authorizeSession,
|
||||
clearAuthMessages,
|
||||
resetRegistrationFlow,
|
||||
consumeAuthReturnPage,
|
||||
refreshSessions,
|
||||
setAuthBusy,
|
||||
setAuthError,
|
||||
setAuthInfo,
|
||||
state,
|
||||
} from '../state.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { clearStoredMessages } from '../services/message-store.js';
|
||||
import { emptyPasswordWords, PASSWORD_MAX_LENGTH } from '../services/password-words.js';
|
||||
|
||||
export const pageMeta = { id: 'login-password-view', get title() { return t('screens.login_password_view.text_001'); }, showAppChrome: false };
|
||||
|
||||
function setStatus(statusEl, message) {
|
||||
statusEl.textContent = message;
|
||||
statusEl.style.display = message ? '' : 'none';
|
||||
}
|
||||
|
||||
export function render({ navigate }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack auth-screen auth-screen--lower';
|
||||
|
||||
clearAuthMessages();
|
||||
|
||||
const login = String(state.loginDraft.login || '').trim();
|
||||
if (!login) {
|
||||
window.setTimeout(() => navigate('login-view'), 0);
|
||||
}
|
||||
|
||||
const panel = document.createElement('section');
|
||||
panel.className = 'login-panel stack';
|
||||
|
||||
const title = document.createElement('h1');
|
||||
title.className = 'login-panel-title';
|
||||
title.textContent = t('screens.login_password_view.text_003');
|
||||
|
||||
const passwordField = document.createElement('label');
|
||||
passwordField.className = 'stack';
|
||||
|
||||
const passwordInput = createExpandablePasswordTextarea();
|
||||
passwordInput.name = 'shine-login-password';
|
||||
passwordInput.autocomplete = 'current-password';
|
||||
passwordInput.autocapitalize = 'off';
|
||||
passwordInput.spellcheck = false;
|
||||
passwordInput.maxLength = PASSWORD_MAX_LENGTH;
|
||||
passwordInput.placeholder = t('screens.login_password_view.text_004');
|
||||
passwordInput.value = '';
|
||||
|
||||
passwordField.append(createVisiblePasswordField(passwordInput));
|
||||
|
||||
const status = document.createElement('p');
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.style.display = 'none';
|
||||
|
||||
const enterButton = document.createElement('button');
|
||||
enterButton.className = 'primary-btn';
|
||||
enterButton.type = 'button';
|
||||
enterButton.textContent = t('screens.login_password_view.text_005');
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'auth-footer-actions';
|
||||
actions.append(enterButton);
|
||||
|
||||
const keyGeneration = createSecretGenerationOverlay();
|
||||
|
||||
const submit = async () => {
|
||||
const currentLogin = String(state.loginDraft.login || '').trim();
|
||||
const password = String(passwordInput.value || '');
|
||||
setStatus(status, '');
|
||||
|
||||
if (!currentLogin) {
|
||||
navigate('login-view');
|
||||
return;
|
||||
}
|
||||
if (password.length > PASSWORD_MAX_LENGTH) {
|
||||
setStatus(status, t('screens.login_password_view.text_009', { value1: PASSWORD_MAX_LENGTH }));
|
||||
return;
|
||||
}
|
||||
|
||||
state.loginDraft.password = password;
|
||||
state.loginDraft.passwordMode = 'single';
|
||||
state.loginDraft.passwordWords = emptyPasswordWords();
|
||||
|
||||
setAuthBusy(true);
|
||||
setAuthError('');
|
||||
enterButton.disabled = true;
|
||||
|
||||
try {
|
||||
authService.resetConnection(state.entrySettings.shineServer, { clearSessionContext: true });
|
||||
|
||||
// Повторная проверка защищает UI от смены access server между первым экраном и входом.
|
||||
const resolved = await authService.resolveLoginForAuth(currentLogin);
|
||||
if (String(resolved?.resolution || '').toUpperCase() !== 'LOCAL') {
|
||||
state.loginDraft.login = String(resolved?.login || currentLogin).trim();
|
||||
navigate('login-view');
|
||||
return;
|
||||
}
|
||||
|
||||
keyGeneration.show();
|
||||
await new Promise(resolve => setTimeout(resolve, 40));
|
||||
const keyBundle = await authService.derivePasswordKeyBundle(currentLogin, password);
|
||||
keyGeneration.hide();
|
||||
|
||||
enterButton.textContent = t('screens.login_password_view.text_006');
|
||||
const result = await authService.createAuthSession(currentLogin, keyBundle);
|
||||
|
||||
// В текущей модели оба рабочих ключа всегда сохраняются автоматически.
|
||||
// Recovery/root private key остаётся только в памяти этого шага и в key-vault не попадает.
|
||||
await authService.persistSelectedKeys(result.login, result.storagePwd, keyBundle);
|
||||
await authService.persistSessionMaterial(result.login, result.sessionMaterial);
|
||||
await clearStoredMessages(result.login).catch(() => {});
|
||||
|
||||
authorizeSession({
|
||||
login: result.login,
|
||||
sessionId: result.sessionId,
|
||||
storagePwd: result.storagePwd,
|
||||
});
|
||||
state.loginDraft.login = result.login;
|
||||
state.loginDraft.password = '';
|
||||
// Clear the actual textarea as soon as login succeeds, before route change.
|
||||
passwordInput.clearPasswordField();
|
||||
state.loginDraft.passwordMode = 'single';
|
||||
state.loginDraft.passwordWords = emptyPasswordWords();
|
||||
resetRegistrationFlow();
|
||||
|
||||
await refreshSessions();
|
||||
setAuthInfo(t('screens.login_password_view.text_010', { value1: result.login }));
|
||||
navigate(consumeAuthReturnPage('profile-view'));
|
||||
} catch (error) {
|
||||
keyGeneration.hide();
|
||||
const message = toUserMessage(error, t('screens.login_password_view.text_008'));
|
||||
setAuthError(message);
|
||||
setStatus(status, message);
|
||||
passwordInput.select();
|
||||
} finally {
|
||||
setAuthBusy(false);
|
||||
enterButton.disabled = false;
|
||||
enterButton.textContent = t('screens.login_password_view.text_007');
|
||||
}
|
||||
};
|
||||
|
||||
enterButton.addEventListener('click', submit);
|
||||
passwordInput.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
|
||||
event.preventDefault();
|
||||
void submit();
|
||||
}
|
||||
});
|
||||
|
||||
panel.append(title, passwordField, status, actions);
|
||||
|
||||
screen.append(
|
||||
createTopBar({
|
||||
title: '',
|
||||
back: { label: '←', onClick: () => navigate('login-view') },
|
||||
}),
|
||||
panel,
|
||||
keyGeneration.overlay,
|
||||
);
|
||||
|
||||
window.setTimeout(() => { passwordInput.resizePasswordField(); passwordInput.focus(); }, 0);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import {
|
||||
authService,
|
||||
cancelAddProfileLogin,
|
||||
clearAuthMessages,
|
||||
setAuthBusy,
|
||||
setAuthError,
|
||||
state,
|
||||
} from '../state.js';
|
||||
import { buildShineHttpUrlFromAddress } from '../services/shine-server-resolver.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'login-view', get title() { return t('screens.login_view.text_001'); }, showAppChrome: false };
|
||||
|
||||
function setStatus(statusEl, message, kind = 'error') {
|
||||
statusEl.classList.toggle('is-unavailable', kind === 'error');
|
||||
statusEl.classList.toggle('is-available', kind !== 'error');
|
||||
statusEl.textContent = message;
|
||||
statusEl.style.display = message ? '' : 'none';
|
||||
}
|
||||
|
||||
function setRemoteServer(remoteWrap, serverLoginEl, serverLinkEl, payload) {
|
||||
const serverLogin = String(payload?.accessServerLogin || '').trim();
|
||||
const serverUrl = String(payload?.accessServerUrl || '').trim();
|
||||
serverLoginEl.textContent = serverLogin || t('screens.login_view.text_014');
|
||||
serverLinkEl.textContent = serverUrl || t('screens.login_view.text_015');
|
||||
serverLinkEl.href = buildShineHttpUrlFromAddress(serverUrl);
|
||||
remoteWrap.style.display = '';
|
||||
}
|
||||
|
||||
export function render({ navigate }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack auth-screen auth-screen--lower login-choice-screen';
|
||||
|
||||
clearAuthMessages();
|
||||
|
||||
const panel = document.createElement('section');
|
||||
panel.className = 'login-panel stack';
|
||||
|
||||
const title = document.createElement('h1');
|
||||
title.className = 'login-panel-title';
|
||||
title.textContent = t('screens.login_view.text_002');
|
||||
|
||||
const loginField = document.createElement('label');
|
||||
loginField.className = 'stack';
|
||||
|
||||
const loginInput = document.createElement('input');
|
||||
loginInput.className = 'input';
|
||||
loginInput.type = 'text';
|
||||
loginInput.autocomplete = 'username';
|
||||
loginInput.autocapitalize = 'off';
|
||||
loginInput.spellcheck = false;
|
||||
loginInput.placeholder = t('screens.login_view.text_003');
|
||||
loginInput.value = String(state.loginDraft.login || '');
|
||||
|
||||
loginField.append(loginInput);
|
||||
|
||||
const status = document.createElement('p');
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.style.display = 'none';
|
||||
|
||||
const remoteWrap = document.createElement('div');
|
||||
remoteWrap.className = 'login-remote-server stack';
|
||||
remoteWrap.style.display = 'none';
|
||||
|
||||
const remoteText = document.createElement('p');
|
||||
remoteText.className = 'auth-copy';
|
||||
const serverLoginEl = document.createElement('strong');
|
||||
const textBefore = document.createTextNode(t('screens.login_view.text_007'));
|
||||
remoteText.append(textBefore, serverLoginEl, document.createTextNode(t('screens.login_view.text_008')));
|
||||
|
||||
const serverLinkEl = document.createElement('a');
|
||||
serverLinkEl.className = 'primary-btn login-server-link';
|
||||
serverLinkEl.target = '_self';
|
||||
serverLinkEl.rel = 'noopener';
|
||||
|
||||
remoteWrap.append(remoteText, serverLinkEl);
|
||||
|
||||
const passwordButton = document.createElement('button');
|
||||
passwordButton.className = 'primary-btn';
|
||||
passwordButton.type = 'button';
|
||||
passwordButton.textContent = t('screens.login_view.text_004');
|
||||
|
||||
const deviceButton = document.createElement('button');
|
||||
deviceButton.className = 'ghost-btn';
|
||||
deviceButton.type = 'button';
|
||||
deviceButton.textContent = t('screens.login_view.text_005');
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'auth-actions login-actions-wide';
|
||||
actions.append(passwordButton, deviceButton);
|
||||
|
||||
const resolveAndContinue = async (targetPage) => {
|
||||
const login = String(loginInput.value || '').trim();
|
||||
setStatus(status, '');
|
||||
remoteWrap.style.display = 'none';
|
||||
if (!login) {
|
||||
setStatus(status, t('screens.login_view.text_009'));
|
||||
loginInput.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
passwordButton.disabled = true;
|
||||
deviceButton.disabled = true;
|
||||
setAuthBusy(true);
|
||||
setAuthError('');
|
||||
|
||||
try {
|
||||
await authService.reconnect(state.entrySettings.shineServer);
|
||||
const resolved = await authService.resolveLoginForAuth(login);
|
||||
const resolution = String(resolved?.resolution || '').trim().toUpperCase();
|
||||
|
||||
if (resolution === 'NOT_FOUND') {
|
||||
setStatus(status, t('screens.login_view.text_010'));
|
||||
return;
|
||||
}
|
||||
if (resolution === 'NO_ACCESS_SERVER') {
|
||||
setStatus(status, t('screens.login_view.text_011'));
|
||||
return;
|
||||
}
|
||||
if (resolution === 'REMOTE') {
|
||||
state.loginDraft.login = String(resolved?.login || login).trim();
|
||||
setRemoteServer(remoteWrap, serverLoginEl, serverLinkEl, resolved);
|
||||
return;
|
||||
}
|
||||
if (resolution !== 'LOCAL') {
|
||||
setStatus(status, t('screens.login_view.text_012'));
|
||||
return;
|
||||
}
|
||||
|
||||
state.loginDraft.login = String(resolved?.login || login).trim();
|
||||
state.loginDraft.password = '';
|
||||
navigate(targetPage);
|
||||
} catch (error) {
|
||||
const message = toUserMessage(error, t('screens.login_view.text_013'));
|
||||
setAuthError(message);
|
||||
setStatus(status, message);
|
||||
} finally {
|
||||
setAuthBusy(false);
|
||||
passwordButton.disabled = false;
|
||||
deviceButton.disabled = false;
|
||||
}
|
||||
};
|
||||
|
||||
passwordButton.addEventListener('click', () => resolveAndContinue('login-password-view'));
|
||||
deviceButton.addEventListener('click', () => resolveAndContinue('login-other-device-view'));
|
||||
loginInput.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
void resolveAndContinue('login-password-view');
|
||||
}
|
||||
});
|
||||
|
||||
panel.append(title, loginField, status, remoteWrap, actions);
|
||||
|
||||
screen.append(
|
||||
createTopBar({
|
||||
title: t('screens.login_view.text_006'),
|
||||
back: {
|
||||
label: '←',
|
||||
onClick: async () => {
|
||||
if (state.authReturnHash === '/profiles') {
|
||||
await cancelAddProfileLogin();
|
||||
navigate('profiles-view');
|
||||
return;
|
||||
}
|
||||
navigate('start-view');
|
||||
},
|
||||
},
|
||||
}),
|
||||
panel,
|
||||
);
|
||||
|
||||
window.setTimeout(() => loginInput.focus(), 0);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,713 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import {
|
||||
authService,
|
||||
getChatMessages,
|
||||
isSessionInvalidError,
|
||||
normalizeDmChatId,
|
||||
rememberDmPeer,
|
||||
setContacts,
|
||||
state,
|
||||
terminateCurrentSession,
|
||||
} from '../state.js';
|
||||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { createSearchTopBar, createTopBar } from '../components/topbar.js';
|
||||
import { createDropdownMenu } from '../components/dropdown-menu.js';
|
||||
import { createTopBarFilterTitle } from '../components/topbar-filter-title.js';
|
||||
import { createDmMuteMenuItem } from '../components/dm-mute-menu.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import {
|
||||
DM_CHAT_PREFS_EVENT,
|
||||
getPinnedDmChats,
|
||||
isDmChatMuted,
|
||||
setDmChatPinned,
|
||||
} from '../services/dm-chat-prefs.js';
|
||||
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||||
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
||||
import { formatListTime } from '../services/channels-ux.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { matchesPeopleQuery } from '../services/people-search.js';
|
||||
import { createErrorState, createLoadingState, createStateMessage } from '../components/feedback.js';
|
||||
import { openHistoryLayer } from '../router.js';
|
||||
|
||||
export const pageMeta = { id: 'messages-list', get title() { return t('screens.messages_list.text_001'); } };
|
||||
const PREVIEW_MAX_LEN = 200;
|
||||
const DM_BLOB_PREVIEW_CACHE = new Map();
|
||||
const DM_BLOB_PREVIEW_PENDING = new Map();
|
||||
const dmAvatarSnapshotCache = new Map();
|
||||
const dmAvatarPendingByLogin = new Map();
|
||||
|
||||
const RELATION_ORDER = new Map([
|
||||
['close_friend', 0],
|
||||
['friend', 1],
|
||||
['contact', 2],
|
||||
['none', 3],
|
||||
]);
|
||||
|
||||
async function loadDmAvatarSnapshot(login) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
if (!cleanLogin) return null;
|
||||
const key = cleanLogin.toLowerCase();
|
||||
if (dmAvatarSnapshotCache.has(key)) return dmAvatarSnapshotCache.get(key);
|
||||
if (dmAvatarPendingByLogin.has(key)) return dmAvatarPendingByLogin.get(key);
|
||||
const pending = loadProfileSnapshot(cleanLogin)
|
||||
.then((snapshot) => {
|
||||
dmAvatarSnapshotCache.set(key, snapshot || null);
|
||||
dmAvatarPendingByLogin.delete(key);
|
||||
return snapshot || null;
|
||||
})
|
||||
.catch(() => {
|
||||
dmAvatarSnapshotCache.set(key, null);
|
||||
dmAvatarPendingByLogin.delete(key);
|
||||
return null;
|
||||
});
|
||||
dmAvatarPendingByLogin.set(key, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
// whenVisible(fn) – отложить запрос профиля до появления строки на экране: в списке на сотни
|
||||
// контактов иначе уходят сотни запросов сразу.
|
||||
function createDmAvatar(login, { className = '', avatar = null, firstName = '', lastName = '', whenVisible = null } = {}) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const title = cleanLogin ? t('screens.messages_list.text_035', { value1: cleanLogin }) : '';
|
||||
const avatarEl = renderUserAvatar({
|
||||
login: cleanLogin || 'unknown',
|
||||
firstName: String(firstName || '').trim(),
|
||||
lastName: String(lastName || '').trim(),
|
||||
avatar: (avatar?.ar || avatar?.pr) ? { ar: String(avatar?.ar || '').trim(), pr: String(avatar?.pr || '').trim() } : null,
|
||||
size: 'lg',
|
||||
title,
|
||||
className,
|
||||
});
|
||||
if (!cleanLogin || avatar?.ar || avatar?.pr) return avatarEl;
|
||||
const upgrade = () => loadDmAvatarSnapshot(cleanLogin).then((snapshot) => {
|
||||
// Фото нет – оставляем инициалы имени как есть (раньше подменялись на букву логина).
|
||||
if (!avatarEl.isConnected || !snapshot?.avatar?.source) return;
|
||||
const upgraded = renderUserAvatar({
|
||||
login: cleanLogin,
|
||||
firstName: String(firstName || '').trim(),
|
||||
lastName: String(lastName || '').trim(),
|
||||
avatar: snapshot?.avatar?.source
|
||||
? {
|
||||
ar: String(snapshot.avatar.txId || snapshot.avatar.ar || '').trim(),
|
||||
pr: String(snapshot?.avatar?.pr || '').trim(),
|
||||
}
|
||||
: null,
|
||||
size: 'lg',
|
||||
title,
|
||||
className,
|
||||
});
|
||||
upgraded.classList.add('avatar');
|
||||
avatarEl.replaceWith(upgraded);
|
||||
});
|
||||
if (typeof whenVisible === 'function') whenVisible(avatarEl, upgrade);
|
||||
else void upgrade();
|
||||
return avatarEl;
|
||||
}
|
||||
|
||||
function normalizeRelationFlag(value) {
|
||||
const clean = String(value || '').trim().toLowerCase();
|
||||
if (clean === 'close_friend' || clean === 'friend' || clean === 'contact') return clean;
|
||||
return 'none';
|
||||
}
|
||||
|
||||
function relationOrder(flag) {
|
||||
return RELATION_ORDER.get(normalizeRelationFlag(flag)) ?? 99;
|
||||
}
|
||||
|
||||
function relationLabel(flag) {
|
||||
switch (normalizeRelationFlag(flag)) {
|
||||
case 'close_friend':
|
||||
return t('screens.messages_list.text_018');
|
||||
case 'friend':
|
||||
return t('screens.messages_list.text_019');
|
||||
case 'contact':
|
||||
return t('screens.messages_list.text_020');
|
||||
default:
|
||||
return t('screens.messages_list.text_021');
|
||||
}
|
||||
}
|
||||
|
||||
function clipPreviewText(text, maxLen = PREVIEW_MAX_LEN) {
|
||||
const normalized = String(text || '').replace(/\s+/g, ' ').trim();
|
||||
if (!normalized) return '';
|
||||
if (normalized.length <= maxLen) return normalized;
|
||||
return `${normalized.slice(0, maxLen - 1)}…`;
|
||||
}
|
||||
|
||||
const DM_PREVIEW_ENCRYPTED = () => t('remaining.messages.dm_preview_encrypted');
|
||||
const DM_PREVIEW_EMPTY = () => t('remaining.messages.dm_preview_empty');
|
||||
|
||||
async function resolveDialogPreview(dialog) {
|
||||
const localText = clipPreviewText(String(dialog?.lastMessageText || '').trim());
|
||||
if (localText) return { text: localText, kind: 'message' };
|
||||
const blobB64 = String(dialog?.lastMessageBlobB64 || '').trim();
|
||||
if (!blobB64) return { text: DM_PREVIEW_EMPTY(), kind: 'empty' };
|
||||
|
||||
const cacheKey = [
|
||||
blobB64,
|
||||
String(state.session.login || '').trim().toLowerCase(),
|
||||
String(state.session.storagePwdInMemory || '').trim(),
|
||||
].join('|');
|
||||
|
||||
// После перезагрузки пароля хранилища в памяти нет — расшифровать нечем. Не кэшируем,
|
||||
// чтобы превью появилось, когда пароль снова будет введён.
|
||||
if (!String(state.session.storagePwdInMemory || '').trim()) return { text: DM_PREVIEW_ENCRYPTED(), kind: 'encrypted' };
|
||||
if (DM_BLOB_PREVIEW_CACHE.has(cacheKey)) return DM_BLOB_PREVIEW_CACHE.get(cacheKey);
|
||||
if (DM_BLOB_PREVIEW_PENDING.has(cacheKey)) return DM_BLOB_PREVIEW_PENDING.get(cacheKey);
|
||||
|
||||
const pending = (async () => {
|
||||
try {
|
||||
const parsed = authService.parseSignedMessageBlob(blobB64);
|
||||
const decrypted = await authService.decryptSignedMessageContent({
|
||||
parsed,
|
||||
blobB64,
|
||||
login: state.session.login,
|
||||
storagePwd: state.session.storagePwdInMemory,
|
||||
});
|
||||
const parsedText = parseDmTechBlocks(String(decrypted?.text || ''));
|
||||
const display = clipPreviewText(String(parsedText.displayText || '').trim());
|
||||
const result = display || t('screens.messages_list.text_033');
|
||||
const preview = { text: result, kind: 'message' };
|
||||
DM_BLOB_PREVIEW_CACHE.set(cacheKey, preview);
|
||||
return preview;
|
||||
} catch {
|
||||
const fallback = { text: DM_PREVIEW_ENCRYPTED(), kind: 'encrypted' };
|
||||
DM_BLOB_PREVIEW_CACHE.set(cacheKey, fallback);
|
||||
return fallback;
|
||||
} finally {
|
||||
DM_BLOB_PREVIEW_PENDING.delete(cacheKey);
|
||||
}
|
||||
})();
|
||||
|
||||
DM_BLOB_PREVIEW_PENDING.set(cacheKey, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
function resolveLocalMessageTimeMs(message) {
|
||||
const keys = [message?.baseKey, message?.messageKey];
|
||||
for (const key of keys) {
|
||||
const parts = String(key || '').split('|');
|
||||
const timeMs = Number(parts[2] || 0);
|
||||
if (parts.length >= 4 && Number.isFinite(timeMs) && timeMs > 0) return timeMs;
|
||||
}
|
||||
const tempParts = String(message?.tempId || '').split('-');
|
||||
const tempTimeMs = Number(tempParts[1] || 0);
|
||||
if (tempParts[0] === 'tmp' && Number.isFinite(tempTimeMs) && tempTimeMs > 0) return tempTimeMs;
|
||||
const createdAtMs = Number(message?.createdAtMs || message?.ts || 0);
|
||||
return Number.isFinite(createdAtMs) && createdAtMs > 0 ? createdAtMs : 0;
|
||||
}
|
||||
|
||||
function latestLocalDialogMessage(peerLogin) {
|
||||
const messages = getChatMessages(peerLogin);
|
||||
const latest = [...messages].sort((a, b) => resolveLocalMessageTimeMs(b) - resolveLocalMessageTimeMs(a))[0];
|
||||
if (!latest) return null;
|
||||
const parsed = parseDmTechBlocks(String(latest?.text || ''));
|
||||
const text = clipPreviewText(String(parsed.displayText || parsed.visibleText || '').trim()) || t('screens.messages_list.text_034');
|
||||
return { text, timeMs: resolveLocalMessageTimeMs(latest) };
|
||||
}
|
||||
|
||||
// Последний загруженный список чатов (в памяти вкладки): при возврате на «Чаты» он рисуется
|
||||
// сразу, без пустого кадра, и тихо обновляется с сервера.
|
||||
let lastChatList = null; // { login, items }
|
||||
|
||||
function formatChatRowTime(ts) {
|
||||
return formatListTime(ts);
|
||||
}
|
||||
|
||||
function compareChatRows(a, b) {
|
||||
const timeA = Number(a?.lastMessageTimeMs || 0);
|
||||
const timeB = Number(b?.lastMessageTimeMs || 0);
|
||||
if (timeA !== timeB) return timeB - timeA;
|
||||
const nameA = String(a?.peerLogin || '').toLowerCase();
|
||||
const nameB = String(b?.peerLogin || '').toLowerCase();
|
||||
return nameA.localeCompare(nameB, 'ru');
|
||||
}
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
const login = String(state.session.login || '').trim();
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack dm-screen dm-list-screen';
|
||||
let disposed = false;
|
||||
let currentChatFilter = 'all';
|
||||
const CHAT_FILTERS = [
|
||||
['all', t('screens.messages_list.text_022')],
|
||||
['close_friend', t('screens.messages_list.text_023')],
|
||||
['friend', t('screens.messages_list.text_024')],
|
||||
['contact', t('screens.messages_list.text_025')],
|
||||
['none', t('screens.messages_list.text_026')],
|
||||
];
|
||||
let reloadForFilter = () => {};
|
||||
let chatHeader = null;
|
||||
const selectFilter = (value) => {
|
||||
if (currentChatFilter === value) return;
|
||||
currentChatFilter = value;
|
||||
chatHeader?.filter.setValue(value);
|
||||
reloadForFilter();
|
||||
};
|
||||
|
||||
// Шапка: поиск по своим чатам и контактам (мгновенно, на устройстве) и «Новый чат».
|
||||
let chatQuery = '';
|
||||
let chatSearch = null;
|
||||
const createChatsHeader = () => {
|
||||
const filter = createTopBarFilterTitle({
|
||||
section: t('screens.messages_list.text_027'),
|
||||
choices: CHAT_FILTERS,
|
||||
value: currentChatFilter,
|
||||
onSelect: selectFilter,
|
||||
});
|
||||
const head = createTopBar({
|
||||
center: filter.element,
|
||||
className: 'topbar--root topbar--section-filter',
|
||||
actions: [
|
||||
{
|
||||
icon: 'search',
|
||||
title: t('screens.messages_list.text_002'),
|
||||
ariaLabel: t('screens.messages_list.text_003'),
|
||||
className: 'messages-search-btn',
|
||||
onClick: () => openChatsSearch(),
|
||||
},
|
||||
{
|
||||
icon: 'compose',
|
||||
title: t('screens.messages_list.text_004'),
|
||||
ariaLabel: t('screens.messages_list.text_005'),
|
||||
className: 'messages-compose-btn',
|
||||
onClick: () => navigate('contact-search-view'),
|
||||
},
|
||||
],
|
||||
});
|
||||
head.addCleanup(() => filter.destroy());
|
||||
return { head, filter };
|
||||
};
|
||||
chatHeader = createChatsHeader();
|
||||
|
||||
function openChatsSearch() {
|
||||
if (chatSearch) return;
|
||||
const bar = createSearchTopBar({
|
||||
placeholder: t('screens.messages_list.text_006'),
|
||||
onInput: (value) => {
|
||||
chatQuery = String(value || '').toLowerCase().replaceAll('ё', 'е').trim();
|
||||
renderList();
|
||||
},
|
||||
onSubmit: () => list.querySelector('.dm-dialog-card')?.click(),
|
||||
onClose: () => closeChatsSearch(),
|
||||
});
|
||||
chatSearch = { bar, layer: openHistoryLayer(() => closeChatsSearch({ fromHistory: true })) };
|
||||
chrome?.setTopbar(bar);
|
||||
bar.searchInput?.focus();
|
||||
}
|
||||
|
||||
function closeChatsSearch({ fromHistory = false } = {}) {
|
||||
if (!chatSearch) return;
|
||||
const { layer } = chatSearch;
|
||||
chatSearch = null;
|
||||
chatQuery = '';
|
||||
if (!fromHistory) layer?.close();
|
||||
if (!disposed) {
|
||||
// Старый TopBar был корректно уничтожен при открытии поиска.
|
||||
chatHeader = createChatsHeader();
|
||||
chrome?.setTopbar(chatHeader.head);
|
||||
renderList();
|
||||
}
|
||||
}
|
||||
|
||||
const list = document.createElement('div');
|
||||
list.className = 'stack dm-list';
|
||||
|
||||
// Меню чата по долгому нажатию (или правой кнопкой): закрепить и выключить звук.
|
||||
// Одно меню на весь список; якорь ставится у строки, на которой его открыли.
|
||||
const rowMenuAnchor = document.createElement('span');
|
||||
rowMenuAnchor.className = 'dm-row-menu-anchor';
|
||||
rowMenuAnchor.setAttribute('aria-hidden', 'true');
|
||||
let rowMenuItem = null;
|
||||
let rowMenuOpenedAt = 0;
|
||||
const rowMenu = createDropdownMenu({
|
||||
anchorEl: rowMenuAnchor,
|
||||
minWidth: 200,
|
||||
transparent: true,
|
||||
items: () => {
|
||||
if (!rowMenuItem) return [];
|
||||
const id = normalizeDmChatId(rowMenuItem.peerLogin);
|
||||
return [
|
||||
{
|
||||
label: rowMenuItem.pinned ? t('screens.messages_list.text_028') : t('screens.messages_list.text_029'),
|
||||
iconHtml: iconHtml('pin'),
|
||||
action: () => setDmChatPinned(id, !rowMenuItem.pinned),
|
||||
},
|
||||
createDmMuteMenuItem(id),
|
||||
];
|
||||
},
|
||||
});
|
||||
const openRowMenu = (row, item) => {
|
||||
if (Date.now() - rowMenuOpenedAt < 700) return;
|
||||
rowMenuItem = item;
|
||||
rowMenuOpenedAt = Date.now();
|
||||
const rect = row.getBoundingClientRect();
|
||||
const listRect = screen.getBoundingClientRect();
|
||||
rowMenuAnchor.style.top = `${rect.top - listRect.top + rect.height / 2}px`;
|
||||
rowMenuAnchor.style.left = `${rect.right - listRect.left - 24}px`;
|
||||
rowMenu.open();
|
||||
try { navigator.vibrate?.(12); } catch { /* вибрация не обязательна */ }
|
||||
};
|
||||
function bindRowMenu(row, item) {
|
||||
let pressTimer = 0;
|
||||
let startX = 0;
|
||||
let startY = 0;
|
||||
const cancel = () => { window.clearTimeout(pressTimer); pressTimer = 0; };
|
||||
row.addEventListener('pointerdown', (event) => {
|
||||
if (event.pointerType === 'mouse') return;
|
||||
startX = event.clientX;
|
||||
startY = event.clientY;
|
||||
cancel();
|
||||
pressTimer = window.setTimeout(() => openRowMenu(row, item), 500);
|
||||
});
|
||||
row.addEventListener('pointermove', (event) => {
|
||||
if (pressTimer && Math.hypot(event.clientX - startX, event.clientY - startY) > 8) cancel();
|
||||
});
|
||||
row.addEventListener('pointerup', cancel);
|
||||
row.addEventListener('pointercancel', cancel);
|
||||
row.addEventListener('contextmenu', (event) => {
|
||||
event.preventDefault();
|
||||
cancel();
|
||||
openRowMenu(row, item);
|
||||
});
|
||||
}
|
||||
|
||||
function renderRow(item) {
|
||||
const row = document.createElement('article');
|
||||
row.className = 'list-item dm-dialog-card';
|
||||
const relationFlag = normalizeRelationFlag(item.relationFlag);
|
||||
const relationBadge = relationFlag === 'none' ? '' : relationLabel(relationFlag);
|
||||
const avatarEl = createDmAvatar(item.peerLogin, {
|
||||
avatar: item.avatar,
|
||||
firstName: item.firstName,
|
||||
lastName: item.lastName,
|
||||
whenVisible,
|
||||
});
|
||||
avatarEl.classList.add('avatar');
|
||||
const avatarWrap = document.createElement('div');
|
||||
avatarWrap.className = 'dm-av dm-av--default';
|
||||
if (relationFlag !== 'none') row.classList.add(`dm-card--${relationFlag === 'close_friend' ? 'family' : 'contact'}`);
|
||||
avatarWrap.append(avatarEl);
|
||||
row.innerHTML = `
|
||||
<div class="dm-row-main">
|
||||
<div class="dm-row-titleline dm-row-titlewrap">
|
||||
<strong class="dm-row-title"></strong>
|
||||
${item.muted ? `<span class="dm-row-muted" title="${th('screens.messages_list.text_038')}">${iconHtml('bell-off')}</span>` : ''}
|
||||
${relationBadge ? `<span class="dm-contact-note dm-contact-note--${relationFlag}">${relationBadge}</span>` : ''}
|
||||
</div>
|
||||
<p class="dm-row-last-message"></p>
|
||||
</div>
|
||||
<div class="dm-row-meta-col">
|
||||
<div class="dm-row-meta-line">
|
||||
${item.lastMessageTimeMs ? '<span class="dm-row-time"></span>' : '<span class="dm-row-time dm-row-time--empty"></span>'}
|
||||
</div>
|
||||
${item.unreadCount
|
||||
? `<span class="dm-unread-badge${item.muted ? ' dm-unread-badge--muted' : ''}">${item.unreadCount > 99 ? '99+' : item.unreadCount}</span>`
|
||||
: (item.pinned
|
||||
? `<span class="dm-row-pin" title="${th('screens.messages_list.text_039')}">${iconHtml('pin')}</span>`
|
||||
: '<span class="dm-row-meta-spacer" aria-hidden="true"></span>')}
|
||||
</div>
|
||||
`;
|
||||
const titleEl = row.querySelector('.dm-row-title');
|
||||
const previewEl = row.querySelector('.dm-row-last-message');
|
||||
const timeEl = row.querySelector('.dm-row-time');
|
||||
if (titleEl) {
|
||||
const fullName = [String(item.firstName || '').trim(), String(item.lastName || '').trim()].filter(Boolean).join(' ');
|
||||
titleEl.textContent = fullName || String(item.peerLogin || '');
|
||||
}
|
||||
if (timeEl) timeEl.textContent = formatChatRowTime(item.lastMessageTimeMs);
|
||||
row.prepend(avatarWrap);
|
||||
// Текст превью ставится сразу, если известен; иначе строка пустая до расшифровки –
|
||||
// без мелькающего «Загрузка…».
|
||||
const showPreview = (text, kind = 'message') => {
|
||||
if (!previewEl) return;
|
||||
previewEl.textContent = String(text || '').trim() || DM_PREVIEW_EMPTY();
|
||||
previewEl.classList.toggle('is-encrypted', kind === 'encrypted');
|
||||
previewEl.classList.toggle('is-empty', kind === 'empty' || !String(text || '').trim());
|
||||
};
|
||||
const knownText = clipPreviewText(String(item.lastMessageText || '').trim());
|
||||
if (knownText || !item.lastMessageBlobB64) showPreview(knownText, knownText ? 'message' : 'empty');
|
||||
else {
|
||||
if (previewEl) previewEl.textContent = '\u00a0';
|
||||
void resolveDialogPreview(item).then((preview) => {
|
||||
if (previewEl?.isConnected) showPreview(preview.text, preview.kind);
|
||||
});
|
||||
}
|
||||
if (item.pinned) row.classList.add('is-pinned');
|
||||
row.addEventListener('click', (event) => {
|
||||
// Долгое нажатие уже открыло меню чата – отпускание пальца не должно открывать сам чат.
|
||||
if (Date.now() - rowMenuOpenedAt < 700) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
navigate(`chat/${encodeURIComponent(normalizeDmChatId(item.peerLogin))}`);
|
||||
});
|
||||
bindRowMenu(row, item);
|
||||
return row;
|
||||
}
|
||||
|
||||
// Профили для аватаров – только у строк, которые видны (или вот-вот будут видны).
|
||||
const visibleWaiters = new Map();
|
||||
const avatarObserver = typeof IntersectionObserver === 'function'
|
||||
? new IntersectionObserver((entries) => {
|
||||
entries.forEach((entry) => {
|
||||
if (!entry.isIntersecting) return;
|
||||
const fn = visibleWaiters.get(entry.target);
|
||||
visibleWaiters.delete(entry.target);
|
||||
avatarObserver.unobserve(entry.target);
|
||||
fn?.();
|
||||
});
|
||||
}, { rootMargin: '200px 0px' })
|
||||
: null;
|
||||
function whenVisible(el, fn) {
|
||||
if (!avatarObserver) { fn(); return; }
|
||||
visibleWaiters.set(el, fn);
|
||||
avatarObserver.observe(el);
|
||||
}
|
||||
|
||||
// Последний ответ сервера, уже разобранный: фильтр перерисовывает без запроса.
|
||||
let lastItems = lastChatList?.login === login ? lastChatList.items : null;
|
||||
let startExpanded = false;
|
||||
const START_PREVIEW = 5;
|
||||
|
||||
function hasConversation(item) {
|
||||
return Boolean(item.hasDialog || item.lastMessageTimeMs > 0 || item.unreadCount > 0 || item.pinned);
|
||||
}
|
||||
|
||||
function matchesChatQuery(item) {
|
||||
return matchesPeopleQuery(`${item.firstName || ''} ${item.lastName || ''} ${item.peerLogin || ''}`, chatQuery);
|
||||
}
|
||||
|
||||
function renderList() {
|
||||
if (!lastItems) return;
|
||||
const pinnedOrder = getPinnedDmChats();
|
||||
// В поиске – по всем чатам и контактам сразу, без фильтра по типу связи.
|
||||
const filtered = chatQuery
|
||||
? lastItems.filter(matchesChatQuery)
|
||||
: lastItems.filter((item) => currentChatFilter === 'all' || normalizeRelationFlag(item.relationFlag) === currentChatFilter);
|
||||
// Переписки – по свежести, закреплённые выше всех (последний закреплённый – первым).
|
||||
const chats = filtered.filter(hasConversation).sort((a, b) => {
|
||||
const pinA = a.pinned ? pinnedOrder.indexOf(normalizeDmChatId(a.peerLogin)) : -1;
|
||||
const pinB = b.pinned ? pinnedOrder.indexOf(normalizeDmChatId(b.peerLogin)) : -1;
|
||||
if (pinA >= 0 || pinB >= 0) {
|
||||
if (pinA < 0) return 1;
|
||||
if (pinB < 0) return -1;
|
||||
return pinA - pinB;
|
||||
}
|
||||
return compareChatRows(a, b);
|
||||
});
|
||||
// Без переписки: во «Всех» – только близкие и друзья (контактов могут быть сотни),
|
||||
// в фильтре по типу связи – все этого типа.
|
||||
const byName = (a, b) => (relationOrder(a.relationFlag) - relationOrder(b.relationFlag))
|
||||
|| String(a.firstName || a.peerLogin).localeCompare(String(b.firstName || b.peerLogin), 'ru');
|
||||
const silent = filtered
|
||||
.filter((item) => !hasConversation(item) && normalizeRelationFlag(item.relationFlag) !== 'none')
|
||||
.filter((item) => chatQuery || currentChatFilter !== 'all' || ['close_friend', 'friend'].includes(normalizeRelationFlag(item.relationFlag)))
|
||||
.sort(byName);
|
||||
|
||||
list.replaceChildren();
|
||||
if (!chats.length && !silent.length) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'empty-note';
|
||||
if (chatQuery) {
|
||||
empty.textContent = t('screens.messages_list.text_007');
|
||||
const wide = document.createElement('button');
|
||||
wide.type = 'button';
|
||||
wide.className = 'secondary-btn dm-search-wide';
|
||||
wide.textContent = t('screens.messages_list.text_008');
|
||||
wide.addEventListener('click', () => navigate('contact-search-view'));
|
||||
list.append(empty, wide);
|
||||
return;
|
||||
}
|
||||
if (currentChatFilter === 'all') {
|
||||
list.append(createStateMessage({
|
||||
icon: 'message',
|
||||
title: t('screens.messages_list.text_009'),
|
||||
text: t('screens.messages_list.text_030'),
|
||||
actionLabel: t('screens.messages_list.text_031'),
|
||||
onAction: () => navigate('contact-search-view'),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
empty.textContent = t('screens.messages_list.text_010');
|
||||
list.append(empty);
|
||||
return;
|
||||
}
|
||||
const frag = document.createDocumentFragment();
|
||||
chats.forEach((item) => frag.append(renderRow(item)));
|
||||
if (silent.length) {
|
||||
const divider = document.createElement('div');
|
||||
divider.className = 'dm-divider';
|
||||
divider.textContent = chats.length ? t('screens.messages_list.text_036', { value1: silent.length }) : t('screens.messages_list.text_037', { value1: silent.length });
|
||||
frag.append(divider);
|
||||
const collapsed = !chatQuery && !startExpanded && silent.length > START_PREVIEW + 1 && chats.length > 0;
|
||||
(collapsed ? silent.slice(0, START_PREVIEW) : silent).forEach((item) => frag.append(renderRow(item)));
|
||||
if (collapsed) {
|
||||
const more = document.createElement('button');
|
||||
more.type = 'button';
|
||||
more.className = 'list-more';
|
||||
more.innerHTML = `${iconHtml('chevron-down')}<span>${th('remaining.html_messages_list.show_all')}${silent.length}</span>`;
|
||||
more.addEventListener('click', () => { startExpanded = true; renderList(); });
|
||||
frag.append(more);
|
||||
}
|
||||
}
|
||||
list.append(frag);
|
||||
}
|
||||
|
||||
let loadSeq = 0;
|
||||
async function loadList() {
|
||||
if (state.session.isLocalDemo) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'card meta-muted';
|
||||
empty.textContent = t('screens.messages_list.text_011');
|
||||
list.replaceChildren(empty);
|
||||
return;
|
||||
}
|
||||
const seq = ++loadSeq;
|
||||
// Первый показ – спиннер, но только если ждать заметно (без мелькания).
|
||||
if (!lastItems && !list.childElementCount) list.replaceChildren(createLoadingState({ label: t('screens.messages_list.text_012') }));
|
||||
|
||||
try {
|
||||
const payload = await authService.listContacts();
|
||||
if (disposed || seq !== loadSeq) return;
|
||||
const dialogs = Array.isArray(payload?.dialogs) ? payload.dialogs : [];
|
||||
const contacts = dialogs
|
||||
.filter((dialog) => normalizeRelationFlag(dialog?.relationFlag) !== 'none')
|
||||
.map((dialog) => String(dialog?.peerLogin || '').trim())
|
||||
.filter(Boolean);
|
||||
setContacts(contacts);
|
||||
|
||||
const byPeer = new Map();
|
||||
dialogs.forEach((dialog) => {
|
||||
const peerLogin = String(dialog?.peerLogin || '').trim();
|
||||
if (!peerLogin) return;
|
||||
const key = peerLogin.toLowerCase();
|
||||
const relationFlag = normalizeRelationFlag(dialog?.relationFlag);
|
||||
const next = {
|
||||
id: peerLogin,
|
||||
peerLogin,
|
||||
relationFlag,
|
||||
firstName: String(dialog?.firstName || '').trim(),
|
||||
lastName: String(dialog?.lastName || '').trim(),
|
||||
avatar: dialog?.avatar && typeof dialog.avatar === 'object' ? dialog.avatar : null,
|
||||
accountRole: String(dialog?.accountRole || '').trim(),
|
||||
shineStatus: String(dialog?.shineStatus || '').trim(),
|
||||
lastMessageBlobB64: String(dialog?.lastMessageBlobB64 || ''),
|
||||
lastMessageTimeMs: Number(dialog?.lastMessageTimeMs || 0),
|
||||
unreadCount: Number(dialog?.unreadCount || 0),
|
||||
hasDialog: Boolean(dialog?.hasDialog),
|
||||
};
|
||||
const localLatest = latestLocalDialogMessage(peerLogin);
|
||||
if (localLatest && localLatest.timeMs >= next.lastMessageTimeMs) {
|
||||
next.lastMessageText = localLatest.text;
|
||||
next.lastMessageTimeMs = localLatest.timeMs;
|
||||
}
|
||||
const current = byPeer.get(key);
|
||||
if (!current) {
|
||||
byPeer.set(key, next);
|
||||
return;
|
||||
}
|
||||
const newest = next.lastMessageTimeMs > current.lastMessageTimeMs ? next : current;
|
||||
newest.relationFlag = relationOrder(relationFlag) < relationOrder(current.relationFlag)
|
||||
? relationFlag
|
||||
: current.relationFlag;
|
||||
newest.unreadCount = Math.max(Number(current.unreadCount || 0), Number(next.unreadCount || 0));
|
||||
newest.hasDialog = Boolean(current.hasDialog || next.hasDialog);
|
||||
byPeer.set(key, newest);
|
||||
});
|
||||
|
||||
byPeer.forEach((item) => rememberDmPeer({
|
||||
login: item.peerLogin,
|
||||
relationType: item.relationFlag,
|
||||
firstName: item.firstName,
|
||||
lastName: item.lastName,
|
||||
avatar: item.avatar,
|
||||
shineStatus: item.shineStatus,
|
||||
}));
|
||||
|
||||
const pinnedOrder = getPinnedDmChats();
|
||||
byPeer.forEach((item) => {
|
||||
const id = normalizeDmChatId(item.peerLogin);
|
||||
item.pinned = pinnedOrder.includes(id);
|
||||
item.muted = isDmChatMuted(id);
|
||||
});
|
||||
// Технический tombstone очистки истории сам по себе не создаёт видимый диалог:
|
||||
// пользователь без связи исчезает после очистки.
|
||||
const nextItems = Array.from(byPeer.values())
|
||||
.filter((item) => normalizeRelationFlag(item.relationFlag) !== 'none' || Boolean(item.hasDialog));
|
||||
// Ничего не изменилось – не перерисовываем (иначе мигают аватары и превью).
|
||||
const unchanged = lastItems && JSON.stringify(nextItems) === JSON.stringify(lastItems) && list.childElementCount;
|
||||
lastItems = nextItems;
|
||||
lastChatList = { login, items: nextItems };
|
||||
if (!unchanged) renderList();
|
||||
} catch (error) {
|
||||
if (disposed || seq !== loadSeq) return;
|
||||
if (isSessionInvalidError(error)) {
|
||||
list.innerHTML = '';
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack';
|
||||
|
||||
const title = document.createElement('strong');
|
||||
title.textContent = t('screens.messages_list.text_013');
|
||||
|
||||
const details = document.createElement('p');
|
||||
details.className = 'meta-muted';
|
||||
details.textContent = t('screens.messages_list.text_014');
|
||||
|
||||
const okBtn = document.createElement('button');
|
||||
okBtn.type = 'button';
|
||||
okBtn.className = 'primary-btn';
|
||||
okBtn.textContent = t('screens.messages_list.text_015');
|
||||
okBtn.addEventListener('click', async () => {
|
||||
await terminateCurrentSession({
|
||||
infoMessage: t('screens.messages_list.text_032'),
|
||||
});
|
||||
navigate('start-view');
|
||||
});
|
||||
|
||||
card.append(title, details, okBtn);
|
||||
list.append(card);
|
||||
return;
|
||||
}
|
||||
// Уже показанный список не стираем из-за неудачного обновления.
|
||||
if (lastItems) return;
|
||||
list.replaceChildren(createErrorState({
|
||||
title: t('screens.messages_list.text_016'),
|
||||
text: toUserMessage(error, t('screens.messages_list.text_017')),
|
||||
onRetry: () => { list.replaceChildren(); void loadList(); },
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
// Фильтр перерисовывает уже загруженный список мгновенно и тихо обновляет его с сервера.
|
||||
reloadForFilter = () => {
|
||||
startExpanded = false;
|
||||
renderList();
|
||||
void loadList();
|
||||
};
|
||||
|
||||
chrome?.setTopbar(chatHeader.head);
|
||||
screen.append(list, rowMenuAnchor);
|
||||
if (lastItems) renderList();
|
||||
loadList();
|
||||
|
||||
// Закрепили или выключили звук (здесь же или в чате) – список перестраивается из кэша сервера.
|
||||
const handlePrefsUpdated = () => { void loadList(); };
|
||||
window.addEventListener(DM_CHAT_PREFS_EVENT, handlePrefsUpdated);
|
||||
|
||||
screen.cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
window.removeEventListener(DM_CHAT_PREFS_EVENT, handlePrefsUpdated);
|
||||
avatarObserver?.disconnect();
|
||||
visibleWaiters.clear();
|
||||
rowMenu.destroy();
|
||||
if (chatSearch) {
|
||||
const { layer } = chatSearch;
|
||||
chatSearch = null;
|
||||
layer?.close();
|
||||
}
|
||||
};
|
||||
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// Экран «Личные сообщения» — единый слой «семантика отношения → визуальное состояние».
|
||||
// messages-list.js только рендерит готовый результат; здесь вся логика выбора тона/статуса/бейджа.
|
||||
// Источник полей — мок directMessages (оффлайн-демо). На проде сюда же подставятся реальные
|
||||
// relationFlagsForTarget / shineConfirmed / shine — UI карточек переписывать не придётся.
|
||||
|
||||
// Тон обода аватара. ВАЖНО: «Подтверждён» НЕ красит обод золотым (золото = семья/близкий круг).
|
||||
// isShining → 'shining' (небесный) ; relationType==='family' → 'family' (золотой) ; иначе 'default' (violet).
|
||||
// toneOverride — только для тестового мока (в проде не задавать).
|
||||
export function resolveAvatarTone(msg) {
|
||||
const o = String(msg?.toneOverride || '').trim();
|
||||
if (o === 'default' || o === 'family' || o === 'shining') return o;
|
||||
if (msg?.isShining) return 'shining';
|
||||
if (msg?.relationType === 'family') return 'family';
|
||||
return 'default';
|
||||
}
|
||||
|
||||
// Непрочитанные: показываем только при >0; 1–99, далее «99+». Отдельная violet-сфера (НЕ изумруд).
|
||||
export function resolveUnreadStyle(msg) {
|
||||
const n = Math.max(0, Math.trunc(Number(msg?.unreadCount ?? msg?.unread ?? 0)) || 0);
|
||||
if (n <= 0) return null;
|
||||
return { count: n, label: n > 99 ? '99+' : String(n) };
|
||||
}
|
||||
|
||||
// Итоговое визуальное состояние карточки.
|
||||
export function resolveDmVisualState(msg) {
|
||||
const via = Array.isArray(msg?.connectedVia) && msg.connectedVia.length ? msg.connectedVia : null;
|
||||
return {
|
||||
tone: resolveAvatarTone(msg), // 'default' | 'family' | 'shining'
|
||||
shining: Boolean(msg?.isShining),
|
||||
confirmed: Boolean(msg?.isConfirmed), // галочка ✓ у имени (без слова «Подтверждён»)
|
||||
via, // путь «через кого»: [{name, photo}, …] | null
|
||||
unread: resolveUnreadStyle(msg), // { count, label } | null
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { render as renderBlockchain } from './my-blockchain-view.js';
|
||||
|
||||
export const pageMeta = { id: 'my-blockchain-history-view', get title() { return t('screens.my_blockchain_history_view.text_001'); } };
|
||||
export function render(context) {
|
||||
return renderBlockchain(context, { historyOnly: true });
|
||||
}
|
||||
@@ -0,0 +1,637 @@
|
||||
import { formatDateTime } from '../i18n/format.js';
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { authService } from '../state.js';
|
||||
import { KeyRotationClient } from '../services/key-rotation-service.js';
|
||||
import { inspectBlockchainDataItem } from '../services/blockchain-entry-inspector.js';
|
||||
import { makeProfileRoute, makeShineChannelRoute, makeShineMessageRoute } from '../services/shine-routes.js';
|
||||
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'my-blockchain-view', get title() { return t('screens.my_blockchain_view.text_001'); } };
|
||||
|
||||
const PROFILE_LABELS = () => new Map([
|
||||
['first_name', t('screens.my_blockchain_view.text_108')],
|
||||
['last_name', t('screens.my_blockchain_view.text_109')],
|
||||
['address', t('screens.my_blockchain_view.text_110')],
|
||||
['web', t('screens.my_blockchain_view.text_111')],
|
||||
['phone', t('screens.my_blockchain_view.text_112')],
|
||||
['about', t('screens.my_blockchain_view.text_113')],
|
||||
['spiritual_path', t('screens.my_blockchain_view.text_114')],
|
||||
['account_role', t('screens.my_blockchain_view.text_115')],
|
||||
['shine', t('screens.my_blockchain_view.text_116')],
|
||||
['gender', t('screens.my_blockchain_view.text_117')],
|
||||
['ava', t('screens.my_blockchain_view.text_118')],
|
||||
]);
|
||||
|
||||
const CONNECTION_LABELS = () => new Map([
|
||||
[10, [t('screens.my_blockchain_view.text_119'), t('screens.my_blockchain_view.text_120')]],
|
||||
[11, [t('screens.my_blockchain_view.text_121'), t('screens.my_blockchain_view.text_122')]],
|
||||
[14, [t('screens.my_blockchain_view.text_123'), t('screens.my_blockchain_view.text_124')]],
|
||||
[15, [t('screens.my_blockchain_view.text_125'), t('screens.my_blockchain_view.text_126')]],
|
||||
[20, [t('screens.my_blockchain_view.text_127'), t('screens.my_blockchain_view.text_128')]],
|
||||
[21, [t('screens.my_blockchain_view.text_129'), t('screens.my_blockchain_view.text_130')]],
|
||||
[30, [t('screens.my_blockchain_view.text_131'), t('screens.my_blockchain_view.text_132')]],
|
||||
[31, [t('screens.my_blockchain_view.text_133'), t('screens.my_blockchain_view.text_134')]],
|
||||
[40, [t('screens.my_blockchain_view.text_135'), t('screens.my_blockchain_view.text_136')]],
|
||||
[41, [t('screens.my_blockchain_view.text_137'), t('screens.my_blockchain_view.text_138')]],
|
||||
[50, [t('screens.my_blockchain_view.text_139'), t('screens.my_blockchain_view.text_140')]],
|
||||
[51, [t('screens.my_blockchain_view.text_141'), t('screens.my_blockchain_view.text_142')]],
|
||||
[52, [t('screens.my_blockchain_view.text_143'), t('screens.my_blockchain_view.text_144')]],
|
||||
[53, [t('screens.my_blockchain_view.text_145'), t('screens.my_blockchain_view.text_146')]],
|
||||
[54, [t('screens.my_blockchain_view.text_147'), t('screens.my_blockchain_view.text_148')]],
|
||||
[55, [t('screens.my_blockchain_view.text_149'), t('screens.my_blockchain_view.text_150')]],
|
||||
[60, [t('screens.my_blockchain_view.text_151'), t('screens.my_blockchain_view.text_152')]],
|
||||
[61, [t('screens.my_blockchain_view.text_153'), t('screens.my_blockchain_view.text_154')]],
|
||||
[70, [t('screens.my_blockchain_view.text_155'), t('screens.my_blockchain_view.text_156')]],
|
||||
[71, [t('screens.my_blockchain_view.text_157'), t('screens.my_blockchain_view.text_158')]],
|
||||
[74, [t('screens.my_blockchain_view.text_159'), t('screens.my_blockchain_view.text_160')]],
|
||||
[75, [t('screens.my_blockchain_view.text_161'), t('screens.my_blockchain_view.text_162')]],
|
||||
[80, [t('screens.my_blockchain_view.text_163'), t('screens.my_blockchain_view.text_164')]],
|
||||
[81, [t('screens.my_blockchain_view.text_165'), t('screens.my_blockchain_view.text_166')]],
|
||||
]);
|
||||
|
||||
const STATUS_LABELS = () => new Map([
|
||||
[10, t('screens.my_blockchain_view.text_167')],
|
||||
[20, t('screens.my_blockchain_view.text_168')],
|
||||
[30, t('screens.my_blockchain_view.text_169')],
|
||||
[100, t('screens.my_blockchain_view.text_170')],
|
||||
[110, t('screens.my_blockchain_view.text_171')],
|
||||
[120, t('screens.my_blockchain_view.text_172')],
|
||||
[130, t('screens.my_blockchain_view.text_173')],
|
||||
[140, t('screens.my_blockchain_view.text_174')],
|
||||
[150, t('screens.my_blockchain_view.text_175')],
|
||||
]);
|
||||
|
||||
const FORK_REASON_LABELS = () => new Map([
|
||||
[1, t('screens.my_blockchain_view.text_176')],
|
||||
[2, t('screens.my_blockchain_view.text_177')],
|
||||
[3, t('screens.my_blockchain_view.text_178')],
|
||||
[4, t('screens.my_blockchain_view.text_179')],
|
||||
]);
|
||||
|
||||
function shortHash(value) {
|
||||
const text = String(value || '');
|
||||
return text.length > 18 ? `${text.slice(0, 9)}…${text.slice(-7)}` : text;
|
||||
}
|
||||
|
||||
function formatDate(ms) {
|
||||
try {
|
||||
return formatDateTime(new Date(Number(ms) || 0));
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function previewText(value) {
|
||||
const rows = String(value || '')
|
||||
.replace(/\r\n/g, '\n')
|
||||
.replace(/\r/g, '\n')
|
||||
.split('\n')
|
||||
.slice(0, 3)
|
||||
.map((row) => row.trim())
|
||||
.filter(Boolean);
|
||||
return rows.join(' ');
|
||||
}
|
||||
|
||||
function profileValueLabel(key, value) {
|
||||
const clean = String(value || '').trim();
|
||||
if (key === 'account_role') {
|
||||
if (clean === 'primary') return t('screens.my_blockchain_view.text_030');
|
||||
if (clean === 'non_voting') return t('screens.my_blockchain_view.text_031');
|
||||
}
|
||||
if (key === 'shine') {
|
||||
if (clean === 'shining' || clean === 'yes') return t('screens.my_blockchain_view.text_032');
|
||||
if (clean === 'not_interested') return t('screens.my_blockchain_view.text_033');
|
||||
if (clean === 'unknown') return t('screens.my_blockchain_view.text_034');
|
||||
}
|
||||
if (key === 'gender') {
|
||||
if (clean === 'male') return t('screens.my_blockchain_view.text_035');
|
||||
if (clean === 'female') return t('screens.my_blockchain_view.text_036');
|
||||
if (clean === 'unknown') return t('screens.my_blockchain_view.text_037');
|
||||
}
|
||||
if (key === 'ava') return t('screens.my_blockchain_view.text_038');
|
||||
return clean;
|
||||
}
|
||||
|
||||
function targetText(target) {
|
||||
if (!target) return '';
|
||||
const login = String(target.toLogin || '').trim();
|
||||
const block = Number(target.toBlockNumber);
|
||||
if (login && Number.isInteger(block) && block >= 0) return t('screens.my_blockchain_view.text_072', { value1: login, value2: block });
|
||||
if (Number.isInteger(block) && block >= 0) return t('screens.my_blockchain_view.text_073', { value1: block });
|
||||
return login || '';
|
||||
}
|
||||
|
||||
function channelNameText(lineCode, channelNames) {
|
||||
const code = Number(lineCode);
|
||||
if (!Number.isInteger(code) || code < 0) return '';
|
||||
const known = channelNames.get(code);
|
||||
if (known) return `«${known}»`;
|
||||
if (code === 0) return '«stories»';
|
||||
return `#${code}`;
|
||||
}
|
||||
|
||||
function channelLabel(lineCode, channelNames) {
|
||||
const name = channelNameText(lineCode, channelNames);
|
||||
return name ? t('screens.my_blockchain_view.text_074', { value1: name }) : t('screens.my_blockchain_view.text_039');
|
||||
}
|
||||
|
||||
function lineTextKindLabel(subType) {
|
||||
if (subType === 100) return t('screens.my_blockchain_view.text_040');
|
||||
if (subType === 110) return t('screens.my_blockchain_view.text_041');
|
||||
if (subType === 120) return t('screens.my_blockchain_view.text_042');
|
||||
if (subType === 130) return t('screens.my_blockchain_view.text_043');
|
||||
return t('screens.my_blockchain_view.text_044');
|
||||
}
|
||||
|
||||
function describeEntry(item, inspection, channelNames) {
|
||||
if (!inspection?.frame) {
|
||||
return {
|
||||
title: t('screens.my_blockchain_view.text_075', { value1: item.msgType, value2: item.msgSubType }),
|
||||
detailTitle: t('screens.my_blockchain_view.text_076', { value1: item.msgType, value2: item.msgSubType }),
|
||||
text: '',
|
||||
attachmentsCount: 0,
|
||||
};
|
||||
}
|
||||
const { frame } = inspection;
|
||||
const body = frame.body || {};
|
||||
const type = Number(frame.type);
|
||||
const subType = Number(frame.subType);
|
||||
|
||||
if (type === 0 && subType === 0) {
|
||||
return { title: t('screens.my_blockchain_view.text_002'), detailTitle: t('screens.my_blockchain_view.text_045'), text: body.login ? t('screens.my_blockchain_view.text_077', { value1: body.login }) : '', attachmentsCount: 0 };
|
||||
}
|
||||
if (type === 0 && subType === 1) {
|
||||
const displayName = String(body.channelMeta?.title || body.channelName || '').trim() || `#${frame.blockNumber}`;
|
||||
return {
|
||||
title: t('screens.my_blockchain_view.text_078', { value1: displayName }),
|
||||
detailTitle: t('screens.my_blockchain_view.text_046'),
|
||||
text: String(body.channelMeta?.description || '').trim(),
|
||||
attachmentsCount: 0,
|
||||
};
|
||||
}
|
||||
if (type === 0 && subType === 2) {
|
||||
const reason = FORK_REASON_LABELS().get(Number(body.reasonCode)) || t('screens.my_blockchain_view.text_079', { value1: body.reasonCode ?? '—' });
|
||||
return {
|
||||
title: t('screens.my_blockchain_view.text_080', { value1: reason }),
|
||||
detailTitle: t('screens.my_blockchain_view.text_047'),
|
||||
text: String(body.comment || '').trim(),
|
||||
attachmentsCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (type === 1 && [10, 100, 110, 120, 130].includes(subType)) {
|
||||
const kind = lineTextKindLabel(subType);
|
||||
const preview = previewText(body.text) || (body.attachmentsCount ? t('screens.my_blockchain_view.text_081', { value1: body.attachmentsCount }) : t('screens.my_blockchain_view.text_048'));
|
||||
return {
|
||||
title: t('screens.my_blockchain_view.text_082', { value1: kind, value2: channelLabel(body.line?.lineCode, channelNames), value3: preview }),
|
||||
detailTitle: t('screens.my_blockchain_view.text_083', { value1: kind, value2: channelLabel(body.line?.lineCode, channelNames) }),
|
||||
text: String(body.text || ''),
|
||||
attachmentsCount: Number(body.attachmentsCount || 0),
|
||||
};
|
||||
}
|
||||
if (type === 1 && subType === 11) {
|
||||
const preview = previewText(body.text) || (body.attachmentsCount ? t('screens.my_blockchain_view.text_084', { value1: body.attachmentsCount }) : t('screens.my_blockchain_view.text_049'));
|
||||
return {
|
||||
title: t('screens.my_blockchain_view.text_085', { value1: preview }),
|
||||
detailTitle: t('screens.my_blockchain_view.text_050'),
|
||||
text: String(body.text || ''),
|
||||
attachmentsCount: Number(body.attachmentsCount || 0),
|
||||
};
|
||||
}
|
||||
if (type === 1 && subType === 20) {
|
||||
const preview = previewText(body.text) || (body.attachmentsCount ? t('screens.my_blockchain_view.text_086', { value1: body.attachmentsCount }) : t('screens.my_blockchain_view.text_051'));
|
||||
return {
|
||||
title: t('screens.my_blockchain_view.text_087', { value1: targetText(body.target), value2: preview }),
|
||||
detailTitle: t('screens.my_blockchain_view.text_088', { value1: targetText(body.target) }),
|
||||
text: String(body.text || ''),
|
||||
attachmentsCount: Number(body.attachmentsCount || 0),
|
||||
};
|
||||
}
|
||||
if (type === 1 && subType === 21) {
|
||||
const preview = previewText(body.text) || (body.attachmentsCount ? t('screens.my_blockchain_view.text_089', { value1: body.attachmentsCount }) : t('screens.my_blockchain_view.text_052'));
|
||||
return {
|
||||
title: t('screens.my_blockchain_view.text_090', { value1: preview }),
|
||||
detailTitle: t('screens.my_blockchain_view.text_053'),
|
||||
text: String(body.text || ''),
|
||||
attachmentsCount: Number(body.attachmentsCount || 0),
|
||||
};
|
||||
}
|
||||
if (type === 1 && subType === 30) {
|
||||
const preview = previewText(body.text) || t('screens.my_blockchain_view.text_067');
|
||||
return {
|
||||
title: t('screens.my_blockchain_view.text_091', { value1: targetText(body.target), value2: preview }),
|
||||
detailTitle: t('screens.my_blockchain_view.text_092', { value1: targetText(body.target) }),
|
||||
text: String(body.text || ''),
|
||||
attachmentsCount: Number(body.attachmentsCount || 0),
|
||||
};
|
||||
}
|
||||
if (type === 1 && subType === 50) {
|
||||
const preview = previewText(body.text) || t('screens.my_blockchain_view.text_068');
|
||||
return {
|
||||
title: t('screens.my_blockchain_view.text_093', { value1: channelLabel(body.line?.lineCode, channelNames), value2: preview }),
|
||||
detailTitle: t('screens.my_blockchain_view.text_094', { value1: targetText(body.target) }),
|
||||
text: String(body.text || ''),
|
||||
attachmentsCount: Number(body.attachmentsCount || 0),
|
||||
};
|
||||
}
|
||||
if (type === 1 && subType === 90) {
|
||||
const channelName = channelNameText(body.line?.lineCode, channelNames);
|
||||
const title = String(body.channelMeta?.title || '').trim();
|
||||
const description = previewText(body.channelMeta?.description || '');
|
||||
const changed = [title ? t('screens.my_blockchain_view.text_095', { value1: title }) : '', (body.channelMeta?.avatarAr || body.channelMeta?.avatarPr) ? t('screens.my_blockchain_view.text_054') : '', description ? t('screens.my_blockchain_view.text_096', { value1: description }) : ''].filter(Boolean).join(' · ');
|
||||
return {
|
||||
title: t('screens.my_blockchain_view.text_097', { value1: channelName ? ` ${channelName}` : '', value2: changed ? ` · ${changed}` : '' }),
|
||||
detailTitle: t('screens.my_blockchain_view.text_098', { value1: channelName ? ` ${channelName}` : '' }),
|
||||
text: String(body.channelMeta?.description || ''),
|
||||
attachmentsCount: 0,
|
||||
};
|
||||
}
|
||||
if (type === 1 && subType === 92) {
|
||||
return {
|
||||
title: t('screens.my_blockchain_view.text_099', { value1: channelNameText(body.line?.lineCode, channelNames) ? ` ${channelNameText(body.line?.lineCode, channelNames)}` : '' }),
|
||||
detailTitle: t('screens.my_blockchain_view.text_055'),
|
||||
text: '',
|
||||
attachmentsCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (type === 2 && (subType === 1 || subType === 2)) {
|
||||
const action = subType === 1 ? t('screens.my_blockchain_view.text_056') : t('screens.my_blockchain_view.text_057');
|
||||
return { title: `${action} · ${targetText(body.target)}`, detailTitle: action, text: '', attachmentsCount: 0 };
|
||||
}
|
||||
|
||||
if (type === 3) {
|
||||
const connection = CONNECTION_LABELS().get(subType);
|
||||
const action = connection?.[0] || t('screens.my_blockchain_view.text_100', { value1: subType });
|
||||
const target = targetText(body.target);
|
||||
return { title: `${action}${target ? ` · ${target}` : ''}`, detailTitle: connection?.[1] || t('screens.my_blockchain_view.text_069'), text: '', attachmentsCount: 0 };
|
||||
}
|
||||
|
||||
if (type === 4 && subType === 1) {
|
||||
const key = String(body.key || '').trim();
|
||||
const label = PROFILE_LABELS().get(key) || key || t('screens.my_blockchain_view.text_070');
|
||||
const value = profileValueLabel(key, body.value);
|
||||
return {
|
||||
title: key === 'ava' ? t('screens.my_blockchain_view.text_058') : t('screens.my_blockchain_view.text_101', { value1: label, value2: previewText(value) || '—' }),
|
||||
detailTitle: t('screens.my_blockchain_view.text_102', { value1: label }),
|
||||
text: key === 'ava' ? '' : String(value || ''),
|
||||
attachmentsCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (type === 5) {
|
||||
const action = STATUS_LABELS().get(subType) || t('screens.my_blockchain_view.text_103', { value1: subType });
|
||||
const preview = previewText(body.text);
|
||||
return {
|
||||
title: `${action} · ${targetText(body.target)}${preview ? `: ${preview}` : ''}`,
|
||||
detailTitle: action,
|
||||
text: String(body.text || ''),
|
||||
attachmentsCount: Number(body.attachmentsCount || 0),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
title: t('screens.my_blockchain_view.text_104', { value1: type, value2: subType }),
|
||||
detailTitle: t('screens.my_blockchain_view.text_105', { value1: type, value2: subType }),
|
||||
text: '',
|
||||
attachmentsCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function targetBlockchainName(target) {
|
||||
const login = String(target?.toLogin || '').trim();
|
||||
const fork = Number(target?.toForkNumber);
|
||||
if (!login || !Number.isInteger(fork) || fork < 1 || fork > 999) return '';
|
||||
return `${login}-${String(fork).padStart(3, '0')}`;
|
||||
}
|
||||
|
||||
function buildInternalAction({ inspection, blockchainName, login }) {
|
||||
const frame = inspection?.frame;
|
||||
const body = frame?.body || {};
|
||||
const type = Number(frame?.type);
|
||||
const subType = Number(frame?.subType);
|
||||
if (type === 0 && subType === 1 && body.channelName) {
|
||||
const route = makeShineChannelRoute({ ownerBlockchainName: blockchainName, channelName: body.channelName });
|
||||
return route ? { label: t('screens.my_blockchain_view.text_003'), route } : null;
|
||||
}
|
||||
if (type === 1 && [10, 20, 50, 100, 110, 120, 130].includes(subType)) {
|
||||
const route = makeShineMessageRoute({ messageBlockchainName: blockchainName, messageBlockNumber: frame.blockNumber });
|
||||
return route ? { label: subType === 20 ? t('screens.my_blockchain_view.text_059') : t('screens.my_blockchain_view.text_060'), route } : null;
|
||||
}
|
||||
if (type === 1 && [11, 21].includes(subType) && Number.isInteger(Number(body.target?.toBlockNumber))) {
|
||||
const route = makeShineMessageRoute({ messageBlockchainName: blockchainName, messageBlockNumber: Number(body.target.toBlockNumber) });
|
||||
return route ? { label: subType === 11 ? t('screens.my_blockchain_view.text_061') : t('screens.my_blockchain_view.text_062'), route } : null;
|
||||
}
|
||||
if ((type === 1 && subType === 30) || type === 2 || type === 5) {
|
||||
const targetBch = targetBlockchainName(body.target);
|
||||
if (!targetBch) return null;
|
||||
const route = makeShineMessageRoute({ messageBlockchainName: targetBch, messageBlockNumber: body.target.toBlockNumber });
|
||||
return route ? { label: t('screens.my_blockchain_view.text_004'), route } : null;
|
||||
}
|
||||
if (type === 4) {
|
||||
const route = makeProfileRoute(login);
|
||||
return route ? { label: t('screens.my_blockchain_view.text_005'), route } : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function addDetailRow(container, label, value, { code = false } = {}) {
|
||||
const clean = String(value ?? '').trim();
|
||||
if (!clean) return;
|
||||
const row = document.createElement('div');
|
||||
row.className = 'my-blockchain-entry__detail-row';
|
||||
const name = document.createElement('span');
|
||||
name.className = 'my-blockchain-entry__detail-key';
|
||||
name.textContent = label;
|
||||
const content = document.createElement(code ? 'code' : 'span');
|
||||
content.className = 'my-blockchain-entry__detail-value';
|
||||
content.textContent = clean;
|
||||
row.append(name, content);
|
||||
container.append(row);
|
||||
}
|
||||
|
||||
function addTargetRows(container, target, fallbackLogin = '') {
|
||||
if (!target) return;
|
||||
const login = String(target.toLogin || fallbackLogin || '').trim();
|
||||
if (login) addDetailRow(container, t('screens.my_blockchain_view.text_012'), login);
|
||||
if (Number.isInteger(Number(target.toForkNumber))) addDetailRow(container, t('screens.my_blockchain_view.text_013'), target.toForkNumber);
|
||||
if (Number.isInteger(Number(target.toBlockNumber))) addDetailRow(container, t('screens.my_blockchain_view.text_014'), `#${target.toBlockNumber}`);
|
||||
if (target.toBlockHash) addDetailRow(container, t('screens.my_blockchain_view.text_015'), target.toBlockHash, { code: true });
|
||||
}
|
||||
|
||||
function createEntryCard({ item, inspection, parseError, channelNames, blockchainName, login, navigate }) {
|
||||
const frame = inspection?.frame;
|
||||
const description = describeEntry(item, inspection, channelNames);
|
||||
const card = document.createElement('article');
|
||||
card.className = 'card my-blockchain-entry';
|
||||
|
||||
const head = document.createElement('div');
|
||||
head.className = 'my-blockchain-entry__head';
|
||||
const copy = document.createElement('div');
|
||||
copy.className = 'my-blockchain-entry__copy';
|
||||
const title = document.createElement('div');
|
||||
title.className = 'my-blockchain-entry__title';
|
||||
title.textContent = `#${item.blockNumber} · ${description.title}`;
|
||||
title.title = title.textContent;
|
||||
const meta = document.createElement('div');
|
||||
meta.className = 'my-blockchain-entry__meta meta-muted';
|
||||
meta.textContent = `${formatDate(item.timestampMs)} · hash ${shortHash(item.blockHash)}`;
|
||||
copy.append(title, meta);
|
||||
|
||||
const toggle = document.createElement('button');
|
||||
toggle.type = 'button';
|
||||
toggle.className = 'ui-button my-blockchain-entry__toggle';
|
||||
toggle.setAttribute('aria-expanded', 'false');
|
||||
toggle.setAttribute('aria-label', t('screens.my_blockchain_view.text_106', { value1: item.blockNumber }));
|
||||
const triangle = document.createElement('span');
|
||||
triangle.className = 'my-blockchain-entry__triangle';
|
||||
triangle.setAttribute('aria-hidden', 'true');
|
||||
toggle.append(triangle);
|
||||
head.append(copy, toggle);
|
||||
|
||||
const details = document.createElement('div');
|
||||
details.className = 'my-blockchain-entry__details';
|
||||
details.hidden = true;
|
||||
|
||||
const detailTitle = document.createElement('strong');
|
||||
detailTitle.className = 'my-blockchain-entry__detail-title';
|
||||
detailTitle.textContent = description.detailTitle;
|
||||
details.append(detailTitle);
|
||||
|
||||
if (description.text) {
|
||||
const fullText = document.createElement('div');
|
||||
fullText.className = 'my-blockchain-entry__full-text';
|
||||
fullText.textContent = description.text;
|
||||
details.append(fullText);
|
||||
}
|
||||
if (description.attachmentsCount > 0) {
|
||||
const attachments = document.createElement('div');
|
||||
attachments.className = 'my-blockchain-entry__attachments meta-muted';
|
||||
attachments.textContent = description.attachmentsCount === 1 ? t('screens.my_blockchain_view.text_063') : t('screens.my_blockchain_view.text_107', { value1: description.attachmentsCount });
|
||||
details.append(attachments);
|
||||
}
|
||||
|
||||
const action = buildInternalAction({ inspection, blockchainName, login });
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'my-blockchain-entry__actions';
|
||||
if (action) {
|
||||
const open = document.createElement('button');
|
||||
open.type = 'button';
|
||||
open.className = 'text-btn my-blockchain-entry__action';
|
||||
open.textContent = action.label;
|
||||
open.addEventListener('click', () => navigate(action.route));
|
||||
actions.append(open);
|
||||
}
|
||||
if (inspection?.arweaveUrl) {
|
||||
const arweave = document.createElement('a');
|
||||
arweave.className = 'my-blockchain-entry__action my-blockchain-entry__external';
|
||||
arweave.href = inspection.arweaveUrl;
|
||||
arweave.target = '_blank';
|
||||
arweave.rel = 'noopener noreferrer';
|
||||
arweave.textContent = t('screens.my_blockchain_view.text_006');
|
||||
actions.append(arweave);
|
||||
}
|
||||
if (actions.childElementCount) details.append(actions);
|
||||
|
||||
const info = document.createElement('div');
|
||||
info.className = 'my-blockchain-entry__detail-grid';
|
||||
const effectiveType = frame ? `${frame.type}/${frame.subType} · v${frame.version}` : `${item.msgType}/${item.msgSubType} · v${item.msgVersion}`;
|
||||
addDetailRow(info, t('screens.my_blockchain_view.text_016'), effectiveType);
|
||||
addDetailRow(info, t('screens.my_blockchain_view.text_017'), `#${item.blockNumber}`);
|
||||
addDetailRow(info, t('screens.my_blockchain_view.text_018'), formatDate(item.timestampMs));
|
||||
addDetailRow(info, t('screens.my_blockchain_view.text_019'), item.blockHash, { code: true });
|
||||
if (inspection?.dataItemId) addDetailRow(info, 'DataItem ID', inspection.dataItemId, { code: true });
|
||||
|
||||
const body = frame?.body || {};
|
||||
if (body.line) {
|
||||
if (Number.isInteger(Number(body.line.lineCode))) addDetailRow(info, t('screens.my_blockchain_view.text_020'), `#${body.line.lineCode}`);
|
||||
if (Number.isInteger(Number(body.line.lineSequence))) addDetailRow(info, t('screens.my_blockchain_view.text_021'), body.line.lineSequence);
|
||||
}
|
||||
if (body.kind === 'profile') {
|
||||
addDetailRow(info, t('screens.my_blockchain_view.text_022'), body.key);
|
||||
addDetailRow(info, t('screens.my_blockchain_view.text_023'), body.value, { code: body.key === 'ava' });
|
||||
}
|
||||
if (body.kind === 'create_channel') {
|
||||
addDetailRow(info, t('screens.my_blockchain_view.text_024'), body.channelName);
|
||||
addDetailRow(info, t('screens.my_blockchain_view.text_025'), `${body.channelType} · v${body.channelTypeVersion}`);
|
||||
}
|
||||
if (body.kind === 'fork') {
|
||||
addDetailRow(info, 'Fork point', `#${body.forkPointBlockNumber}`);
|
||||
addDetailRow(info, t('screens.my_blockchain_view.text_026'), `#${body.parentTipBlockNumber}`);
|
||||
addDetailRow(info, t('screens.my_blockchain_view.text_027'), body.discardedBlocksCount);
|
||||
}
|
||||
if (body.target) addTargetRows(info, body.target, (frame?.type === 1 && [11, 21].includes(Number(frame?.subType))) ? login : '');
|
||||
if (!body.target && item.toLogin) {
|
||||
addTargetRows(info, {
|
||||
toLogin: item.toLogin,
|
||||
toForkNumber: item.toForkNumber,
|
||||
toBlockNumber: item.toBlockNumber,
|
||||
toBlockHash: item.toBlockHash,
|
||||
});
|
||||
}
|
||||
if (parseError) addDetailRow(info, t('screens.my_blockchain_view.text_028'), parseError);
|
||||
details.append(info);
|
||||
|
||||
toggle.addEventListener('click', () => {
|
||||
const expanded = toggle.getAttribute('aria-expanded') !== 'true';
|
||||
toggle.setAttribute('aria-expanded', String(expanded));
|
||||
details.hidden = !expanded;
|
||||
card.classList.toggle('is-expanded', expanded);
|
||||
});
|
||||
|
||||
card.append(head, details);
|
||||
return card;
|
||||
}
|
||||
|
||||
export function render({ navigate, chrome }, { historyOnly = false } = {}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack my-blockchain-screen';
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: historyOnly ? t('screens.my_blockchain_view.text_064') : t('screens.my_blockchain_view.text_065'),
|
||||
back: { label: '←', onClick: () => navigate(historyOnly ? 'my-blockchain-view' : 'settings-view') },
|
||||
}));
|
||||
|
||||
if (!historyOnly) {
|
||||
const intro = document.createElement('div');
|
||||
intro.className = 'card stack';
|
||||
const historyButton = document.createElement('button');
|
||||
historyButton.type = 'button';
|
||||
historyButton.className = 'nav-row';
|
||||
historyButton.textContent = t('screens.my_blockchain_view.text_007');
|
||||
historyButton.addEventListener('click', () => navigate('my-blockchain-history-view'));
|
||||
const filesButton = document.createElement('button');
|
||||
filesButton.type = 'button';
|
||||
filesButton.className = 'nav-row';
|
||||
filesButton.textContent = t('screens.my_blockchain_view.text_008');
|
||||
filesButton.addEventListener('click', () => navigate('arweave-uploads-view'));
|
||||
const remoteButton = document.createElement('button');
|
||||
remoteButton.type = 'button';
|
||||
remoteButton.className = 'nav-row';
|
||||
remoteButton.textContent = t('screens.my_blockchain_view.text_009');
|
||||
remoteButton.addEventListener('click', () => navigate('remote-addblock-session-view'));
|
||||
intro.append(historyButton, filesButton, remoteButton);
|
||||
screen.append(intro);
|
||||
return screen;
|
||||
}
|
||||
|
||||
const list = document.createElement('div');
|
||||
list.className = 'stack my-blockchain-list';
|
||||
list.hidden = false;
|
||||
screen.append(list);
|
||||
const more = document.createElement('button');
|
||||
more.type = 'button';
|
||||
more.className = 'secondary-btn';
|
||||
more.textContent = t('screens.my_blockchain_view.text_010');
|
||||
more.hidden = true;
|
||||
screen.append(more);
|
||||
|
||||
const client = new KeyRotationClient(authService);
|
||||
const channelNames = new Map([[0, 'stories']]);
|
||||
let channelsLoaded = false;
|
||||
let before = null;
|
||||
let loading = false;
|
||||
let disposed = false;
|
||||
let loadSeq = 0;
|
||||
|
||||
async function ensureChannelNames(login) {
|
||||
if (channelsLoaded || !login) return;
|
||||
channelsLoaded = true;
|
||||
try {
|
||||
const payload = await authService.listUserProfileChannels(login, 'owned', 500, 0, true);
|
||||
if (disposed) return;
|
||||
for (const row of Array.isArray(payload?.channels) ? payload.channels : []) {
|
||||
const root = Number(row?.rootBlockNumber);
|
||||
if (!Number.isInteger(root) || root < 0) continue;
|
||||
const name = String(row?.displayName || row?.slug || '').trim();
|
||||
if (name) channelNames.set(root, name);
|
||||
}
|
||||
} catch {
|
||||
// Имена каналов улучшают подписи, но их отсутствие не мешает читать сам сырой блок.
|
||||
}
|
||||
}
|
||||
|
||||
async function load(reset = false) {
|
||||
if (loading || disposed) return;
|
||||
loading = true;
|
||||
more.disabled = true;
|
||||
const seq = ++loadSeq;
|
||||
if (reset) {
|
||||
list.innerHTML = '';
|
||||
before = null;
|
||||
}
|
||||
try {
|
||||
const data = await client.getMyBlockchain({ beforeBlock: before, limit: 50, includeBlockBytes: true });
|
||||
if (disposed || seq !== loadSeq) return;
|
||||
await ensureChannelNames(String(data.login || '').trim());
|
||||
if (disposed || seq !== loadSeq) return;
|
||||
|
||||
if (reset) {
|
||||
const head = document.createElement('div');
|
||||
head.className = 'card stack';
|
||||
head.innerHTML = `<strong>${escapeHtml(data.blockchainName || '—')}</strong><span class="meta-muted">${th('remaining.html_my_blockchain_view.last_block')}${Number(data.tipBlockNumber ?? -1)} · ${shortHash(data.tipBlockHash)}</span>`;
|
||||
list.append(head);
|
||||
}
|
||||
|
||||
const rows = await Promise.all((data.blocks || []).map(async (item) => {
|
||||
if (!item?.blockBytesB64) return { item, inspection: null, parseError: t('screens.my_blockchain_view.text_066') };
|
||||
try {
|
||||
const inspection = await inspectBlockchainDataItem(item.blockBytesB64);
|
||||
const body = inspection?.frame?.body;
|
||||
if (inspection?.frame?.type === 0 && inspection?.frame?.subType === 1) {
|
||||
const root = Number(inspection.frame.blockNumber);
|
||||
const name = String(body?.channelMeta?.title || body?.channelName || '').trim();
|
||||
if (Number.isInteger(root) && root >= 0 && name) channelNames.set(root, name);
|
||||
}
|
||||
return { item, inspection, parseError: '' };
|
||||
} catch (error) {
|
||||
return { item, inspection: null, parseError: String(error?.message || error || t('screens.my_blockchain_view.text_071')) };
|
||||
}
|
||||
}));
|
||||
if (disposed || seq !== loadSeq) return;
|
||||
|
||||
for (const row of rows) {
|
||||
list.append(createEntryCard({
|
||||
...row,
|
||||
channelNames,
|
||||
blockchainName: String(data.blockchainName || '').trim(),
|
||||
login: String(data.login || '').trim(),
|
||||
navigate,
|
||||
}));
|
||||
}
|
||||
|
||||
before = data.nextBeforeBlock;
|
||||
more.hidden = before == null;
|
||||
if (!(data.blocks || []).length && reset) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'card';
|
||||
empty.textContent = t('screens.my_blockchain_view.text_011');
|
||||
list.append(empty);
|
||||
}
|
||||
} catch (error) {
|
||||
if (disposed || seq !== loadSeq) return;
|
||||
const err = document.createElement('div');
|
||||
err.className = 'card';
|
||||
err.textContent = actionErrorText(t('screens.my_blockchain_view.text_029'), error);
|
||||
list.append(err);
|
||||
} finally {
|
||||
if (seq === loadSeq) {
|
||||
loading = false;
|
||||
more.disabled = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
more.addEventListener('click', () => void load(false));
|
||||
void load(true);
|
||||
screen.cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
loadSeq += 1;
|
||||
};
|
||||
return screen;
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value ?? '').replace(/[&<>"]/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[char]));
|
||||
}
|
||||
@@ -0,0 +1,582 @@
|
||||
// SHiNE Explorer V4: та же модель V3, но две статические Canvas 2D-плоскости.
|
||||
// В простое нет requestAnimationFrame, физики, SVG-фильтров и CSS-анимаций.
|
||||
import { buildAvatarInitials } from '../../components/avatar-image.js';
|
||||
import { state } from '../../state.js';
|
||||
import { buildArweaveDataUrl } from '../../services/arweave-file-service.js';
|
||||
import { resolvePublicFileUrl } from '../../services/public-file-service.js';
|
||||
import { PALETTES, ORB_DIAMETER, clamp, rgba, color, keyOf, edgeGradient, edgeCoreGradient, geometryFor } from './graph-style.js';
|
||||
|
||||
export const ZOOM_MIN = 0.55;
|
||||
export const ZOOM_MAX = 2.2;
|
||||
export const DIVE_ZOOM = 1.7;
|
||||
|
||||
// V4: стеклянная внешняя кромка V3 под непрозрачной фотографией; неон V3 на Canvas.
|
||||
const LONG_PRESS_MS = 480;
|
||||
const DRAG_SLOP = 8;
|
||||
const MAX_SPRITES_PER_FRAME = 16;
|
||||
const SPRITE_MEMORY_BUDGET = 96 * 1024 * 1024;
|
||||
const GLASS_URL = '/assets/glass_overlay_faithful.png';
|
||||
const GLASS_SCALE = 1.19; // V3 .fg-pngorb: размер накладки 119% от узла
|
||||
const PHOTO_RATIO = 0.78; // фотография 78% от стеклянного бокса, но рисуется ПОВЕРХ
|
||||
const BADGE_URL = '/assets/shine-official-badge.svg?v=2';
|
||||
|
||||
function makeSpriteCanvas(size) {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = size; canvas.height = size;
|
||||
return canvas;
|
||||
}
|
||||
|
||||
function loadImage(src, notify) {
|
||||
const img = new Image();
|
||||
img.decoding = 'async';
|
||||
img.referrerPolicy = 'no-referrer';
|
||||
// Не устанавливаем crossOrigin: не все внешние Arweave/R2 шлюзы возвращают CORS.
|
||||
// Canvas используется только для отображения, а не для экспорта/readback.
|
||||
img.onload = () => notify(true, img);
|
||||
img.onerror = () => notify(false, img);
|
||||
img.src = src;
|
||||
return img;
|
||||
}
|
||||
|
||||
function avatarSource(node) {
|
||||
const direct = String(node.photo || '').trim();
|
||||
if (direct) return direct;
|
||||
if (typeof node.avatar === 'string') return node.avatar.trim();
|
||||
const txId = String(node.avatar?.ar || '').trim();
|
||||
if (!txId) return '';
|
||||
try {
|
||||
return buildArweaveDataUrl({ gateway: state?.entrySettings?.arweaveServer, txId }) || '';
|
||||
} catch { return ''; }
|
||||
}
|
||||
|
||||
export function createExplorerCanvasGraph({ stage, model, onCenterTap, onNodeTap, onNodeLongPress, onNodeMoveEnd } = {}) {
|
||||
if (!stage) throw new Error('createExplorerCanvasGraph: stage обязателен');
|
||||
const edgesCanvas = document.createElement('canvas');
|
||||
edgesCanvas.className = 'fg-canvas-v4 fg-canvas-v4--edges';
|
||||
edgesCanvas.setAttribute('aria-hidden', 'true');
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.className = 'fg-canvas-v4 fg-canvas-v4--nodes';
|
||||
canvas.setAttribute('role', 'img');
|
||||
const ectx = edgesCanvas.getContext('2d');
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ectx || !ctx) throw new Error('Canvas 2D недоступен');
|
||||
stage.append(edgesCanvas, canvas);
|
||||
const a11y = document.createElement('div');
|
||||
a11y.className = 'fg-a11y';
|
||||
a11y.setAttribute('role', 'region');
|
||||
stage.append(a11y);
|
||||
|
||||
let destroyed = false;
|
||||
let nodes = [];
|
||||
let nodeById = new Map();
|
||||
let focusId = '';
|
||||
let width = 1, height = 1, dpr = 1;
|
||||
let zoom = 1, camX = 0, camY = 0;
|
||||
let frame = 0;
|
||||
let edgesDirty = true;
|
||||
let palette = PALETTES.dark;
|
||||
let spriteScale = 1;
|
||||
let auraSprite = null;
|
||||
const spriteCache = new Map(); // id -> { key, scale, canvas }, меняется только при смене фотографии/LOD
|
||||
const photos = new Map(); // id -> { key, image, ready }
|
||||
let badge = null, glass = null;
|
||||
let badgeReady = false, glassReady = false;
|
||||
|
||||
const requestDraw = (redrawEdges = true) => {
|
||||
if (redrawEdges) edgesDirty = true;
|
||||
if (destroyed || frame) return;
|
||||
frame = requestAnimationFrame(() => { frame = 0; if (!destroyed) draw(); });
|
||||
};
|
||||
badge = loadImage(BADGE_URL, (ok) => { badgeReady = ok; requestDraw(false); });
|
||||
glass = loadImage(GLASS_URL, (ok) => { glassReady = ok; spriteCache.clear(); requestDraw(false); });
|
||||
|
||||
function setupPhoto(node) {
|
||||
const id = keyOf(node.id);
|
||||
const key = JSON.stringify([node.avatar || null, node.photo || '', node.login || '']);
|
||||
if (photos.get(id)?.key === key) return;
|
||||
const entry = { key, image: null, ready: false };
|
||||
photos.set(id, entry);
|
||||
spriteCache.delete(id);
|
||||
let url = avatarSource(node);
|
||||
if (!url && node.avatar?.pr && !node.avatar?.ar) {
|
||||
void resolvePublicFileUrl({ pr: String(node.avatar.pr), authorLogin: String(node.login || '') })
|
||||
.then((resolved) => { if (!destroyed && photos.get(id) === entry && resolved) start(resolved); })
|
||||
.catch(() => {});
|
||||
} else if (url) start(url);
|
||||
function start(src) {
|
||||
entry.image = loadImage(src, (ok, image) => {
|
||||
if (destroyed || photos.get(id) !== entry) return;
|
||||
entry.ready = ok && image.naturalWidth > 0;
|
||||
spriteCache.delete(id);
|
||||
requestDraw(false);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function makeAura() {
|
||||
const c = makeSpriteCanvas(160);
|
||||
const a = c.getContext('2d');
|
||||
const g = a.createRadialGradient(80, 80, 15, 80, 80, 80);
|
||||
g.addColorStop(0, rgba(palette.shine, .50));
|
||||
g.addColorStop(.45, rgba(palette.shine, .23));
|
||||
g.addColorStop(1, rgba(palette.shine, 0));
|
||||
a.fillStyle = g; a.fillRect(0, 0, 160, 160);
|
||||
return c;
|
||||
}
|
||||
|
||||
function desiredSpriteScale() {
|
||||
const need = Math.max(1, dpr * zoom * 1.15);
|
||||
// Подготавливаем всех пользователей, поэтому масштаб также ограничен общим бюджетом памяти.
|
||||
const bytesPerScale = Math.max(1, nodes.length) * (ORB_DIAMETER * GLASS_SCALE) ** 2 * 4;
|
||||
const budgetScale = Math.max(1, Math.sqrt(SPRITE_MEMORY_BUDGET / bytesPerScale));
|
||||
const maxScale = Math.min(8, budgetScale);
|
||||
let candidate = 1;
|
||||
while (candidate * 2 <= maxScale && candidate < need) candidate *= 2;
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function spriteKey(node, photo) {
|
||||
return JSON.stringify([node.id, node.name, node.login, photo?.key, photo?.ready, glassReady, palette === PALETTES.light]);
|
||||
}
|
||||
|
||||
function buildSprite(node) {
|
||||
const photo = photos.get(keyOf(node.id));
|
||||
const key = spriteKey(node, photo);
|
||||
// Единый спрайт: стеклянная кромка снизу, полностью непрозрачный аватар сверху.
|
||||
// Отдельного красного/синего кольца категории НЕ рисуем.
|
||||
const side = Math.max(2, Math.ceil(ORB_DIAMETER * GLASS_SCALE * spriteScale));
|
||||
const sprite = makeSpriteCanvas(side);
|
||||
const g = sprite.getContext('2d');
|
||||
const center = side / 2;
|
||||
const photoRadius = center * PHOTO_RATIO;
|
||||
const diameter = photoRadius * 2;
|
||||
|
||||
// Непрозрачный фон между фотографией и стеклянным краем:
|
||||
// неон нижнего canvas не просвечивает через стеклянную сферу.
|
||||
g.fillStyle = palette.bg;
|
||||
g.beginPath(); g.arc(center, center, center - .5 * spriteScale, 0, Math.PI * 2); g.fill();
|
||||
if (glassReady && glass?.naturalWidth) {
|
||||
g.drawImage(glass, 0, 0, side, side);
|
||||
} else {
|
||||
// Минимальный резервный стеклянный край, если файл пока не загрузился.
|
||||
g.strokeStyle = rgba(palette.shine, .33);
|
||||
g.lineWidth = Math.max(1, spriteScale * 1.2);
|
||||
g.beginPath(); g.arc(center, center, center - g.lineWidth * 1.4, 0, 2 * Math.PI); g.stroke();
|
||||
}
|
||||
|
||||
// Фото В ПОСЛЕДНЮЮ ОЧЕРЕДЬ поверх самого стекла, без затенения бликами.
|
||||
g.save();
|
||||
g.beginPath(); g.arc(center, center, photoRadius, 0, Math.PI * 2); g.clip();
|
||||
g.fillStyle = palette.bg;
|
||||
g.fillRect(center - photoRadius, center - photoRadius, diameter, diameter);
|
||||
if (photo?.ready && photo.image?.naturalWidth) {
|
||||
const img = photo.image;
|
||||
const crop = Math.min(img.naturalWidth, img.naturalHeight);
|
||||
g.drawImage(img, (img.naturalWidth - crop) / 2, (img.naturalHeight - crop) / 2,
|
||||
crop, crop, center - photoRadius, center - photoRadius, diameter, diameter);
|
||||
} else {
|
||||
const initials = buildAvatarInitials({ login: node.login || node.id, firstName: node.name || '' });
|
||||
g.fillStyle = palette.text;
|
||||
g.textAlign = 'center'; g.textBaseline = 'middle';
|
||||
g.font = `600 ${Math.round(side * .24)}px system-ui, sans-serif`;
|
||||
g.fillText(initials, center, center, side * .58);
|
||||
}
|
||||
g.restore();
|
||||
|
||||
const result = { key, scale: spriteScale, canvas: sprite };
|
||||
spriteCache.set(keyOf(node.id), result);
|
||||
return result;
|
||||
}
|
||||
|
||||
function screenPoint(node) {
|
||||
return { x: width / 2 + camX + node.x * zoom, y: height / 2 + camY + node.y * zoom };
|
||||
}
|
||||
function nodeScreenPoint(node) {
|
||||
const p = screenPoint(node);
|
||||
const size = ORB_DIAMETER * (node.visualSmall ? .5 : 1) * zoom;
|
||||
const box = canvas.getBoundingClientRect();
|
||||
const rect = { left: box.left + p.x - size / 2, top: box.top + p.y - size / 2,
|
||||
width: size, height: size, right: box.left + p.x + size / 2, bottom: box.top + p.y + size / 2 };
|
||||
return { x: box.left + p.x, y: rect.top, rect };
|
||||
}
|
||||
|
||||
// Неоновый композит из V3: мягкое размытое поле (16px / blur6),
|
||||
// размытая трубка (6px / blur2), сверху чёткое светлое ядро (2px).
|
||||
// Каждое размытие выполняется ОДИН раз для всех сияющих связей, а не для каждого ребра.
|
||||
const flareCanvas = makeSpriteCanvas(1);
|
||||
const tubeCanvas = makeSpriteCanvas(1);
|
||||
const flareCtx = flareCanvas.getContext('2d');
|
||||
const tubeCtx = tubeCanvas.getContext('2d');
|
||||
|
||||
function drawStroke(g, path, widthPx, strokeStyle, alpha, dash = null) {
|
||||
g.save();
|
||||
g.globalAlpha = alpha;
|
||||
g.lineWidth = widthPx;
|
||||
g.strokeStyle = strokeStyle;
|
||||
g.lineCap = 'round';
|
||||
g.lineJoin = 'round';
|
||||
if (dash) g.setLineDash(dash.map((v) => v * zoom));
|
||||
g.stroke(path);
|
||||
g.restore();
|
||||
}
|
||||
|
||||
function drawNormalEdge(g, path, geo, ref) {
|
||||
// V3: две аккуратные нити вместо двух тяжёлых цветных полос.
|
||||
const gradient = edgeGradient(g, geo, ref, palette);
|
||||
const strength = clamp(Number(ref.strength) || .5, 0, 1);
|
||||
drawStroke(g, path, (2.6 + strength * 1.4) * zoom, gradient, .22);
|
||||
drawStroke(g, path, 1.2 * zoom, gradient, .70);
|
||||
}
|
||||
|
||||
function edgePath(geo, shining, directed) {
|
||||
const path = new Path2D();
|
||||
path.moveTo(geo.x1, geo.y1);
|
||||
if (shining && !directed) {
|
||||
const dx = geo.x2 - geo.x1, dy = geo.y2 - geo.y1;
|
||||
const perpX = -geo.uy, perpY = geo.ux;
|
||||
const amp = Math.min(13, 5 + Math.hypot(dx, dy) * .05);
|
||||
const bowX = geo.cpx - geo.mx, bowY = geo.cpy - geo.my;
|
||||
path.bezierCurveTo(geo.x1 + dx / 3 + bowX + perpX * amp,
|
||||
geo.y1 + dy / 3 + bowY + perpY * amp,
|
||||
geo.x1 + dx * 2 / 3 + bowX - perpX * amp,
|
||||
geo.y1 + dy * 2 / 3 + bowY - perpY * amp,
|
||||
geo.x2, geo.y2);
|
||||
} else path.quadraticCurveTo(geo.cpx, geo.cpy, geo.x2, geo.y2);
|
||||
return path;
|
||||
}
|
||||
|
||||
function paintEdges() {
|
||||
// Вспомогательные холсты создаются один раз и переиспользуются; анимации нет.
|
||||
for (const g of [flareCtx, tubeCtx]) {
|
||||
g.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
g.clearRect(0, 0, width, height);
|
||||
}
|
||||
const origin = { x: width / 2 + camX, y: height / 2 + camY };
|
||||
const shiningEdges = [];
|
||||
for (const node of nodes) {
|
||||
for (const ref of node.edgeParents || []) {
|
||||
const parent = nodeById.get(keyOf(ref?.id));
|
||||
if (!parent || parent === node) continue;
|
||||
const geo = geometryFor(parent, node, zoom, origin, origin);
|
||||
const shining = Boolean(node.shining && parent.shining);
|
||||
const directed = ref.mutual === false;
|
||||
const path = edgePath(geo, shining, directed);
|
||||
if (!shining) {
|
||||
drawNormalEdge(ectx, path, geo, ref);
|
||||
continue;
|
||||
}
|
||||
shiningEdges.push({ path, geo, ref, directed });
|
||||
const dash = directed ? [20, 4] : null; // V3: только направленная сияющая связь пунктирная.
|
||||
drawStroke(flareCtx, path, 16 * zoom, edgeGradient(flareCtx, geo, ref, palette), .42, dash);
|
||||
drawStroke(tubeCtx, path, 6 * zoom, edgeGradient(tubeCtx, geo, ref, palette), .85, dash);
|
||||
}
|
||||
}
|
||||
if (!shiningEdges.length) return;
|
||||
// screen-подсветка и двухслойное размытие соответствуют CSS .fg-plasma-* в V3.
|
||||
// Нет резкой непрозрачной 14px-полосы — только светлая узкая сердцевина.
|
||||
ectx.save();
|
||||
ectx.globalCompositeOperation = 'screen';
|
||||
ectx.filter = `blur(${(6 * zoom).toFixed(2)}px)`;
|
||||
ectx.drawImage(flareCanvas, 0, 0, width, height);
|
||||
ectx.filter = `blur(${(2 * zoom).toFixed(2)}px)`;
|
||||
ectx.drawImage(tubeCanvas, 0, 0, width, height);
|
||||
ectx.filter = 'none';
|
||||
for (const { path, geo, ref, directed } of shiningEdges) {
|
||||
drawStroke(ectx, path, 2 * zoom, edgeCoreGradient(ectx, geo, ref, palette), 1,
|
||||
directed ? [20, 4] : null);
|
||||
}
|
||||
ectx.restore();
|
||||
}
|
||||
|
||||
function paintNodes() {
|
||||
if (!auraSprite) auraSprite = makeAura();
|
||||
let built = 0, needsBuild = false;
|
||||
// Весь свет под всеми аватарками, а не поверх соседних фотографий.
|
||||
for (const node of nodes) {
|
||||
if (!node.shining) continue;
|
||||
const { x, y } = screenPoint(node);
|
||||
const size = ORB_DIAMETER * (node.visualSmall ? .5 : 1) * zoom * 1.95;
|
||||
ctx.drawImage(auraSprite, x - size / 2, y - size / 2, size, size);
|
||||
}
|
||||
// Все пользователи рисуются, в том числе за пределами экрана — по решению для V4.
|
||||
for (const node of nodes) {
|
||||
const { x, y } = screenPoint(node);
|
||||
const size = ORB_DIAMETER * (node.visualSmall ? .5 : 1) * zoom;
|
||||
const id = keyOf(node.id);
|
||||
const cached = spriteCache.get(id);
|
||||
const photo = photos.get(id);
|
||||
const currentKey = spriteKey(node, photo);
|
||||
let sprite = cached;
|
||||
if (!cached || cached.key !== currentKey || cached.scale !== spriteScale) {
|
||||
if (built < MAX_SPRITES_PER_FRAME) { sprite = buildSprite(node); built += 1; }
|
||||
else needsBuild = true;
|
||||
}
|
||||
if (sprite) {
|
||||
const imageSize = size * GLASS_SCALE;
|
||||
ctx.drawImage(sprite.canvas, x - imageSize / 2, y - imageSize / 2, imageSize, imageSize);
|
||||
} else {
|
||||
ctx.fillStyle = rgba(color(palette, node.relationType), .8);
|
||||
ctx.beginPath(); ctx.arc(x, y, size / 2, 0, 2 * Math.PI); ctx.fill();
|
||||
}
|
||||
if (badgeReady && node.official) {
|
||||
const badgeSize = Math.max(12, size * .32);
|
||||
ctx.drawImage(badge, x - size / 2, y + size / 2 - badgeSize, badgeSize, badgeSize);
|
||||
}
|
||||
}
|
||||
// Подписи V2: компактные округлённые плашки без толстого контура текста.
|
||||
// Приоритет центра и близких, защита от пересечений и резервная позиция сверху.
|
||||
ctx.save();
|
||||
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
|
||||
const fontFamily = getComputedStyle(stage).fontFamily || 'sans-serif';
|
||||
const occupied = nodes.map((node) => {
|
||||
const { x, y } = screenPoint(node);
|
||||
const r = ORB_DIAMETER * (node.visualSmall ? .25 : .5) * zoom;
|
||||
return { left: x - r - 2, right: x + r + 2, top: y - r - 2, bottom: y + r + 2 };
|
||||
});
|
||||
const collides = (r) => occupied.some((other) =>
|
||||
r.left < other.right && r.right > other.left && r.top < other.bottom && r.bottom > other.top);
|
||||
const priority = (node) => node.id === focusId ? 0 :
|
||||
(node.relationType === 'close_friend' ? 1 : node.relationType === 'friend' ? 2 : 3) +
|
||||
Math.max(0, Number(node.distance) || 0) * 5;
|
||||
const ordered = [...nodes].sort((a, b) => priority(a) - priority(b) || a.id.localeCompare(b.id));
|
||||
const MAX_LABEL_CHARS = 18;
|
||||
for (const node of ordered) {
|
||||
const { x, y } = screenPoint(node);
|
||||
const isFocus = node.id === focusId;
|
||||
const r = ORB_DIAMETER * (node.visualSmall ? .25 : .5) * zoom;
|
||||
if (!isFocus && r < 6.5) continue;
|
||||
const original = String(node.name || node.login || node.id).trim();
|
||||
const words = original.split(/\s+/).filter(Boolean);
|
||||
// Вторая версия показывает «Имя Ф.» для обычных участников и полное имя центра.
|
||||
const short = !isFocus && words.length >= 2 ? `${words[0]} ${words[1][0]}.` : original;
|
||||
const label = short.length > MAX_LABEL_CHARS ? `${short.slice(0, MAX_LABEL_CHARS - 1)}…` : short;
|
||||
const fontSize = Math.round(clamp((isFocus ? 13 : node.visualSmall ? 10.5 : 12) * zoom,
|
||||
isFocus ? 12.5 : node.visualSmall ? 10 : 11, isFocus ? 16 : node.visualSmall ? 13 : 15) * 2) / 2;
|
||||
ctx.font = `${isFocus ? 700 : 500} ${fontSize}px ${fontFamily}`;
|
||||
const labelW = ctx.measureText(label).width;
|
||||
const padX = fontSize * .5;
|
||||
const w = labelW + padX * 2;
|
||||
const h = Math.round(fontSize * 1.5);
|
||||
const gap = isFocus ? 5 : 3;
|
||||
let y0 = y + r + gap;
|
||||
let bounds = { left: x - w / 2 - 2, right: x + w / 2 + 2, top: y0 - 1, bottom: y0 + h + 1 };
|
||||
if (collides(bounds)) {
|
||||
const above = y - r - gap - h;
|
||||
const alternate = { ...bounds, top: above - 1, bottom: above + h + 1 };
|
||||
if (!collides(alternate)) { y0 = above; bounds = alternate; }
|
||||
else if (!isFocus) continue;
|
||||
}
|
||||
occupied.push(bounds);
|
||||
const x0 = x - w / 2;
|
||||
ctx.fillStyle = palette === PALETTES.light ? 'rgba(230,237,243,.88)' : 'rgba(23,36,49,.82)';
|
||||
ctx.beginPath();
|
||||
if (ctx.roundRect) ctx.roundRect(x0, y0, w, h, h / 2);
|
||||
else ctx.rect(x0, y0, w, h);
|
||||
ctx.fill();
|
||||
ctx.fillStyle = palette.text;
|
||||
ctx.fillText(label, x, y0 + h / 2 + .5);
|
||||
}
|
||||
ctx.restore();
|
||||
return needsBuild;
|
||||
}
|
||||
|
||||
function draw() {
|
||||
if (width <= 0 || height <= 0) return;
|
||||
if (edgesDirty) {
|
||||
ectx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
ectx.clearRect(0, 0, width, height);
|
||||
paintEdges();
|
||||
edgesDirty = false;
|
||||
}
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
ctx.clearRect(0, 0, width, height);
|
||||
if (paintNodes()) requestDraw(false);
|
||||
}
|
||||
|
||||
function updateSize() {
|
||||
const rect = stage.getBoundingClientRect();
|
||||
const w = Math.max(1, Math.round(rect.width || stage.clientWidth || 1));
|
||||
const h = Math.max(1, Math.round(rect.height || stage.clientHeight || 1));
|
||||
const ratio = clamp(window.devicePixelRatio || 1, 1, 2.5);
|
||||
if (w === width && h === height && ratio === dpr) return;
|
||||
width = w; height = h; dpr = ratio;
|
||||
for (const element of [canvas, edgesCanvas, flareCanvas, tubeCanvas]) {
|
||||
element.width = Math.ceil(w * dpr); element.height = Math.ceil(h * dpr);
|
||||
if (element === canvas || element === edgesCanvas) {
|
||||
element.style.width = `${w}px`; element.style.height = `${h}px`;
|
||||
}
|
||||
}
|
||||
const nextScale = desiredSpriteScale();
|
||||
if (nextScale !== spriteScale) spriteScale = nextScale;
|
||||
requestDraw();
|
||||
}
|
||||
|
||||
function setModel(next) {
|
||||
const oldFocus = focusId;
|
||||
focusId = keyOf(next?.focusId);
|
||||
const seen = new Set();
|
||||
nodes = (Array.isArray(next?.nodes) ? next.nodes : []).map((raw) => {
|
||||
const id = keyOf(raw.id);
|
||||
seen.add(id);
|
||||
const node = { ...raw, id, x: Number(raw.layoutX) || 0, y: Number(raw.layoutY) || 0 };
|
||||
setupPhoto(node);
|
||||
return node;
|
||||
});
|
||||
nodeById = new Map(nodes.map((n) => [n.id, n]));
|
||||
for (const id of photos.keys()) if (!seen.has(id)) { photos.delete(id); spriteCache.delete(id); }
|
||||
for (const id of spriteCache.keys()) if (!seen.has(id)) spriteCache.delete(id);
|
||||
if (oldFocus && focusId !== oldFocus) { camX = 0; camY = 0; }
|
||||
spriteScale = desiredSpriteScale();
|
||||
a11y.textContent = `Граф связей: ${nodes.length} пользователей. Центр: ${nodes.find((n) => n.id === focusId)?.name || focusId}.`;
|
||||
requestDraw();
|
||||
}
|
||||
|
||||
function updateZoom(next, sx = width / 2, sy = height / 2) {
|
||||
const value = clamp(next, ZOOM_MIN, ZOOM_MAX);
|
||||
if (Math.abs(value - zoom) < .00001) return;
|
||||
const factor = value / zoom;
|
||||
camX = sx - width / 2 - (sx - width / 2 - camX) * factor;
|
||||
camY = sy - height / 2 - (sy - height / 2 - camY) * factor;
|
||||
zoom = value;
|
||||
spriteScale = desiredSpriteScale();
|
||||
requestDraw();
|
||||
}
|
||||
|
||||
function hitNode(clientX, clientY) {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const sx = clientX - rect.left, sy = clientY - rect.top;
|
||||
for (let i = nodes.length - 1; i >= 0; i -= 1) {
|
||||
const node = nodes[i];
|
||||
const p = screenPoint(node);
|
||||
const r = Math.max(8, ORB_DIAMETER / 2 * (node.visualSmall ? .5 : 1) * zoom);
|
||||
if (Math.hypot(sx - p.x, sy - p.y) <= r) return node;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const pointers = new Map();
|
||||
let gesture = null, pinchDistance = 0, longTimer = 0;
|
||||
const clearLong = () => { if (longTimer) window.clearTimeout(longTimer); longTimer = 0; };
|
||||
function pointerDown(e) {
|
||||
if (e.button !== undefined && e.button !== 0) return;
|
||||
e.preventDefault();
|
||||
try { canvas.setPointerCapture(e.pointerId); } catch {}
|
||||
pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
||||
clearLong();
|
||||
if (pointers.size >= 2) {
|
||||
const pts = [...pointers.values()];
|
||||
pinchDistance = Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y) || 1;
|
||||
gesture = { pinching: true };
|
||||
return;
|
||||
}
|
||||
const node = hitNode(e.clientX, e.clientY);
|
||||
gesture = { id: e.pointerId, x: e.clientX, y: e.clientY, camX, camY,
|
||||
node, nodeX: node?.x || 0, nodeY: node?.y || 0, moved: false, longFired: false };
|
||||
if (node && typeof onNodeLongPress === 'function') {
|
||||
longTimer = window.setTimeout(() => {
|
||||
if (!gesture || gesture.moved || gesture.pinching || destroyed) return;
|
||||
gesture.longFired = true;
|
||||
onNodeLongPress(node, nodeScreenPoint(node));
|
||||
}, LONG_PRESS_MS);
|
||||
}
|
||||
}
|
||||
function pointerMove(e) {
|
||||
if (pointers.has(e.pointerId)) pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
||||
if (pointers.size >= 2 && gesture?.pinching) {
|
||||
const pts = [...pointers.values()];
|
||||
const dist = Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y) || 1;
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
updateZoom(zoom * dist / (pinchDistance || dist), (pts[0].x + pts[1].x) / 2 - rect.left,
|
||||
(pts[0].y + pts[1].y) / 2 - rect.top);
|
||||
pinchDistance = dist;
|
||||
return;
|
||||
}
|
||||
if (!gesture || gesture.id !== e.pointerId || gesture.longFired) {
|
||||
canvas.classList.toggle('is-over-node', Boolean(hitNode(e.clientX, e.clientY)));
|
||||
return;
|
||||
}
|
||||
const dx = e.clientX - gesture.x, dy = e.clientY - gesture.y;
|
||||
if (Math.hypot(dx, dy) > DRAG_SLOP) { gesture.moved = true; clearLong(); }
|
||||
if (!gesture.moved) return;
|
||||
if (gesture.node) {
|
||||
gesture.node.x = gesture.nodeX + dx / zoom;
|
||||
gesture.node.y = gesture.nodeY + dy / zoom;
|
||||
} else { camX = gesture.camX + dx; camY = gesture.camY + dy; }
|
||||
requestDraw();
|
||||
}
|
||||
function pointerUp(e) {
|
||||
pointers.delete(e.pointerId);
|
||||
clearLong();
|
||||
try { canvas.releasePointerCapture(e.pointerId); } catch {}
|
||||
if (gesture?.pinching) { if (pointers.size < 2) gesture = null; return; }
|
||||
if (!gesture || gesture.id !== e.pointerId) return;
|
||||
const completed = gesture;
|
||||
gesture = null;
|
||||
if (completed.longFired) return;
|
||||
if (completed.moved) {
|
||||
if (completed.node) onNodeMoveEnd?.(completed.node, { x: completed.node.x, y: completed.node.y });
|
||||
return;
|
||||
}
|
||||
if (!completed.node) return;
|
||||
if (completed.node.id === focusId) onCenterTap?.(completed.node, nodeScreenPoint(completed.node));
|
||||
else onNodeTap?.(completed.node);
|
||||
}
|
||||
function onCancel(e) { pointers.delete(e.pointerId); clearLong(); gesture = null; }
|
||||
function onWheel(e) {
|
||||
e.preventDefault();
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
updateZoom(zoom * Math.exp(-e.deltaY * .0016), e.clientX - rect.left, e.clientY - rect.top);
|
||||
}
|
||||
function onContextMenu(e) {
|
||||
e.preventDefault();
|
||||
const node = hitNode(e.clientX, e.clientY);
|
||||
if (node) onNodeLongPress?.(node, nodeScreenPoint(node));
|
||||
}
|
||||
function onTheme() {
|
||||
const next = document.documentElement.dataset.theme === 'light' ? PALETTES.light : PALETTES.dark;
|
||||
if (palette === next) return;
|
||||
palette = next; spriteCache.clear(); auraSprite = null; requestDraw();
|
||||
}
|
||||
|
||||
canvas.addEventListener('pointerdown', pointerDown);
|
||||
canvas.addEventListener('pointermove', pointerMove);
|
||||
canvas.addEventListener('pointerup', pointerUp);
|
||||
canvas.addEventListener('pointercancel', onCancel);
|
||||
canvas.addEventListener('lostpointercapture', onCancel);
|
||||
canvas.addEventListener('wheel', onWheel, { passive: false });
|
||||
canvas.addEventListener('contextmenu', onContextMenu);
|
||||
const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(updateSize) : null;
|
||||
observer?.observe(stage);
|
||||
window.addEventListener('resize', updateSize);
|
||||
const themeObserver = typeof MutationObserver === 'function' ?
|
||||
new MutationObserver(onTheme) : null;
|
||||
themeObserver?.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
|
||||
onTheme();
|
||||
updateSize();
|
||||
setModel(model);
|
||||
|
||||
return {
|
||||
setModel, nodeScreenPoint,
|
||||
getFocusNode: () => nodeById.get(focusId) || null,
|
||||
recenter: () => { camX = 0; camY = 0; updateZoom(DIVE_ZOOM); requestDraw(); },
|
||||
destroy: () => {
|
||||
if (destroyed) return;
|
||||
destroyed = true;
|
||||
clearLong(); pointers.clear();
|
||||
if (frame) cancelAnimationFrame(frame);
|
||||
observer?.disconnect(); themeObserver?.disconnect();
|
||||
window.removeEventListener('resize', updateSize);
|
||||
canvas.removeEventListener('pointerdown', pointerDown);
|
||||
canvas.removeEventListener('pointermove', pointerMove);
|
||||
canvas.removeEventListener('pointerup', pointerUp);
|
||||
canvas.removeEventListener('pointercancel', onCancel);
|
||||
canvas.removeEventListener('lostpointercapture', onCancel);
|
||||
canvas.removeEventListener('wheel', onWheel);
|
||||
canvas.removeEventListener('contextmenu', onContextMenu);
|
||||
photos.clear(); spriteCache.clear();
|
||||
edgesCanvas.remove(); canvas.remove(); a11y.remove();
|
||||
},
|
||||
// Диагностика без зависимости от структуры canvas.
|
||||
debugState: () => ({ nodeCount: nodes.length, zoom, spriteScale, cachedSprites: spriteCache.size, frameQueued: !!frame }),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// Цвета и геометрия V4: чистые функции без DOM и загрузки картинок.
|
||||
export const ORB_DIAMETER = 58;
|
||||
export const PALETTES = {
|
||||
dark: {
|
||||
family: [255, 159, 94], friend: [120, 179, 255], close_friend: [255, 76, 92],
|
||||
business: [190, 150, 255], contact: [170, 190, 220], self: [140, 240, 255],
|
||||
shine: [0, 229, 255], text: '#e7ebf3', shadow: 'rgba(0, 0, 0, .78)', bg: '#172431',
|
||||
},
|
||||
light: {
|
||||
family: [184, 92, 20], friend: [38, 96, 196], close_friend: [214, 38, 55],
|
||||
business: [108, 62, 200], contact: [92, 98, 121], self: [6, 86, 122],
|
||||
shine: [10, 127, 179], text: '#202332', shadow: 'rgba(255, 255, 255, .86)', bg: '#e6edf3',
|
||||
},
|
||||
};
|
||||
|
||||
export const clamp = (v, min, max) => Math.max(min, Math.min(max, v));
|
||||
export const rgba = (rgb, alpha = 1) => `rgba(${rgb[0]},${rgb[1]},${rgb[2]},${alpha})`;
|
||||
export const color = (palette, type) => palette[type] || palette.contact;
|
||||
export const keyOf = (id) => String(id ?? '').toLowerCase();
|
||||
|
||||
export function hash01(value) {
|
||||
let h = 2166136261;
|
||||
for (const ch of String(value)) { h ^= ch.charCodeAt(0); h = Math.imul(h, 16777619); }
|
||||
return (h >>> 0) / 4294967296;
|
||||
}
|
||||
// Градиент на концах кривой: исходящий тип -> обратный тип (если он известен).
|
||||
// У одностороннего отношения линия затухает к адресату, без бегущих штрихов.
|
||||
export function edgeGradient(ctx, geometry, ref, palette) {
|
||||
const forward = color(palette, ref.relationType || 'friend');
|
||||
const reverse = color(palette, ref.reverseRelationType || ref.relationType || 'friend');
|
||||
const grad = ctx.createLinearGradient(geometry.x1, geometry.y1, geometry.x2, geometry.y2);
|
||||
grad.addColorStop(0, rgba(forward, 0.98));
|
||||
grad.addColorStop(1, rgba(reverse, ref.mutual === false ? 0.035 : 0.98));
|
||||
return grad;
|
||||
}
|
||||
// V3 рисует светлую сердцевину, а не ещё один толстый насыщенный цветной слой.
|
||||
// Здесь слегка высветляем цвет для сохранения сине-красного перехода взаимной связи.
|
||||
export function edgeCoreGradient(ctx, geometry, ref, palette) {
|
||||
const tint = (rgb, alpha) => rgba(rgb.map((v) => Math.round(v * .36 + 255 * .64)), alpha);
|
||||
const forward = color(palette, ref.relationType || 'friend');
|
||||
const reverse = color(palette, ref.reverseRelationType || ref.relationType || 'friend');
|
||||
const grad = ctx.createLinearGradient(geometry.x1, geometry.y1, geometry.x2, geometry.y2);
|
||||
grad.addColorStop(0, tint(forward, .98));
|
||||
grad.addColorStop(1, tint(reverse, ref.mutual === false ? .035 : .98));
|
||||
return grad;
|
||||
}
|
||||
|
||||
export function geometryFor(parent, child, zoom, cx, cy) {
|
||||
const fx = cx.x + parent.x * zoom, fy = cx.y + parent.y * zoom;
|
||||
const tx = cx.x + child.x * zoom, ty = cx.y + child.y * zoom;
|
||||
const dx = tx - fx, dy = ty - fy;
|
||||
const len = Math.hypot(dx, dy) || 1;
|
||||
const ux = dx / len, uy = dy / len;
|
||||
const startR = ORB_DIAMETER * (parent.visualSmall ? .25 : .5) * zoom;
|
||||
const endR = ORB_DIAMETER * (child.visualSmall ? .25 : .5) * zoom;
|
||||
const x1 = fx + ux * startR, y1 = fy + uy * startR;
|
||||
const x2 = tx - ux * endR, y2 = ty - uy * endR;
|
||||
const mx = (x1 + x2) / 2, my = (y1 + y2) / 2;
|
||||
const bow = clamp(Math.hypot(x2 - x1, y2 - y1) * .10, 7, 22) *
|
||||
(hash01(`${parent.id}|${child.id}|edge`) > .5 ? 1 : -1);
|
||||
const cpx = mx - uy * bow * 2, cpy = my + ux * bow * 2;
|
||||
return { x1, y1, x2, y2, cpx, cpy, ux, uy, mx, my, bow };
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// Экран V4 использует ту же модель/состояние/фильтры, что и V3.
|
||||
import { pageMeta, renderExplorer } from '../network-explorer/network-view.js';
|
||||
export { pageMeta };
|
||||
export function render(context = {}) {
|
||||
return renderExplorer(context, { canvas: true });
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
// V3-only cache: IndexedDB + memory fallback, TTL 24 hours. V1/V2 retain 2-minute TTL.
|
||||
export const EXPLORER_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
const DB_NAME = 'shine-network-explorer-v3';
|
||||
const STORE = 'connections';
|
||||
let dbPromise = null;
|
||||
const memory = new Map();
|
||||
const inflight = new Map();
|
||||
let epoch = 0;
|
||||
|
||||
function dbOpen() {
|
||||
if (typeof indexedDB === 'undefined') return Promise.resolve(null);
|
||||
if (!dbPromise) dbPromise = new Promise((resolve) => {
|
||||
try {
|
||||
const request = indexedDB.open(DB_NAME, 1);
|
||||
request.onupgradeneeded = () => request.result.createObjectStore(STORE, { keyPath: 'key' });
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => resolve(null);
|
||||
request.onblocked = () => resolve(null);
|
||||
} catch { resolve(null); }
|
||||
});
|
||||
return dbPromise;
|
||||
}
|
||||
|
||||
async function read(key) {
|
||||
const db = await dbOpen();
|
||||
if (!db) return null;
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
const req = db.transaction(STORE, 'readonly').objectStore(STORE).get(key);
|
||||
req.onsuccess = () => resolve(req.result || null);
|
||||
req.onerror = () => resolve(null);
|
||||
} catch { resolve(null); }
|
||||
});
|
||||
}
|
||||
|
||||
async function write(record) {
|
||||
const db = await dbOpen();
|
||||
if (!db) return;
|
||||
await new Promise((resolve) => {
|
||||
try {
|
||||
const tx = db.transaction(STORE, 'readwrite');
|
||||
tx.objectStore(STORE).put(record);
|
||||
tx.oncomplete = resolve;
|
||||
tx.onerror = resolve;
|
||||
tx.onabort = resolve;
|
||||
} catch { resolve(); }
|
||||
});
|
||||
}
|
||||
|
||||
// Восстанавливаем ранее исследованную карту без сети. Просроченные графы не выдаём:
|
||||
// их обновит обычный запрос, когда пользователь снова откроет соответствующую ветку.
|
||||
export async function readExplorerCachedGraphs(scope, limit = 1000) {
|
||||
const prefix = `${scope}|`;
|
||||
const collected = new Map();
|
||||
for (const row of memory.values()) {
|
||||
if (row.key.startsWith(prefix) && row.savedAt <= Date.now() && Date.now() - row.savedAt < EXPLORER_CACHE_TTL_MS)
|
||||
collected.set(row.key, row);
|
||||
}
|
||||
const db = await dbOpen();
|
||||
if (!db) return [...collected.values()].slice(0, limit);
|
||||
await new Promise((resolve) => {
|
||||
try {
|
||||
const range = IDBKeyRange.bound(prefix, `${prefix}\uffff`);
|
||||
const request = db.transaction(STORE, 'readonly').objectStore(STORE).openCursor(range);
|
||||
request.onerror = () => resolve();
|
||||
request.onsuccess = () => {
|
||||
const cursor = request.result;
|
||||
if (!cursor || collected.size >= limit) { resolve(); return; }
|
||||
const row = cursor.value;
|
||||
if (row?.savedAt <= Date.now() && Date.now() - row.savedAt < EXPLORER_CACHE_TTL_MS)
|
||||
collected.set(row.key, row);
|
||||
cursor.continue();
|
||||
};
|
||||
} catch { resolve(); }
|
||||
});
|
||||
return [...collected.values()].slice(0, limit);
|
||||
}
|
||||
|
||||
export function explorerCacheScope(service, sessionLogin) {
|
||||
return `${String(service?.serverUrl || '').trim().toLowerCase()}|${String(sessionLogin || '').trim()}`;
|
||||
}
|
||||
|
||||
export async function getExplorerGraph(service, login, { scope, force = false } = {}) {
|
||||
const key = `${scope || explorerCacheScope(service, '')}|${String(login || '').trim().toLowerCase()}`;
|
||||
if (!login) throw new Error('LOGIN_REQUIRED');
|
||||
const valid = (record) => record && record.graph && Date.now() - record.savedAt < EXPLORER_CACHE_TTL_MS && record.savedAt <= Date.now();
|
||||
if (!force) {
|
||||
const item = memory.get(key) || await read(key);
|
||||
if (valid(item)) {
|
||||
memory.set(key, item);
|
||||
return item.graph;
|
||||
}
|
||||
}
|
||||
if (inflight.has(key)) return inflight.get(key);
|
||||
const started = epoch;
|
||||
const task = (async () => {
|
||||
const graph = await service.getUserConnectionsGraph(login);
|
||||
if (started !== epoch) throw new Error('EXPLORER_CACHE_INVALIDATED');
|
||||
const record = { key, graph, savedAt: Date.now() };
|
||||
memory.set(key, record);
|
||||
// Ограничиваем горячий слой. Записи IndexedDB остаются до ручной очистки или перезаписи по TTL.
|
||||
while (memory.size > 800) memory.delete(memory.keys().next().value);
|
||||
await write(record);
|
||||
return graph;
|
||||
})();
|
||||
inflight.set(key, task);
|
||||
try { return await task; }
|
||||
finally { if (inflight.get(key) === task) inflight.delete(key); }
|
||||
}
|
||||
|
||||
// Модель V3 должна наследовать время фактического получения ответа, а не время
|
||||
// очередного чтения его из IndexedDB: иначе повторные визиты продлевали бы TTL.
|
||||
export function explorerGraphSavedAt(scope, login) {
|
||||
const key = `${scope}|${String(login || '').trim().toLowerCase()}`;
|
||||
return memory.get(key)?.savedAt || null;
|
||||
}
|
||||
|
||||
export async function clearExplorerGraphCache() {
|
||||
epoch += 1;
|
||||
inflight.clear();
|
||||
memory.clear();
|
||||
const db = await dbOpen();
|
||||
if (!db) return;
|
||||
await new Promise((resolve) => {
|
||||
try {
|
||||
const tx = db.transaction(STORE, 'readwrite');
|
||||
tx.objectStore(STORE).clear();
|
||||
tx.oncomplete = resolve;
|
||||
tx.onerror = resolve;
|
||||
tx.onabort = resolve;
|
||||
} catch { resolve(); }
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
// V3: исследованный (не ограниченный историей центров) граф и видимый BFS-срез.
|
||||
// Храним исходящие дружеские связи с направлением; расстояние для карты считаем
|
||||
// по неориентированному представлению только уже обнаруженных рёбер.
|
||||
export const EXPLORER_MAX_DEPTH = 4;
|
||||
export const EXPLORER_DEFAULT_DEPTH = 1;
|
||||
export const keyOf = (value) => String(value || '').trim().toLowerCase();
|
||||
|
||||
const isFriend = (type) => type === 'friend' || type === 'close_friend';
|
||||
|
||||
function decorate(row, fallback) {
|
||||
const login = String(row?.login || fallback || '').trim();
|
||||
const avatar = row?.avatar?.ar || row?.avatar?.pr
|
||||
? { ar: String(row.avatar.ar || ''), pr: String(row.avatar.pr || row.avatar.pr || '') }
|
||||
: (row?.avatarTxId ? { ar: String(row.avatarTxId) } : null);
|
||||
return {
|
||||
login,
|
||||
name: [row?.firstName, row?.lastName].filter(Boolean).join(' ').trim() || login,
|
||||
avatar,
|
||||
shining: row?.shine === true || row?.shine === 'true' || row?.shineStatus === 'shining',
|
||||
official: row?.official === true || row?.official === 'true' || row?.accountRole === 'primary',
|
||||
shineKnown: row?.shine !== undefined || row?.shineStatus !== undefined,
|
||||
officialKnown: row?.official !== undefined || row?.accountRole !== undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function createExplorerGraph() {
|
||||
const graphs = new Map(); // известные полные исходящие списки
|
||||
const people = new Map();
|
||||
const edges = new Map(); // owner -> friend (направленные)
|
||||
const updatedAt = new Map();
|
||||
|
||||
function remember(row, fallback) {
|
||||
const data = decorate(row, fallback);
|
||||
const id = keyOf(data.login);
|
||||
if (!id) return;
|
||||
const previous = people.get(id);
|
||||
if (!previous) people.set(id, data);
|
||||
else people.set(id, {
|
||||
login: previous.login || data.login,
|
||||
name: data.name && data.name !== data.login ? data.name : previous.name,
|
||||
avatar: data.avatar || previous.avatar,
|
||||
shining: data.shineKnown ? data.shining : previous.shining,
|
||||
official: data.officialKnown ? data.official : previous.official,
|
||||
shineKnown: previous.shineKnown || data.shineKnown,
|
||||
officialKnown: previous.officialKnown || data.officialKnown,
|
||||
});
|
||||
}
|
||||
|
||||
function add(graph, fallbackLogin, savedAt = Date.now()) {
|
||||
const login = String(graph?.login || fallbackLogin || '').trim();
|
||||
const owner = keyOf(login);
|
||||
if (!owner) return;
|
||||
remember({ login }, login);
|
||||
(Array.isArray(graph?.allUsers) ? graph.allUsers : []).forEach((row) => remember(row));
|
||||
// Если граф обновился, старые исходящие рёбра этого владельца больше не действуют.
|
||||
for (const edgeKey of edges.keys()) if (edgeKey.startsWith(`${owner}\u0000`)) edges.delete(edgeKey);
|
||||
const close = new Set((graph?.outCloseFriends || []).map(keyOf));
|
||||
const inboundClose = new Set((graph?.inCloseFriends || []).map(keyOf));
|
||||
const inbound = new Set([...(graph?.inFriends || []), ...inboundClose].map(keyOf));
|
||||
// Сохраняем оригинальный регистр логина для серверного API (ключи графа
|
||||
// нормализуем независимо, только для сопоставления вершин).
|
||||
const friendNames = new Map();
|
||||
for (const raw of [...(graph?.outFriends || []), ...(graph?.outCloseFriends || [])]) {
|
||||
const id = keyOf(raw);
|
||||
if (id && id !== owner && !friendNames.has(id)) friendNames.set(id, String(raw).trim());
|
||||
}
|
||||
const friends = new Set(friendNames.keys());
|
||||
for (const id of friends) {
|
||||
remember({ login: friendNames.get(id) }, id);
|
||||
edges.set(`${owner}\u0000${id}`, {
|
||||
from: owner, to: id, type: close.has(id) ? 'close_friend' : 'friend',
|
||||
reverseType: inboundClose.has(id) ? 'close_friend' : (inbound.has(id) ? 'friend' : null),
|
||||
mutual: inbound.has(id),
|
||||
});
|
||||
}
|
||||
graphs.set(owner, { login, friends, friendLogins: [...friendNames.values()] });
|
||||
updatedAt.set(owner, savedAt);
|
||||
}
|
||||
|
||||
function clear() {
|
||||
graphs.clear(); people.clear(); edges.clear(); updatedAt.clear();
|
||||
}
|
||||
|
||||
function getFriends(login) {
|
||||
return graphs.get(keyOf(login))?.friendLogins || null;
|
||||
}
|
||||
|
||||
function pruneExpired(now = Date.now()) {
|
||||
for (const [id, savedAt] of updatedAt) {
|
||||
if (savedAt <= now && now - savedAt < 24 * 60 * 60 * 1000) continue;
|
||||
graphs.delete(id);
|
||||
updatedAt.delete(id);
|
||||
for (const edgeKey of edges.keys()) {
|
||||
if (edgeKey.startsWith(`${id}\u0000`)) edges.delete(edgeKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function snapshot(centerLogin, { depth = EXPLORER_DEFAULT_DEPTH, x2 = false, close = false, shining = false } = {}) {
|
||||
pruneExpired();
|
||||
const center = keyOf(centerLogin);
|
||||
if (!center) return { focusId: '', nodes: [], preserveHistory: true };
|
||||
const radius = Math.max(0, Math.min(EXPLORER_MAX_DEPTH, Number(depth) || 0)) + (x2 ? 2 : 1);
|
||||
const allowed = (id) => id === center || !shining || Boolean(people.get(id)?.shining);
|
||||
const neighbors = new Map();
|
||||
const eligibleEdges = [];
|
||||
for (const edge of edges.values()) {
|
||||
if (!isFriend(edge.type) || (close && edge.type !== 'close_friend')) continue;
|
||||
if (!allowed(edge.from) || !allowed(edge.to)) continue;
|
||||
eligibleEdges.push(edge);
|
||||
if (!neighbors.has(edge.from)) neighbors.set(edge.from, new Set());
|
||||
if (!neighbors.has(edge.to)) neighbors.set(edge.to, new Set());
|
||||
neighbors.get(edge.from).add(edge.to);
|
||||
neighbors.get(edge.to).add(edge.from);
|
||||
}
|
||||
const distances = new Map([[center, 0]]);
|
||||
const queue = [center];
|
||||
for (let i = 0; i < queue.length; i += 1) {
|
||||
const from = queue[i];
|
||||
const d = distances.get(from);
|
||||
if (d >= radius) continue;
|
||||
for (const to of neighbors.get(from) || []) {
|
||||
if (distances.has(to)) continue;
|
||||
distances.set(to, d + 1);
|
||||
queue.push(to);
|
||||
}
|
||||
}
|
||||
|
||||
// Полностью раскрыт = его исходящий список известен, и ВСЕ разрешённые фильтрами
|
||||
// друзья сейчас видимы. За границей глубины большой аватар становится маленьким.
|
||||
const expanded = new Map();
|
||||
const isExpanded = (id) => {
|
||||
if (expanded.has(id)) return expanded.get(id);
|
||||
const own = graphs.get(id);
|
||||
if (!own) { expanded.set(id, false); return false; }
|
||||
let complete = true;
|
||||
for (const friend of own.friends) {
|
||||
if (!allowed(friend)) continue;
|
||||
if (close && edges.get(`${id}\u0000${friend}`)?.type !== 'close_friend') continue;
|
||||
if (!distances.has(friend)) { complete = false; break; }
|
||||
}
|
||||
expanded.set(id, complete);
|
||||
return complete;
|
||||
};
|
||||
|
||||
const refs = new Map();
|
||||
const edgePairs = new Set();
|
||||
const immediateEdges = new Map();
|
||||
for (const edge of eligibleEdges) {
|
||||
if (!distances.has(edge.from) || !distances.has(edge.to)) continue;
|
||||
if (!immediateEdges.has(edge.from)) immediateEdges.set(edge.from, edge);
|
||||
if (!immediateEdges.has(edge.to)) immediateEdges.set(edge.to, edge);
|
||||
const pair = [edge.from, edge.to].sort();
|
||||
const pairKey = pair.join('\u0000');
|
||||
if (edgePairs.has(pairKey)) continue;
|
||||
edgePairs.add(pairKey);
|
||||
// Линия одна на пару, направленность сохранена в исходном графе.
|
||||
// Направленное ребро оставляем owner -> friend (не алфавитный порядок).
|
||||
const child = edge.to;
|
||||
const parent = edge.from;
|
||||
const reverse = edges.get(`${edge.to}\u0000${edge.from}`);
|
||||
// Периферийные маленькие пользователи не раскрывают собственные связи.
|
||||
// Если оба конца сжаты из-за глубины, линия между ними не рисуется.
|
||||
if (!isExpanded(edge.from) && !isExpanded(edge.to)) continue;
|
||||
const detail = {
|
||||
id: parent,
|
||||
relationType: edge.type,
|
||||
reverseRelationType: reverse?.type || edge.reverseType || null,
|
||||
mutual: Boolean(edge.mutual || reverse),
|
||||
strength: edge.type === 'close_friend' ? 0.9 : 0.55,
|
||||
};
|
||||
if (!refs.has(child)) refs.set(child, []);
|
||||
refs.get(child).push(detail);
|
||||
}
|
||||
const nodes = [...distances].map(([id, d]) => {
|
||||
const person = people.get(id) || { login: id, name: id };
|
||||
const ownEdge = immediateEdges.get(id);
|
||||
return {
|
||||
id,
|
||||
login: person.login,
|
||||
name: person.name,
|
||||
avatar: person.avatar || null,
|
||||
shining: Boolean(person.shining),
|
||||
official: Boolean(person.official),
|
||||
relationType: id === center ? 'self' : (ownEdge?.type || 'friend'),
|
||||
mutual: Boolean(ownEdge?.mutual),
|
||||
strength: ownEdge?.type === 'close_friend' ? 0.9 : 0.55,
|
||||
distance: d,
|
||||
tier: 1, // фиксированная карта; размер определяется visualSmall, НЕ tier.
|
||||
visualSmall: !isExpanded(id),
|
||||
edgeParents: refs.get(id) || [],
|
||||
keepVisible: id === center,
|
||||
};
|
||||
});
|
||||
return { focusId: center, nodes, preserveHistory: true, radius };
|
||||
}
|
||||
|
||||
return { add, clear, snapshot, getFriends, has: (login) => graphs.has(keyOf(login)),
|
||||
isFresh: (login, now = Date.now()) => {
|
||||
const saved = updatedAt.get(keyOf(login));
|
||||
return saved != null && saved <= now && now - saved < 24 * 60 * 60 * 1000;
|
||||
},
|
||||
size: () => graphs.size };
|
||||
}
|
||||
@@ -0,0 +1,480 @@
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { createTopBar } from '../../components/topbar.js';
|
||||
import { iconHtml } from '../../components/ui-icon.js';
|
||||
import { authService, state } from '../../state.js';
|
||||
import { makeProfileRoute, makeProfileLinksRoute } from '../../services/shine-routes.js';
|
||||
import { CONNECTIONS_GRAPH_CHANGED } from '../../services/connections-graph-cache.js';
|
||||
import { createForceGraph } from '../network-legacy/force-graph.js';
|
||||
import { createExplorerCanvasGraph } from '../network-canvas-v4/graph-renderer.js';
|
||||
import { openNodeMenu } from '../network-legacy/node-menu.js';
|
||||
import { createExplorerGraph, keyOf, EXPLORER_DEFAULT_DEPTH, EXPLORER_MAX_DEPTH } from './graph-model.js';
|
||||
import { getExplorerGraph, readExplorerCachedGraphs, clearExplorerGraphCache, explorerCacheScope, explorerGraphSavedAt } from './graph-cache.js';
|
||||
|
||||
export const pageMeta = {
|
||||
id: 'network-view',
|
||||
get title() { return t('screens.network_view.text_001'); },
|
||||
shellMode: {
|
||||
topFade: true, bottomFade: true, bottomFadeAnchor: 'toolbar',
|
||||
fadeProfile: 'edge', contentUnderTopbar: true, scrollContainer: 'locked',
|
||||
},
|
||||
};
|
||||
|
||||
const normalizeLogin = (value) => String(value || '').trim();
|
||||
const escapeHtml = (text) => String(text || '').replaceAll('&', '&').replaceAll('<', '<')
|
||||
.replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", ''');
|
||||
function createDebounced(fn, ms = 2000) {
|
||||
let timer = 0;
|
||||
const debounced = (...args) => { if (timer) window.clearTimeout(timer); timer = window.setTimeout(() => { timer = 0; fn(...args); }, ms); };
|
||||
debounced.cancel = () => { if (timer) window.clearTimeout(timer); timer = 0; };
|
||||
return debounced;
|
||||
}
|
||||
function hash01(value) {
|
||||
let h = 2166136261;
|
||||
for (const ch of String(value)) { h ^= ch.charCodeAt(0); h = Math.imul(h, 16777619); }
|
||||
return (h >>> 0) / 4294967296;
|
||||
}
|
||||
|
||||
// V3/V4 сохраняют исследование при переключении версий внутри вкладки.
|
||||
// Новый вход через нижнюю кнопку «Связи» очищает карту и IndexedDB-графы.
|
||||
let retained = null;
|
||||
let resetBarrier = Promise.resolve();
|
||||
export function resetExplorerOnTabEntry() {
|
||||
retained = null;
|
||||
// Новые загрузки обязаны дождаться очистки, иначе IndexedDB вернёт старую карту.
|
||||
resetBarrier = resetBarrier.catch(() => {}).then(() => clearExplorerGraphCache());
|
||||
}
|
||||
|
||||
export function render(context = {}) {
|
||||
return renderExplorer(context);
|
||||
}
|
||||
|
||||
// Общие для V3 и V4 поиск, кэш, BFS, фильтры и жизненный цикл страницы.
|
||||
export function renderExplorer({ navigate, route, chrome } = {}, { canvas = false } = {}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = `network-screen network-explorer${canvas ? ' network-explorer--canvas' : ''}`;
|
||||
const stage = document.createElement('div');
|
||||
stage.className = 'network-stage';
|
||||
const board = document.createElement('div');
|
||||
board.className = 'network-board network-board--full fg-stage';
|
||||
const toolbar = document.createElement('div');
|
||||
toolbar.className = 'fg-filter-bar app-top-tabs';
|
||||
toolbar.addEventListener('pointerdown', (event) => event.stopPropagation());
|
||||
const status = document.createElement('div');
|
||||
status.className = 'network-explorer__status';
|
||||
status.setAttribute('role', 'status');
|
||||
status.setAttribute('aria-live', 'polite');
|
||||
stage.append(board, toolbar, status);
|
||||
screen.append(stage);
|
||||
|
||||
const scope = explorerCacheScope(authService, state.session.login);
|
||||
if (!retained || retained.scope !== scope) retained = {
|
||||
scope, graph: createExplorerGraph(), positions: new Map(), center: '',
|
||||
depth: EXPLORER_DEFAULT_DEPTH, x2: false, close: false, shining: false, compact: false,
|
||||
};
|
||||
const session = retained;
|
||||
let centerLogin = normalizeLogin(route?.params?.login || session.center || state.session.login);
|
||||
session.center = centerLogin;
|
||||
let engine = null;
|
||||
let disposed = false;
|
||||
let loadSeq = 0;
|
||||
let drawTimer = 0;
|
||||
let searchClose = null;
|
||||
let cacheWasCleared = false;
|
||||
|
||||
function profileRoute(login) {
|
||||
if (keyOf(login) === keyOf(state.session.login)) return 'profile-view';
|
||||
return makeProfileRoute(login);
|
||||
}
|
||||
function updateStatus(text = '') {
|
||||
if (disposed) return;
|
||||
status.textContent = text;
|
||||
status.hidden = !text;
|
||||
}
|
||||
function getSnapshot() {
|
||||
return session.graph.snapshot(centerLogin, session);
|
||||
}
|
||||
function shiftToCenter(login) {
|
||||
const pivot = session.positions.get(keyOf(login));
|
||||
if (!pivot) return;
|
||||
for (const [key, p] of session.positions) {
|
||||
session.positions.set(key, { x: p.x - pivot.x, y: p.y - pivot.y });
|
||||
}
|
||||
}
|
||||
|
||||
// Расставляем только новые узлы. Старые координаты не меняются при загрузке/фильтрах.
|
||||
function placeNodes(nodes) {
|
||||
const occupied = [...session.positions.values()];
|
||||
const byId = new Map(nodes.map((node) => [node.id, node]));
|
||||
const adjacency = new Map();
|
||||
for (const node of nodes) {
|
||||
for (const edge of node.edgeParents || []) {
|
||||
const parent = edge.id;
|
||||
if (!adjacency.has(node.id)) adjacency.set(node.id, []);
|
||||
if (!adjacency.has(parent)) adjacency.set(parent, []);
|
||||
adjacency.get(node.id).push(parent);
|
||||
adjacency.get(parent).push(node.id);
|
||||
}
|
||||
}
|
||||
const center = keyOf(centerLogin);
|
||||
if (!session.positions.has(center)) session.positions.set(center, { x: 0, y: 0 });
|
||||
const pending = nodes.filter((node) => !session.positions.has(node.id)).sort((a, b) => a.distance - b.distance);
|
||||
const spacing = session.compact ? 62 : 84;
|
||||
const minNodeGap = session.compact ? 48 : 66;
|
||||
for (const node of pending) {
|
||||
const connected = (adjacency.get(node.id) || []).filter((id) => session.positions.has(id));
|
||||
const nearest = connected.sort((a, b) => (byId.get(a)?.distance ?? 99) - (byId.get(b)?.distance ?? 99))[0];
|
||||
const base = session.positions.get(nearest) || { x: 0, y: 0 };
|
||||
let point = null;
|
||||
const phase = hash01(node.id) * Math.PI * 2;
|
||||
for (let ring = 1; ring <= 35 && !point; ring += 1) {
|
||||
const count = Math.max(8, Math.round(6 * ring));
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
const angle = phase + Math.PI * 2 * i / count;
|
||||
const x = base.x + Math.cos(angle) * ring * spacing;
|
||||
const y = base.y + Math.sin(angle) * ring * spacing;
|
||||
if (occupied.every((p) => Math.hypot(x - p.x, y - p.y) >= minNodeGap)) { point = { x, y }; break; }
|
||||
}
|
||||
}
|
||||
point ||= { x: base.x + 300, y: base.y + 300 };
|
||||
session.positions.set(node.id, point);
|
||||
occupied.push(point);
|
||||
}
|
||||
}
|
||||
|
||||
function draw() {
|
||||
if (disposed || !centerLogin) return;
|
||||
const model = getSnapshot();
|
||||
placeNodes(model.nodes);
|
||||
model.nodes = model.nodes.map((node) => ({
|
||||
...node, layoutX: session.positions.get(node.id)?.x || 0,
|
||||
layoutY: session.positions.get(node.id)?.y || 0, fixedLayout: true,
|
||||
}));
|
||||
if (engine) engine.setModel(model);
|
||||
else engine = (canvas ? createExplorerCanvasGraph : createForceGraph)({
|
||||
stage: board, model, explorerMode: true,
|
||||
onNodeTap: (node) => { void load(node.login, true); },
|
||||
onCenterTap: (node) => nodeMenu(node, false),
|
||||
onNodeLongPress: (node, point) => nodeMenu(node, true, point),
|
||||
onNodeMoveEnd: (node, point) => savePositions([{ id: node.id, ...point }]),
|
||||
onGroupMoveEnd: savePositions,
|
||||
});
|
||||
}
|
||||
function scheduleDraw() {
|
||||
if (drawTimer || disposed) return;
|
||||
drawTimer = window.setTimeout(() => { drawTimer = 0; draw(); }, 120);
|
||||
}
|
||||
function savePositions(rows) {
|
||||
(rows || []).forEach((row) => {
|
||||
const x = Number(row?.x); const y = Number(row?.y);
|
||||
if (keyOf(row?.id) && Number.isFinite(x) && Number.isFinite(y)) session.positions.set(keyOf(row.id), { x, y });
|
||||
});
|
||||
}
|
||||
function nodeMenu(node, long = false, point = null) {
|
||||
const canvasPoint = canvas ? engine?.nodeScreenPoint?.(node) : null;
|
||||
const rect = node?.el?.getBoundingClientRect?.() || canvasPoint?.rect;
|
||||
openNodeMenu({
|
||||
login: normalizeLogin(node?.login), displayName: String(node?.name || '').trim(),
|
||||
relationType: node?.relationType,
|
||||
point: point || canvasPoint || (rect ? { x: rect.left + rect.width / 2, y: rect.top, rect } : undefined),
|
||||
actions: [
|
||||
{ label: t(long ? 'screens.network_view.text_006' : 'screens.network_view.text_004'), onClick: () => navigate?.(profileRoute(node?.login)) },
|
||||
{ label: t(long ? 'screens.network_view.text_007' : 'screens.network_view.text_005'), onClick: () => navigate?.(`chat/${encodeURIComponent(normalizeLogin(node?.login))}`) },
|
||||
],
|
||||
});
|
||||
}
|
||||
function updateUrl(login, push = false) {
|
||||
const nextPath = `/${makeProfileLinksRoute(login)}`;
|
||||
if (window.location.pathname === nextPath) return;
|
||||
if (push) window.history.pushState({}, '', nextPath);
|
||||
else window.history.replaceState({}, '', nextPath);
|
||||
}
|
||||
async function fetchGraph(login, currentSeq) {
|
||||
const key = keyOf(login);
|
||||
if (session.graph.isFresh(key)) return true;
|
||||
try {
|
||||
const graph = await getExplorerGraph(authService, login, { scope });
|
||||
if (disposed || currentSeq !== loadSeq) return false;
|
||||
session.graph.add(graph, login, explorerGraphSavedAt(scope, login) || Date.now());
|
||||
scheduleDraw();
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (!disposed && currentSeq === loadSeq) console.warn('[Network V3] Failed to load', login, error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
async function load(nextLogin, push = false) {
|
||||
const next = normalizeLogin(nextLogin);
|
||||
if (!next || disposed) return;
|
||||
const seq = ++loadSeq;
|
||||
if (keyOf(next) !== keyOf(centerLogin)) {
|
||||
if (session.positions.has(keyOf(next))) shiftToCenter(next);
|
||||
else {
|
||||
// Поиск неизвестного ранее человека: сдвигаем старую карту от нового центра.
|
||||
for (const [id, p] of session.positions)
|
||||
session.positions.set(id, { x: p.x - 190, y: p.y });
|
||||
}
|
||||
}
|
||||
centerLogin = next;
|
||||
session.center = next;
|
||||
updateUrl(next, push);
|
||||
draw(); // мгновенно показать уже исследованную карту, ещё до завершения сетевых запросов
|
||||
updateStatus(t('screens.network_explorer.loading'));
|
||||
const ok = await fetchGraph(next, seq);
|
||||
if (disposed || seq !== loadSeq) return;
|
||||
if (!ok) { updateStatus(t('screens.network_explorer.error')); return; }
|
||||
draw();
|
||||
if (!session.x2) { updateStatus(); return; }
|
||||
|
||||
const friends = [...(session.graph.getFriends(next) || [])];
|
||||
let index = 0;
|
||||
let finished = 0;
|
||||
let failed = 0;
|
||||
const workers = Array.from({ length: Math.min(4, friends.length) }, async () => {
|
||||
while (index < friends.length && !disposed && seq === loadSeq && session.x2) {
|
||||
const friend = friends[index++];
|
||||
if (!await fetchGraph(friend, seq)) failed += 1;
|
||||
finished += 1;
|
||||
if (!disposed && seq === loadSeq) updateStatus(t('screens.network_explorer.progress', { value1: finished, value2: friends.length }));
|
||||
}
|
||||
});
|
||||
await Promise.all(workers);
|
||||
if (disposed || seq !== loadSeq) return;
|
||||
draw();
|
||||
updateStatus(failed ? t('screens.network_explorer.partial', { value1: failed }) : '');
|
||||
}
|
||||
|
||||
function chip(label, fn, selected = false) {
|
||||
const element = document.createElement('button');
|
||||
element.type = 'button'; element.className = `fg-filter-chip${selected ? ' is-active' : ''}`;
|
||||
element.textContent = label;
|
||||
element.setAttribute('aria-pressed', selected ? 'true' : 'false');
|
||||
element.addEventListener('click', fn);
|
||||
toolbar.append(element);
|
||||
return element;
|
||||
}
|
||||
function actionChip(label, fn) {
|
||||
const element = document.createElement('button');
|
||||
element.type = 'button'; element.className = 'fg-filter-chip';
|
||||
element.textContent = label;
|
||||
element.addEventListener('click', fn);
|
||||
toolbar.append(element);
|
||||
return element;
|
||||
}
|
||||
const closeChip = chip(t('screens.network_view.text_002'), () => {
|
||||
session.close = !session.close;
|
||||
closeChip.classList.toggle('is-active', session.close);
|
||||
closeChip.setAttribute('aria-pressed', String(session.close));
|
||||
draw();
|
||||
}, session.close);
|
||||
const shineChip = chip(t('screens.network_view.text_003'), () => {
|
||||
session.shining = !session.shining;
|
||||
shineChip.classList.toggle('is-active', session.shining);
|
||||
shineChip.setAttribute('aria-pressed', String(session.shining));
|
||||
draw();
|
||||
}, session.shining);
|
||||
const x2Chip = chip('X2', () => {
|
||||
session.x2 = !session.x2;
|
||||
x2Chip.classList.toggle('is-active', session.x2);
|
||||
x2Chip.setAttribute('aria-pressed', String(session.x2));
|
||||
void load(centerLogin);
|
||||
}, session.x2);
|
||||
const depthChip = chip('', () => {
|
||||
session.depth = (session.depth + 1) % (EXPLORER_MAX_DEPTH + 1);
|
||||
syncDepth(); draw();
|
||||
});
|
||||
actionChip(t('screens.network_explorer.compact'), () => {
|
||||
session.compact = true;
|
||||
session.positions.clear();
|
||||
draw();
|
||||
});
|
||||
function syncDepth() {
|
||||
depthChip.textContent = t('screens.network_explorer.depth', { value1: session.depth });
|
||||
depthChip.title = t('screens.network_explorer.depth_hint', { value1: session.depth + (session.x2 ? 2 : 1) });
|
||||
depthChip.setAttribute('aria-label', depthChip.title);
|
||||
}
|
||||
syncDepth();
|
||||
|
||||
async function resetCache() {
|
||||
++loadSeq;
|
||||
cacheWasCleared = true;
|
||||
updateStatus(t('screens.network_explorer.clearing'));
|
||||
await clearExplorerGraphCache();
|
||||
session.graph.clear();
|
||||
session.positions.clear();
|
||||
if (!disposed) void load(centerLogin);
|
||||
}
|
||||
|
||||
|
||||
function openSearchModal() {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!(root instanceof HTMLElement)) return;
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="network-search-modal">
|
||||
<div class="modal-card stack">
|
||||
<button class="icon-btn" type="button" id="network-search-close" style="justify-self:end;">✕</button>
|
||||
<h3 class="modal-title">${t('dialogs.modals.network_view.label_002')}</h3>
|
||||
<div class="row" style="gap:8px;">
|
||||
<input class="input" id="network-search-input" type="text" maxlength="30" placeholder="${t('dialogs.modals.network_view.label_001')}" />
|
||||
<button class="primary-btn" type="button" id="network-search-run">${t('dialogs.modals.network_view.label_003')}</button>
|
||||
</div>
|
||||
<div class="meta-muted" id="network-search-meta">${t('dialogs.modals.network_view.label_004')}</div>
|
||||
<div class="stack" id="network-search-results"></div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const modal = root.querySelector('#network-search-modal');
|
||||
const closeBtn = root.querySelector('#network-search-close');
|
||||
const inputEl = root.querySelector('#network-search-input');
|
||||
const runBtn = root.querySelector('#network-search-run');
|
||||
const metaEl = root.querySelector('#network-search-meta');
|
||||
const resultsEl = root.querySelector('#network-search-results');
|
||||
if (!(modal instanceof HTMLElement) || !(inputEl instanceof HTMLInputElement) || !(resultsEl instanceof HTMLElement)) {
|
||||
root.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
|
||||
let selectedLogin = '';
|
||||
let searchSeq = 0;
|
||||
|
||||
let debouncedSearch = null;
|
||||
const close = () => {
|
||||
++searchSeq;
|
||||
debouncedSearch?.cancel();
|
||||
if (root.contains(modal)) root.innerHTML = '';
|
||||
searchClose = null;
|
||||
};
|
||||
searchClose = close;
|
||||
|
||||
const applySelection = (login) => {
|
||||
selectedLogin = normalizeLogin(login);
|
||||
const rows = resultsEl.querySelectorAll('[data-candidate]');
|
||||
rows.forEach((row) => {
|
||||
if (!(row instanceof HTMLElement)) return;
|
||||
row.classList.toggle('is-selected', String(row.dataset.candidate || '') === selectedLogin);
|
||||
});
|
||||
};
|
||||
|
||||
const renderCandidates = (logins) => {
|
||||
const items = (Array.isArray(logins) ? logins : [])
|
||||
.map((item) => normalizeLogin(item))
|
||||
.filter(Boolean)
|
||||
.slice(0, 5);
|
||||
if (!items.length) {
|
||||
resultsEl.innerHTML = `<div class="meta-muted">${t('dialogs.remaining.pages.network_legacy.network_view.markup.kandidaty_ne_naydeny')}</div>`;
|
||||
applySelection('');
|
||||
return;
|
||||
}
|
||||
resultsEl.innerHTML = items.map((login) => (
|
||||
`<button type="button" class="ghost-btn network-search-candidate" data-candidate="${escapeHtml(login)}">${escapeHtml(login)}</button>`
|
||||
)).join('');
|
||||
applySelection('');
|
||||
};
|
||||
|
||||
const runSearch = async () => {
|
||||
if (disposed || !root.contains(modal)) return;
|
||||
const query = normalizeLogin(inputEl.value);
|
||||
if (!query) {
|
||||
metaEl.textContent = t('dialogs.modals.network_view.label_006');
|
||||
renderCandidates([]);
|
||||
return;
|
||||
}
|
||||
const reqId = ++searchSeq;
|
||||
metaEl.textContent = t('dialogs.remaining.pages.network_legacy_network_view.opensearchmodal.poisk_po_value1', { value1: query });
|
||||
if (runBtn instanceof HTMLButtonElement) runBtn.disabled = true;
|
||||
try {
|
||||
const found = await authService.searchUsers(query);
|
||||
if (disposed || reqId !== searchSeq || !root.contains(modal)) return;
|
||||
renderCandidates(found);
|
||||
const foundCount = Math.min(5, Array.isArray(found) ? found.length : 0);
|
||||
metaEl.textContent = foundCount > 0
|
||||
? t('dialogs.remaining.pages.network_legacy_network_view.opensearchmodal.naydeno_kandidatov_value1_vyberite_odnogo', { value1: foundCount })
|
||||
: t('dialogs.remaining.pages.network_legacy_network_view.opensearchmodal.kandidaty_ne_naydeny');
|
||||
} catch (error) {
|
||||
if (disposed || reqId !== searchSeq || !root.contains(modal)) return;
|
||||
renderCandidates([]);
|
||||
metaEl.textContent = t('dialogs.remaining.pages.network_legacy_network_view.opensearchmodal.oshibka_poiska_value1', { value1: error?.message || 'unknown' });
|
||||
} finally {
|
||||
if (runBtn instanceof HTMLButtonElement) runBtn.disabled = false;
|
||||
}
|
||||
};
|
||||
|
||||
modal.addEventListener('click', (event) => {
|
||||
if (event.target === modal) close();
|
||||
});
|
||||
closeBtn?.addEventListener('click', close);
|
||||
runBtn?.addEventListener('click', () => { void runSearch(); });
|
||||
debouncedSearch = createDebounced(() => { if (!disposed && root.contains(modal)) void runSearch(); }, 2000);
|
||||
inputEl.addEventListener('input', debouncedSearch);
|
||||
inputEl.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
void runSearch();
|
||||
}
|
||||
});
|
||||
resultsEl.addEventListener('click', (event) => {
|
||||
const target = event.target;
|
||||
if (!(target instanceof HTMLElement)) return;
|
||||
const button = target.closest('[data-candidate]');
|
||||
if (!(button instanceof HTMLElement)) return;
|
||||
const nextLogin = String(button.dataset.candidate || '');
|
||||
applySelection(nextLogin);
|
||||
if (!nextLogin) return;
|
||||
close();
|
||||
void load(nextLogin, true);
|
||||
});
|
||||
|
||||
window.setTimeout(() => { if (!disposed && root.contains(modal)) inputEl.focus(); }, 0);
|
||||
}
|
||||
|
||||
// SEARCH_MODAL
|
||||
|
||||
const header = createTopBar({
|
||||
title: t('screens.network_view.text_008'), className: 'topbar--root',
|
||||
actions: [{
|
||||
icon: 'moreVertical', title: t('screens.network_explorer.menu'),
|
||||
ariaLabel: t('screens.network_explorer.menu'),
|
||||
menu: {
|
||||
items: [
|
||||
{ iconHtml: iconHtml('search'), label: t('screens.network_explorer.search'), action: openSearchModal },
|
||||
{ iconHtml: iconHtml('trash'), label: t('screens.network_explorer.clear_cache'), action: () => void resetCache() },
|
||||
],
|
||||
},
|
||||
}],
|
||||
});
|
||||
chrome?.setTopbar(header);
|
||||
const onGraphChanged = () => { void resetCache(); };
|
||||
window.addEventListener(CONNECTIONS_GRAPH_CHANGED, onGraphChanged);
|
||||
const refreshTimer = window.setInterval(() => {
|
||||
if (!disposed && !document.hidden && centerLogin && !session.graph.isFresh(centerLogin))
|
||||
void load(centerLogin);
|
||||
}, 5 * 60 * 1000);
|
||||
screen.cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
++loadSeq;
|
||||
if (drawTimer) window.clearTimeout(drawTimer);
|
||||
window.clearInterval(refreshTimer);
|
||||
window.removeEventListener(CONNECTIONS_GRAPH_CHANGED, onGraphChanged);
|
||||
engine?.destroy(); engine = null;
|
||||
searchClose?.();
|
||||
// TopBar lifetime owned by AppShell, not this screen.
|
||||
};
|
||||
// Кэш графов восстанавливаем только после завершения возможного сброса вкладки.
|
||||
// Фотографии и кэш изображений сброс не затрагивает.
|
||||
void resetBarrier.then(async () => {
|
||||
if (disposed || session !== retained) return;
|
||||
const entries = await readExplorerCachedGraphs(scope);
|
||||
if (disposed || cacheWasCleared || session !== retained) return;
|
||||
entries.forEach((entry) => {
|
||||
const login = entry?.graph?.login || entry?.key?.slice(scope.length + 1);
|
||||
if (login && !session.graph.isFresh(login)) session.graph.add(entry.graph, login, entry.savedAt);
|
||||
});
|
||||
scheduleDraw();
|
||||
if (centerLogin) void load(centerLogin);
|
||||
else window.setTimeout(() => { if (!disposed) openSearchModal(); }, 0);
|
||||
}).catch((error) => {
|
||||
if (!disposed) { console.warn('[Network explorer] Cache reset/read failed', error); if (centerLogin) void load(centerLogin); }
|
||||
});
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// Адаптер реальных данных → нейтральная модель движка force-графа.
|
||||
//
|
||||
// Источник — результат buildGraphModel() из network-view.js (он уже нормализует ответ
|
||||
// authService.getUserConnectionsGraph в роли/направления/метки). Здесь только конвертация
|
||||
// в форму, которую понимает движок ({ focusId, nodes[] }). Сервер не трогаем — это чтение.
|
||||
|
||||
function normLogin(value) {
|
||||
return String(value || '').trim();
|
||||
}
|
||||
const FAMILY_ROLES = ['parent', 'child', 'spouse', 'sibling'];
|
||||
|
||||
function relationTypeFromRelation(relation) {
|
||||
// Тип отношения выбирает владелец рассматриваемого графа.
|
||||
const ownType = String(relation?.relationType || '').trim().toLowerCase();
|
||||
if (ownType === 'close_friend' || ownType === 'friend') return ownType;
|
||||
if (relation?.role === 'friend') return 'friend';
|
||||
return 'contact';
|
||||
}
|
||||
|
||||
// Сила связи (0..1) → радиус орбиты в движке. Реальный API пока не отдаёт численную силу,
|
||||
// поэтому выводим её эвристически из роли и направления связи:
|
||||
// - родственники держим ближе всего, контакты — дальше всего;
|
||||
// - взаимные дружеские связи ближе односторонних.
|
||||
function deriveStrength(relation) {
|
||||
if (relation.isRelative) return 0.9;
|
||||
if (relation?.relationType === 'close_friend') return 0.9;
|
||||
if (relation.role === 'contact') return 0.4;
|
||||
if (relation.forward && relation.backward) return 0.8;
|
||||
return 0.55;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{centerLogin:string, centerMark:object|null, relations:Array}} graphModel
|
||||
* @returns {{focusId:string, nodes:Array}}
|
||||
*/
|
||||
export function engineModelFromGraphModel(graphModel) {
|
||||
const focusLogin = normLogin(graphModel?.centerLogin);
|
||||
const centerMark = graphModel?.centerMark || null;
|
||||
|
||||
const focusNode = {
|
||||
id: focusLogin,
|
||||
login: focusLogin,
|
||||
name: centerMark?.displayName || centerMark?.login || focusLogin,
|
||||
avatar: centerMark?.avatar || null,
|
||||
relationType: 'self',
|
||||
strength: 1,
|
||||
shining: Boolean(centerMark?.shine),
|
||||
official: Boolean(centerMark?.official),
|
||||
tier: 1,
|
||||
};
|
||||
|
||||
const relations = Array.isArray(graphModel?.relations) ? graphModel.relations : [];
|
||||
const seen = new Set();
|
||||
const nodes = relations
|
||||
.map((r) => {
|
||||
const login = normLogin(r?.login);
|
||||
const key = login.toLowerCase();
|
||||
// исключаем сам фокус (не должно быть линии на собственный ник) и дубли
|
||||
if (!login || key === focusLogin.toLowerCase() || seen.has(key)) return null;
|
||||
seen.add(key);
|
||||
return {
|
||||
id: login,
|
||||
login,
|
||||
name: r?.mark?.displayName || login,
|
||||
avatar: r?.mark?.avatar || null,
|
||||
relationType: relationTypeFromRelation(r),
|
||||
strength: deriveStrength(r || {}),
|
||||
shining: Boolean(r?.mark?.shine),
|
||||
official: Boolean(r?.mark?.official),
|
||||
tier: 1,
|
||||
mutual: Boolean(r?.forward && r?.backward),
|
||||
};
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
return { focusId: focusLogin, nodes: [focusNode, ...nodes] };
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,84 @@
|
||||
import { t } from '../../i18n/index.js';
|
||||
// Общее контекстное меню узла (долгое нажатие) для карты связей.
|
||||
// Рендерится в #modal-root (вне масштабируемого холста), позиционируется по экранному rect узла.
|
||||
// Используется и реальным путём (network-view.js), и лабораторией (lab.js).
|
||||
|
||||
const REL_RU = {
|
||||
get family() { return t('screens.node_menu.text_002'); },
|
||||
get friend() { return t('screens.node_menu.text_003'); },
|
||||
get business() { return t('screens.node_menu.text_004'); },
|
||||
get contact() { return t('screens.node_menu.text_005'); },
|
||||
get self() { return t('screens.node_menu.text_006'); },
|
||||
};
|
||||
|
||||
function escapeHtml(text) {
|
||||
return String(text || '')
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
export function relationLabelRu(relationType) {
|
||||
return REL_RU[relationType] || t('screens.node_menu.text_001');
|
||||
}
|
||||
|
||||
/**
|
||||
* Открывает контекстное меню узла.
|
||||
* @param {Object} opts
|
||||
* @param {string} opts.login - логин/идентификатор для заголовка
|
||||
* @param {string} opts.relationType - тип связи (для подписи)
|
||||
* @param {{x:number,y:number,rect?:DOMRect}} opts.point - экранная точка/rect узла
|
||||
* @param {Array<{label:string, onClick:Function, disabled?:boolean}>} opts.actions - пункты меню
|
||||
*/
|
||||
export function openNodeMenu({ login, displayName = '', relationType, point, actions = [] } = {}) {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!(root instanceof HTMLElement)) return;
|
||||
|
||||
const itemsHtml = actions
|
||||
.map((a, i) => `<button class="ui-button fg-menu-item${a.disabled ? ' is-stub' : ''}" type="button" data-i="${i}" role="menuitem"${a.disabled ? ' disabled' : ''}>${escapeHtml(a.label)}</button>`)
|
||||
.join('');
|
||||
|
||||
root.innerHTML = `
|
||||
<div class="fg-menu-overlay" id="fg-menu-overlay">
|
||||
<div class="fg-menu" id="fg-menu" role="menu">
|
||||
<div class="fg-menu-head">
|
||||
<span class="fg-menu-login">${escapeHtml(displayName || login)}</span>${displayName && displayName !== login ? `<small class="fg-menu-secondary-login">${escapeHtml(login)}</small>` : ''}
|
||||
<span class="fg-menu-rel">${escapeHtml(relationLabelRu(relationType))}</span>
|
||||
</div>
|
||||
${itemsHtml}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const overlay = root.querySelector('#fg-menu-overlay');
|
||||
const menu = root.querySelector('#fg-menu');
|
||||
if (!(overlay instanceof HTMLElement) || !(menu instanceof HTMLElement)) { root.innerHTML = ''; return; }
|
||||
|
||||
// позиционируем рядом с узлом по его экранному rect (синхронно, без rAF — он может троттлиться)
|
||||
const rect = point?.rect;
|
||||
const px = point?.x ?? (rect ? rect.left + rect.width / 2 : window.innerWidth / 2);
|
||||
const belowY = rect ? rect.bottom + 8 : (point?.y ?? 80);
|
||||
const mw = menu.offsetWidth;
|
||||
const mh = menu.offsetHeight;
|
||||
let left = px - mw / 2;
|
||||
left = Math.max(8, Math.min(left, window.innerWidth - mw - 8));
|
||||
let top = belowY;
|
||||
if (top + mh > window.innerHeight - 8) top = Math.max(8, (rect ? rect.top : belowY) - mh - 8);
|
||||
menu.style.left = `${left}px`;
|
||||
menu.style.top = `${top}px`;
|
||||
|
||||
const close = () => { root.innerHTML = ''; };
|
||||
overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });
|
||||
menu.addEventListener('click', (e) => {
|
||||
const btn = e.target instanceof HTMLElement ? e.target.closest('[data-i]') : null;
|
||||
if (!(btn instanceof HTMLElement)) return;
|
||||
const idx = Number(btn.dataset.i);
|
||||
const action = actions[idx];
|
||||
if (!action || action.disabled) return;
|
||||
close();
|
||||
if (typeof action.onClick === 'function') action.onClick();
|
||||
});
|
||||
|
||||
return close;
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import * as modernNetworkView from './network-view.js';
|
||||
import * as legacyNetworkView from './network-legacy/network-view.js';
|
||||
import * as explorerNetworkView from './network-explorer/network-view.js';
|
||||
import * as explorerCanvasView from './network-canvas-v4/network-view.js';
|
||||
|
||||
const NETWORK_VERSION_STORAGE_KEY = 'shine.network.version';
|
||||
const MODES = new Set(['legacy', 'modern', 'explorer', 'explorer-canvas']);
|
||||
const DEFAULT_MODE = 'explorer-canvas';
|
||||
|
||||
// Нижняя вкладка сбрасывает только исследованный граф V3/V4, не изображения и не V1/V2.
|
||||
window.addEventListener('shine:network-tab-enter', explorerNetworkView.resetExplorerOnTabEntry);
|
||||
|
||||
export const pageMeta = modernNetworkView.pageMeta;
|
||||
|
||||
function selectedMode() {
|
||||
try {
|
||||
const saved = window.localStorage.getItem(NETWORK_VERSION_STORAGE_KEY);
|
||||
return MODES.has(saved) ? saved : DEFAULT_MODE;
|
||||
} catch {
|
||||
return DEFAULT_MODE;
|
||||
}
|
||||
}
|
||||
|
||||
function saveMode(mode) {
|
||||
try {
|
||||
window.localStorage.setItem(NETWORK_VERSION_STORAGE_KEY, mode);
|
||||
} catch {
|
||||
// Браузер может запретить хранилище в приватном режиме: экран всё равно переключается.
|
||||
}
|
||||
}
|
||||
|
||||
function createModeSwitcher(mode, navigate) {
|
||||
const label = document.createElement('label');
|
||||
label.className = 'network-version-switcher network-version-switcher--topbar';
|
||||
label.innerHTML = t('screens.network_version_switcher.text_001');
|
||||
|
||||
const select = document.createElement('select');
|
||||
select.setAttribute('aria-label', t('screens.network_version_switcher.text_004'));
|
||||
select.innerHTML = `
|
||||
<option value="legacy">${th('screens.network_version_switcher.text_002')}</option>
|
||||
<option value="modern">${th('screens.network_version_switcher.text_003')}</option>
|
||||
<option value="explorer">${th('screens.network_version_switcher.text_005')}</option>
|
||||
<option value="explorer-canvas">V4 · Canvas</option>
|
||||
`;
|
||||
select.value = mode;
|
||||
select.addEventListener('change', () => {
|
||||
const nextMode = MODES.has(select.value) ? select.value : DEFAULT_MODE;
|
||||
saveMode(nextMode);
|
||||
navigate?.('network-view');
|
||||
});
|
||||
label.append(select);
|
||||
return label;
|
||||
}
|
||||
|
||||
export function render(context = {}) {
|
||||
const mode = selectedMode();
|
||||
const implementation = mode === 'legacy' ? legacyNetworkView : (mode === 'explorer' ? explorerNetworkView : (mode === 'explorer-canvas' ? explorerCanvasView : modernNetworkView));
|
||||
const screen = implementation.render(context);
|
||||
screen.classList.add(`network-screen--${mode}`);
|
||||
|
||||
const attachSwitcher = () => {
|
||||
const topbarLeft = document.querySelector('#topbar-slot .topbar__left');
|
||||
if (!topbarLeft || topbarLeft.querySelector('.network-version-switcher')) return;
|
||||
topbarLeft.append(createModeSwitcher(mode, context.navigate));
|
||||
};
|
||||
attachSwitcher();
|
||||
|
||||
const topbarSlot = document.getElementById('topbar-slot');
|
||||
const observer = typeof MutationObserver === 'function' && topbarSlot
|
||||
? new MutationObserver(attachSwitcher)
|
||||
: null;
|
||||
observer?.observe(topbarSlot, { childList: true, subtree: true });
|
||||
|
||||
const pageCleanup = screen.cleanup;
|
||||
screen.cleanup = () => {
|
||||
observer?.disconnect();
|
||||
pageCleanup?.();
|
||||
};
|
||||
return screen;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,61 @@
|
||||
// Ответ сервера (после buildGraphModel в network-view.js) → люди и нити для карты связей.
|
||||
// Сервер не трогаем – только чтение.
|
||||
|
||||
function normLogin(value) {
|
||||
return String(value || '').trim();
|
||||
}
|
||||
|
||||
function normKey(value) {
|
||||
return normLogin(value).toLowerCase();
|
||||
}
|
||||
|
||||
const FAMILY_ROLES = ['parent', 'child', 'spouse', 'sibling'];
|
||||
|
||||
export function relationTypeFromRelation(relation) {
|
||||
// Тип отношения выбирает владелец рассматриваемого графа.
|
||||
const ownType = String(relation?.relationType || '').trim().toLowerCase();
|
||||
if (ownType === 'close_friend' || ownType === 'friend') return ownType;
|
||||
if (relation?.role === 'friend') return 'friend';
|
||||
return 'contact';
|
||||
}
|
||||
|
||||
function personFromMark(login, mark) {
|
||||
return {
|
||||
id: normKey(login),
|
||||
login,
|
||||
name: mark?.displayName || login,
|
||||
firstName: mark?.firstName || '',
|
||||
lastName: mark?.lastName || '',
|
||||
avatar: mark?.avatar || null,
|
||||
shining: Boolean(mark?.shine),
|
||||
official: Boolean(mark?.official),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{centerLogin:string, centerMark:object|null, relations:Array}} graphModel
|
||||
* @returns {{ center: object, peers: Array<{ person: object, relationType: string, mutual: boolean, direction: string }> }}
|
||||
*/
|
||||
export function peopleFromGraphModel(graphModel) {
|
||||
const centerLogin = normLogin(graphModel?.centerLogin);
|
||||
const center = personFromMark(centerLogin, graphModel?.centerMark || null);
|
||||
const seen = new Set([center.id]);
|
||||
const peers = [];
|
||||
for (const relation of Array.isArray(graphModel?.relations) ? graphModel.relations : []) {
|
||||
const login = normLogin(relation?.login);
|
||||
const key = normKey(login);
|
||||
if (!login || seen.has(key) || !relation?.forward) continue;
|
||||
seen.add(key);
|
||||
const forward = Boolean(relation?.forward);
|
||||
const backward = Boolean(relation?.backward);
|
||||
peers.push({
|
||||
person: personFromMark(login, relation?.mark || null),
|
||||
relationType: relationTypeFromRelation(relation),
|
||||
// Пунктир на карте – связь только с одной стороны.
|
||||
mutual: forward && backward,
|
||||
// Со стороны центра: взаимно, только центр (out) или только этот человек (in – «ждёт ответа»).
|
||||
direction: forward && backward ? 'mutual' : (forward ? 'out' : 'in'),
|
||||
});
|
||||
}
|
||||
return { center, peers };
|
||||
}
|
||||
@@ -0,0 +1,660 @@
|
||||
import { t } from '../../i18n/index.js';
|
||||
// Группы людей на карте связей: «Компании» (кто с кем знаком), «Интересы» (кто на что подписан)
|
||||
// и «Города» (кто где живёт).
|
||||
//
|
||||
// Компании ищутся по знакомствам между людьми первого круга – из их собственных графов связей.
|
||||
// Метод Лувена (максимум модулярности) собирает вместе тех, кто плотно знаком между собой:
|
||||
// школа кунг-фу знакома внутри себя, коллеги – внутри себя, а между ними редкие мостики.
|
||||
// Всё считается на устройстве за миллисекунды и детерминированно: те же данные – та же картина.
|
||||
//
|
||||
// Названия: своё (дал владелец карты) → по каналу, который читает большинство компании и
|
||||
// заметно реже остальные → по самому связанному человеку («Илья С. и др.»).
|
||||
//
|
||||
// Раскладка «островами»: внутри компании люди стоят сотами (ровный шаг, подписи не
|
||||
// налезают), в середине – самые связанные, знакомые – рядом. Острова упаковываются вокруг
|
||||
// человека в центре: крупные ближе, связанные между собой – по соседству.
|
||||
|
||||
export const REST_GROUP = 'rest';
|
||||
export const ISLAND_COLORS = 8; // цветов подложек; сами цвета – в движке карты (зависят от темы)
|
||||
|
||||
// Вес знакомства по виду связи: близкие сближают сильнее контактов.
|
||||
const TIE_WEIGHT = { close_friend: 3, family: 3, friend: 2, contact: 1 };
|
||||
const RELATION_RANK = { close_friend: 0, family: 1, friend: 2, contact: 3 };
|
||||
|
||||
export function tieWeight(type, mutual = true) {
|
||||
return (TIE_WEIGHT[type] || 1) * (mutual ? 1 : 0.6);
|
||||
}
|
||||
|
||||
function byName(a, b) {
|
||||
return String(a.name || a.id).localeCompare(String(b.name || b.id), 'ru');
|
||||
}
|
||||
|
||||
// Короткое имя для подписей: «Илья С.»; без фамилии – как есть.
|
||||
export function shortPersonName(person) {
|
||||
const first = String(person?.firstName || '').trim();
|
||||
const last = String(person?.lastName || '').trim();
|
||||
const text = first && last ? `${first} ${last[0]}.` : String(person?.name || person?.login || person?.id || '');
|
||||
return text.length > 18 ? `${text.slice(0, 17)}…` : text;
|
||||
}
|
||||
|
||||
function jaccard(a, b) {
|
||||
if (!a.size || !b.size) return 0;
|
||||
let common = 0;
|
||||
const [small, big] = a.size <= b.size ? [a, b] : [b, a];
|
||||
small.forEach((id) => { if (big.has(id)) common += 1; });
|
||||
return common / (a.size + b.size - common);
|
||||
}
|
||||
|
||||
// --- Сообщества -----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Метод Лувена: узлы переходят в соседнее сообщество, пока это повышает модулярность,
|
||||
* затем сообщества сворачиваются в узлы, и всё повторяется уровнем выше.
|
||||
* @param {string[]} ids
|
||||
* @param {Map<string, Map<string, number>>} weights – веса знакомств (можно несимметрично)
|
||||
* @returns {string[][]} сообщества (одиночки – тоже сообщества)
|
||||
*/
|
||||
export function detectCommunities(ids, weights, { resolution = 1 } = {}) {
|
||||
const order = [...new Set(ids)].sort();
|
||||
if (!order.length) return [];
|
||||
const index = new Map(order.map((id, i) => [id, i]));
|
||||
// Неориентированный граф: у пары – наибольший из весов в обе стороны.
|
||||
const pairs = new Map();
|
||||
weights.forEach((near, a) => {
|
||||
const i = index.get(a);
|
||||
if (i === undefined) return;
|
||||
near.forEach((w, b) => {
|
||||
const j = index.get(b);
|
||||
if (j === undefined || j === i || !(w > 0)) return;
|
||||
const key = i < j ? i * order.length + j : j * order.length + i;
|
||||
pairs.set(key, Math.max(pairs.get(key) || 0, w));
|
||||
});
|
||||
});
|
||||
let adj = order.map(() => new Map());
|
||||
let loops = new Float64Array(order.length);
|
||||
let total = 0;
|
||||
pairs.forEach((w, key) => {
|
||||
const i = Math.floor(key / order.length);
|
||||
const j = key % order.length;
|
||||
adj[i].set(j, w);
|
||||
adj[j].set(i, w);
|
||||
total += w;
|
||||
});
|
||||
if (total <= 0) return order.map((id) => [id]);
|
||||
|
||||
let membership = order.map((_, i) => i); // исходный человек → узел текущего уровня
|
||||
for (let level = 0; level < 16; level += 1) {
|
||||
const n = adj.length;
|
||||
const degree = new Float64Array(n);
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
let k = 2 * loops[i];
|
||||
adj[i].forEach((w) => { k += w; });
|
||||
degree[i] = k;
|
||||
}
|
||||
const m2 = 2 * total;
|
||||
const comm = Int32Array.from({ length: n }, (_, i) => i);
|
||||
const tot = Float64Array.from(degree);
|
||||
let improved = false;
|
||||
for (let pass = 0; pass < 40; pass += 1) {
|
||||
let moved = 0;
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
const own = comm[i];
|
||||
const links = new Map();
|
||||
adj[i].forEach((w, j) => { links.set(comm[j], (links.get(comm[j]) || 0) + w); });
|
||||
tot[own] -= degree[i];
|
||||
let best = own;
|
||||
let bestGain = (links.get(own) || 0) - (resolution * tot[own] * degree[i]) / m2;
|
||||
links.forEach((w, c) => {
|
||||
if (c === own) return;
|
||||
const gain = w - (resolution * tot[c] * degree[i]) / m2;
|
||||
if (gain > bestGain + 1e-12) { best = c; bestGain = gain; }
|
||||
else if (best !== own && Math.abs(gain - bestGain) <= 1e-12 && c < best) best = c;
|
||||
});
|
||||
tot[best] += degree[i];
|
||||
if (best !== own) { comm[i] = best; moved += 1; }
|
||||
}
|
||||
if (!moved) break;
|
||||
improved = true;
|
||||
}
|
||||
if (!improved) break;
|
||||
const renum = new Map();
|
||||
for (let i = 0; i < n; i += 1) if (!renum.has(comm[i])) renum.set(comm[i], renum.size);
|
||||
if (renum.size === n) break;
|
||||
const nextAdj = Array.from({ length: renum.size }, () => new Map());
|
||||
const nextLoops = new Float64Array(renum.size);
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
const ci = renum.get(comm[i]);
|
||||
nextLoops[ci] += loops[i];
|
||||
adj[i].forEach((w, j) => {
|
||||
const cj = renum.get(comm[j]);
|
||||
if (ci === cj) {
|
||||
if (i < j) nextLoops[ci] += w;
|
||||
} else {
|
||||
nextAdj[ci].set(cj, (nextAdj[ci].get(cj) || 0) + w);
|
||||
}
|
||||
});
|
||||
}
|
||||
membership = membership.map((node) => renum.get(comm[node]));
|
||||
adj = nextAdj;
|
||||
loops = nextLoops;
|
||||
}
|
||||
const groups = new Map();
|
||||
membership.forEach((c, i) => {
|
||||
if (!groups.has(c)) groups.set(c, []);
|
||||
groups.get(c).push(order[i]);
|
||||
});
|
||||
return [...groups.values()];
|
||||
}
|
||||
|
||||
// Самый связанный внутри группы: по нему компания узнаётся («Илья С. и др.»).
|
||||
// При равенстве – тот, кто ближе вам, затем по имени.
|
||||
function hubOf(members, weights, byId) {
|
||||
const inside = new Set(members);
|
||||
const rows = members.map((id) => {
|
||||
let score = 0;
|
||||
weights.get(id)?.forEach((w, other) => { if (inside.has(other)) score += w; });
|
||||
const person = byId.get(id) || { id };
|
||||
return { id, score, rank: RELATION_RANK[person.relationType] ?? 9, person };
|
||||
});
|
||||
rows.sort((a, b) => b.score - a.score || a.rank - b.rank || byName(a.person, b.person));
|
||||
return rows[0]?.id || '';
|
||||
}
|
||||
|
||||
// «Илья С. и др.»: число людей подпись покажет отдельно («· 26»), как у названных компаний.
|
||||
function autoLabel(members, hubId, byId) {
|
||||
const hub = shortPersonName(byId.get(hubId) || { id: hubId });
|
||||
return members.length > 1 ? t('screens.communities.text_013', { value1: hub }) : hub;
|
||||
}
|
||||
|
||||
/**
|
||||
* Названия по подпискам: канал, который читает заметная часть группы и заметно чаще,
|
||||
* чем все остальные. Каждый канал – одной группе (с самым сильным перевесом).
|
||||
* @returns {Map<string, string>} id группы → ключ канала
|
||||
*/
|
||||
function channelNames(groups, subs, everyone) {
|
||||
const out = new Map();
|
||||
if (!subs?.of?.size) return out;
|
||||
const total = new Map();
|
||||
let known = 0;
|
||||
for (const id of everyone) {
|
||||
const list = subs.of.get(id);
|
||||
if (!list) continue;
|
||||
known += 1;
|
||||
list.forEach((key) => total.set(key, (total.get(key) || 0) + 1));
|
||||
}
|
||||
if (!known) return out;
|
||||
const candidates = [];
|
||||
for (const group of groups) {
|
||||
const n = group.members.length;
|
||||
if (n < 3) continue;
|
||||
const counts = new Map();
|
||||
group.members.forEach((id) => subs.of.get(id)?.forEach((key) => counts.set(key, (counts.get(key) || 0) + 1)));
|
||||
counts.forEach((count, key) => {
|
||||
const share = count / n;
|
||||
const lift = share / ((total.get(key) || count) / known);
|
||||
if (count >= 3 && share >= 0.34 && lift >= 1.3) candidates.push({ group: group.id, key, score: count * lift });
|
||||
});
|
||||
}
|
||||
candidates.sort((a, b) => b.score - a.score || (a.key < b.key ? -1 : 1));
|
||||
const usedChannels = new Set();
|
||||
for (const row of candidates) {
|
||||
if (out.has(row.group) || usedChannels.has(row.key)) continue;
|
||||
out.set(row.group, row.key);
|
||||
usedChannels.add(row.key);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Цвета островов: свои (сохранённые) остаются; остальным – свободный цвет, а когда свободных
|
||||
// нет – тот, что у наименее связанных с этой группой (на карте связанные стоят рядом,
|
||||
// и одинаковые цвета соседей сливались бы).
|
||||
function assignColors(groups, savedColors, weights = null) {
|
||||
const used = new Map(); // цвет → группы
|
||||
const take = (group, color) => {
|
||||
group.color = color;
|
||||
if (!used.has(color)) used.set(color, []);
|
||||
used.get(color).push(group);
|
||||
};
|
||||
groups.forEach((group) => {
|
||||
const color = savedColors.get(group.id);
|
||||
if (group.kind !== 'rest' && Number.isInteger(color) && color >= 0 && color < ISLAND_COLORS && !used.has(color)) take(group, color);
|
||||
});
|
||||
const affinity = (g1, g2) => {
|
||||
if (!weights) return 0;
|
||||
const inside = new Set(g2.members);
|
||||
let sum = 0;
|
||||
g1.members.forEach((id) => weights.get(id)?.forEach((w, other) => { if (inside.has(other)) sum += w; }));
|
||||
return sum;
|
||||
};
|
||||
groups.forEach((group) => {
|
||||
if (group.kind === 'rest' || Number.isInteger(group.color)) return;
|
||||
// Свой цвет у группы – от её id (у компании это её самый связанный человек): перенос
|
||||
// одного человека или новые знакомые не перекрашивают всю карту.
|
||||
const own = hashColor(group.id);
|
||||
let pick = -1;
|
||||
for (let k = 0; k < ISLAND_COLORS; k += 1) {
|
||||
const c = (own + k) % ISLAND_COLORS;
|
||||
if (!used.has(c)) { pick = c; break; }
|
||||
}
|
||||
if (pick < 0) {
|
||||
let best = Infinity;
|
||||
for (let c = 0; c < ISLAND_COLORS; c += 1) {
|
||||
const clash = used.get(c).reduce((sum, other) => sum + 1 + affinity(group, other), 0);
|
||||
if (clash < best) { best = clash; pick = c; }
|
||||
}
|
||||
}
|
||||
take(group, pick);
|
||||
});
|
||||
}
|
||||
|
||||
function hashColor(text) {
|
||||
let h = 2166136261;
|
||||
for (let i = 0; i < text.length; i += 1) {
|
||||
h ^= text.charCodeAt(i);
|
||||
h = Math.imul(h, 16777619);
|
||||
}
|
||||
return (h >>> 0) % ISLAND_COLORS;
|
||||
}
|
||||
|
||||
function sortGroups(groups) {
|
||||
return groups.sort((a, b) => (a.kind === 'rest') - (b.kind === 'rest')
|
||||
|| b.members.length - a.members.length
|
||||
|| String(a.label).localeCompare(String(b.label), 'ru'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Компании первого круга.
|
||||
* @param {Object} o
|
||||
* @param {Array<{id:string, name:string, firstName?:string, lastName?:string, relationType:string}>} o.people
|
||||
* @param {Map<string, Map<string, number>>} o.weights – веса знакомств
|
||||
* @param {{ groups: Array<{id:string, name:string, members:string[], color?:number}>, assign: Map<string,string> }} o.saved
|
||||
* @param {{ of: Map<string,string[]>, info: Map<string,{name:string}> } | null} [o.subs] – подписки для названий
|
||||
* @returns {{ groups: Array<object>, byPerson: Map<string,string>, snapshots: Array<{id:string, members:string[]}> }}
|
||||
*/
|
||||
export function buildCompanies({ people, weights, saved, subs = null }) {
|
||||
const byId = new Map(people.map((person) => [person.id, person]));
|
||||
const ids = people.map((person) => person.id);
|
||||
const assign = new Map([...(saved?.assign || new Map())].filter(([id]) => byId.has(id)));
|
||||
const savedGroups = (saved?.groups || []).filter((group) => group && group.id);
|
||||
const savedById = new Map(savedGroups.map((group) => [group.id, group]));
|
||||
|
||||
const communities = detectCommunities(ids, weights)
|
||||
.map((members) => members.filter((id) => !assign.has(id)))
|
||||
.filter((members) => members.length);
|
||||
|
||||
// Сохранённые компании узнаются по составу: наибольшее совпадение, не меньше трети.
|
||||
const scores = [];
|
||||
communities.forEach((members, ci) => {
|
||||
const set = new Set(members);
|
||||
savedGroups.forEach((group) => {
|
||||
const score = jaccard(set, new Set((group.members || []).filter((id) => byId.has(id) && !assign.has(id))));
|
||||
if (score >= 0.3) scores.push({ ci, id: group.id, score });
|
||||
});
|
||||
});
|
||||
scores.sort((a, b) => b.score - a.score || a.ci - b.ci || (a.id < b.id ? -1 : 1));
|
||||
const matchedCommunity = new Map();
|
||||
const matchedSaved = new Set();
|
||||
for (const row of scores) {
|
||||
if (matchedCommunity.has(row.ci) || matchedSaved.has(row.id)) continue;
|
||||
matchedCommunity.set(row.ci, row.id);
|
||||
matchedSaved.add(row.id);
|
||||
}
|
||||
|
||||
const groups = new Map();
|
||||
const rest = [];
|
||||
communities.forEach((members, ci) => {
|
||||
const savedId = matchedCommunity.get(ci);
|
||||
if (savedId) {
|
||||
groups.set(savedId, { id: savedId, kind: 'company', members: [...members], saved: true });
|
||||
} else if (members.length >= 3) {
|
||||
const hub = hubOf(members, weights, byId);
|
||||
const id = `a:${hub}`;
|
||||
groups.set(id, { id, kind: 'company', members: [...members], saved: false });
|
||||
} else {
|
||||
rest.push(...members);
|
||||
}
|
||||
});
|
||||
// Перенесённые вручную – в свою компанию (даже если её состав сейчас не узнан).
|
||||
assign.forEach((groupId, personId) => {
|
||||
if (groupId === REST_GROUP) { rest.push(personId); return; }
|
||||
let group = groups.get(groupId);
|
||||
if (!group && savedById.has(groupId)) {
|
||||
group = { id: groupId, kind: 'company', members: [], saved: true };
|
||||
groups.set(groupId, group);
|
||||
}
|
||||
if (group) group.members.push(personId);
|
||||
else rest.push(personId);
|
||||
});
|
||||
|
||||
const list = [...groups.values()].filter((group) => group.members.length);
|
||||
const named = channelNames(list.filter((group) => !savedById.get(group.id)?.name), subs, ids);
|
||||
for (const group of list) {
|
||||
group.members.sort((a, b) => byName(byId.get(a) || { id: a }, byId.get(b) || { id: b }));
|
||||
group.hubId = hubOf(group.members, weights, byId);
|
||||
const own = savedById.get(group.id);
|
||||
group.name = String(own?.name || '').trim();
|
||||
group.channel = named.get(group.id) || '';
|
||||
group.autoLabel = group.channel ? (subs.info.get(group.channel)?.name || '') : '';
|
||||
if (!group.autoLabel) group.autoLabel = autoLabel(group.members, group.hubId, byId);
|
||||
group.label = group.name || group.autoLabel;
|
||||
// Коротко – для подписи на мелкой карте: без «и др.».
|
||||
group.shortLabel = group.name || (group.channel ? group.autoLabel : shortPersonName(byId.get(group.hubId) || { id: group.hubId }));
|
||||
}
|
||||
if (rest.length) {
|
||||
rest.sort((a, b) => byName(byId.get(a) || { id: a }, byId.get(b) || { id: b }));
|
||||
list.push({ id: REST_GROUP, kind: 'rest', members: rest, name: '', autoLabel: t('screens.communities.text_005'), label: t('screens.communities.text_001'), shortLabel: t('screens.communities.text_006'), hubId: '' });
|
||||
}
|
||||
sortGroups(list);
|
||||
assignColors(list, new Map(savedGroups.map((group) => [group.id, group.color])), weights);
|
||||
|
||||
// Состав узнанных компаний обновляется, чтобы их узнавать и дальше, когда люди прибавятся.
|
||||
const snapshots = [];
|
||||
list.forEach((group) => {
|
||||
const own = savedById.get(group.id);
|
||||
if (!own) return;
|
||||
const now = group.members.filter((id) => !assign.has(id));
|
||||
if (jaccard(new Set(now), new Set(own.members || [])) < 0.85 || own.color !== group.color) {
|
||||
snapshots.push({ id: group.id, members: now, color: group.color });
|
||||
}
|
||||
});
|
||||
|
||||
const byPerson = new Map();
|
||||
list.forEach((group) => group.members.forEach((id) => byPerson.set(id, group.id)));
|
||||
return { groups: list, byPerson, snapshots };
|
||||
}
|
||||
|
||||
/**
|
||||
* Интересы: люди собираются у каналов, на которые подписаны. Каждый – у одного канала, самого
|
||||
* «своего»: из читаемых им каналов – того, что реже всего встречается среди этих людей (общие
|
||||
* «Новости района» читают все, а «Ушу» – только свои). Канал, у которого так набирается
|
||||
* меньше minSize человек, группой не считается – его читатели переходят к следующему.
|
||||
* @param {Object} o
|
||||
* @param {Array<{id:string, name:string}>} o.people
|
||||
* @param {{ of: Map<string,string[]>, info: Map<string,{name:string}> }} o.subs
|
||||
*/
|
||||
export function buildInterestGroups({ people, subs }) {
|
||||
const byId = new Map(people.map((person) => [person.id, person]));
|
||||
const followers = new Map();
|
||||
people.forEach((person) => subs?.of?.get(person.id)?.forEach((key) => {
|
||||
if (!followers.has(key)) followers.set(key, []);
|
||||
followers.get(key).push(person.id);
|
||||
}));
|
||||
const minSize = people.length > 30 ? 3 : 2;
|
||||
const eligible = new Set([...followers.entries()].filter(([, ids]) => ids.length >= minSize).map(([key]) => key));
|
||||
let assignment = new Map();
|
||||
for (let round = 0; round < 12; round += 1) {
|
||||
assignment = new Map();
|
||||
for (const person of people) {
|
||||
let best = '';
|
||||
for (const key of subs?.of?.get(person.id) || []) {
|
||||
if (!eligible.has(key)) continue;
|
||||
const n = followers.get(key).length;
|
||||
if (!best || n < followers.get(best).length || (n === followers.get(best).length && key < best)) best = key;
|
||||
}
|
||||
if (best) assignment.set(person.id, best);
|
||||
}
|
||||
const sizes = new Map();
|
||||
assignment.forEach((key) => sizes.set(key, (sizes.get(key) || 0) + 1));
|
||||
let dropped = false;
|
||||
eligible.forEach((key) => {
|
||||
if ((sizes.get(key) || 0) < minSize) { eligible.delete(key); dropped = true; }
|
||||
});
|
||||
if (!dropped) break;
|
||||
}
|
||||
const byChannel = new Map();
|
||||
assignment.forEach((key, id) => {
|
||||
if (!byChannel.has(key)) byChannel.set(key, []);
|
||||
byChannel.get(key).push(id);
|
||||
});
|
||||
const list = [...byChannel.entries()].map(([key, members]) => {
|
||||
const name = String(subs.info.get(key)?.name || key);
|
||||
return { id: `c:${key}`, kind: 'interest', channel: key, members, name: '', autoLabel: name, label: name, shortLabel: name, hubId: '' };
|
||||
});
|
||||
const remaining = new Set(people.map((person) => person.id).filter((id) => !assignment.has(id)));
|
||||
for (const group of list) {
|
||||
group.members.sort((a, b) => byName(byId.get(a) || { id: a }, byId.get(b) || { id: b }));
|
||||
// Что ещё читают в этой группе – для карточки группы.
|
||||
const counts = new Map();
|
||||
group.members.forEach((id) => subs.of.get(id)?.forEach((key) => {
|
||||
if (key !== group.channel) counts.set(key, (counts.get(key) || 0) + 1);
|
||||
}));
|
||||
group.alsoRead = [...counts.entries()]
|
||||
.filter(([, count]) => count >= 2)
|
||||
.sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
|
||||
.slice(0, 3)
|
||||
.map(([key, count]) => ({ key, count, name: String(subs.info.get(key)?.name || key) }));
|
||||
}
|
||||
if (remaining.size) {
|
||||
const members = [...remaining].sort((a, b) => byName(byId.get(a) || { id: a }, byId.get(b) || { id: b }));
|
||||
list.push({ id: REST_GROUP, kind: 'rest', members, name: '', autoLabel: t('screens.communities.text_007'), label: t('screens.communities.text_002'), shortLabel: t('screens.communities.text_008'), hubId: '' });
|
||||
}
|
||||
sortGroups(list);
|
||||
assignColors(list, new Map());
|
||||
const byPerson = new Map();
|
||||
list.forEach((group) => group.members.forEach((id) => byPerson.set(id, group.id)));
|
||||
return { groups: list, byPerson, snapshots: [] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Города: кто где живёт (по полю «Город» в профиле). Разные написания одного города – одна
|
||||
* группа (cities.js). Когда городов много, города с одним человеком собираются в «Другие города».
|
||||
* @param {Object} o
|
||||
* @param {Array<{id:string, name:string}>} o.people
|
||||
* @param {{ of: Map<string,string> }} o.cities
|
||||
* @param {(value:string) => string} o.cityKey
|
||||
* @param {(key:string, spellings:string[]) => string} o.cityLabel
|
||||
*/
|
||||
export function buildCityGroups({ people, cities, cityKey, cityLabel }) {
|
||||
const byId = new Map(people.map((person) => [person.id, person]));
|
||||
const byCity = new Map();
|
||||
const unknown = [];
|
||||
for (const person of people) {
|
||||
const raw = cities?.of?.get(person.id) || '';
|
||||
const key = raw ? cityKey(raw) : '';
|
||||
if (!key) { unknown.push(person.id); continue; }
|
||||
if (!byCity.has(key)) byCity.set(key, { members: [], spellings: [] });
|
||||
byCity.get(key).members.push(person.id);
|
||||
byCity.get(key).spellings.push(raw);
|
||||
}
|
||||
let list = [...byCity.entries()].map(([key, row]) => {
|
||||
const name = cityLabel(key, row.spellings);
|
||||
return { id: `city:${key}`, kind: 'city', city: key, members: row.members, name: '', autoLabel: name, label: name, shortLabel: name, hubId: '' };
|
||||
});
|
||||
const singles = list.filter((group) => group.members.length === 1);
|
||||
if (list.length > 14 && singles.length > 1) {
|
||||
list = list.filter((group) => group.members.length > 1);
|
||||
const members = singles.flatMap((group) => group.members);
|
||||
list.push({ id: 'city:*', kind: 'city', city: '', members, name: '', autoLabel: t('screens.communities.text_009'), label: t('screens.communities.text_003'), shortLabel: t('screens.communities.text_010'), hubId: '' });
|
||||
}
|
||||
for (const group of list) group.members.sort((a, b) => byName(byId.get(a) || { id: a }, byId.get(b) || { id: b }));
|
||||
if (unknown.length) {
|
||||
unknown.sort((a, b) => byName(byId.get(a) || { id: a }, byId.get(b) || { id: b }));
|
||||
list.push({ id: REST_GROUP, kind: 'rest', members: unknown, name: '', autoLabel: t('screens.communities.text_011'), label: t('screens.communities.text_004'), shortLabel: t('screens.communities.text_012'), hubId: '' });
|
||||
}
|
||||
sortGroups(list);
|
||||
assignColors(list, new Map());
|
||||
const byPerson = new Map();
|
||||
list.forEach((group) => group.members.forEach((id) => byPerson.set(id, group.id)));
|
||||
return { groups: list, byPerson, snapshots: [] };
|
||||
}
|
||||
|
||||
// --- Раскладка островами --------------------------------------------------------------------
|
||||
|
||||
export const ISLAND_STEP = 74; // шаг сот: точка и подпись под ней не налезают на соседей
|
||||
export const ISLAND_PAD = 30; // от края точек до края острова (для упаковки)
|
||||
const ISLAND_GAP = 62; // между островами: над каждым – его подпись
|
||||
const NODE_RADIUS = 22; // точка первого круга (как в движке карты)
|
||||
|
||||
// Места на шестиугольной сетке, ближайшие к середине: остров получается круглым при любом
|
||||
// числе людей (а не шестиугольником с недостроенным краем). При равном расстоянии – по углу.
|
||||
function hexSlots(count) {
|
||||
const size = ISLAND_STEP / Math.sqrt(3);
|
||||
const rings = Math.ceil(Math.sqrt(count / 3)) + 2;
|
||||
const all = [];
|
||||
for (let q = -rings; q <= rings; q += 1) {
|
||||
for (let r = Math.max(-rings, -q - rings); r <= Math.min(rings, -q + rings); r += 1) {
|
||||
const x = size * Math.sqrt(3) * (q + r / 2);
|
||||
const y = size * 1.5 * r;
|
||||
all.push({ x, y, d: Math.round(Math.hypot(x, y) * 100), a: Math.atan2(y, x) });
|
||||
}
|
||||
}
|
||||
all.sort((p, s) => p.d - s.d || p.a - s.a);
|
||||
return all.slice(0, count).map(({ x, y }) => ({ x, y }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Люди острова по сотам: самые связанные – в середине, знакомые – рядом. Начальная
|
||||
* расстановка по спирали, затем жадные обмены местами, пока они сокращают сумму длин
|
||||
* знакомств (с весом) и держат связанных ближе к середине.
|
||||
*/
|
||||
function islandSlots(members, weights, rankOf) {
|
||||
const n = members.length;
|
||||
const slots = hexSlots(n);
|
||||
const index = new Map(members.map((id, i) => [id, i]));
|
||||
const links = members.map(() => []);
|
||||
const strength = new Float64Array(n);
|
||||
members.forEach((a, i) => {
|
||||
weights.get(a)?.forEach((w, b) => {
|
||||
const j = index.get(b);
|
||||
if (j === undefined || j === i) return;
|
||||
links[i].push([j, w]);
|
||||
strength[i] += w;
|
||||
});
|
||||
});
|
||||
// Начало: по связанности, при равенстве – ближе к вам, затем по имени (порядок members).
|
||||
const order = members.map((_, i) => i).sort((a, b) => strength[b] - strength[a] || rankOf(members[a]) - rankOf(members[b]) || a - b);
|
||||
const at = new Int32Array(n); // человек → номер места
|
||||
order.forEach((person, k) => { at[person] = k; });
|
||||
const radius = slots.map((p) => Math.hypot(p.x, p.y));
|
||||
const centerPull = 0.35;
|
||||
const dist = (s, t) => Math.hypot(slots[s].x - slots[t].x, slots[s].y - slots[t].y);
|
||||
const costAt = (i, s, skip) => {
|
||||
let c = centerPull * strength[i] * radius[s] + 4 * rankOf(members[i]) * radius[s] / ISLAND_STEP;
|
||||
for (const [j, w] of links[i]) if (j !== skip) c += w * dist(s, at[j]);
|
||||
return c;
|
||||
};
|
||||
if (n > 2 && n <= 260) {
|
||||
for (let pass = 0; pass < 8; pass += 1) {
|
||||
let swapped = 0;
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
for (let j = i + 1; j < n; j += 1) {
|
||||
const si = at[i];
|
||||
const sj = at[j];
|
||||
const before = costAt(i, si, j) + costAt(j, sj, i);
|
||||
const after = costAt(i, sj, j) + costAt(j, si, i);
|
||||
if (after < before - 1e-6) {
|
||||
at[i] = sj;
|
||||
at[j] = si;
|
||||
swapped += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!swapped) break;
|
||||
}
|
||||
}
|
||||
const out = new Map();
|
||||
members.forEach((id, i) => out.set(id, { x: slots[at[i]].x, y: slots[at[i]].y }));
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Острова вокруг центра. Каждый следующий – туда, где он ближе всего к центру (с учётом
|
||||
* растяжения под экран), но рядом с теми островами, с кем у него больше знакомств.
|
||||
* Положение по каждому направлению считается точно: для каждого уже стоящего острова
|
||||
* запретный отрезок расстояний – корни квадратного уравнения.
|
||||
*/
|
||||
function packIslands(islands, affinity, focusRadius, stretch) {
|
||||
const placed = [];
|
||||
const centers = new Map();
|
||||
const ANGLES = 96;
|
||||
for (const island of islands) {
|
||||
let best = null;
|
||||
for (let k = 0; k < ANGLES; k += 1) {
|
||||
const theta = -Math.PI / 2 + (k * Math.PI * 2) / ANGLES;
|
||||
const ux = Math.cos(theta) * stretch.x;
|
||||
const uy = Math.sin(theta) * stretch.y;
|
||||
const uu = ux * ux + uy * uy;
|
||||
const intervals = [];
|
||||
const keep = focusRadius + island.r + ISLAND_GAP;
|
||||
intervals.push([-Infinity, keep / Math.sqrt(uu)]);
|
||||
for (const other of placed) {
|
||||
const reach = island.r + other.r + ISLAND_GAP;
|
||||
const b = -2 * (ux * other.x + uy * other.y);
|
||||
const c = other.x * other.x + other.y * other.y - reach * reach;
|
||||
const disc = b * b - 4 * uu * c;
|
||||
if (disc <= 0) continue;
|
||||
const sq = Math.sqrt(disc);
|
||||
intervals.push([(-b - sq) / (2 * uu), (-b + sq) / (2 * uu)]);
|
||||
}
|
||||
intervals.sort((p, q) => p[0] - q[0]);
|
||||
let d = 0;
|
||||
for (let guard = 0; guard < intervals.length + 2; guard += 1) {
|
||||
let moved = false;
|
||||
for (const [d1, d2] of intervals) {
|
||||
if (d1 < d + 1e-6 && d < d2 - 1e-6) { d = d2; moved = true; }
|
||||
}
|
||||
if (!moved) break;
|
||||
}
|
||||
const x = ux * d;
|
||||
const y = uy * d;
|
||||
let pull = 0;
|
||||
let pullW = 0;
|
||||
affinity.get(island.id)?.forEach((w, otherId) => {
|
||||
const c = centers.get(otherId);
|
||||
if (!c) return;
|
||||
pull += w * Math.hypot(x - c.x, y - c.y);
|
||||
pullW += w;
|
||||
});
|
||||
const cost = d + (pullW ? (0.55 * pull) / pullW : 0) + k * 1e-6;
|
||||
if (!best || cost < best.cost) best = { x, y, cost };
|
||||
}
|
||||
const spot = { id: island.id, x: best.x, y: best.y, r: island.r };
|
||||
placed.push(spot);
|
||||
centers.set(island.id, spot);
|
||||
}
|
||||
return centers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Координаты людей первого круга островами.
|
||||
* @param {Object} o
|
||||
* @param {Array<{id:string, kind:string, members:string[]}>} o.groups – по порядку (крупные первыми)
|
||||
* @param {Map<string, Map<string, number>>} o.weights
|
||||
* @param {(id:string) => number} o.rankOf – близость к центру (0 – близкий … 3 – контакт)
|
||||
* @param {number} o.focusRadius – сколько места оставить вокруг человека в центре
|
||||
* @param {{x:number, y:number}} o.stretch
|
||||
* @returns {{ positions: Map<string,{x:number,y:number}>, islands: Map<string,{x:number,y:number,r:number}> }}
|
||||
*/
|
||||
export function layoutIslands({ groups, weights, rankOf, focusRadius = 70, stretch = { x: 1, y: 1 } }) {
|
||||
const local = new Map();
|
||||
const islands = [];
|
||||
for (const group of groups) {
|
||||
if (!group.members.length) continue;
|
||||
const slots = islandSlots(group.members, weights, rankOf);
|
||||
let r = 0;
|
||||
slots.forEach((p) => { r = Math.max(r, Math.hypot(p.x, p.y)); });
|
||||
local.set(group.id, slots);
|
||||
islands.push({ id: group.id, r: r + NODE_RADIUS + ISLAND_PAD });
|
||||
}
|
||||
// Сколько знакомств между островами – соседями становятся самые связанные.
|
||||
const groupOf = new Map();
|
||||
groups.forEach((group) => group.members.forEach((id) => groupOf.set(id, group.id)));
|
||||
const affinity = new Map();
|
||||
weights.forEach((near, a) => {
|
||||
const ga = groupOf.get(a);
|
||||
if (!ga) return;
|
||||
near.forEach((w, b) => {
|
||||
const gb = groupOf.get(b);
|
||||
if (!gb || gb === ga) return;
|
||||
if (!affinity.has(ga)) affinity.set(ga, new Map());
|
||||
affinity.get(ga).set(gb, (affinity.get(ga).get(gb) || 0) + w);
|
||||
});
|
||||
});
|
||||
const centers = packIslands(islands, affinity, focusRadius, stretch);
|
||||
const positions = new Map();
|
||||
local.forEach((slots, groupId) => {
|
||||
const c = centers.get(groupId);
|
||||
slots.forEach((p, id) => positions.set(id, { x: c.x + p.x, y: c.y + p.y }));
|
||||
});
|
||||
return { positions, islands: centers };
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
// Компании карты связей на этом устройстве: свои названия и кого куда перенесли вручную.
|
||||
// Отдельно для аккаунта и для каждой карты (человека в центре). Сами компании каждый раз
|
||||
// находятся заново по знакомствам (communities.js); здесь – только то, что владелец решил сам:
|
||||
// названная компания узнаётся по составу, перенесённый человек остаётся там, куда его поставили.
|
||||
import { state } from '../../state.js';
|
||||
import { REST_GROUP } from './communities.js';
|
||||
|
||||
const PREFIX = 'shine-network-companies-v1:';
|
||||
const MAX_MAPS = 20;
|
||||
const MAX_NAME = 40;
|
||||
|
||||
function ownerLogin() {
|
||||
return String(state.session?.login || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function readAll() {
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return {};
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(PREFIX + owner) || '{}');
|
||||
return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function writeAll(all) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return;
|
||||
const keys = Object.keys(all);
|
||||
if (keys.length > MAX_MAPS) {
|
||||
keys.sort((a, b) => (all[a]?.updatedAt || 0) - (all[b]?.updatedAt || 0))
|
||||
.slice(0, keys.length - MAX_MAPS)
|
||||
.forEach((key) => { delete all[key]; });
|
||||
}
|
||||
try {
|
||||
localStorage.setItem(PREFIX + owner, JSON.stringify(all));
|
||||
} catch {
|
||||
// Нет места или приватный режим – названия проживут до закрытия экрана.
|
||||
}
|
||||
}
|
||||
|
||||
function emptyEntry() {
|
||||
return { groups: {}, assign: {}, updatedAt: 0 };
|
||||
}
|
||||
|
||||
function entryOf(all, centerKey) {
|
||||
const entry = all[centerKey];
|
||||
if (!entry || typeof entry !== 'object') return emptyEntry();
|
||||
return {
|
||||
groups: entry.groups && typeof entry.groups === 'object' ? entry.groups : {},
|
||||
assign: entry.assign && typeof entry.assign === 'object' ? entry.assign : {},
|
||||
updatedAt: Number(entry.updatedAt) || 0,
|
||||
};
|
||||
}
|
||||
|
||||
function save(centerKey, entry) {
|
||||
if (!centerKey) return;
|
||||
const all = readAll();
|
||||
// Компания без названия и без перенесённых в неё людей больше ничего не значит.
|
||||
const used = new Set(Object.values(entry.assign));
|
||||
Object.keys(entry.groups).forEach((id) => {
|
||||
if (!String(entry.groups[id]?.name || '').trim() && !used.has(id)) delete entry.groups[id];
|
||||
});
|
||||
if (!Object.keys(entry.groups).length && !Object.keys(entry.assign).length) delete all[centerKey];
|
||||
else all[centerKey] = { ...entry, updatedAt: Date.now() };
|
||||
writeAll(all);
|
||||
}
|
||||
|
||||
function newId() {
|
||||
return `u${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
||||
}
|
||||
|
||||
/** Что владелец решил сам: { groups: [{ id, name, members, color }], assign: Map(человек → компания) }. */
|
||||
export function getCompanySettings(centerKey) {
|
||||
const entry = entryOf(readAll(), centerKey);
|
||||
return {
|
||||
groups: Object.entries(entry.groups).map(([id, group]) => ({
|
||||
id,
|
||||
name: String(group?.name || '').slice(0, MAX_NAME),
|
||||
members: Array.isArray(group?.members) ? group.members.map(String) : [],
|
||||
color: Number.isInteger(group?.color) ? group.color : undefined,
|
||||
})),
|
||||
assign: new Map(Object.entries(entry.assign).map(([id, group]) => [id, String(group)])),
|
||||
};
|
||||
}
|
||||
|
||||
/** Снимок для «Отменить»: вернуть всё как было – restoreCompanySettings. */
|
||||
export function snapshotCompanySettings(centerKey) {
|
||||
return JSON.parse(JSON.stringify(entryOf(readAll(), centerKey)));
|
||||
}
|
||||
|
||||
export function restoreCompanySettings(centerKey, snapshot) {
|
||||
if (!snapshot) return;
|
||||
save(centerKey, entryOf({ [centerKey]: snapshot }, centerKey));
|
||||
}
|
||||
|
||||
// Компания, найденная автоматически, становится «своей» (с постоянным id), как только ей
|
||||
// дали название или перенесли в неё человека: дальше её узнают по составу.
|
||||
function ensureSaved(entry, group) {
|
||||
if (entry.groups[group.id]) return group.id;
|
||||
const id = newId();
|
||||
entry.groups[id] = {
|
||||
name: '',
|
||||
members: group.members.filter((personId) => !entry.assign[personId]),
|
||||
color: Number.isInteger(group.color) && group.color >= 0 ? group.color : undefined,
|
||||
};
|
||||
return id;
|
||||
}
|
||||
|
||||
/** Название компании (пустое – вернуть автоматическое). Возвращает id компании. */
|
||||
export function setCompanyName(centerKey, group, name) {
|
||||
const entry = entryOf(readAll(), centerKey);
|
||||
const id = ensureSaved(entry, group);
|
||||
entry.groups[id].name = String(name || '').trim().slice(0, MAX_NAME);
|
||||
save(centerKey, entry);
|
||||
return id;
|
||||
}
|
||||
|
||||
/** Перенести человека в компанию (group – из buildCompanies или { id: REST_GROUP }). */
|
||||
export function assignToCompany(centerKey, personId, group) {
|
||||
const entry = entryOf(readAll(), centerKey);
|
||||
if (group.id === REST_GROUP) {
|
||||
entry.assign[personId] = REST_GROUP;
|
||||
} else {
|
||||
const id = ensureSaved(entry, group);
|
||||
entry.assign[personId] = id;
|
||||
}
|
||||
save(centerKey, entry);
|
||||
}
|
||||
|
||||
/** Новая компания с одним человеком. Возвращает её id. */
|
||||
export function createCompany(centerKey, name, personId) {
|
||||
const entry = entryOf(readAll(), centerKey);
|
||||
const id = newId();
|
||||
entry.groups[id] = { name: String(name || '').trim().slice(0, MAX_NAME), members: [], color: undefined };
|
||||
entry.assign[personId] = id;
|
||||
save(centerKey, entry);
|
||||
return id;
|
||||
}
|
||||
|
||||
/** Обновить состав и цвет узнанных компаний (чтобы узнавать их и дальше). */
|
||||
export function updateCompanySnapshots(centerKey, snapshots) {
|
||||
if (!snapshots?.length) return;
|
||||
const entry = entryOf(readAll(), centerKey);
|
||||
let changed = false;
|
||||
for (const row of snapshots) {
|
||||
const group = entry.groups[row.id];
|
||||
if (!group) continue;
|
||||
group.members = row.members;
|
||||
if (Number.isInteger(row.color)) group.color = row.color;
|
||||
changed = true;
|
||||
}
|
||||
if (changed) save(centerKey, entry);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,173 @@
|
||||
// Раскладки карты связей – на этом устройстве, отдельно для аккаунта.
|
||||
// Автоматические раскладки (rings – по близости, companies – компании по знакомствам,
|
||||
// interests – по подпискам, cities – по городам) считаются заново при каждом открытии.
|
||||
// Прежние «по группам», «Подсолнух» и «Мандала» убраны: это была та же близость другой
|
||||
// формой; сохранённые с ними карты открываются «по близости».
|
||||
// «Своя» (manual) – расстановка людей, сохранённая для каждой карты отдельно: координаты
|
||||
// относительно человека в центре плюс базовая автоматическая раскладка, по которой встают
|
||||
// люди, появившиеся на карте позже.
|
||||
import { state } from '../../state.js';
|
||||
|
||||
const LAYOUT_PREFIX = 'shine-network-layout-v1:';
|
||||
const VIEW_PREFIX = 'shine-network-view-v1:';
|
||||
const MAX_MAPS = 40; // старые раскладки вытесняются, чтобы хранилище не росло бесконечно
|
||||
|
||||
export const AUTO_LAYOUT_MODES = ['rings', 'companies', 'interests', 'cities'];
|
||||
const LAYOUT_MODES = [...AUTO_LAYOUT_MODES, 'manual'];
|
||||
|
||||
function ownerLogin() {
|
||||
return String(state.session?.login || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function readJson(key) {
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(key) || '{}');
|
||||
return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function writeJson(key, value) {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(value));
|
||||
} catch {
|
||||
// Нет места или приватный режим – раскладка проживёт до закрытия экрана.
|
||||
}
|
||||
}
|
||||
|
||||
function autoMode(value) {
|
||||
return AUTO_LAYOUT_MODES.includes(value) ? value : 'rings';
|
||||
}
|
||||
|
||||
// Раньше перетащенные точки действовали в любой раскладке. Чтобы после обновления карта
|
||||
// выглядела как прежде, такие карты считаются «своей раскладкой» поверх прежнего режима.
|
||||
function migrateLegacy(owner) {
|
||||
const view = readJson(VIEW_PREFIX + owner);
|
||||
if (view.layoutV === 2) return;
|
||||
const all = readJson(LAYOUT_PREFIX + owner);
|
||||
const previousMode = autoMode(view.mode);
|
||||
let legacy = false;
|
||||
Object.values(all).forEach((entry) => {
|
||||
if (entry && typeof entry === 'object' && !entry.base) {
|
||||
entry.base = previousMode;
|
||||
legacy = true;
|
||||
}
|
||||
});
|
||||
if (legacy) {
|
||||
writeJson(LAYOUT_PREFIX + owner, all);
|
||||
view.autoMode = previousMode;
|
||||
view.mode = 'manual';
|
||||
}
|
||||
view.layoutV = 2;
|
||||
writeJson(VIEW_PREFIX + owner, view);
|
||||
}
|
||||
|
||||
function entryOf(centerKey) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner || !centerKey) return null;
|
||||
const entry = readJson(LAYOUT_PREFIX + owner)[centerKey];
|
||||
return entry && typeof entry === 'object' && entry.points && Object.keys(entry.points).length ? entry : null;
|
||||
}
|
||||
|
||||
export function hasManualLayout(centerKey) {
|
||||
return Boolean(entryOf(centerKey));
|
||||
}
|
||||
|
||||
export function getManualLayout(centerKey) {
|
||||
const out = new Map();
|
||||
const points = entryOf(centerKey)?.points || {};
|
||||
for (const [id, point] of Object.entries(points)) {
|
||||
if (Array.isArray(point) && Number.isFinite(point[0]) && Number.isFinite(point[1])) out.set(id, { x: point[0], y: point[1] });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// По какой автоматической раскладке встают те, кого в своей раскладке ещё нет.
|
||||
export function getManualBase(centerKey) {
|
||||
return autoMode(entryOf(centerKey)?.base);
|
||||
}
|
||||
|
||||
function writeEntry(centerKey, entry) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner || !centerKey) return;
|
||||
const all = readJson(LAYOUT_PREFIX + owner);
|
||||
if (entry) all[centerKey] = entry;
|
||||
else delete all[centerKey];
|
||||
const keys = Object.keys(all);
|
||||
if (keys.length > MAX_MAPS) {
|
||||
keys.sort((a, b) => (all[a].updatedAt || 0) - (all[b].updatedAt || 0))
|
||||
.slice(0, keys.length - MAX_MAPS)
|
||||
.forEach((key) => { delete all[key]; });
|
||||
}
|
||||
writeJson(LAYOUT_PREFIX + owner, all);
|
||||
}
|
||||
|
||||
/** Сохраняет всю расстановку как «свою»; возвращает прежнюю (для «Отменить») или null. */
|
||||
export function saveManualLayout(centerKey, points, base) {
|
||||
const previous = entryOf(centerKey);
|
||||
const stored = {};
|
||||
points.forEach((point, id) => { stored[id] = [Math.round(point.x), Math.round(point.y)]; });
|
||||
writeEntry(centerKey, { points: stored, base: autoMode(base), updatedAt: Date.now() });
|
||||
return previous;
|
||||
}
|
||||
|
||||
export function setManualPoint(centerKey, id, point) {
|
||||
if (!id) return;
|
||||
const entry = entryOf(centerKey) || { points: {}, base: 'rings' };
|
||||
entry.points[id] = [Math.round(point.x), Math.round(point.y)];
|
||||
entry.updatedAt = Date.now();
|
||||
writeEntry(centerKey, entry);
|
||||
}
|
||||
|
||||
/** Удаляет свою раскладку карты; возвращает удалённую (для «Вернуть») или null. */
|
||||
export function clearManualLayout(centerKey) {
|
||||
const previous = entryOf(centerKey);
|
||||
writeEntry(centerKey, null);
|
||||
return previous;
|
||||
}
|
||||
|
||||
/** Возвращает раскладку, снятую clearManualLayout / saveManualLayout (null – удалить). */
|
||||
export function restoreManualLayout(centerKey, entry) {
|
||||
writeEntry(centerKey, entry && entry.points ? entry : null);
|
||||
}
|
||||
|
||||
export function getLayoutMode() {
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return 'rings';
|
||||
migrateLegacy(owner);
|
||||
const mode = readJson(VIEW_PREFIX + owner).mode;
|
||||
return LAYOUT_MODES.includes(mode) ? mode : 'rings';
|
||||
}
|
||||
|
||||
// Последняя выбранная автоматическая – для карт, у которых своей раскладки нет.
|
||||
export function getAutoLayoutMode() {
|
||||
const owner = ownerLogin();
|
||||
const view = readJson(VIEW_PREFIX + owner);
|
||||
return autoMode(AUTO_LAYOUT_MODES.includes(view.mode) ? view.mode : view.autoMode);
|
||||
}
|
||||
|
||||
export function setLayoutMode(mode) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return;
|
||||
const view = readJson(VIEW_PREFIX + owner);
|
||||
view.mode = LAYOUT_MODES.includes(mode) ? mode : 'rings';
|
||||
if (AUTO_LAYOUT_MODES.includes(view.mode)) view.autoMode = view.mode;
|
||||
view.layoutV = 2;
|
||||
writeJson(VIEW_PREFIX + owner, view);
|
||||
}
|
||||
|
||||
// Прочие настройки экрана на этом устройстве: карта или список, порядок списка.
|
||||
export function getViewSetting(key, fallback) {
|
||||
const owner = ownerLogin();
|
||||
const value = readJson(VIEW_PREFIX + owner)[key];
|
||||
return value === undefined ? fallback : value;
|
||||
}
|
||||
|
||||
export function setViewSetting(key, value) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return;
|
||||
const view = readJson(VIEW_PREFIX + owner);
|
||||
view[key] = value;
|
||||
writeJson(VIEW_PREFIX + owner, view);
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// Кто с кем знаком, кто на что подписан и кто где живёт – данные для «Компаний», «Интересов»
|
||||
// и «Городов».
|
||||
// Собираются по одному запросу на человека, поэтому не перезапрашиваются при каждом открытии:
|
||||
// для своей карты лежат на устройстве, для чужих – в памяти, пока открыто приложение.
|
||||
// Сервер не трогаем: знакомства – из графа связей каждого человека, подписки – из списка
|
||||
// «Подписки» его профиля (публичные каналы), город – из параметра city его профиля.
|
||||
import { state } from '../../state.js';
|
||||
import { CONNECTIONS_GRAPH_CHANGED } from '../../services/connections-graph-cache.js';
|
||||
|
||||
const PREFIX = { ties: 'shine-network-ties-v2:', subs: 'shine-network-subs-v1:', cities: 'shine-network-cities-v1:' };
|
||||
export const PEOPLE_DATA_FRESH_MS = 12 * 60 * 60 * 1000; // старше – освежаются в фоне
|
||||
const TYPE_CODE = { close_friend: 3, family: 3, friend: 2, contact: 1 };
|
||||
const CODE_TYPE = { 3: 'close_friend', 2: 'friend', 1: 'contact' };
|
||||
|
||||
const memory = new Map(); // `${kind}|${owner}|${center}` → запись
|
||||
|
||||
let peopleGeneration = 0;
|
||||
export function peopleDataGeneration() { return peopleGeneration; }
|
||||
|
||||
export function invalidatePeopleData() {
|
||||
peopleGeneration += 1;
|
||||
memory.clear();
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return;
|
||||
for (const prefix of Object.values(PREFIX)) {
|
||||
try { localStorage.removeItem(prefix + owner); } catch { /* хранилище может быть недоступно */ }
|
||||
}
|
||||
}
|
||||
if (typeof window !== 'undefined') window.addEventListener(CONNECTIONS_GRAPH_CHANGED, invalidatePeopleData);
|
||||
|
||||
function ownerLogin() {
|
||||
return String(state.session?.login || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function persistent(centerKey) {
|
||||
return Boolean(centerKey) && centerKey === ownerLogin();
|
||||
}
|
||||
|
||||
function readStored(kind, centerKey) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner || !persistent(centerKey)) return null;
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(PREFIX[kind] + owner) || 'null');
|
||||
return raw && typeof raw === 'object' ? raw : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeStored(kind, centerKey, value) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner || !persistent(centerKey)) return;
|
||||
try {
|
||||
localStorage.setItem(PREFIX[kind] + owner, JSON.stringify(value));
|
||||
} catch {
|
||||
// Нет места – данные останутся в памяти до закрытия приложения.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Знакомства: { at, people: Map(человек → Map(знакомый → { type, mutual })) }.
|
||||
* people хранит только тех, у кого граф уже загружен (в том числе пустой).
|
||||
*/
|
||||
export function getTies(centerKey) {
|
||||
const key = `ties|${ownerLogin()}|${centerKey}`;
|
||||
if (memory.has(key)) return memory.get(key);
|
||||
const raw = readStored('ties', centerKey);
|
||||
if (!raw || typeof raw.people !== 'object') return null;
|
||||
const people = new Map();
|
||||
for (const [id, list] of Object.entries(raw.people)) {
|
||||
const near = new Map();
|
||||
if (Array.isArray(list)) {
|
||||
list.forEach((row) => {
|
||||
if (Array.isArray(row) && row[0]) near.set(String(row[0]), { type: CODE_TYPE[row[1]] || 'contact', mutual: row[2] !== 0 });
|
||||
});
|
||||
}
|
||||
people.set(id, near);
|
||||
}
|
||||
const entry = { at: Number(raw.at) || 0, people };
|
||||
memory.set(key, entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
export function saveTies(centerKey, entry) {
|
||||
memory.set(`ties|${ownerLogin()}|${centerKey}`, entry);
|
||||
const people = {};
|
||||
entry.people.forEach((near, id) => {
|
||||
people[id] = [...near.entries()].map(([other, tie]) => [other, TYPE_CODE[tie.type] || 1, tie.mutual ? 1 : 0]);
|
||||
});
|
||||
writeStored('ties', centerKey, { at: entry.at, people });
|
||||
}
|
||||
|
||||
/**
|
||||
* Подписки: { at, of: Map(человек → [ключ канала]), info: Map(ключ → { name, owner, slug, bch, root, hash }) }.
|
||||
*/
|
||||
export function getSubs(centerKey) {
|
||||
const key = `subs|${ownerLogin()}|${centerKey}`;
|
||||
if (memory.has(key)) return memory.get(key);
|
||||
const raw = readStored('subs', centerKey);
|
||||
if (!raw || typeof raw.of !== 'object' || typeof raw.info !== 'object') return null;
|
||||
const of = new Map(Object.entries(raw.of).map(([id, list]) => [id, Array.isArray(list) ? list.map(String) : []]));
|
||||
const info = new Map(Object.entries(raw.info).map(([channel, row]) => [channel, {
|
||||
name: String(row?.n || channel),
|
||||
owner: String(row?.o || ''),
|
||||
slug: String(row?.s || ''),
|
||||
bch: String(row?.b || ''),
|
||||
root: Number(row?.r) || 0,
|
||||
hash: String(row?.h || ''),
|
||||
}]));
|
||||
const entry = { at: Number(raw.at) || 0, of, info };
|
||||
memory.set(key, entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
export function saveSubs(centerKey, entry) {
|
||||
memory.set(`subs|${ownerLogin()}|${centerKey}`, entry);
|
||||
// Каналы, которые больше никто не читает, не храним.
|
||||
const used = new Set();
|
||||
entry.of.forEach((list) => list.forEach((channel) => used.add(channel)));
|
||||
const info = {};
|
||||
entry.info.forEach((row, channel) => {
|
||||
if (used.has(channel)) info[channel] = { n: row.name, o: row.owner, s: row.slug, b: row.bch, r: row.root, h: row.hash };
|
||||
});
|
||||
writeStored('subs', centerKey, { at: entry.at, of: Object.fromEntries(entry.of), info });
|
||||
}
|
||||
|
||||
/** Города: { at, of: Map(человек → город как написан; '' – не указан) }. */
|
||||
export function getCities(centerKey) {
|
||||
const key = `cities|${ownerLogin()}|${centerKey}`;
|
||||
if (memory.has(key)) return memory.get(key);
|
||||
const raw = readStored('cities', centerKey);
|
||||
if (!raw || typeof raw.of !== 'object') return null;
|
||||
const entry = { at: Number(raw.at) || 0, of: new Map(Object.entries(raw.of).map(([id, city]) => [id, String(city || '')])) };
|
||||
memory.set(key, entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
export function saveCities(centerKey, entry) {
|
||||
memory.set(`cities|${ownerLogin()}|${centerKey}`, entry);
|
||||
writeStored('cities', centerKey, { at: entry.at, of: Object.fromEntries(entry.of) });
|
||||
}
|
||||
|
||||
// Ключ канала: владелец и короткое имя – одинаковые у всех подписчиков.
|
||||
export function channelKey(row) {
|
||||
return `${String(row?.ownerLogin || '').trim().toLowerCase()}/${String(row?.slug || '').trim().toLowerCase()}`;
|
||||
}
|
||||
|
||||
export function channelInfo(row) {
|
||||
return {
|
||||
name: String(row?.displayName || row?.slug || '').trim() || channelKey(row),
|
||||
owner: String(row?.ownerLogin || ''),
|
||||
slug: String(row?.slug || ''),
|
||||
bch: String(row?.ownerBlockchainName || ''),
|
||||
root: Number(row?.rootBlockNumber) || 0,
|
||||
hash: String(row?.rootBlockHashHex || ''),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
// «Уведомления» в настройках: звук сообщений, разрешение системных уведомлений и чаты
|
||||
// «без звука». Всё – настройки этого устройства, сервер про них не знает.
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createPersonRow } from '../components/person-row.js';
|
||||
import { authService, getRememberedDmPeer, normalizeDmChatId, rememberDmPeer } from '../state.js';
|
||||
import {
|
||||
DM_CHAT_PREFS_EVENT, formatDmMuteUntil, getMutedDmChats, setDmChatMuted,
|
||||
} from '../services/dm-chat-prefs.js';
|
||||
import { DEVICE_PREFS_EVENT, getDevicePref, setDevicePref } from '../services/device-prefs.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
|
||||
export const pageMeta = { id: 'notification-settings-view', get title() { return t('screens.notification_settings_view.text_001'); } };
|
||||
|
||||
function permissionState() {
|
||||
if (typeof Notification === 'undefined') return 'unsupported';
|
||||
return Notification.permission; // granted | denied | default
|
||||
}
|
||||
|
||||
export function render({ navigate, chrome } = {}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack notification-settings-screen';
|
||||
let disposed = false;
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.notification_settings_view.text_002'),
|
||||
back: { onClick: () => navigate('settings-view') },
|
||||
}));
|
||||
|
||||
const soundTitle = document.createElement('p');
|
||||
soundTitle.className = 'nav-list__title';
|
||||
soundTitle.textContent = t('screens.notification_settings_view.text_003');
|
||||
const soundList = document.createElement('div');
|
||||
soundList.className = 'nav-list';
|
||||
const soundRow = document.createElement('label');
|
||||
soundRow.className = 'nav-row nav-row--switch';
|
||||
soundRow.innerHTML = `
|
||||
<span class="nav-row__text">
|
||||
<span class="nav-row__label">${th('screens.notification_settings_view.text_020')}</span>
|
||||
<span class="nav-row__hint">${th('screens.notification_settings_view.text_021')}</span>
|
||||
</span>
|
||||
<input class="switch" type="checkbox" />
|
||||
`;
|
||||
const soundSwitch = soundRow.querySelector('input');
|
||||
soundSwitch.checked = getDevicePref('dmSound', true) !== false;
|
||||
soundSwitch.addEventListener('change', () => setDevicePref('dmSound', soundSwitch.checked));
|
||||
soundList.append(soundRow);
|
||||
|
||||
// Системные уведомления – когда приложение свёрнуто или закрыто.
|
||||
const systemList = document.createElement('div');
|
||||
systemList.className = 'nav-list';
|
||||
const systemRow = document.createElement('div');
|
||||
systemRow.className = 'nav-row nav-row--action';
|
||||
systemList.append(systemRow);
|
||||
|
||||
function renderSystemRow() {
|
||||
const permission = permissionState();
|
||||
const texts = {
|
||||
granted: [t('screens.notification_settings_view.text_009'), t('screens.notification_settings_view.text_010')],
|
||||
denied: [t('screens.notification_settings_view.text_011'), t('screens.notification_settings_view.text_012')],
|
||||
default: [t('screens.notification_settings_view.text_013'), t('screens.notification_settings_view.text_014')],
|
||||
unsupported: [t('screens.notification_settings_view.text_015'), t('screens.notification_settings_view.text_016')],
|
||||
};
|
||||
const [label, hint] = texts[permission] || texts.unsupported;
|
||||
systemRow.innerHTML = `
|
||||
<span class="nav-row__text">
|
||||
<span class="nav-row__label"></span>
|
||||
<span class="nav-row__hint"></span>
|
||||
</span>
|
||||
`;
|
||||
systemRow.querySelector('.nav-row__label').textContent = label;
|
||||
systemRow.querySelector('.nav-row__hint').textContent = hint;
|
||||
if (permission === 'default') {
|
||||
const allow = document.createElement('button');
|
||||
allow.type = 'button';
|
||||
allow.className = 'primary-btn nav-row__button';
|
||||
allow.textContent = t('screens.notification_settings_view.text_004');
|
||||
allow.addEventListener('click', async () => {
|
||||
allow.disabled = true;
|
||||
try {
|
||||
const result = await Notification.requestPermission();
|
||||
if (result === 'granted') showToast(t('screens.notification_settings_view.text_007'));
|
||||
} catch {
|
||||
showToast(t('screens.notification_settings_view.text_008'), { kind: 'error' });
|
||||
}
|
||||
if (!disposed) renderSystemRow();
|
||||
});
|
||||
systemRow.append(allow);
|
||||
}
|
||||
}
|
||||
renderSystemRow();
|
||||
|
||||
// Чаты «без звука»: кто и до какого времени; звук возвращается кнопкой в строке.
|
||||
const mutedTitle = document.createElement('p');
|
||||
mutedTitle.className = 'nav-list__title';
|
||||
const mutedList = document.createElement('div');
|
||||
mutedList.className = 'notification-settings-muted';
|
||||
const mutedEmpty = document.createElement('p');
|
||||
mutedEmpty.className = 'meta-muted appearance-hint';
|
||||
mutedEmpty.textContent = t('screens.notification_settings_view.text_005');
|
||||
let peersRequested = false;
|
||||
|
||||
function mutedRow({ chatId, until }) {
|
||||
const peer = getRememberedDmPeer(chatId) || {};
|
||||
const fullName = [peer.firstName, peer.lastName].map((part) => String(part || '').trim()).filter(Boolean).join(' ');
|
||||
const login = peer.login || chatId;
|
||||
return createPersonRow({
|
||||
login,
|
||||
name: fullName || login,
|
||||
firstName: peer.firstName,
|
||||
lastName: peer.lastName,
|
||||
avatar: peer.avatar || null,
|
||||
sub: [fullName ? login : '', until ? formatDmMuteUntil(until) : t('screens.notification_settings_view.text_017')].filter(Boolean).join(' · '),
|
||||
onClick: () => navigate(`chat/${encodeURIComponent(normalizeDmChatId(chatId))}`),
|
||||
actions: [{ icon: 'bell', label: t('screens.notification_settings_view.text_006'), onClick: () => setDmChatMuted(chatId, false) }],
|
||||
});
|
||||
}
|
||||
|
||||
// Имена и аватары – из списка чатов; если его в этот раз не открывали, спрашиваем сервер один раз.
|
||||
async function loadPeers() {
|
||||
peersRequested = true;
|
||||
try {
|
||||
const payload = await authService.listContacts();
|
||||
if (disposed) return;
|
||||
(Array.isArray(payload?.dialogs) ? payload.dialogs : []).forEach((dialog) => rememberDmPeer({
|
||||
login: dialog?.peerLogin,
|
||||
firstName: dialog?.firstName,
|
||||
lastName: dialog?.lastName,
|
||||
avatar: dialog?.avatar,
|
||||
}));
|
||||
renderMuted();
|
||||
} catch {
|
||||
// Без имён строки остаются с логинами – этого достаточно.
|
||||
}
|
||||
}
|
||||
|
||||
function renderMuted() {
|
||||
const muted = getMutedDmChats();
|
||||
mutedTitle.textContent = muted.length ? t('screens.notification_settings_view.text_019', { value1: muted.length }) : t('screens.notification_settings_view.text_018');
|
||||
mutedList.hidden = !muted.length;
|
||||
mutedEmpty.hidden = Boolean(muted.length);
|
||||
mutedList.replaceChildren(...muted.map(mutedRow));
|
||||
if (!peersRequested && muted.some(({ chatId }) => !getRememberedDmPeer(chatId))) void loadPeers();
|
||||
}
|
||||
renderMuted();
|
||||
|
||||
const onPrefs = () => { if (!disposed) renderMuted(); };
|
||||
const onDevicePrefs = () => { if (!disposed) soundSwitch.checked = getDevicePref('dmSound', true) !== false; };
|
||||
window.addEventListener(DM_CHAT_PREFS_EVENT, onPrefs);
|
||||
window.addEventListener(DEVICE_PREFS_EVENT, onDevicePrefs);
|
||||
|
||||
screen.append(soundTitle, soundList, systemList, mutedTitle, mutedList, mutedEmpty);
|
||||
screen.cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
window.removeEventListener(DM_CHAT_PREFS_EVENT, onPrefs);
|
||||
window.removeEventListener(DEVICE_PREFS_EVENT, onDevicePrefs);
|
||||
};
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,586 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||||
import { makeProfileRoute, makeShineMessageRoute } from '../services/shine-routes.js';
|
||||
import { formatListTime, showToast } from '../services/channels-ux.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { createErrorState, createLoadingState, createStateMessage } from '../components/feedback.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
|
||||
const CONNECTION_CLOSE_FRIEND = 10;
|
||||
const CONNECTION_UNCLOSE_FRIEND = 11;
|
||||
const CONNECTION_FRIEND = 14;
|
||||
const CONNECTION_UNFRIEND = 15;
|
||||
const CONNECTION_FOLLOW = 30;
|
||||
const CONNECTION_UNFOLLOW = 31;
|
||||
const CONNECTION_SHINE_CONFIRMED = 70;
|
||||
const CONNECTION_SHINE_UNCONFIRMED = 71;
|
||||
const CONNECTION_OFFICIAL_CONFIRMED = 80;
|
||||
const CONNECTION_OFFICIAL_UNCONFIRMED = 81;
|
||||
const profileSnapshotCache = new Map();
|
||||
const profileSnapshotPending = new Map();
|
||||
|
||||
// Глагол по полу из профиля автора («Добавила вас в друзья»); пока профиль не пришёл или пол
|
||||
// не указан – нейтральное «Добавил(а)».
|
||||
function byGender(gender, male, female, neutral) {
|
||||
if (gender === 'male') return male;
|
||||
if (gender === 'female') return female;
|
||||
return neutral;
|
||||
}
|
||||
|
||||
function connectionActionLabel(typeCode, gender = '') {
|
||||
const verb = (male, female) => byGender(gender, male, female, t('screens.notifications_view.text_032', { value1: male }));
|
||||
switch (Number(typeCode)) {
|
||||
case CONNECTION_CLOSE_FRIEND: return t('screens.notifications_view.text_033', { value1: verb(t('screens.notifications_view.text_047'), t('screens.notifications_view.text_048')) });
|
||||
case CONNECTION_UNCLOSE_FRIEND: return t('screens.notifications_view.text_034', { value1: verb(t('screens.notifications_view.text_049'), t('screens.notifications_view.text_050')) });
|
||||
case CONNECTION_FRIEND: return t('screens.notifications_view.text_035', { value1: verb(t('screens.notifications_view.text_051'), t('screens.notifications_view.text_052')) });
|
||||
case CONNECTION_UNFRIEND: return t('screens.notifications_view.text_036', { value1: verb(t('screens.notifications_view.text_053'), t('screens.notifications_view.text_054')) });
|
||||
case CONNECTION_SHINE_CONFIRMED: return t('screens.notifications_view.text_037', { value1: verb(t('screens.notifications_view.text_055'), t('screens.notifications_view.text_056')) });
|
||||
case CONNECTION_SHINE_UNCONFIRMED: return t('screens.notifications_view.text_038', { value1: verb(t('screens.notifications_view.text_057'), t('screens.notifications_view.text_058')) });
|
||||
case CONNECTION_OFFICIAL_CONFIRMED: return t('screens.notifications_view.text_039', { value1: verb(t('screens.notifications_view.text_059'), t('screens.notifications_view.text_060')) });
|
||||
case CONNECTION_OFFICIAL_UNCONFIRMED: return t('screens.notifications_view.text_040', { value1: verb(t('screens.notifications_view.text_061'), t('screens.notifications_view.text_062')) });
|
||||
default: return t('screens.notifications_view.text_041', { value1: verb(t('screens.notifications_view.text_063'), t('screens.notifications_view.text_064')) });
|
||||
}
|
||||
}
|
||||
|
||||
function eventActionLabel(typeCode, gender = '') {
|
||||
if (Number(typeCode) === CONNECTION_UNFOLLOW) return t('screens.notifications_view.text_042', { value1: byGender(gender, t('screens.notifications_view.text_065'), t('screens.notifications_view.text_066'), t('screens.notifications_view.text_067')) });
|
||||
return t('screens.notifications_view.text_043', { value1: byGender(gender, t('screens.notifications_view.text_068'), t('screens.notifications_view.text_069'), t('screens.notifications_view.text_070')) });
|
||||
}
|
||||
|
||||
function actionLabel(item, activeTab) {
|
||||
const gender = String(item.profile?.gender || '');
|
||||
return activeTab === 'connections'
|
||||
? connectionActionLabel(item.connectionTypeCode ?? item.sourceMsgSubType, gender)
|
||||
: eventActionLabel(item.sourceMsgSubType, gender);
|
||||
}
|
||||
|
||||
function reciprocalRelationKind(item) {
|
||||
return Number(item?.connectionTypeCode ?? item?.sourceMsgSubType) === CONNECTION_CLOSE_FRIEND
|
||||
? 'close_friend'
|
||||
: 'friend';
|
||||
}
|
||||
|
||||
function reciprocalRelationLabel(kind) {
|
||||
return kind === 'close_friend'
|
||||
? t('screens.notifications_view.text_072')
|
||||
: t('screens.notifications_view.text_009');
|
||||
}
|
||||
|
||||
function reciprocalRelationSuccessLabel(kind) {
|
||||
return kind === 'close_friend'
|
||||
? t('screens.notifications_view.text_073')
|
||||
: t('screens.notifications_view.text_015');
|
||||
}
|
||||
|
||||
export const pageMeta = { id: 'notifications-view', get title() { return t('screens.notifications_view.text_001'); } };
|
||||
|
||||
function normalizeItem(item) {
|
||||
return {
|
||||
kind: String(item?.kind || ''),
|
||||
createdAtMs: Number(item?.createdAtMs || 0),
|
||||
sourceLogin: String(item?.sourceLogin || ''),
|
||||
sourceBlockchainName: String(item?.sourceBlockchainName || ''),
|
||||
sourceBlockNumber: Number(item?.sourceBlockNumber || 0),
|
||||
sourceBlockHash: String(item?.sourceBlockHash || ''),
|
||||
sourceMsgSubType: item?.sourceMsgSubType == null ? null : Number(item.sourceMsgSubType),
|
||||
sourceText: String(item?.sourceText || ''),
|
||||
connectionTypeCode: item?.connectionTypeCode == null ? null : Number(item.connectionTypeCode),
|
||||
targetLogin: String(item?.targetLogin || ''),
|
||||
targetBlockchainName: String(item?.targetBlockchainName || ''),
|
||||
targetBlockNumber: item?.targetBlockNumber == null ? null : Number(item.targetBlockNumber),
|
||||
targetBlockHash: String(item?.targetBlockHash || ''),
|
||||
profile: null,
|
||||
engagement: null,
|
||||
};
|
||||
}
|
||||
|
||||
function profileField(snapshot, key) {
|
||||
const row = (Array.isArray(snapshot?.fields) ? snapshot.fields : [])
|
||||
.find((field) => String(field?.key || '') === key);
|
||||
return String(row?.value || '').trim();
|
||||
}
|
||||
|
||||
async function loadCachedProfileSnapshot(login) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
if (!cleanLogin) return null;
|
||||
const key = cleanLogin.toLowerCase();
|
||||
if (profileSnapshotCache.has(key)) return profileSnapshotCache.get(key);
|
||||
if (profileSnapshotPending.has(key)) return profileSnapshotPending.get(key);
|
||||
|
||||
const pending = loadProfileSnapshot(cleanLogin)
|
||||
.then((snapshot) => {
|
||||
profileSnapshotCache.set(key, snapshot || null);
|
||||
profileSnapshotPending.delete(key);
|
||||
return snapshot || null;
|
||||
})
|
||||
.catch(() => {
|
||||
profileSnapshotCache.set(key, null);
|
||||
profileSnapshotPending.delete(key);
|
||||
return null;
|
||||
});
|
||||
|
||||
profileSnapshotPending.set(key, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
function normalizeEngagement(source) {
|
||||
if (!source || typeof source !== 'object') return null;
|
||||
const likesCount = Math.max(0, Number(source.likesCount || 0));
|
||||
const repliesCount = Math.max(0, Number(source.repliesCount || 0));
|
||||
const ratingsCount = Math.max(0, Number(source.ratingsCount || 0));
|
||||
const repostsCount = Math.max(0, Number(source.repostsCount ?? source.repostCount ?? 0));
|
||||
const sharesCount = Math.max(0, Number(source.sharesCount ?? source.shareCount ?? 0));
|
||||
|
||||
const result = {
|
||||
likesCount: Number.isFinite(likesCount) ? likesCount : 0,
|
||||
repliesCount: Number.isFinite(repliesCount) ? repliesCount : 0,
|
||||
ratingsCount: Number.isFinite(ratingsCount) ? ratingsCount : 0,
|
||||
repostsCount: Number.isFinite(repostsCount) ? repostsCount : 0,
|
||||
sharesCount: Number.isFinite(sharesCount) ? sharesCount : 0,
|
||||
};
|
||||
|
||||
return Object.values(result).some((count) => count > 0) ? result : null;
|
||||
}
|
||||
|
||||
async function loadSourceEngagement(item) {
|
||||
const blockchainName = String(item?.sourceBlockchainName || '').trim();
|
||||
const blockNumber = Number(item?.sourceBlockNumber);
|
||||
const blockHash = String(item?.sourceBlockHash || '').trim();
|
||||
if (!blockchainName || !Number.isFinite(blockNumber) || blockNumber < 0 || !blockHash) return null;
|
||||
|
||||
try {
|
||||
const payload = await authService.getMessageThread(
|
||||
{ blockchainName, blockNumber, blockHash },
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
String(state.session.login || '').trim(),
|
||||
);
|
||||
return normalizeEngagement(payload?.focus);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function enrichItem(item, activeTab) {
|
||||
const [profile, engagement] = await Promise.all([
|
||||
loadCachedProfileSnapshot(item.sourceLogin),
|
||||
activeTab === 'replies' ? loadSourceEngagement(item) : Promise.resolve(null),
|
||||
]);
|
||||
return { ...item, profile, engagement };
|
||||
}
|
||||
|
||||
function renderEmpty(activeTab) {
|
||||
return createStateMessage({
|
||||
icon: activeTab === 'events' ? 'channels' : activeTab === 'connections' ? 'network' : 'reply',
|
||||
title: activeTab === 'events' ? t('screens.notifications_view.text_021') : activeTab === 'connections' ? t('screens.notifications_view.text_022') : t('screens.notifications_view.text_023'),
|
||||
text: activeTab === 'events'
|
||||
? t('screens.notifications_view.text_024')
|
||||
: activeTab === 'connections'
|
||||
? t('screens.notifications_view.text_025')
|
||||
: t('screens.notifications_view.text_026'),
|
||||
});
|
||||
}
|
||||
|
||||
function renderAvatar(item) {
|
||||
const profile = item.profile;
|
||||
const avatar = (profile?.avatar?.txId || profile?.avatar?.pr)
|
||||
? {
|
||||
ar: String(profile.avatar.txId || profile.avatar.ar || '').trim(),
|
||||
pr: String(profile.avatar.pr || '').trim(),
|
||||
}
|
||||
: null;
|
||||
return renderUserAvatar({
|
||||
login: item.sourceLogin || 'unknown',
|
||||
firstName: profileField(profile, 'first_name'),
|
||||
lastName: profileField(profile, 'last_name'),
|
||||
avatar,
|
||||
size: 'md',
|
||||
className: 'notification-avatar',
|
||||
});
|
||||
}
|
||||
|
||||
// Строка как в списке чатов: имя и время, ниже – что произошло и текст ответа.
|
||||
function renderHead(item) {
|
||||
const profile = item.profile;
|
||||
const fullName = [profileField(profile, 'first_name'), profileField(profile, 'last_name')].filter(Boolean).join(' ')
|
||||
|| item.sourceLogin || t('screens.notifications_view.text_030');
|
||||
const head = document.createElement('div');
|
||||
head.className = 'notification-card__head';
|
||||
const identity = document.createElement('div');
|
||||
identity.className = 'notification-card__identity';
|
||||
const name = document.createElement('strong');
|
||||
name.className = 'notification-card__name';
|
||||
name.textContent = fullName;
|
||||
identity.append(name);
|
||||
if (item.sourceLogin) {
|
||||
const login = document.createElement('span');
|
||||
login.className = 'notification-card__login';
|
||||
login.textContent = item.sourceLogin;
|
||||
identity.append(login);
|
||||
}
|
||||
head.append(identity);
|
||||
const time = document.createElement('span');
|
||||
time.className = 'notification-card__time';
|
||||
time.textContent = formatListTime(item.createdAtMs);
|
||||
head.append(time);
|
||||
return head;
|
||||
}
|
||||
|
||||
function renderEngagement(engagement) {
|
||||
if (!engagement) return null;
|
||||
|
||||
const stats = [
|
||||
{ key: 'likesCount', icon: 'heart', label: t('screens.notifications_view.text_002') },
|
||||
{ key: 'repliesCount', icon: 'message', label: t('screens.notifications_view.text_003') },
|
||||
{ key: 'repostsCount', icon: 'refresh', label: t('screens.notifications_view.text_004') },
|
||||
{ key: 'sharesCount', icon: 'forward', label: t('screens.notifications_view.text_005') },
|
||||
].filter(({ key }) => Number(engagement[key] || 0) > 0);
|
||||
|
||||
if (!stats.length) return null;
|
||||
|
||||
const row = document.createElement('div');
|
||||
row.className = 'notification-engagement';
|
||||
stats.forEach(({ key, icon, label }) => {
|
||||
const stat = document.createElement('span');
|
||||
stat.className = 'notification-engagement-item';
|
||||
stat.title = label;
|
||||
|
||||
const iconEl = document.createElement('span');
|
||||
iconEl.className = 'notification-engagement-icon';
|
||||
iconEl.setAttribute('aria-hidden', 'true');
|
||||
iconEl.innerHTML = iconHtml(icon);
|
||||
|
||||
const countEl = document.createElement('span');
|
||||
countEl.className = 'notification-engagement-count';
|
||||
countEl.textContent = String(engagement[key]);
|
||||
stat.append(iconEl, countEl);
|
||||
row.append(stat);
|
||||
});
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
function notificationRoute(item, activeTab) {
|
||||
if (activeTab === 'events' || activeTab === 'connections') {
|
||||
const login = String(item?.sourceLogin || '').trim();
|
||||
return login ? makeProfileRoute(login) : '';
|
||||
}
|
||||
|
||||
const blockchainName = String(item?.sourceBlockchainName || '').trim();
|
||||
const blockNumber = Number(item?.sourceBlockNumber);
|
||||
if (!blockchainName || !Number.isFinite(blockNumber) || blockNumber < 0) return '';
|
||||
|
||||
return makeShineMessageRoute({
|
||||
messageBlockchainName: blockchainName,
|
||||
messageBlockNumber: blockNumber,
|
||||
});
|
||||
}
|
||||
|
||||
function bindNotificationNavigation(row, routePath, navigate) {
|
||||
if (!routePath || typeof navigate !== 'function') return;
|
||||
|
||||
row.classList.add('notification-card--clickable');
|
||||
row.tabIndex = 0;
|
||||
row.setAttribute('role', 'link');
|
||||
|
||||
const open = () => navigate(routePath);
|
||||
row.addEventListener('click', open);
|
||||
row.addEventListener('keydown', (event) => {
|
||||
if (event.key !== 'Enter' && event.key !== ' ') return;
|
||||
event.preventDefault();
|
||||
open();
|
||||
});
|
||||
}
|
||||
|
||||
function renderItem(item, activeTab, navigate) {
|
||||
const row = document.createElement('article');
|
||||
row.className = 'notification-card';
|
||||
bindNotificationNavigation(row, notificationRoute(item, activeTab), navigate);
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'notification-card__body';
|
||||
body.append(renderHead(item));
|
||||
|
||||
if (activeTab === 'replies') {
|
||||
// Во вкладке «Ответы» всё – ответы: подпись «ответил(а)» не нужна, сразу текст.
|
||||
const text = document.createElement('p');
|
||||
text.className = 'notification-card__text';
|
||||
text.textContent = item.sourceText || t('screens.notifications_view.text_031');
|
||||
body.append(text);
|
||||
const engagement = renderEngagement(item.engagement);
|
||||
if (engagement) body.append(engagement);
|
||||
} else {
|
||||
const action = document.createElement('p');
|
||||
action.className = 'notification-card__action';
|
||||
action.textContent = actionLabel(item, activeTab);
|
||||
body.append(action);
|
||||
}
|
||||
|
||||
row.append(renderAvatar(item), body);
|
||||
return row;
|
||||
}
|
||||
|
||||
// Профиль и счётчики пришли позже – обновляем строку на месте (наблюдение «прочитано» не теряется).
|
||||
function refreshItemRow(row, item, activeTab) {
|
||||
if (!row?.isConnected) return;
|
||||
row.querySelector('.notification-avatar')?.replaceWith(renderAvatar(item));
|
||||
row.querySelector('.notification-card__head')?.replaceWith(renderHead(item));
|
||||
const action = row.querySelector('.notification-card__action');
|
||||
if (action && activeTab !== 'replies') action.textContent = actionLabel(item, activeTab);
|
||||
if (activeTab === 'replies' && item.engagement && !row.querySelector('.notification-engagement')) {
|
||||
const engagement = renderEngagement(item.engagement);
|
||||
if (engagement) row.querySelector('.notification-card__body')?.append(engagement);
|
||||
}
|
||||
}
|
||||
|
||||
// Последние уведомления – только в памяти вкладки: при повторном заходе экран рисуется сразу, без пустого кадра.
|
||||
let lastNotifications = null;
|
||||
|
||||
export function render({ navigate, chrome } = {}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack notifications-screen';
|
||||
|
||||
const tabs = document.createElement('div');
|
||||
tabs.className = 'tabs tabs--three notification-feed-tabs';
|
||||
tabs.setAttribute('role', 'radiogroup');
|
||||
tabs.setAttribute('aria-label', t('screens.notifications_view.text_071'));
|
||||
const tabDefs = [['replies',t('screens.notifications_view.text_027')],['connections',t('screens.notifications_view.text_028')],['events',t('screens.notifications_view.text_029')]];
|
||||
const topbar = createTopBar({
|
||||
title: t('screens.notifications_view.text_006'),
|
||||
className: 'topbar--root notifications-topbar',
|
||||
actions: [{
|
||||
icon: 'check-double',
|
||||
title: t('screens.notifications_view.text_007'),
|
||||
ariaLabel: t('screens.notifications_view.text_008'),
|
||||
className: 'notifications-read-all',
|
||||
onClick: () => { void markAllRead(); },
|
||||
}],
|
||||
});
|
||||
chrome?.setTopbar(topbar);
|
||||
const readAllBtn = topbar.querySelector('.notifications-read-all');
|
||||
if (readAllBtn) readAllBtn.disabled = true;
|
||||
screen.append(tabs);
|
||||
|
||||
const list = document.createElement('div');
|
||||
list.className = 'notifications-list';
|
||||
let payloadCache = null;
|
||||
let requestSeq = 0;
|
||||
let observer = null;
|
||||
const pendingSeenTimers = { replies: null, connections: null, events: null };
|
||||
const localSeen = { replies: 0, connections: 0, events: 0 };
|
||||
|
||||
function countsFromPayload(payload) {
|
||||
return {
|
||||
replies: Number(payload?.repliesUnseenCount || 0),
|
||||
connections: Number(payload?.connectionsUnseenCount || 0),
|
||||
events: Number(payload?.eventsUnseenCount || 0),
|
||||
};
|
||||
}
|
||||
|
||||
function updateToolbarBadge(payload) {
|
||||
const c = countsFromPayload(payload);
|
||||
state.notificationUnreadTotal = c.replies + c.connections + c.events;
|
||||
if (readAllBtn) readAllBtn.disabled = state.notificationUnreadTotal <= 0;
|
||||
const btn = document.querySelector('[data-toolbar-page="notifications-view"]');
|
||||
if (!btn) return;
|
||||
let badge = btn.querySelector('.notification-toolbar-badge');
|
||||
if (state.notificationUnreadTotal <= 0) { badge?.remove(); return; }
|
||||
if (!badge) { badge = document.createElement('span'); badge.className = 'toolbar-unread-badge notification-toolbar-badge'; (btn.querySelector('.toolbar-icon') || btn).append(badge); }
|
||||
badge.textContent = state.notificationUnreadTotal > 99 ? '99+' : String(state.notificationUnreadTotal);
|
||||
}
|
||||
|
||||
function renderTabs(payload) {
|
||||
const counts = countsFromPayload(payload);
|
||||
tabs.replaceChildren(...tabDefs.map(([key,label]) => {
|
||||
const b=document.createElement('button'); b.type='button'; b.className='tab-btn notification-tab-btn'; b.dataset.tab=key; b.setAttribute('role','radio'); b.setAttribute('aria-checked',state.notificationsTab===key?'true':'false');
|
||||
b.textContent = label;
|
||||
if (counts[key] > 0) {
|
||||
const count = document.createElement('span');
|
||||
count.className = 'tab-count';
|
||||
count.textContent = counts[key] > 99 ? '99+' : String(counts[key]);
|
||||
count.setAttribute('aria-label', t('screens.notifications_view.text_044', { value1: counts[key] }));
|
||||
b.append(count);
|
||||
}
|
||||
b.addEventListener('click',()=>{ if(state.notificationsTab===key)return; state.notificationsTab=key; renderCurrent(); });
|
||||
return b;
|
||||
}));
|
||||
}
|
||||
|
||||
function categoryData(payload, tab) {
|
||||
if (tab === 'connections') return { items: payload?.connections || [], seenAt: Number(payload?.connectionsSeenAtMs || 0) };
|
||||
if (tab === 'events') return { items: payload?.events || [], seenAt: Number(payload?.eventsSeenAtMs || 0) };
|
||||
return { items: payload?.replies || [], seenAt: Number(payload?.repliesSeenAtMs || 0) };
|
||||
}
|
||||
|
||||
function scheduleSeen(category, seenAtMs) {
|
||||
if (seenAtMs <= Number(localSeen[category] || 0)) return;
|
||||
localSeen[category] = seenAtMs;
|
||||
clearTimeout(pendingSeenTimers[category]);
|
||||
pendingSeenTimers[category] = setTimeout(async () => {
|
||||
const target = Number(localSeen[category] || 0);
|
||||
try {
|
||||
await authService.setNotificationSeen({ login: state.session.login, category, seenAtMs: target, storagePwd: state.session.storagePwdInMemory });
|
||||
if (!payloadCache) return;
|
||||
const key = category === 'connections' ? 'connectionsSeenAtMs' : category === 'events' ? 'eventsSeenAtMs' : 'repliesSeenAtMs';
|
||||
const countKey = category === 'connections' ? 'connectionsUnseenCount' : category === 'events' ? 'eventsUnseenCount' : 'repliesUnseenCount';
|
||||
payloadCache[key] = Math.max(Number(payloadCache[key] || 0), target);
|
||||
payloadCache[countKey] = (payloadCache[category] || []).filter(x => Number(x?.createdAtMs || 0) > payloadCache[key]).length;
|
||||
renderTabs(payloadCache); updateToolbarBadge(payloadCache);
|
||||
} catch (e) { console.warn('Не удалось подписать watermark уведомлений', e); }
|
||||
}, 350);
|
||||
}
|
||||
|
||||
let renderSeq = 0;
|
||||
async function renderCurrent() {
|
||||
const seq = ++renderSeq;
|
||||
observer?.disconnect(); observer=null; renderTabs(payloadCache || {});
|
||||
const tab=state.notificationsTab; const {items:raw,seenAt}=categoryData(payloadCache || {},tab); localSeen[tab]=Math.max(localSeen[tab]||0,seenAt);
|
||||
const base=raw.map(normalizeItem); if(!base.length){list.replaceChildren(renderEmpty(tab));return;}
|
||||
// Список рисуется сразу – с профилями из кэша; остальное догружается в фоне и
|
||||
// обновляет строки на месте (раньше экран ждал загрузки профиля каждого автора).
|
||||
const items=base.map((x)=>({ ...x, profile: profileSnapshotCache.get(String(x.sourceLogin || '').toLowerCase()) || null }));
|
||||
const rowByItem = new Map();
|
||||
const unread=items.filter(x=>x.createdAtMs>seenAt); const old=items.filter(x=>x.createdAtMs<=seenAt);
|
||||
const nodes=[];
|
||||
const groupTitle=(text)=>{const el=document.createElement('h2');el.className='notification-group-title';el.textContent=text;return el;};
|
||||
if(unread.length) nodes.push(groupTitle(t('screens.notifications_view.text_045', { value1: unread.length })));
|
||||
unread.forEach(x=>{const n=renderItem(x,tab,navigate);n.classList.add('notification-card--new');n.dataset.createdAtMs=String(x.createdAtMs);rowByItem.set(x,n);nodes.push(n);});
|
||||
if(unread.length && old.length) nodes.push(groupTitle(t('screens.notifications_view.text_014')));
|
||||
old.forEach(x=>{const n=renderItem(x,tab,navigate);rowByItem.set(x,n);nodes.push(n);}); list.replaceChildren(...nodes);
|
||||
void enrichInBackground(items, tab, rowByItem, seq);
|
||||
if (tab === 'connections') void offerFriendBack(items, rowByItem, seq);
|
||||
if(unread.length && 'IntersectionObserver' in window){
|
||||
observer=new IntersectionObserver(entries=>{ entries.forEach(e=>{ if(e.isIntersecting && e.intersectionRatio>=0.5){ const ts=Number(e.target.dataset.createdAtMs||0); if(ts>0){e.target.classList.remove('notification-card--new');scheduleSeen(tab,ts);} } }); },{threshold:[0.5]});
|
||||
list.querySelectorAll('.notification-card--new').forEach(n=>observer.observe(n));
|
||||
}
|
||||
}
|
||||
|
||||
// «Добавил(а) вас в друзья», а вы ещё нет – кнопка «Дружить в ответ» прямо в уведомлении.
|
||||
// Кто у вас уже в друзьях – из одного запроса своего графа связей.
|
||||
async function offerFriendBack(items, rowByItem, seq) {
|
||||
const self = String(state.session.login || '').trim();
|
||||
const candidates = items.filter((x) => [CONNECTION_FRIEND, CONNECTION_CLOSE_FRIEND].includes(Number(x.connectionTypeCode ?? x.sourceMsgSubType)));
|
||||
if (!self || !candidates.length) return;
|
||||
let graph;
|
||||
try { graph = await authService.getUserConnectionsGraph(self); } catch { return; }
|
||||
if (seq !== renderSeq) return;
|
||||
const mine = new Set([...(graph?.outFriends || []), ...(graph?.outCloseFriends || [])].map((login) => String(login).toLowerCase()));
|
||||
const offered = new Set();
|
||||
for (const item of candidates) {
|
||||
const login = String(item.sourceLogin || '').trim();
|
||||
const key = login.toLowerCase();
|
||||
// Одна кнопка на человека – у самого свежего уведомления.
|
||||
if (!login || mine.has(key) || offered.has(key)) continue;
|
||||
offered.add(key);
|
||||
const row = rowByItem.get(item);
|
||||
const body = row?.querySelector('.notification-card__body');
|
||||
if (!body) continue;
|
||||
const kind = reciprocalRelationKind(item);
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'secondary-btn notification-card__answer';
|
||||
button.textContent = reciprocalRelationLabel(kind);
|
||||
button.addEventListener('click', async (event) => {
|
||||
event.stopPropagation();
|
||||
button.disabled = true;
|
||||
button.textContent = t('screens.notifications_view.text_010');
|
||||
try {
|
||||
await authService.setUserRelation({ login: self, toLogin: login, kind, enabled: true, storagePwd: state.session.storagePwdInMemory });
|
||||
const done = document.createElement('span');
|
||||
done.className = 'notification-card__answered';
|
||||
done.innerHTML = `${iconHtml('check')}<span>${th(reciprocalRelationSuccessLabel(kind))}</span>`;
|
||||
button.replaceWith(done);
|
||||
showToast(reciprocalRelationSuccessLabel(kind));
|
||||
} catch (error) {
|
||||
button.disabled = false;
|
||||
button.textContent = reciprocalRelationLabel(kind);
|
||||
showToast(toUserMessage(error, t('screens.notifications_view.text_016')), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
body.append(button);
|
||||
}
|
||||
}
|
||||
|
||||
async function enrichInBackground(items, tab, rowByItem, seq) {
|
||||
let cursor = 0;
|
||||
const worker = async () => {
|
||||
while (cursor < items.length) {
|
||||
const item = items[cursor++];
|
||||
const needProfile = !item.profile;
|
||||
if (!needProfile && tab !== 'replies') continue;
|
||||
const enriched = await enrichItem(item, tab);
|
||||
if (seq !== renderSeq) return;
|
||||
refreshItemRow(rowByItem.get(item), enriched, tab);
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: 6 }, worker));
|
||||
}
|
||||
|
||||
async function markAllRead() {
|
||||
if (!payloadCache) return;
|
||||
const jobs = ['replies', 'connections', 'events'].map((category) => {
|
||||
const { items, seenAt } = categoryData(payloadCache, category);
|
||||
const maxTs = items.reduce((max, x) => Math.max(max, Number(x?.createdAtMs || 0)), 0);
|
||||
return { category, maxTs, seenAt };
|
||||
}).filter((job) => job.maxTs > job.seenAt);
|
||||
if (!jobs.length) return;
|
||||
if (readAllBtn) readAllBtn.disabled = true;
|
||||
try {
|
||||
for (const job of jobs) {
|
||||
await authService.setNotificationSeen({ login: state.session.login, category: job.category, seenAtMs: job.maxTs, storagePwd: state.session.storagePwdInMemory });
|
||||
const seenKey = job.category === 'connections' ? 'connectionsSeenAtMs' : job.category === 'events' ? 'eventsSeenAtMs' : 'repliesSeenAtMs';
|
||||
const countKey = job.category === 'connections' ? 'connectionsUnseenCount' : job.category === 'events' ? 'eventsUnseenCount' : 'repliesUnseenCount';
|
||||
payloadCache[seenKey] = job.maxTs;
|
||||
payloadCache[countKey] = 0;
|
||||
localSeen[job.category] = Math.max(localSeen[job.category] || 0, job.maxTs);
|
||||
}
|
||||
if (lastNotifications?.payload) lastNotifications = { ...lastNotifications, payload: structuredClone(payloadCache), signature: '' };
|
||||
updateToolbarBadge(payloadCache);
|
||||
await renderCurrent();
|
||||
showToast(t('screens.notifications_view.text_017'));
|
||||
} catch (error) {
|
||||
updateToolbarBadge(payloadCache);
|
||||
showToast(toUserMessage(error, t('screens.notifications_view.text_018')), { kind: 'error' });
|
||||
}
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const seq=++requestSeq;
|
||||
const login = state.session.login;
|
||||
const cached = lastNotifications?.login === login ? lastNotifications : null;
|
||||
if (cached) { payloadCache = structuredClone(cached.payload); void renderCurrent(); }
|
||||
else { renderTabs({}); if (!list.childElementCount) list.replaceChildren(createLoadingState({ label: t('screens.notifications_view.text_012') })); }
|
||||
try {
|
||||
const fresh=await authService.getNotifications(); if(seq!==requestSeq)return;
|
||||
const signature = JSON.stringify(fresh);
|
||||
lastNotifications = { login, payload: structuredClone(fresh), signature };
|
||||
updateToolbarBadge(fresh);
|
||||
if (cached?.signature === signature) return;
|
||||
payloadCache=fresh; await renderCurrent();
|
||||
}
|
||||
catch(error){
|
||||
if(seq!==requestSeq)return;
|
||||
if (payloadCache) { showToast(toUserMessage(error, t('screens.notifications_view.text_019')), { kind: 'error' }); return; }
|
||||
list.replaceChildren(createErrorState({
|
||||
title: t('screens.notifications_view.text_013'),
|
||||
text: toUserMessage(error, t('screens.notifications_view.text_020')),
|
||||
onRetry: () => { list.replaceChildren(); void load(); },
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
if (!['replies','connections','events'].includes(state.notificationsTab)) state.notificationsTab='replies';
|
||||
screen.cleanup = () => {
|
||||
renderSeq += 1; // фоновая догрузка профилей больше не трогает экран
|
||||
requestSeq += 1;
|
||||
observer?.disconnect();
|
||||
Object.values(pendingSeenTimers).forEach((timer) => clearTimeout(timer));
|
||||
};
|
||||
screen.append(list);
|
||||
void load();
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,561 @@
|
||||
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_GENDER_FEMALE,
|
||||
PROFILE_GENDER_MALE,
|
||||
PROFILE_GENDER_UNKNOWN,
|
||||
PROFILE_ACCOUNT_ROLE_PRIMARY,
|
||||
PROFILE_ACCOUNT_ROLE_NON_VOTING,
|
||||
PROFILE_SHINE_SHINING,
|
||||
PROFILE_SHINE_UNKNOWN,
|
||||
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', get title() { return t('screens.profile_edit_view.text_001'); } };
|
||||
|
||||
function accountRoleLabel(value) {
|
||||
return value === PROFILE_ACCOUNT_ROLE_PRIMARY ? t('screens.profile_edit_view.text_009') : t('screens.profile_edit_view.text_010');
|
||||
}
|
||||
|
||||
function shineStatusLabel(value) {
|
||||
return value === PROFILE_SHINE_SHINING ? t('screens.profile_edit_view.text_011') : t('screens.profile_edit_view.text_012');
|
||||
}
|
||||
|
||||
|
||||
|
||||
function officialSteps(firstName, lastName) {
|
||||
const name = `${firstName} ${lastName}`.trim();
|
||||
return [
|
||||
{ title: t('dialogs.final.consent.official_steps.odin_chelovek_odin_ofitsialnyy_akkaunt'), text: t('dialogs.final.consent.official_steps.ofitsialnyy_akkaunt_vashe_zayavlenie_chto_eto_vash') },
|
||||
{ title: t('dialogs.final.consent.official_steps.priznanie_zavisit_ot_drugih_lyudey'), text: t('dialogs.final.consent.official_steps.samo_zayavlenie_ne_delaet_lichnost_proverennoy_dru') },
|
||||
{ title: t('dialogs.final.consent.official_steps.istoriya_perezhivaet_akkaunt'), text: t('dialogs.final.consent.official_steps.esli_vy_poteryaete_dostup_mozhno_zaregistrirovat_n') },
|
||||
{ title: t('dialogs.final.consent.official_steps.eto_deystvitelno_vy'), text: t('dialogs.final.consent.official_steps.v_profile_ukazano_value1_podtverzhdayte_tolko_esli', { value1: name }), accept: t('dialogs.final.consent.official_steps.podtverzhdayu_chto_value1_moi_nastoyaschie_imya_i', { value1: name }) },
|
||||
{ title: t('dialogs.final.consent.official_steps.podtverzhdaya_drugih_otvechayte_za_svoi_slova'), text: t('dialogs.final.consent.official_steps.ofitsialnyy_akkaunt_mozhet_podtverzhdat_osnovnye_a'), accept: t('dialogs.final.consent.official_steps.ponimayu_otvetstvennost_za_svoi_podtverzhdeniya') },
|
||||
{ title: t('dialogs.final.consent.official_steps.publichnaya_zapis'), text: t('dialogs.final.consent.official_steps.zayavlenie_i_buduschie_podtverzhdeniya_popadayut_v'), accept: t('dialogs.final.consent.official_steps.ya_ponimayu_publichnost_i_dolgovremennoe_hranenie'), button: t('dialogs.final.consent.official_steps.stat_ofitsialnym') },
|
||||
];
|
||||
}
|
||||
|
||||
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 genderLabel(value) {
|
||||
if (value === PROFILE_GENDER_MALE) return t('screens.profile_edit_view.text_013');
|
||||
if (value === PROFILE_GENDER_FEMALE) return t('screens.profile_edit_view.text_014');
|
||||
return t('screens.profile_edit_view.text_015');
|
||||
}
|
||||
|
||||
const GENDER_OPTIONS = Object.freeze([
|
||||
{ value: PROFILE_GENDER_MALE, get label() { return t('screens.profile_edit_view.text_002'); } },
|
||||
{ value: PROFILE_GENDER_FEMALE, get label() { return t('screens.profile_edit_view.text_003'); } },
|
||||
{ value: PROFILE_GENDER_UNKNOWN, get label() { return t('screens.profile_edit_view.text_004'); } },
|
||||
]);
|
||||
|
||||
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 = `
|
||||
<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>${th('screens.profile_edit_view.text_028')}</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">${th('screens.profile_edit_view.text_029')}</button>
|
||||
<button class="chip profile-toggle-btn is-no" type="button" data-status="shine">${th('screens.profile_edit_view.text_030')}</button>
|
||||
`;
|
||||
|
||||
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 currentGender = PROFILE_GENDER_UNKNOWN;
|
||||
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 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">${t('dialogs.modals.profile_edit_view.label_001')}</h3>
|
||||
<p class="meta-muted">${t('dialogs.modals.profile_edit_view.label_002')}</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">${t('dialogs.remaining.pages.profile_edit_view.markup.otmena')}</button>
|
||||
<button class="primary-btn" id="profile-gender-save" type="button">${t('dialogs.remaining.pages.profile_edit_view.markup.sohranit')}</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.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('screens.profile_edit_view.text_020', { value1: 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 = 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 updateGenderUi() {
|
||||
const genderValueEl = listWrap.querySelector('[data-gender-value]');
|
||||
if (!genderValueEl) return;
|
||||
genderValueEl.textContent = genderLabel(currentGender);
|
||||
}
|
||||
|
||||
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">${t('dialogs.modals.profile_edit_view.change_prefix')}${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 || t('dialogs.remaining.pages.profile_edit_view.openfieldeditmodal.vvedite_value1', { value1: label.toLowerCase() }))}"
|
||||
>${escapeHtml(String(value || ''))}</textarea>` : `<input
|
||||
id="profile-field-edit-input"
|
||||
class="input"
|
||||
type="text"
|
||||
maxlength="${Number(maxLength || 300)}"
|
||||
placeholder="${escapeHtml(placeholder || t('dialogs.remaining.pages.profile_edit_view.openfieldeditmodal.vvedite_value1', { value1: 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">${t('dialogs.final.profile.char_limit', { count: Number(maxLength || 300) })}</div>
|
||||
<div class="form-actions-grid">
|
||||
<button class="secondary-btn" id="profile-field-edit-cancel" type="button">${t('dialogs.remaining.pages.profile_edit_view.markup.otmena')}</button>
|
||||
<button class="primary-btn" id="profile-field-edit-save" type="button">${t('dialogs.remaining.pages.profile_edit_view.markup.sohranit')}</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 || t('screens.profile_edit_view.text_019'))}</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 = currentGender !== PROFILE_GENDER_MALE && currentGender !== PROFILE_GENDER_FEMALE;
|
||||
genderRow.innerHTML = `<span class="nav-row__hint">${th('screens.profile_edit_view.text_031')}</span><span class="nav-row__label${genderEmpty ? ' is-empty' : ''}" data-gender-value>${escapeHtml(genderEmpty ? t('screens.profile_edit_view.text_016') : genderText)}</span>`;
|
||||
listWrap.append(genderRow);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function refreshProfileSnapshot() {
|
||||
status.className = 'status-line';
|
||||
status.textContent = t('dialogs.modals.profile_edit_view.label_003');
|
||||
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: '', pr: '', 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(t('dialogs.modals.profile_edit_view.label_004'), error);
|
||||
showLocalErrorAlert(t('screens.profile_edit_view.text_007'), error);
|
||||
} finally {
|
||||
reloadBtn.disabled = false;
|
||||
accountRoleBtn.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 (statusFlowOpen) return;
|
||||
statusFlowOpen = true;
|
||||
try {
|
||||
const isAccountRole = statusKey === 'account_role';
|
||||
const alreadyOn = isAccountRole
|
||||
? currentAccountRole === PROFILE_ACCOUNT_ROLE_PRIMARY
|
||||
: currentShineStatus === PROFILE_SHINE_SHINING;
|
||||
let accepted = false;
|
||||
if (alreadyOn) {
|
||||
accepted = await confirmDialog({
|
||||
title: isAccountRole ? t('dialogs.final.consent.remove_official') : t('dialogs.final.consent.remove_shining'),
|
||||
text: t('dialogs.pages.profile_edit_view.text_001'),
|
||||
confirmLabel: t('dialogs.pages.profile_edit_view.confirmLabel_002'),
|
||||
});
|
||||
} else if (isAccountRole) {
|
||||
const firstName = String(currentFields.find((field) => field.key === 'first_name')?.value || '').trim();
|
||||
const lastName = String(currentFields.find((field) => field.key === 'last_name')?.value || '').trim();
|
||||
if (!firstName || !lastName) {
|
||||
await confirmDialog({
|
||||
title: t('dialogs.pages.profile_edit_view.title_003'),
|
||||
text: t('dialogs.pages.profile_edit_view.text_004'),
|
||||
confirmLabel: t('dialogs.pages.profile_edit_view.confirmLabel_005'),
|
||||
cancelLabel: t('dialogs.pages.profile_edit_view.cancelLabel_006'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
accepted = await confirmConsentSteps({ title: t('dialogs.final.consent.official_title'), steps: officialSteps(firstName, lastName) });
|
||||
} else {
|
||||
accepted = await confirmConsentSteps({ title: t('dialogs.final.consent.shining_title'), steps: shiningSteps() });
|
||||
}
|
||||
if (!accepted || !screen.isConnected) return;
|
||||
const nextValue = isAccountRole
|
||||
? (alreadyOn ? PROFILE_ACCOUNT_ROLE_NON_VOTING : PROFILE_ACCOUNT_ROLE_PRIMARY)
|
||||
: (alreadyOn ? PROFILE_SHINE_UNKNOWN : PROFILE_SHINE_SHINING);
|
||||
status.className = 'status-line';
|
||||
status.textContent = t('dialogs.modals.profile_edit_view.label_009');
|
||||
accountRoleBtn.disabled = true;
|
||||
shineBtn.disabled = true;
|
||||
try {
|
||||
await saveProfileStatus(login, statusKey, nextValue);
|
||||
if (!screen.isConnected) return;
|
||||
await refreshProfileSnapshot();
|
||||
} catch (error) {
|
||||
if (!screen.isConnected) return;
|
||||
status.className = 'status-line is-unavailable';
|
||||
const what = isAccountRole ? t('screens.profile_edit_view.text_017') : 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) {
|
||||
accountRoleBtn.disabled = false;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
async function onGenderClick() {
|
||||
const nextGender = await openGenderPickerModal(currentGender);
|
||||
if (!nextGender || nextGender === currentGender) return;
|
||||
const accepted = await confirmPublicHistoryAction({
|
||||
title: t('dialogs.final.consent.gender_publish_title'),
|
||||
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 saveProfileGender(login, nextGender);
|
||||
await refreshProfileSnapshot();
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = t('screens.profile_edit_view.text_027', { value1: toUserMessage(error, t('dialogs.modals.profile_edit_view.label_010')) });
|
||||
showLocalErrorAlert(t('screens.profile_edit_view.text_008'), 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;
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { attachSupportStats } from '../components/support-stats.js';
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { profile } from '../mock-data.js';
|
||||
import { state } from '../state.js';
|
||||
import { attachProfileAvatarPreview } from '../components/profile-avatar-preview.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { loadUserProfileCard } from '../services/user-connections.js';
|
||||
import { profileCardHtml, profileTileHtml } from '../components/profile-card.js';
|
||||
import { openShareSheet } from '../components/share-sheet.js';
|
||||
import { createErrorState, createLoadingState } from '../components/feedback.js';
|
||||
import { makeSharedProfileRoute } from '../services/shine-routes.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'profile-view', get title() { return t('screens.profile_view.text_001'); } };
|
||||
|
||||
// Последняя загруженная карточка своего профиля: при повторном заходе показываем её сразу и тихо обновляем.
|
||||
const cardCache = new Map();
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
const login = String(state.session.login || profile.login || '').trim();
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack user-profile-screen';
|
||||
|
||||
// Ссылка на свой профиль – самое частое «поделиться» в соцсети.
|
||||
const shareProfile = () => {
|
||||
const url = new URL(window.location.href);
|
||||
url.pathname = `/${makeSharedProfileRoute(card?.login || login)}`;
|
||||
url.search = '';
|
||||
url.hash = '';
|
||||
const name = [card?.firstName, card?.lastName].map((part) => String(part || '').trim()).filter(Boolean).join(' ');
|
||||
const displayLogin = String(card?.login || login).trim();
|
||||
openShareSheet({ title: t('screens.profile_view.text_002'), kicker: name ? `${name} · ${displayLogin}` : displayLogin, text: t('screens.profile_view.text_014'), url: url.toString() });
|
||||
};
|
||||
const topbar = createTopBar({
|
||||
title: t('screens.profile_view.text_003'),
|
||||
className: 'topbar--root user-profile-header',
|
||||
actions: [{ icon: 'share', title: t('screens.profile_view.text_004'), ariaLabel: t('screens.profile_view.text_005'), className: 'profile-share-btn', onClick: shareProfile }],
|
||||
});
|
||||
chrome?.setTopbar(topbar);
|
||||
|
||||
const status = document.createElement('div');
|
||||
status.className = 'user-profile-status';
|
||||
let card = cardCache.get(login.toLowerCase()) || null;
|
||||
// Первый заход – спиннер, но только если профиль грузится заметно долго.
|
||||
if (!card) status.append(createLoadingState({ label: t('screens.profile_view.text_006') }));
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'user-profile-body';
|
||||
screen.append(status, body);
|
||||
|
||||
let avatarPreview = null;
|
||||
let disposed = false;
|
||||
function renderProfile() {
|
||||
if (!card || disposed) return;
|
||||
avatarPreview?.cleanup();
|
||||
avatarPreview = null;
|
||||
body.innerHTML = profileCardHtml({
|
||||
card,
|
||||
login,
|
||||
tilesHtml: [
|
||||
profileTileHtml({ icon: 'edit', label: t('screens.profile_view.text_007'), attrs: 'data-self-profile-action="edit"' }),
|
||||
profileTileHtml({ icon: 'wallet', label: t('screens.profile_view.text_008'), attrs: 'data-self-profile-action="wallet"' }),
|
||||
profileTileHtml({ icon: 'settings', label: t('screens.profile_view.text_009'), attrs: 'data-self-profile-action="settings"' }),
|
||||
].join(''),
|
||||
}) + `
|
||||
<div class="nav-list profile-more-list">
|
||||
<button class="nav-row" type="button" data-self-profile-action="profiles"><span class="nav-row__label">${th('screens.profile_view.text_015')}</span><span class="nav-row__hint">${th('screens.profile_view.text_016')}</span></button>
|
||||
</div>`;
|
||||
|
||||
attachSupportStats(body, { login: card.login || login, isActive: () => !disposed });
|
||||
avatarPreview = attachProfileAvatarPreview(body.querySelector('.user-profile-avatar-slot'), card);
|
||||
|
||||
status.replaceChildren();
|
||||
}
|
||||
|
||||
body.addEventListener('click', (event) => {
|
||||
if (!card) return;
|
||||
|
||||
const listButton = event.target.closest('[data-profile-list]');
|
||||
if (listButton) {
|
||||
const kind = listButton.dataset.profileList;
|
||||
if (kind) navigate(`SHiNE/${encodeURIComponent(card.login)}/list/${encodeURIComponent(kind)}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const actionButton = event.target.closest('[data-self-profile-action]');
|
||||
if (actionButton) {
|
||||
const action = actionButton.dataset.selfProfileAction;
|
||||
if (action === 'edit') navigate('profile-edit-view');
|
||||
if (action === 'wallet') navigate('wallet-view');
|
||||
if (action === 'settings') navigate('settings-view');
|
||||
if (action === 'profiles') navigate('profiles-view');
|
||||
return;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
async function refresh() {
|
||||
if (state.session.isLocalDemo) {
|
||||
status.textContent = t('screens.profile_view.text_010');
|
||||
return;
|
||||
}
|
||||
const fresh = await loadUserProfileCard(login);
|
||||
if (disposed || (!screen.isConnected && card)) return;
|
||||
// Та же карточка – не перерисовываем, иначе аватар и счётчики мигают.
|
||||
if (card && JSON.stringify(card) === JSON.stringify(fresh)) return;
|
||||
card = fresh;
|
||||
cardCache.set(login.toLowerCase(), card);
|
||||
renderProfile();
|
||||
}
|
||||
|
||||
renderProfile();
|
||||
|
||||
const showLoadError = (error) => {
|
||||
if (card) return;
|
||||
status.replaceChildren(createErrorState({
|
||||
title: t('screens.profile_view.text_011'),
|
||||
text: toUserMessage(error, t('screens.profile_view.text_013')),
|
||||
onRetry: () => {
|
||||
status.replaceChildren(createLoadingState({ label: t('screens.profile_view.text_012'), delayMs: 0 }));
|
||||
refresh().catch(showLoadError);
|
||||
},
|
||||
}));
|
||||
};
|
||||
refresh().catch(showLoadError);
|
||||
|
||||
screen.cleanup = () => {
|
||||
disposed = true;
|
||||
avatarPreview?.cleanup();
|
||||
avatarPreview = null;
|
||||
};
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import {
|
||||
closeAllSavedProfiles,
|
||||
closeSavedProfile,
|
||||
getSavedProfiles,
|
||||
prepareAddProfileLogin,
|
||||
switchToSavedProfile,
|
||||
} from '../state.js';
|
||||
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'profiles-view', get title() { return t('screens.profiles_view.text_001'); } };
|
||||
|
||||
function reloadTo(path) {
|
||||
const clean = String(path || '/profile').trim() || '/profile';
|
||||
window.location.assign(clean.startsWith('/') ? clean : `/${clean}`);
|
||||
}
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack profiles-screen';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.profiles_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigate('profile-view') },
|
||||
}));
|
||||
|
||||
const intro = document.createElement('div');
|
||||
intro.className = 'meta-muted profiles-summary';
|
||||
|
||||
const list = document.createElement('div');
|
||||
list.className = 'stack profiles-list';
|
||||
|
||||
const status = document.createElement('div');
|
||||
status.className = 'status-line';
|
||||
status.hidden = true;
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'stack profiles-actions';
|
||||
|
||||
const addButton = document.createElement('button');
|
||||
addButton.type = 'button';
|
||||
addButton.className = 'secondary-btn';
|
||||
addButton.textContent = t('screens.profiles_view.text_003');
|
||||
addButton.addEventListener('click', async () => {
|
||||
addButton.disabled = true;
|
||||
status.hidden = false;
|
||||
status.className = 'status-line';
|
||||
status.textContent = t('screens.profiles_view.text_004');
|
||||
try {
|
||||
await prepareAddProfileLogin();
|
||||
navigate('login-view');
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = actionErrorText(t('screens.profiles_view.text_013'), error);
|
||||
addButton.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
const closeAllButton = document.createElement('button');
|
||||
closeAllButton.type = 'button';
|
||||
closeAllButton.className = 'destructive-btn profiles-close-all';
|
||||
closeAllButton.textContent = t('screens.profiles_view.text_005');
|
||||
closeAllButton.addEventListener('click', async () => {
|
||||
const profiles = getSavedProfiles();
|
||||
if (!profiles.length) return;
|
||||
const confirmed = await confirmDialog({ title: t('screens.profiles_view.text_006'), text: t('screens.profiles_view.text_017'), confirmLabel: t('screens.profiles_view.text_007'), danger: true });
|
||||
if (!confirmed) return;
|
||||
closeAllButton.disabled = true;
|
||||
status.hidden = false;
|
||||
status.textContent = t('screens.profiles_view.text_008');
|
||||
try {
|
||||
await closeAllSavedProfiles();
|
||||
reloadTo('/start');
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = actionErrorText(t('screens.profiles_view.text_014'), error);
|
||||
closeAllButton.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
actions.append(addButton, closeAllButton);
|
||||
screen.append(intro, list, status, actions);
|
||||
|
||||
const renderList = () => {
|
||||
const profiles = getSavedProfiles();
|
||||
intro.textContent = profiles.length ? '' : t('screens.profiles_view.text_018');
|
||||
intro.hidden = profiles.length > 0;
|
||||
closeAllButton.disabled = profiles.length === 0;
|
||||
list.innerHTML = '';
|
||||
|
||||
profiles.forEach((profile) => {
|
||||
const row = document.createElement('div');
|
||||
row.className = `card profiles-row${profile.isActive ? ' is-active' : ''}`;
|
||||
|
||||
const select = document.createElement('button');
|
||||
select.type = 'button';
|
||||
select.className = 'profiles-select';
|
||||
select.innerHTML = `<span class="profiles-login">${profile.login}</span>${profile.isActive ? t('screens.profiles_view.text_019') : ''}`;
|
||||
select.disabled = profile.isActive;
|
||||
select.addEventListener('click', async () => {
|
||||
if (profile.isActive) return;
|
||||
const confirmed = await confirmDialog({ title: t('screens.profiles_view.text_009'), text: t('screens.profiles_view.text_023', { value1: profile.login }), confirmLabel: t('screens.profiles_view.text_010') });
|
||||
if (!confirmed) return;
|
||||
status.hidden = false;
|
||||
status.className = 'status-line';
|
||||
status.textContent = t('screens.profiles_view.text_024', { value1: profile.login });
|
||||
try {
|
||||
await switchToSavedProfile(profile.login);
|
||||
reloadTo('/profile');
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = actionErrorText(t('screens.profiles_view.text_015'), error);
|
||||
}
|
||||
});
|
||||
|
||||
const close = document.createElement('button');
|
||||
close.type = 'button';
|
||||
close.className = 'profiles-close';
|
||||
close.setAttribute('aria-label', t('screens.profiles_view.text_025', { value1: profile.login }));
|
||||
close.title = t('screens.profiles_view.text_011');
|
||||
close.textContent = '×';
|
||||
close.addEventListener('click', async () => {
|
||||
const others = profiles.filter((item) => item.login.toLowerCase() !== profile.login.toLowerCase());
|
||||
const message = profile.isActive
|
||||
? (others.length
|
||||
? t('screens.profiles_view.text_020')
|
||||
: t('screens.profiles_view.text_021'))
|
||||
: t('screens.profiles_view.text_022');
|
||||
if (!await confirmDialog({ title: t('screens.profiles_view.text_026', { value1: profile.login }), text: message, confirmLabel: t('screens.profiles_view.text_012'), danger: true })) return;
|
||||
|
||||
status.hidden = false;
|
||||
status.className = 'status-line';
|
||||
status.textContent = t('screens.profiles_view.text_027', { value1: profile.login });
|
||||
try {
|
||||
const result = await closeSavedProfile(profile.login);
|
||||
if (profile.isActive) {
|
||||
reloadTo(result.nextProfile ? '/profile' : '/start');
|
||||
return;
|
||||
}
|
||||
status.hidden = true;
|
||||
renderList();
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = actionErrorText(t('screens.profiles_view.text_016'), error);
|
||||
}
|
||||
});
|
||||
|
||||
row.append(select, close);
|
||||
list.append(row);
|
||||
});
|
||||
};
|
||||
|
||||
renderList();
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
import { formatNumber } from '../i18n/format.js';
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { getSolanaCluster } from '../services/solana-rpc-gateway.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { state } from '../state.js';
|
||||
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
||||
|
||||
export const pageMeta = { id: 'queue', get title() { return t('screens.public_support_queue_view.text_001'); } };
|
||||
|
||||
const SHINE_PAYMENTS_PROGRAM_ID = 'SHiPmXbM9Fs9khzRUW3TGKsS2W84aqaXTxs3ZkajW9v';
|
||||
const SHINE_PAYMENTS_ORACLE_ACCOUNT = '7UVimffxr9ow1uXYxsr4LHAcV58mLzhmwaeKvJ1pjLiE';
|
||||
const SHINE_PAYMENTS_SEEDS = {
|
||||
config: 'shine_payments_config',
|
||||
coef: 'shine_payments_coef_limit',
|
||||
queues: 'shine_payments_queues',
|
||||
q1: 'shine_payments_q1_ticket',
|
||||
q2: 'shine_payments_q2_ticket',
|
||||
q3: 'shine_payments_q3_ticket',
|
||||
};
|
||||
|
||||
function isTestDeployUi() {
|
||||
return getSolanaCluster() === 'devnet';
|
||||
}
|
||||
|
||||
function resolveQueueEndpoint(useMainnetQueue) {
|
||||
return state.entrySettings.solanaServer;
|
||||
}
|
||||
|
||||
function utf8Bytes(text) {
|
||||
return new TextEncoder().encode(String(text || ''));
|
||||
}
|
||||
|
||||
function u64ToBytes(value) {
|
||||
const out = new Uint8Array(8);
|
||||
let current = BigInt(value || 0);
|
||||
for (let i = 0; i < 8; i += 1) {
|
||||
out[i] = Number(current & 0xffn);
|
||||
current >>= 8n;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function readU64(data, offset) {
|
||||
let value = 0n;
|
||||
for (let i = 0; i < 8; i += 1) {
|
||||
value |= BigInt(data[offset + i]) << (8n * BigInt(i));
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function readI64(data, offset) {
|
||||
let value = readU64(data, offset);
|
||||
if (value > 0x7fffffffffffffffn) {
|
||||
value -= 0x10000000000000000n;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function readI32(data, offset) {
|
||||
let value = Number(readU64(data, offset) & 0xffffffffn);
|
||||
if (value > 0x7fffffff) value -= 0x100000000;
|
||||
return value;
|
||||
}
|
||||
|
||||
function formatQueuePrefix(queueId) {
|
||||
if (queueId === 2) return 'Q2';
|
||||
if (queueId === 3) return 'Q3';
|
||||
return 'Q1';
|
||||
}
|
||||
|
||||
function formatQueueTitle(queueId) {
|
||||
if (queueId === 2) return t('screens.public_support_queue_view.text_008');
|
||||
if (queueId === 3) return t('screens.public_support_queue_view.text_009');
|
||||
return t('screens.public_support_queue_view.text_010');
|
||||
}
|
||||
|
||||
function formatSupportTicketLabel(queueId, index) {
|
||||
const cleanIndex = BigInt(index || 0n).toString();
|
||||
if (queueId === 2 || queueId === 3) return `${queueId}/${cleanIndex}`;
|
||||
return cleanIndex;
|
||||
}
|
||||
|
||||
function formatUsdCentsText(cents) {
|
||||
const value = Number(cents || 0n) / 100;
|
||||
return formatNumber(value, { minimumFractionDigits: 0, maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
function parsePaymentsCoef(data) {
|
||||
let offset = 0;
|
||||
const version = data[offset];
|
||||
offset += 1;
|
||||
const coefPpm = readU64(data, offset);
|
||||
offset += 8;
|
||||
const limitUsdCents = readU64(data, offset);
|
||||
offset += 8;
|
||||
const callRewardLamports = readU64(data, offset);
|
||||
return { version, coefPpm, limitUsdCents, callRewardLamports };
|
||||
}
|
||||
|
||||
function parsePaymentsQueues(data) {
|
||||
let offset = 0;
|
||||
const version = data[offset];
|
||||
offset += 1;
|
||||
const q1TicketsTotal = readU64(data, offset); offset += 8;
|
||||
const q1TicketsPaid = readU64(data, offset); offset += 8;
|
||||
const q1SumTotalUsdCents = readU64(data, offset); offset += 8;
|
||||
const q1SumPaidUsdCents = readU64(data, offset); offset += 8;
|
||||
const q2TicketsTotal = readU64(data, offset); offset += 8;
|
||||
const q2TicketsPaid = readU64(data, offset); offset += 8;
|
||||
const q2SumTotalUsdCents = readU64(data, offset); offset += 8;
|
||||
const q2SumPaidUsdCents = readU64(data, offset); offset += 8;
|
||||
const q3TicketsTotal = readU64(data, offset); offset += 8;
|
||||
const q3TicketsPaid = readU64(data, offset); offset += 8;
|
||||
const q3SumTotalUsdCents = readU64(data, offset); offset += 8;
|
||||
const q3SumPaidUsdCents = readU64(data, offset);
|
||||
return {
|
||||
version,
|
||||
q1TicketsTotal,
|
||||
q1TicketsPaid,
|
||||
q1SumTotalUsdCents,
|
||||
q1SumPaidUsdCents,
|
||||
q2TicketsTotal,
|
||||
q2TicketsPaid,
|
||||
q2SumTotalUsdCents,
|
||||
q2SumPaidUsdCents,
|
||||
q3TicketsTotal,
|
||||
q3TicketsPaid,
|
||||
q3SumTotalUsdCents,
|
||||
q3SumPaidUsdCents,
|
||||
};
|
||||
}
|
||||
|
||||
function parsePaymentsTicket(data) {
|
||||
let offset = 0;
|
||||
const version = data[offset];
|
||||
offset += 1;
|
||||
const queueId = data[offset];
|
||||
offset += 1;
|
||||
const index = readU64(data, offset);
|
||||
offset += 8;
|
||||
const isPaid = Boolean(data[offset]);
|
||||
offset += 1;
|
||||
const solana = window.solanaWeb3;
|
||||
const recipientWallet = new solana.PublicKey(data.slice(offset, offset + 32)).toBase58();
|
||||
offset += 32;
|
||||
const payoutUsdCents = readU64(data, offset);
|
||||
offset += 8;
|
||||
const debtBeforeUsdCents = readU64(data, offset);
|
||||
return {
|
||||
version,
|
||||
queueId,
|
||||
index,
|
||||
isPaid,
|
||||
recipientWallet,
|
||||
payoutUsdCents,
|
||||
debtBeforeUsdCents,
|
||||
};
|
||||
}
|
||||
|
||||
function parseSupportTicketInput(rawValue) {
|
||||
const clean = String(rawValue || '').trim();
|
||||
if (!clean) throw new Error(t('screens.public_support_queue_view.text_015'));
|
||||
if (/^\d+$/.test(clean)) {
|
||||
return { queueId: 1, index: BigInt(clean) };
|
||||
}
|
||||
const match = clean.match(/^([23])\s*\/\s*(\d+)$/);
|
||||
if (!match) {
|
||||
throw new Error(t('screens.public_support_queue_view.text_016'));
|
||||
}
|
||||
return {
|
||||
queueId: Number(match[1]),
|
||||
index: BigInt(match[2]),
|
||||
};
|
||||
}
|
||||
|
||||
async function loadSupportPaymentsCore(endpoint) {
|
||||
const solana = await loadSolanaWeb3();
|
||||
const rpc = String(endpoint || '').trim();
|
||||
const connection = new solana.Connection(rpc, 'confirmed');
|
||||
const programId = new solana.PublicKey(SHINE_PAYMENTS_PROGRAM_ID);
|
||||
const oracleAccount = new solana.PublicKey(SHINE_PAYMENTS_ORACLE_ACCOUNT);
|
||||
const [configPda] = solana.PublicKey.findProgramAddressSync([utf8Bytes(SHINE_PAYMENTS_SEEDS.config)], programId);
|
||||
const [coefPda] = solana.PublicKey.findProgramAddressSync([utf8Bytes(SHINE_PAYMENTS_SEEDS.coef)], programId);
|
||||
const [queuesPda] = solana.PublicKey.findProgramAddressSync([utf8Bytes(SHINE_PAYMENTS_SEEDS.queues)], programId);
|
||||
const [oracleAi, configAi, coefAi, queuesAi] = await Promise.all([
|
||||
connection.getAccountInfo(oracleAccount, 'confirmed'),
|
||||
connection.getAccountInfo(configPda, 'confirmed'),
|
||||
connection.getAccountInfo(coefPda, 'confirmed'),
|
||||
connection.getAccountInfo(queuesPda, 'confirmed'),
|
||||
]);
|
||||
if (!oracleAi) throw new Error(t('screens.public_support_queue_view.text_017'));
|
||||
if (!configAi || !coefAi || !queuesAi) throw new Error(t('screens.public_support_queue_view.text_018'));
|
||||
|
||||
const parsePrice = (data) => {
|
||||
const price = readI64(data, 73);
|
||||
const exponent = readI32(data, 89);
|
||||
const publishTime = readI64(data, 93);
|
||||
if (price <= 0n) throw new Error(t('screens.public_support_queue_view.text_019'));
|
||||
let num = price * 100n;
|
||||
let den = 1n;
|
||||
if (exponent >= 0) {
|
||||
num *= 10n ** BigInt(exponent);
|
||||
} else {
|
||||
den *= 10n ** BigInt(-exponent);
|
||||
}
|
||||
return { priceNum: num, priceDen: den, publishTime };
|
||||
};
|
||||
|
||||
return {
|
||||
connection,
|
||||
programId,
|
||||
coef: parsePaymentsCoef(coefAi.data),
|
||||
queues: parsePaymentsQueues(queuesAi.data),
|
||||
pyth: parsePrice(oracleAi.data),
|
||||
};
|
||||
}
|
||||
|
||||
function queueStateView(queues, queueId) {
|
||||
if (queueId === 2) {
|
||||
return {
|
||||
ticketsTotal: queues.q2TicketsTotal,
|
||||
ticketsPaid: queues.q2TicketsPaid,
|
||||
sumTotalUsdCents: queues.q2SumTotalUsdCents,
|
||||
sumPaidUsdCents: queues.q2SumPaidUsdCents,
|
||||
};
|
||||
}
|
||||
if (queueId === 3) {
|
||||
return {
|
||||
ticketsTotal: queues.q3TicketsTotal,
|
||||
ticketsPaid: queues.q3TicketsPaid,
|
||||
sumTotalUsdCents: queues.q3SumTotalUsdCents,
|
||||
sumPaidUsdCents: queues.q3SumPaidUsdCents,
|
||||
};
|
||||
}
|
||||
return {
|
||||
ticketsTotal: queues.q1TicketsTotal,
|
||||
ticketsPaid: queues.q1TicketsPaid,
|
||||
sumTotalUsdCents: queues.q1SumTotalUsdCents,
|
||||
sumPaidUsdCents: queues.q1SumPaidUsdCents,
|
||||
};
|
||||
}
|
||||
|
||||
function queueSeedFor(queueId) {
|
||||
if (queueId === 2) return SHINE_PAYMENTS_SEEDS.q2;
|
||||
if (queueId === 3) return SHINE_PAYMENTS_SEEDS.q3;
|
||||
return SHINE_PAYMENTS_SEEDS.q1;
|
||||
}
|
||||
|
||||
function styleInputField(field) {
|
||||
if (!field) return;
|
||||
field.style.color = 'var(--text-primary)';
|
||||
field.style.webkitTextFillColor = 'var(--text-primary)';
|
||||
field.style.caretColor = 'var(--accent)';
|
||||
field.style.backgroundColor = 'var(--surface)';
|
||||
}
|
||||
|
||||
function readTicketFromUrl() {
|
||||
try {
|
||||
const params = new URLSearchParams(window.location.search || '');
|
||||
return String(params.get('ticket') || '').trim();
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
const content = document.createElement('div');
|
||||
content.className = 'stack';
|
||||
|
||||
const status = document.createElement('p');
|
||||
status.className = 'meta-muted';
|
||||
status.textContent = t('screens.public_support_queue_view.text_002');
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack';
|
||||
card.innerHTML = `
|
||||
<h2 style="margin:0;">${th('screens.public_support_queue_view.text_025')}</h2>
|
||||
<p class="meta-muted" style="margin:0; line-height:1.55;">
|
||||
${th('screens.public_support_queue_view.text_026')}
|
||||
</p>
|
||||
`;
|
||||
|
||||
const inputLabel = document.createElement('label');
|
||||
inputLabel.className = 'meta-muted';
|
||||
inputLabel.setAttribute('for', 'public-queue-ticket-query');
|
||||
inputLabel.textContent = t('screens.public_support_queue_view.text_003');
|
||||
|
||||
const queryInput = document.createElement('input');
|
||||
queryInput.id = 'public-queue-ticket-query';
|
||||
queryInput.type = 'text';
|
||||
queryInput.placeholder = t('screens.public_support_queue_view.text_004');
|
||||
queryInput.autocomplete = 'off';
|
||||
queryInput.spellcheck = false;
|
||||
styleInputField(queryInput);
|
||||
queryInput.value = readTicketFromUrl();
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'row';
|
||||
actions.innerHTML = `
|
||||
<button class="primary-btn" type="button" id="public-queue-load" style="width:100%;">${th('screens.public_support_queue_view.text_027')}</button>
|
||||
<button class="ghost-btn" type="button" id="public-queue-reset" style="width:100%;">${th('screens.public_support_queue_view.text_028')}</button>
|
||||
`;
|
||||
|
||||
const result = document.createElement('div');
|
||||
result.className = 'card stack';
|
||||
result.innerHTML = `<p class="meta-muted" style="margin:0;">${th('screens.public_support_queue_view.text_029')}</p>`;
|
||||
|
||||
const testDeploy = isTestDeployUi();
|
||||
const mainnetRow = document.createElement('label');
|
||||
mainnetRow.className = 'checkbox-row';
|
||||
mainnetRow.innerHTML = `
|
||||
<input type="checkbox" id="public-queue-mainnet-source" ${testDeploy ? 'checked' : ''} />
|
||||
<span>${th('screens.public_support_queue_view.text_030')}</span>
|
||||
`;
|
||||
mainnetRow.style.display = 'none';
|
||||
const mainnetCheckbox = mainnetRow.querySelector('#public-queue-mainnet-source');
|
||||
|
||||
let lastCoreState = null;
|
||||
let lastEndpoint = '';
|
||||
|
||||
async function renderTicketInfo() {
|
||||
const raw = String(queryInput.value || '').trim();
|
||||
if (!raw) {
|
||||
result.innerHTML = `<p class="meta-muted" style="margin:0;">${th('screens.public_support_queue_view.text_031')}</p>`;
|
||||
status.textContent = t('screens.public_support_queue_view.text_005');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const parsed = parseSupportTicketInput(raw);
|
||||
const endpoint = resolveQueueEndpoint(Boolean(testDeploy && mainnetCheckbox?.checked));
|
||||
const core = lastCoreState && lastEndpoint === endpoint
|
||||
? lastCoreState
|
||||
: await loadSupportPaymentsCore(endpoint);
|
||||
lastCoreState = core;
|
||||
lastEndpoint = endpoint;
|
||||
const solana = await loadSolanaWeb3();
|
||||
const ticketPdaSeed = queueSeedFor(parsed.queueId);
|
||||
const ticketIndexBytes = u64ToBytes(parsed.index);
|
||||
const [ticketPda] = solana.PublicKey.findProgramAddressSync(
|
||||
[utf8Bytes(ticketPdaSeed), ticketIndexBytes],
|
||||
core.programId,
|
||||
);
|
||||
const ticketInfo = await core.connection.getAccountInfo(ticketPda, 'confirmed');
|
||||
if (!ticketInfo) {
|
||||
result.innerHTML = `
|
||||
<p class="meta-muted" style="margin:0;">${th('remaining.html_public_support_queue_view.ticket')}${formatSupportTicketLabel(parsed.queueId, parsed.index)}${th('remaining.html_public_support_queue_view.has_not_been_created_yet')}</p>
|
||||
`;
|
||||
status.textContent = t('screens.public_support_queue_view.text_021', { value1: formatSupportTicketLabel(parsed.queueId, parsed.index) });
|
||||
return;
|
||||
}
|
||||
const ticket = parsePaymentsTicket(ticketInfo.data);
|
||||
const queueState = queueStateView(core.queues, parsed.queueId);
|
||||
const ticketsBefore = parsed.index > 0n ? parsed.index - 1n : 0n;
|
||||
const paidBefore = queueState.ticketsPaid < ticketsBefore ? queueState.ticketsPaid : ticketsBefore;
|
||||
const remainingBefore = ticketsBefore > paidBefore ? ticketsBefore - paidBefore : 0n;
|
||||
if (ticket.queueId === 2 || ticket.queueId === 3) {
|
||||
result.innerHTML = `
|
||||
<div>${formatQueueTitle(ticket.queueId)}</div>
|
||||
<div><b>${th('screens.public_support_queue_view.text_032')}</b> ${ticket.index.toString()}</div>
|
||||
<div><b>${th('screens.public_support_queue_view.text_033')}</b> ${ticket.isPaid ? t('screens.public_support_queue_view.text_011') : t('screens.public_support_queue_view.text_012')}</div>
|
||||
<div><b>${th('screens.public_support_queue_view.text_034')}</b> <span style="word-break:break-all;">${ticket.recipientWallet}</span></div>
|
||||
<div><b>${th('screens.public_support_queue_view.text_035')}</b> ${formatUsdCentsText(ticket.payoutUsdCents)} USD</div>
|
||||
`;
|
||||
} else {
|
||||
result.innerHTML = `
|
||||
<div><b>${th('screens.public_support_queue_view.text_036')}</b> ${formatSupportTicketLabel(parsed.queueId, ticket.index)}</div>
|
||||
<div><b>${th('screens.public_support_queue_view.text_037')}</b> ${ticket.isPaid ? t('screens.public_support_queue_view.text_013') : t('screens.public_support_queue_view.text_014')}</div>
|
||||
<div><b>${th('screens.public_support_queue_view.text_038')}</b> <span style="word-break:break-all;">${ticket.recipientWallet}</span></div>
|
||||
<div><b>${th('screens.public_support_queue_view.text_039')}</b> ${ticketsBefore.toString()}${th('remaining.html_public_support_queue_view.tickets_div')}
|
||||
<div><b>${th('screens.public_support_queue_view.text_040')}</b> ${paidBefore.toString()}${th('remaining.html_public_support_queue_view.tickets_div')}
|
||||
<div><b>${th('screens.public_support_queue_view.text_041')}</b> ${remainingBefore.toString()}${th('remaining.html_public_support_queue_view.tickets_div')}
|
||||
<div><b>${th('screens.public_support_queue_view.text_042')}</b> ${formatUsdCentsText(queueState.sumPaidUsdCents)} USD</div>
|
||||
<div><b>${th('screens.public_support_queue_view.text_043')}</b> ${formatUsdCentsText(ticket.payoutUsdCents)} USD</div>
|
||||
<div><b>${th('screens.public_support_queue_view.text_044')}</b> ${formatUsdCentsText(ticket.debtBeforeUsdCents)}${th('remaining.html_public_support_queue_view.usd_ahead_of_it_in_the_queue_div')}
|
||||
`;
|
||||
}
|
||||
status.textContent = t('screens.public_support_queue_view.text_022', { value1: formatSupportTicketLabel(ticket.queueId, ticket.index), value2: endpoint });
|
||||
} catch (error) {
|
||||
result.innerHTML = `<p class="meta-muted" style="margin:0;">${String(error?.message || t('screens.public_support_queue_view.text_020'))}</p>`;
|
||||
status.textContent = t('screens.public_support_queue_view.text_023', { value1: error?.message || 'unknown' });
|
||||
}
|
||||
}
|
||||
|
||||
actions.querySelector('#public-queue-load')?.addEventListener('click', () => {
|
||||
void renderTicketInfo();
|
||||
});
|
||||
mainnetCheckbox?.addEventListener('change', () => {
|
||||
lastCoreState = null;
|
||||
lastEndpoint = '';
|
||||
status.textContent = t('screens.public_support_queue_view.text_024', { value1: resolveQueueEndpoint(Boolean(testDeploy && mainnetCheckbox.checked)) });
|
||||
});
|
||||
actions.querySelector('#public-queue-reset')?.addEventListener('click', () => {
|
||||
queryInput.value = '';
|
||||
result.innerHTML = `<p class="meta-muted" style="margin:0;">${th('screens.public_support_queue_view.text_045')}</p>`;
|
||||
status.textContent = t('screens.public_support_queue_view.text_006');
|
||||
});
|
||||
queryInput.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
void renderTicketInfo();
|
||||
}
|
||||
});
|
||||
|
||||
content.append(card, mainnetRow, inputLabel, queryInput, actions, result, status);
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.public_support_queue_view.text_007'),
|
||||
back: { label: '←', onClick: () => navigate('start-view') },
|
||||
}));
|
||||
screen.append(
|
||||
content,
|
||||
);
|
||||
|
||||
if (queryInput.value) {
|
||||
void renderTicketInfo();
|
||||
}
|
||||
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,558 @@
|
||||
import { formatDateTime, formatTime } from '../i18n/format.js';
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { canInstallPwa, isStandalonePwaMode } from '../services/pwa-install-service.js';
|
||||
|
||||
export const pageMeta = { id: 'pwa-diagnostics-view', get title() { return t('screens.pwa_diagnostics_view.text_001'); } };
|
||||
|
||||
const LS_SUBSCRIPTION_KEY = 'shine-ui-webpush-subscription-v1';
|
||||
const LS_SUBSCRIPTION_UPDATED_AT_KEY = 'shine-ui-webpush-subscription-updated-at-v1';
|
||||
const LS_LAST_TEST_STATUS_KEY = 'shine-ui-last-test-push-status-v1';
|
||||
const LS_LAST_TEST_AT_KEY = 'shine-ui-last-test-push-at-v1';
|
||||
const LS_LAST_PUSH_PAYLOAD_KEY = 'shine-ui-last-push-payload-v1';
|
||||
|
||||
function vapidBase64ToUint8Array(base64String) {
|
||||
const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
|
||||
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
|
||||
const rawData = window.atob(base64);
|
||||
const outputArray = new Uint8Array(rawData.length);
|
||||
for (let i = 0; i < rawData.length; i += 1) {
|
||||
outputArray[i] = rawData.charCodeAt(i);
|
||||
}
|
||||
return outputArray;
|
||||
}
|
||||
|
||||
function formatTs(ts) {
|
||||
const num = Number(ts);
|
||||
if (!Number.isFinite(num) || num <= 0) return '–';
|
||||
try {
|
||||
return formatDateTime(new Date(num));
|
||||
} catch {
|
||||
return String(num);
|
||||
}
|
||||
}
|
||||
|
||||
function detectLaunchMode() {
|
||||
try {
|
||||
if (window.matchMedia?.('(display-mode: standalone)')?.matches || window.navigator?.standalone === true) {
|
||||
return 'standalone';
|
||||
}
|
||||
if (window.matchMedia?.('(display-mode: fullscreen)')?.matches) {
|
||||
return 'fullscreen';
|
||||
}
|
||||
if (window.matchMedia?.('(display-mode: browser)')?.matches) {
|
||||
return 'browser';
|
||||
}
|
||||
return 'unknown';
|
||||
} catch {
|
||||
return 'unknown';
|
||||
}
|
||||
}
|
||||
|
||||
function detectIosSafari() {
|
||||
const ua = String(navigator.userAgent || '').toLowerCase();
|
||||
const isIos = /iphone|ipad|ipod/.test(ua);
|
||||
const isSafari = /safari/.test(ua) && !/crios|fxios|edgios|opr\//.test(ua);
|
||||
return isIos && isSafari;
|
||||
}
|
||||
|
||||
function buildInstallState({ launchMode, manifestOk, swRegistered }) {
|
||||
if (launchMode === 'standalone' || launchMode === 'fullscreen') return 'installed';
|
||||
if (canInstallPwa()) return 'prompt';
|
||||
if (!window.isSecureContext || !manifestOk || !swRegistered) return 'unavailable';
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
function installStateText(code) {
|
||||
const keys = { installed: 'text_023', prompt: 'text_024', unavailable: 'text_025', unknown: 'text_026' };
|
||||
return t(`screens.pwa_diagnostics_view.${keys[code] || 'text_026'}`);
|
||||
}
|
||||
|
||||
// Разрешения браузера и статусы диагностики — коды, а не переводимые подписи.
|
||||
// Старые сохранённые значения push (русские слова) читаем ради совместимости.
|
||||
function normalizeTestPushCode(value) {
|
||||
const code = String(value || '').trim().toLowerCase();
|
||||
if (code === 'отправлен' || code === 'sent') return 'sent';
|
||||
if (code === 'доставлен' || code === 'delivered') return 'delivered';
|
||||
if (code === 'ошибка' || code === 'error') return 'error';
|
||||
return 'never';
|
||||
}
|
||||
|
||||
function testPushText(code) {
|
||||
const keys = { sent: 'test_push_sent', delivered: 'test_push_delivered', error: 'test_push_error' };
|
||||
return keys[code] ? t(`screens.pwa_diagnostics_view.${keys[code]}`) : t('screens.pwa_diagnostics_view.text_033');
|
||||
}
|
||||
|
||||
function toneFor(code, type = 'binary') {
|
||||
if (type === 'permission') return { granted: 'ok', default: 'warn', denied: 'bad' }[code] || 'neutral';
|
||||
if (type === 'testPush') return { delivered: 'ok', sent: 'warn', error: 'bad' }[code] || 'neutral';
|
||||
if (type === 'install') return { installed: 'ok', prompt: 'ok', unavailable: 'warn', unknown: 'warn' }[code] || 'neutral';
|
||||
if (type === 'launchMode') return ['standalone', 'fullscreen', 'browser'].includes(code) ? 'ok' : 'neutral';
|
||||
if (['yes', 'found', 'registered', 'supported', 'present'].includes(code)) return 'ok';
|
||||
if (['no', 'missing', 'not_registered', 'error', 'unavailable'].includes(code)) return 'bad';
|
||||
return 'neutral';
|
||||
}
|
||||
|
||||
function rowEl(label, value, tone) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'pwa-diag-row';
|
||||
|
||||
const left = document.createElement('span');
|
||||
left.className = 'pwa-diag-key';
|
||||
left.textContent = label;
|
||||
|
||||
const right = document.createElement('span');
|
||||
right.className = 'pwa-diag-value';
|
||||
right.textContent = String(value || '–');
|
||||
|
||||
const indicator = document.createElement('span');
|
||||
indicator.className = `pwa-diag-indicator is-${tone || 'neutral'}`;
|
||||
|
||||
row.append(left, right, indicator);
|
||||
return row;
|
||||
}
|
||||
|
||||
async function collectDiagnostics() {
|
||||
const result = {
|
||||
secureContext: window.isSecureContext === true,
|
||||
manifestStatus: t('screens.pwa_diagnostics_view.text_027'),
|
||||
manifestCode: 'missing',
|
||||
manifestUrl: '',
|
||||
swStatus: t('screens.pwa_diagnostics_view.text_028'),
|
||||
swCode: 'not_registered',
|
||||
swError: '',
|
||||
launchMode: detectLaunchMode(),
|
||||
installAvailability: t('screens.pwa_diagnostics_view.text_029'),
|
||||
installCode: 'unknown',
|
||||
notificationsApi: t('screens.pwa_diagnostics_view.text_030'),
|
||||
notificationsApiCode: 'no',
|
||||
pushApi: t('screens.pwa_diagnostics_view.text_031'),
|
||||
pushApiCode: 'no',
|
||||
notificationPermission: 'default',
|
||||
pushSubscription: t('screens.pwa_diagnostics_view.text_032'),
|
||||
subscriptionCode: 'no',
|
||||
subscriptionEndpoint: '',
|
||||
subscriptionUpdatedAtMs: 0,
|
||||
lastTestPush: t('screens.pwa_diagnostics_view.text_033'),
|
||||
lastTestPushCode: 'never',
|
||||
lastTestPushAtMs: 0,
|
||||
lastPushPayload: null,
|
||||
iosSafariHint: false,
|
||||
tech: {},
|
||||
};
|
||||
|
||||
result.notificationsApiCode = 'Notification' in window ? 'supported' : 'no';
|
||||
result.notificationsApi = 'Notification' in window ? t('screens.pwa_diagnostics_view.text_034') : t('screens.pwa_diagnostics_view.text_035');
|
||||
result.pushApiCode = 'PushManager' in window ? 'supported' : 'no';
|
||||
result.pushApi = 'PushManager' in window ? t('screens.pwa_diagnostics_view.text_036') : t('screens.pwa_diagnostics_view.text_037');
|
||||
if ('Notification' in window) {
|
||||
result.notificationPermission = String(Notification.permission || 'default');
|
||||
}
|
||||
|
||||
try {
|
||||
const linkEl = document.querySelector('link[rel="manifest"]');
|
||||
const href = String(linkEl?.getAttribute('href') || '').trim();
|
||||
if (href) {
|
||||
const url = new URL(href, window.location.href).toString();
|
||||
const resp = await fetch(url, { cache: 'no-store' });
|
||||
result.manifestCode = resp.ok ? 'found' : 'missing';
|
||||
result.manifestStatus = resp.ok ? t('screens.pwa_diagnostics_view.text_038') : t('screens.pwa_diagnostics_view.text_039');
|
||||
result.manifestUrl = url;
|
||||
} else {
|
||||
result.manifestStatus = t('screens.pwa_diagnostics_view.text_048');
|
||||
}
|
||||
} catch {
|
||||
result.manifestStatus = t('screens.pwa_diagnostics_view.text_049');
|
||||
}
|
||||
|
||||
let registration = null;
|
||||
if ('serviceWorker' in navigator) {
|
||||
try {
|
||||
registration = await navigator.serviceWorker.getRegistration();
|
||||
result.swCode = registration ? 'registered' : 'not_registered';
|
||||
result.swStatus = registration ? t('screens.pwa_diagnostics_view.text_040') : t('screens.pwa_diagnostics_view.text_041');
|
||||
} catch (error) {
|
||||
result.swCode = 'error';
|
||||
result.swStatus = t('screens.pwa_diagnostics_view.text_050');
|
||||
result.swError = error?.message || 'unknown';
|
||||
}
|
||||
} else {
|
||||
result.swStatus = t('screens.pwa_diagnostics_view.text_051');
|
||||
}
|
||||
|
||||
result.installCode = buildInstallState({
|
||||
launchMode: result.launchMode,
|
||||
manifestOk: result.manifestCode === 'found',
|
||||
swRegistered: result.swCode === 'registered',
|
||||
});
|
||||
result.installAvailability = installStateText(result.installCode);
|
||||
|
||||
if (registration && ('PushManager' in window)) {
|
||||
try {
|
||||
const subscription = await registration.pushManager.getSubscription();
|
||||
if (subscription) {
|
||||
result.subscriptionCode = 'present';
|
||||
result.pushSubscription = t('screens.pwa_diagnostics_view.text_052');
|
||||
result.subscriptionEndpoint = String(subscription.endpoint || '');
|
||||
} else {
|
||||
result.pushSubscription = t('screens.pwa_diagnostics_view.text_053');
|
||||
}
|
||||
} catch (error) {
|
||||
result.subscriptionCode = 'error';
|
||||
result.pushSubscription = t('screens.pwa_diagnostics_view.text_054');
|
||||
result.swError = result.swError || (error?.message || 'unknown');
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const updatedAt = Number(localStorage.getItem(LS_SUBSCRIPTION_UPDATED_AT_KEY) || 0);
|
||||
result.subscriptionUpdatedAtMs = Number.isFinite(updatedAt) ? updatedAt : 0;
|
||||
} catch {
|
||||
result.subscriptionUpdatedAtMs = 0;
|
||||
}
|
||||
|
||||
try {
|
||||
const st = String(localStorage.getItem(LS_LAST_TEST_STATUS_KEY) || '').trim();
|
||||
const at = Number(localStorage.getItem(LS_LAST_TEST_AT_KEY) || 0);
|
||||
if (st) {
|
||||
result.lastTestPushCode = normalizeTestPushCode(st);
|
||||
result.lastTestPush = testPushText(result.lastTestPushCode);
|
||||
}
|
||||
if (Number.isFinite(at) && at > 0) result.lastTestPushAtMs = at;
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = localStorage.getItem(LS_LAST_PUSH_PAYLOAD_KEY);
|
||||
if (raw) result.lastPushPayload = JSON.parse(raw);
|
||||
} catch {
|
||||
result.lastPushPayload = null;
|
||||
}
|
||||
|
||||
result.iosSafariHint = detectIosSafari() && !isStandalonePwaMode();
|
||||
|
||||
result.tech = {
|
||||
secureContext: window.isSecureContext,
|
||||
hasServiceWorkerApi: 'serviceWorker' in navigator,
|
||||
hasPushManagerApi: 'PushManager' in window,
|
||||
hasNotificationsApi: 'Notification' in window,
|
||||
notificationPermission: result.notificationPermission,
|
||||
launchMode: result.launchMode,
|
||||
canInstallPrompt: canInstallPwa(),
|
||||
swStatus: result.swStatus,
|
||||
swCode: result.swCode,
|
||||
swError: result.swError,
|
||||
manifestStatus: result.manifestStatus,
|
||||
manifestCode: result.manifestCode,
|
||||
manifestUrl: result.manifestUrl,
|
||||
pushSubscription: result.pushSubscription,
|
||||
subscriptionCode: result.subscriptionCode,
|
||||
installCode: result.installCode,
|
||||
subscriptionEndpoint: result.subscriptionEndpoint,
|
||||
subscriptionUpdatedAtMs: result.subscriptionUpdatedAtMs,
|
||||
lastTestPush: result.lastTestPush,
|
||||
lastTestPushCode: result.lastTestPushCode,
|
||||
lastTestPushAtMs: result.lastTestPushAtMs,
|
||||
lastPushPayload: result.lastPushPayload,
|
||||
};
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function buildRecommendations(diag) {
|
||||
const rows = [];
|
||||
if (!diag.secureContext) {
|
||||
rows.push(t('screens.pwa_diagnostics_view.text_068'));
|
||||
}
|
||||
if (diag.manifestCode !== 'found') {
|
||||
rows.push(t('screens.pwa_diagnostics_view.text_069'));
|
||||
}
|
||||
if (diag.swCode !== 'registered') {
|
||||
rows.push(t('screens.pwa_diagnostics_view.text_070'));
|
||||
}
|
||||
if (diag.notificationPermission === 'default') {
|
||||
rows.push(t('screens.pwa_diagnostics_view.text_071'));
|
||||
} else if (diag.notificationPermission === 'denied') {
|
||||
rows.push(t('screens.pwa_diagnostics_view.text_072'));
|
||||
}
|
||||
if (diag.subscriptionCode !== 'present') {
|
||||
rows.push(t('screens.pwa_diagnostics_view.text_073'));
|
||||
}
|
||||
if (diag.installCode === 'prompt') {
|
||||
rows.push(t('screens.pwa_diagnostics_view.text_074'));
|
||||
}
|
||||
if (diag.iosSafariHint) {
|
||||
rows.push(t('screens.pwa_diagnostics_view.text_075'));
|
||||
}
|
||||
if (!rows.length) {
|
||||
rows.push(t('screens.pwa_diagnostics_view.text_076'));
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.pwa_diagnostics_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigate('developer-settings-view') },
|
||||
}));
|
||||
|
||||
const statusCard = document.createElement('div');
|
||||
statusCard.className = 'card stack';
|
||||
const statusList = document.createElement('div');
|
||||
statusList.className = 'stack pwa-diag-list';
|
||||
statusCard.append(statusList);
|
||||
|
||||
const actionsCard = document.createElement('div');
|
||||
actionsCard.className = 'card stack';
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'pwa-diag-actions';
|
||||
actions.innerHTML = `
|
||||
<button class="text-btn" type="button" id="diag-refresh">${th('screens.pwa_diagnostics_view.text_062')}</button>
|
||||
<button class="text-btn" type="button" id="diag-notif">${th('screens.pwa_diagnostics_view.text_063')}</button>
|
||||
<button class="text-btn" type="button" id="diag-subscribe">${th('screens.pwa_diagnostics_view.text_064')}</button>
|
||||
<button class="text-btn" type="button" id="diag-unsubscribe">${th('screens.pwa_diagnostics_view.text_065')}</button>
|
||||
<button class="text-btn" type="button" id="diag-testpush">${th('screens.pwa_diagnostics_view.text_066')}</button>
|
||||
<button class="text-btn" type="button" id="diag-toggle-details">${th('screens.pwa_diagnostics_view.text_067')}</button>
|
||||
`;
|
||||
actionsCard.append(actions);
|
||||
|
||||
const recommendationsCard = document.createElement('div');
|
||||
recommendationsCard.className = 'card stack';
|
||||
const recommendationsTitle = document.createElement('strong');
|
||||
recommendationsTitle.textContent = t('screens.pwa_diagnostics_view.text_003');
|
||||
const recommendationsList = document.createElement('div');
|
||||
recommendationsList.className = 'stack pwa-diag-recommendations';
|
||||
recommendationsCard.append(recommendationsTitle, recommendationsList);
|
||||
|
||||
const detailsCard = document.createElement('div');
|
||||
detailsCard.className = 'card stack';
|
||||
detailsCard.hidden = true;
|
||||
const detailsTitle = document.createElement('strong');
|
||||
detailsTitle.textContent = t('screens.pwa_diagnostics_view.text_004');
|
||||
const detailsPre = document.createElement('pre');
|
||||
detailsPre.className = 'pwa-diag-json';
|
||||
detailsCard.append(detailsTitle, detailsPre);
|
||||
|
||||
const info = document.createElement('div');
|
||||
info.className = 'meta-muted';
|
||||
|
||||
screen.append(statusCard, actionsCard, recommendationsCard, detailsCard, info);
|
||||
|
||||
let latestDiag = null;
|
||||
let lastTestResponse = null;
|
||||
|
||||
const setInfo = (text) => {
|
||||
info.textContent = String(text || '');
|
||||
};
|
||||
|
||||
const rerender = () => {
|
||||
if (!latestDiag) return;
|
||||
statusList.innerHTML = '';
|
||||
|
||||
statusList.append(
|
||||
rowEl('HTTPS', latestDiag.secureContext ? t('screens.pwa_diagnostics_view.text_042') : t('screens.pwa_diagnostics_view.text_043'), toneFor(latestDiag.secureContext ? 'yes' : 'no')),
|
||||
rowEl('Manifest', latestDiag.manifestStatus, toneFor(latestDiag.manifestCode)),
|
||||
rowEl('Service Worker', latestDiag.swStatus, toneFor(latestDiag.swCode)),
|
||||
rowEl(t('screens.pwa_diagnostics_view.text_006'), latestDiag.launchMode === 'browser' ? t('screens.pwa_diagnostics_view.text_022') : latestDiag.launchMode, toneFor(latestDiag.launchMode, 'launchMode')),
|
||||
rowEl(t('screens.pwa_diagnostics_view.text_007'), latestDiag.installAvailability, toneFor(latestDiag.installCode, 'install')),
|
||||
rowEl('Notifications API', latestDiag.notificationsApi, toneFor(latestDiag.notificationsApiCode)),
|
||||
rowEl('Push API', latestDiag.pushApi, toneFor(latestDiag.pushApiCode)),
|
||||
rowEl(t('screens.pwa_diagnostics_view.text_008'), latestDiag.notificationPermission, toneFor(latestDiag.notificationPermission, 'permission')),
|
||||
rowEl('Push subscription', latestDiag.pushSubscription, toneFor(latestDiag.subscriptionCode)),
|
||||
rowEl(t('screens.pwa_diagnostics_view.text_009'), latestDiag.lastTestPush, toneFor(latestDiag.lastTestPushCode, 'testPush')),
|
||||
);
|
||||
|
||||
if (latestDiag.subscriptionEndpoint) {
|
||||
statusList.append(rowEl(t('screens.pwa_diagnostics_view.text_010'), latestDiag.subscriptionEndpoint, 'neutral'));
|
||||
}
|
||||
if (latestDiag.subscriptionUpdatedAtMs) {
|
||||
statusList.append(rowEl(t('screens.pwa_diagnostics_view.text_011'), formatTs(latestDiag.subscriptionUpdatedAtMs), 'neutral'));
|
||||
}
|
||||
if (latestDiag.lastTestPushAtMs) {
|
||||
statusList.append(rowEl(t('screens.pwa_diagnostics_view.text_012'), formatTs(latestDiag.lastTestPushAtMs), 'neutral'));
|
||||
}
|
||||
|
||||
recommendationsList.innerHTML = '';
|
||||
buildRecommendations(latestDiag).forEach((entry) => {
|
||||
const p = document.createElement('p');
|
||||
p.className = 'meta-muted';
|
||||
p.textContent = `• ${entry}`;
|
||||
recommendationsList.append(p);
|
||||
});
|
||||
|
||||
const details = {
|
||||
diagnostics: latestDiag.tech || {},
|
||||
lastTestPushResponse: lastTestResponse,
|
||||
login: state.session.login || '',
|
||||
sessionId: state.session.sessionId || '',
|
||||
};
|
||||
detailsPre.textContent = JSON.stringify(details, null, 2);
|
||||
};
|
||||
|
||||
const reloadStatuses = async () => {
|
||||
setInfo(t('screens.pwa_diagnostics_view.text_013'));
|
||||
latestDiag = await collectDiagnostics();
|
||||
rerender();
|
||||
if (latestDiag.swError) {
|
||||
setInfo(t('screens.pwa_diagnostics_view.text_055', { value1: latestDiag.swError }));
|
||||
} else {
|
||||
setInfo(t('screens.pwa_diagnostics_view.text_056', { value1: formatTime(new Date()) }));
|
||||
}
|
||||
};
|
||||
|
||||
const withButtonBusy = async (btn, fn) => {
|
||||
btn.disabled = true;
|
||||
try {
|
||||
await fn();
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
};
|
||||
|
||||
actions.querySelector('#diag-refresh').addEventListener('click', async (event) => {
|
||||
await withButtonBusy(event.currentTarget, reloadStatuses);
|
||||
});
|
||||
|
||||
actions.querySelector('#diag-notif').addEventListener('click', async (event) => {
|
||||
await withButtonBusy(event.currentTarget, async () => {
|
||||
if (!('Notification' in window)) {
|
||||
setInfo(t('screens.pwa_diagnostics_view.text_014'));
|
||||
return;
|
||||
}
|
||||
const permission = await Notification.requestPermission();
|
||||
setInfo(t('screens.pwa_diagnostics_view.text_057', { value1: permission }));
|
||||
await reloadStatuses();
|
||||
});
|
||||
});
|
||||
|
||||
actions.querySelector('#diag-subscribe').addEventListener('click', async (event) => {
|
||||
await withButtonBusy(event.currentTarget, async () => {
|
||||
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
|
||||
setInfo(t('screens.pwa_diagnostics_view.text_015'));
|
||||
return;
|
||||
}
|
||||
const vapidPublicKey = String(window.__SHINE_WEBPUSH_VAPID_PUBLIC_KEY__ || '').trim();
|
||||
if (!vapidPublicKey) {
|
||||
setInfo(t('screens.pwa_diagnostics_view.text_016'));
|
||||
return;
|
||||
}
|
||||
|
||||
const registration = await navigator.serviceWorker.register('./firebase-messaging-sw.js');
|
||||
let permission = String(Notification.permission || 'default');
|
||||
if (permission !== 'granted') {
|
||||
permission = await Notification.requestPermission();
|
||||
}
|
||||
if (permission !== 'granted') {
|
||||
setInfo(t('screens.pwa_diagnostics_view.text_058', { value1: permission }));
|
||||
await reloadStatuses();
|
||||
return;
|
||||
}
|
||||
|
||||
let sub = await registration.pushManager.getSubscription();
|
||||
if (!sub) {
|
||||
sub = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: vapidBase64ToUint8Array(vapidPublicKey),
|
||||
});
|
||||
}
|
||||
const json = sub.toJSON();
|
||||
await authService.upsertPushToken({
|
||||
endpoint: json.endpoint || '',
|
||||
p256dhKey: json.keys?.p256dh || '',
|
||||
authKey: json.keys?.auth || '',
|
||||
platform: 'web',
|
||||
userAgent: navigator.userAgent || '',
|
||||
});
|
||||
const now = Date.now();
|
||||
try {
|
||||
localStorage.setItem(LS_SUBSCRIPTION_KEY, JSON.stringify(sub));
|
||||
localStorage.setItem(LS_SUBSCRIPTION_UPDATED_AT_KEY, String(now));
|
||||
} catch {
|
||||
// ignore local storage errors
|
||||
}
|
||||
setInfo(t('screens.pwa_diagnostics_view.text_017'));
|
||||
await reloadStatuses();
|
||||
});
|
||||
});
|
||||
|
||||
actions.querySelector('#diag-unsubscribe').addEventListener('click', async (event) => {
|
||||
await withButtonBusy(event.currentTarget, async () => {
|
||||
if (!('serviceWorker' in navigator)) {
|
||||
setInfo(t('screens.pwa_diagnostics_view.text_018'));
|
||||
return;
|
||||
}
|
||||
const registration = await navigator.serviceWorker.getRegistration();
|
||||
if (!registration || !registration.pushManager) {
|
||||
setInfo(t('screens.pwa_diagnostics_view.text_019'));
|
||||
await reloadStatuses();
|
||||
return;
|
||||
}
|
||||
const sub = await registration.pushManager.getSubscription();
|
||||
if (!sub) {
|
||||
setInfo(t('screens.pwa_diagnostics_view.text_020'));
|
||||
await reloadStatuses();
|
||||
return;
|
||||
}
|
||||
await sub.unsubscribe();
|
||||
try {
|
||||
localStorage.removeItem(LS_SUBSCRIPTION_KEY);
|
||||
localStorage.setItem(LS_SUBSCRIPTION_UPDATED_AT_KEY, String(Date.now()));
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
setInfo(t('screens.pwa_diagnostics_view.text_021'));
|
||||
await reloadStatuses();
|
||||
});
|
||||
});
|
||||
|
||||
actions.querySelector('#diag-testpush').addEventListener('click', async (event) => {
|
||||
await withButtonBusy(event.currentTarget, async () => {
|
||||
try {
|
||||
localStorage.setItem(LS_LAST_TEST_STATUS_KEY, 'sent');
|
||||
localStorage.setItem(LS_LAST_TEST_AT_KEY, String(Date.now()));
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
const resp = await authService.sendTestWebPush({
|
||||
login: state.session.login || '',
|
||||
title: t('screens.pwa_diagnostics_view.text_005'),
|
||||
text: t('screens.pwa_diagnostics_view.text_059', { value1: state.session.login || 'unknown' }),
|
||||
});
|
||||
lastTestResponse = resp;
|
||||
setInfo(t('screens.pwa_diagnostics_view.text_060', { value1: Number(resp?.delivered || 0) }));
|
||||
await reloadStatuses();
|
||||
}).catch(async (error) => {
|
||||
try {
|
||||
localStorage.setItem(LS_LAST_TEST_STATUS_KEY, 'error');
|
||||
localStorage.setItem(LS_LAST_TEST_AT_KEY, String(Date.now()));
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
setInfo(t('screens.pwa_diagnostics_view.text_061', { value1: error?.message || 'unknown' }));
|
||||
await reloadStatuses();
|
||||
});
|
||||
});
|
||||
|
||||
actions.querySelector('#diag-toggle-details').addEventListener('click', (event) => {
|
||||
detailsCard.hidden = !detailsCard.hidden;
|
||||
event.currentTarget.textContent = detailsCard.hidden ? t('screens.pwa_diagnostics_view.text_046') : t('screens.pwa_diagnostics_view.text_047');
|
||||
});
|
||||
|
||||
const onPushDiagUpdate = async () => {
|
||||
await reloadStatuses();
|
||||
};
|
||||
window.addEventListener('shine-push-diagnostics-update', onPushDiagUpdate);
|
||||
|
||||
void reloadStatuses();
|
||||
|
||||
screen.cleanup = () => {
|
||||
window.removeEventListener('shine-push-diagnostics-update', onPushDiagUpdate);
|
||||
};
|
||||
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
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 { 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) === 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));
|
||||
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));
|
||||
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();
|
||||
navigate(flowType === 'free' ? 'registration-email-view' : 'registration-payment-view');
|
||||
} 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);
|
||||
}
|
||||
|
||||
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 = 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;
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { resetRegistrationFlow, state } from '../state.js';
|
||||
import { getRegistrationNamespaces } from '../services/registration-v2-api.js';
|
||||
|
||||
export const pageMeta = { id: 'registration-choice-view', get title() { return t('screens.registration_choice_view.text_001'); }, showAppChrome: false };
|
||||
|
||||
export function render({ navigate }) {
|
||||
// Экран выбора начинает новую регистрацию. Старый незавершённый черновик
|
||||
// нельзя переносить в новый сценарий, особенно после неудачной попытки.
|
||||
resetRegistrationFlow();
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack registration-screen signup-choice';
|
||||
const title = document.createElement('h1');
|
||||
title.className = 'signup-title';
|
||||
title.textContent = t('screens.registration_choice_view.text_002');
|
||||
const intro = document.createElement('p');
|
||||
intro.className = 'signup-lead';
|
||||
intro.textContent = t('screens.registration_choice_view.text_003');
|
||||
|
||||
function card({ type, icon, heading, price, lead, perks, button }) {
|
||||
const box = document.createElement('article');
|
||||
box.className = `signup-plan signup-plan--${type}`;
|
||||
const top = document.createElement('div');
|
||||
top.className = 'signup-plan__top';
|
||||
const symbol = document.createElement('span');
|
||||
symbol.className = 'signup-plan__symbol';
|
||||
symbol.textContent = icon;
|
||||
const header = document.createElement('div');
|
||||
const name = document.createElement('h2');
|
||||
name.textContent = heading;
|
||||
const cost = document.createElement('p');
|
||||
cost.className = 'signup-plan__price';
|
||||
cost.textContent = price;
|
||||
header.append(name, cost);
|
||||
top.append(symbol, header);
|
||||
const description = document.createElement('p');
|
||||
description.className = 'signup-plan__lead';
|
||||
description.textContent = lead;
|
||||
const list = document.createElement('ul');
|
||||
for (const perk of perks) {
|
||||
const li = document.createElement('li');
|
||||
li.textContent = perk;
|
||||
list.append(li);
|
||||
}
|
||||
const action = document.createElement('button');
|
||||
action.type = 'button';
|
||||
action.className = type === 'paid' ? 'primary-btn' : 'secondary-btn';
|
||||
action.textContent = button;
|
||||
action.addEventListener('click', () => {
|
||||
const draft = state.registrationDraft;
|
||||
draft.flowType = type;
|
||||
draft.uiStep = 1;
|
||||
navigate('register-view');
|
||||
});
|
||||
box.append(top, description, list, action);
|
||||
return box;
|
||||
}
|
||||
const topBar = createTopBar({ title: t('screens.registration_choice_view.text_004'), back: { label: '←', onClick: () => navigate('registration-intro-view') } });
|
||||
const plans = document.createElement('div');
|
||||
plans.className = 'stack';
|
||||
const paidCard = card({
|
||||
type: 'paid', icon: '◇', heading: t('screens.registration_choice_view.text_005'),
|
||||
price: t('screens.registration_choice_view.text_007'),
|
||||
lead: t('screens.registration_choice_view.text_008'),
|
||||
perks: [t('screens.registration_choice_view.text_009'), t('screens.registration_choice_view.text_010'), t('screens.registration_choice_view.text_011')],
|
||||
button: t('screens.registration_choice_view.text_012'),
|
||||
});
|
||||
plans.append(paidCard);
|
||||
screen.append(topBar, title, intro, plans);
|
||||
|
||||
// Бесплатная регистрация доступна только если текущий сервер сам объявил
|
||||
// привязанный к нему type-2 namespace. При ошибке запроса безопасно оставляем
|
||||
// только платный сценарий.
|
||||
void getRegistrationNamespaces().then(({ namespaces }) => {
|
||||
if (!screen.isConnected || !Array.isArray(namespaces) || !namespaces.some(n => Number(n.type) === 2)) return;
|
||||
plans.append(card({
|
||||
type: 'free', icon: '♧', heading: t('screens.registration_choice_view.text_006'),
|
||||
price: t('screens.registration_choice_view.text_013'),
|
||||
lead: t('screens.registration_choice_view.text_014'),
|
||||
perks: [t('screens.registration_choice_view.text_015'), t('screens.registration_choice_view.text_016'), t('screens.registration_choice_view.text_017')],
|
||||
button: t('screens.registration_choice_view.text_018'),
|
||||
}));
|
||||
});
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { state } from '../state.js';
|
||||
import { base64ToBytes, bytesToBase58 } from '../services/crypto-utils.js';
|
||||
import { extractSeed32FromPkcs8B64 } from '../services/client-key-utils.js';
|
||||
|
||||
export const pageMeta = { id: 'registration-draft-keys-view', get title() { return t('screens.registration_draft_keys_view.text_001'); }, showAppChrome: false };
|
||||
|
||||
function makeSecretField({ label, value }) {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'stack';
|
||||
|
||||
const labelEl = document.createElement('span');
|
||||
labelEl.className = 'field-label';
|
||||
labelEl.textContent = label;
|
||||
|
||||
const row = document.createElement('div');
|
||||
row.className = 'inline-input-row';
|
||||
const eyeIcon = `
|
||||
<svg class="key-toggle-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d="M2.4 12s3.6-6.5 9.6-6.5S21.6 12 21.6 12s-3.6 6.5-9.6 6.5S2.4 12 2.4 12Z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
|
||||
<circle cx="12" cy="12" r="2.9" fill="none" stroke="currentColor" stroke-width="1.8"/>
|
||||
</svg>
|
||||
`;
|
||||
const eyeOffIcon = `
|
||||
<svg class="key-toggle-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d="M3 4l18 16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>
|
||||
<path d="M2.4 12s3.6-6.5 9.6-6.5c2.4 0 4.5.8 6.1 1.9" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
|
||||
<path d="M21.6 12s-3.6 6.5-9.6 6.5c-2.4 0-4.5-.8-6.1-1.9" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
`;
|
||||
|
||||
const input = document.createElement('input');
|
||||
input.className = 'input key-input';
|
||||
input.type = 'password';
|
||||
input.readOnly = true;
|
||||
input.value = value;
|
||||
|
||||
const toggleBtn = document.createElement('button');
|
||||
toggleBtn.className = 'icon-btn key-toggle-btn';
|
||||
toggleBtn.type = 'button';
|
||||
toggleBtn.innerHTML = eyeOffIcon;
|
||||
toggleBtn.setAttribute('aria-label', t('screens.registration_draft_keys_view.text_017'));
|
||||
toggleBtn.title = t('screens.registration_draft_keys_view.text_002');
|
||||
toggleBtn.addEventListener('click', () => {
|
||||
if (input.type === 'password') {
|
||||
input.type = 'text';
|
||||
toggleBtn.innerHTML = eyeIcon;
|
||||
toggleBtn.setAttribute('aria-label', t('screens.registration_draft_keys_view.text_018'));
|
||||
toggleBtn.title = t('screens.registration_draft_keys_view.text_003');
|
||||
} else {
|
||||
input.type = 'password';
|
||||
toggleBtn.innerHTML = eyeOffIcon;
|
||||
toggleBtn.setAttribute('aria-label', t('screens.registration_draft_keys_view.text_019'));
|
||||
toggleBtn.title = t('screens.registration_draft_keys_view.text_004');
|
||||
}
|
||||
});
|
||||
|
||||
row.append(input, toggleBtn);
|
||||
wrap.append(labelEl, row);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
function makePublicField({ label, value }) {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'stack';
|
||||
|
||||
const labelEl = document.createElement('span');
|
||||
labelEl.className = 'field-label';
|
||||
labelEl.textContent = label;
|
||||
|
||||
const input = document.createElement('input');
|
||||
input.className = 'input key-input';
|
||||
input.type = 'text';
|
||||
input.readOnly = true;
|
||||
input.value = value;
|
||||
|
||||
wrap.append(labelEl, input);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
export function render({ navigate }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
const keyBundle = state.registrationDraft.preGeneratedKeyBundle;
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack';
|
||||
|
||||
if (!keyBundle) {
|
||||
const msg = document.createElement('p');
|
||||
msg.className = 'status-line is-unavailable';
|
||||
msg.textContent = t('screens.registration_draft_keys_view.text_005');
|
||||
card.append(msg);
|
||||
} else {
|
||||
const warning = document.createElement('p');
|
||||
warning.className = 'meta-muted';
|
||||
warning.textContent =
|
||||
t('screens.registration_draft_keys_view.text_006');
|
||||
|
||||
card.append(warning);
|
||||
|
||||
// Master secret
|
||||
let secretB58 = '';
|
||||
try {
|
||||
secretB58 = bytesToBase58(base64ToBytes(keyBundle.masterSecretB64));
|
||||
} catch {
|
||||
secretB58 = t('screens.registration_draft_keys_view.text_016');
|
||||
}
|
||||
card.append(makeSecretField({ label: t('screens.registration_draft_keys_view.text_007'), value: secretB58 }));
|
||||
|
||||
// Root key
|
||||
const rootSep = document.createElement('p');
|
||||
rootSep.className = 'field-label';
|
||||
rootSep.textContent = 'Root key (recovery)';
|
||||
card.append(rootSep);
|
||||
card.append(makePublicField({
|
||||
label: t('screens.registration_draft_keys_view.text_008'),
|
||||
value: bytesToBase58(base64ToBytes(keyBundle.rootPair.publicKeyB64)),
|
||||
}));
|
||||
card.append(makeSecretField({
|
||||
label: t('screens.registration_draft_keys_view.text_009'),
|
||||
value: bytesToBase58(extractSeed32FromPkcs8B64(keyBundle.rootPair.privatePkcs8B64)),
|
||||
}));
|
||||
|
||||
// Blockchain key
|
||||
const bchSep = document.createElement('p');
|
||||
bchSep.className = 'field-label';
|
||||
bchSep.textContent = 'Blockchain key (= Solana wallet)';
|
||||
card.append(bchSep);
|
||||
card.append(makePublicField({
|
||||
label: t('screens.registration_draft_keys_view.text_010'),
|
||||
value: bytesToBase58(base64ToBytes(keyBundle.blockchainPair.publicKeyB64)),
|
||||
}));
|
||||
card.append(makeSecretField({
|
||||
label: t('screens.registration_draft_keys_view.text_011'),
|
||||
value: bytesToBase58(extractSeed32FromPkcs8B64(keyBundle.blockchainPair.privatePkcs8B64)),
|
||||
}));
|
||||
|
||||
// Client key
|
||||
const devSep = document.createElement('p');
|
||||
devSep.className = 'field-label';
|
||||
devSep.textContent = 'Client key';
|
||||
card.append(devSep);
|
||||
card.append(makePublicField({
|
||||
label: t('screens.registration_draft_keys_view.text_012'),
|
||||
value: bytesToBase58(base64ToBytes(keyBundle.clientPair.publicKeyB64)),
|
||||
}));
|
||||
card.append(makeSecretField({
|
||||
label: t('screens.registration_draft_keys_view.text_013'),
|
||||
value: bytesToBase58(extractSeed32FromPkcs8B64(keyBundle.clientPair.privatePkcs8B64)),
|
||||
}));
|
||||
}
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'auth-footer-actions';
|
||||
|
||||
const backButton = document.createElement('button');
|
||||
backButton.className = 'ghost-btn';
|
||||
backButton.type = 'button';
|
||||
backButton.textContent = t('screens.registration_draft_keys_view.text_014');
|
||||
backButton.addEventListener('click', () => navigate('registration-payment-view'));
|
||||
|
||||
actions.append(backButton);
|
||||
|
||||
screen.append(
|
||||
createTopBar({
|
||||
title: t('screens.registration_draft_keys_view.text_015'),
|
||||
back: { label: '←', onClick: () => navigate('registration-payment-view') },
|
||||
}),
|
||||
card,
|
||||
actions,
|
||||
);
|
||||
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createRegistrationStepper } from '../components/registration-stepper.js';
|
||||
import { state } from '../state.js';
|
||||
import { checkRegistrationEmail, startFreeRegistration, confirmFreeRegistration } from '../services/registration-v2-api.js';
|
||||
import { completeRegistrationLogin } from './registration-payment-view.js';
|
||||
|
||||
export const pageMeta = { id: 'registration-email-view', get title() { return t('screens.registration_email_view.text_001'); }, showAppChrome: false };
|
||||
export function render({ navigate }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack registration-screen signup-wizard';
|
||||
const form = document.createElement('div');
|
||||
form.className = 'card stack registration-form signup-wizard__body';
|
||||
const draft = state.registrationDraft;
|
||||
|
||||
const title = document.createElement('h1');
|
||||
title.className = 'signup-title';
|
||||
title.textContent = t('screens.registration_email_view.text_002');
|
||||
const lead = document.createElement('p');
|
||||
lead.className = 'signup-lead';
|
||||
lead.textContent = t('screens.registration_email_view.text_003');
|
||||
const inputLabel = document.createElement('label');
|
||||
inputLabel.className = 'stack';
|
||||
const inputName = document.createElement('span');
|
||||
inputName.className = 'field-label';
|
||||
inputName.textContent = t('screens.registration_email_view.text_004');
|
||||
const input = document.createElement('input');
|
||||
input.className = 'input';
|
||||
input.type = 'email';
|
||||
input.autocomplete = 'email';
|
||||
input.placeholder = 'example@gmail.com';
|
||||
input.value = draft.email || '';
|
||||
inputLabel.append(inputName, input);
|
||||
const info = document.createElement('div');
|
||||
info.className = 'signup-guidance';
|
||||
info.innerHTML = `
|
||||
<strong>${th('screens.registration_email_view.text_034')}</strong>
|
||||
<p>${th('screens.registration_email_view.text_035')}</p>
|
||||
<p>${th('screens.registration_email_view.text_036')}</p>
|
||||
`;
|
||||
const status = document.createElement('p');
|
||||
status.className = 'status-line';
|
||||
status.setAttribute('aria-live','polite');
|
||||
const next = document.createElement('button');
|
||||
next.type = 'button';
|
||||
next.className = 'primary-btn signup-next';
|
||||
next.textContent = t('screens.registration_email_view.text_005');
|
||||
|
||||
const codeLabel = document.createElement('label');
|
||||
codeLabel.className = 'stack';
|
||||
const codeHeading = document.createElement('span');
|
||||
codeHeading.className = 'field-label';
|
||||
codeHeading.textContent = t('screens.registration_email_view.text_006');
|
||||
const code = document.createElement('input');
|
||||
code.className = 'input signup-code-input';
|
||||
code.inputMode = 'numeric';
|
||||
code.pattern = '[0-9]*';
|
||||
code.placeholder = '000000';
|
||||
code.maxLength = 6;
|
||||
code.autocomplete = 'one-time-code';
|
||||
codeLabel.append(codeHeading, code);
|
||||
const codeInfo = document.createElement('p');
|
||||
codeInfo.className = 'meta-muted';
|
||||
codeInfo.textContent = t('screens.registration_email_view.text_007');
|
||||
const confirm = document.createElement('button');
|
||||
confirm.type = 'button';
|
||||
confirm.className = 'primary-btn signup-next';
|
||||
confirm.textContent = t('screens.registration_email_view.text_008');
|
||||
const resend = document.createElement('button');
|
||||
resend.type = 'button';
|
||||
resend.className = 'secondary-btn';
|
||||
resend.textContent = t('screens.registration_email_view.text_010');
|
||||
const edit = document.createElement('button');
|
||||
edit.type = 'button';
|
||||
edit.className = 'ghost-btn';
|
||||
edit.textContent = t('screens.registration_email_view.text_011');
|
||||
|
||||
form.append(createRegistrationStepper(3), title, lead, inputLabel, info, status, next, codeLabel, codeInfo, confirm, resend, edit);
|
||||
let disposed = false;
|
||||
let emailRequestId = 0;
|
||||
let confirming = false;
|
||||
function showCode() {
|
||||
inputLabel.hidden = true;
|
||||
info.hidden = true;
|
||||
next.hidden = true;
|
||||
codeLabel.hidden = false;
|
||||
codeInfo.hidden = false;
|
||||
confirm.hidden = false;
|
||||
resend.hidden = false;
|
||||
edit.hidden = false;
|
||||
lead.textContent = t('screens.registration_email_view.text_032', { value1: draft.email });
|
||||
}
|
||||
function showEmail() {
|
||||
inputLabel.hidden = false;
|
||||
info.hidden = false;
|
||||
next.hidden = false;
|
||||
codeLabel.hidden = true;
|
||||
codeInfo.hidden = true;
|
||||
confirm.hidden = true;
|
||||
resend.hidden = true;
|
||||
edit.hidden = true;
|
||||
lead.textContent = t('screens.registration_email_view.text_012');
|
||||
}
|
||||
next.addEventListener('click', async () => {
|
||||
if (draft.flowType !== 'free' || !draft.preGeneratedKeyBundle) {
|
||||
status.textContent = t('screens.registration_email_view.text_013');
|
||||
return;
|
||||
}
|
||||
const address = input.value.trim();
|
||||
if (!input.checkValidity() || !address) { status.textContent = t('screens.registration_email_view.text_014'); return; }
|
||||
const requestId = ++emailRequestId;
|
||||
next.disabled = true;
|
||||
status.textContent = t('screens.registration_email_view.text_015');
|
||||
try {
|
||||
const available = await checkRegistrationEmail(address);
|
||||
if (!available.emailAvailable) {
|
||||
if (available.emailStatus === 'DOMAIN_NOT_ALLOWED') {
|
||||
throw new Error(t('screens.registration_email_view.text_026'));
|
||||
}
|
||||
if (available.emailStatus === 'ALREADY_REGISTERED') {
|
||||
throw new Error(t('screens.registration_email_view.text_027'));
|
||||
}
|
||||
throw new Error(t('screens.registration_email_view.text_028'));
|
||||
}
|
||||
status.textContent = t('screens.registration_email_view.text_016');
|
||||
const started = await startFreeRegistration({ fullLogin: draft.login, keyBundle: draft.preGeneratedKeyBundle, email: address });
|
||||
if (!screen.isConnected || disposed || requestId !== emailRequestId) return;
|
||||
draft.email = address;
|
||||
draft.challengeId = started.challengeId;
|
||||
draft.challengeExpiresAtMs = started.expiresAtMs;
|
||||
showCode();
|
||||
status.textContent = t('screens.registration_email_view.text_017');
|
||||
code.focus();
|
||||
} catch (error) { if (screen.isConnected && !disposed) status.textContent = error.message || t('screens.registration_email_view.text_029'); }
|
||||
finally { next.disabled = false; }
|
||||
});
|
||||
resend.addEventListener('click', async () => {
|
||||
resend.disabled = true;
|
||||
status.textContent = t('screens.registration_email_view.text_018');
|
||||
try {
|
||||
const started = await startFreeRegistration({ fullLogin: draft.login, keyBundle: draft.preGeneratedKeyBundle, email: draft.email });
|
||||
if (!screen.isConnected || disposed) return;
|
||||
draft.challengeId = started.challengeId;
|
||||
draft.challengeExpiresAtMs = started.expiresAtMs;
|
||||
code.value = '';
|
||||
status.textContent = t('screens.registration_email_view.text_019');
|
||||
} catch (error) { if (screen.isConnected && !disposed) status.textContent = error.message || t('screens.registration_email_view.text_030'); }
|
||||
finally { resend.disabled = false; }
|
||||
});
|
||||
edit.addEventListener('click', () => {
|
||||
emailRequestId += 1;
|
||||
draft.challengeId = '';
|
||||
draft.challengeExpiresAtMs = 0;
|
||||
draft.email = '';
|
||||
input.value = '';
|
||||
code.value = '';
|
||||
status.textContent = '';
|
||||
input.setCustomValidity('');
|
||||
next.disabled = false;
|
||||
showEmail();
|
||||
input.focus();
|
||||
});
|
||||
async function submit() {
|
||||
if (confirming) return;
|
||||
if (!draft.challengeId) { status.textContent = t('screens.registration_email_view.text_020'); return; }
|
||||
if (!/^[0-9]{6}$/.test(code.value.trim())) { status.textContent = t('screens.registration_email_view.text_021'); return; }
|
||||
confirming = true;
|
||||
confirm.disabled = true;
|
||||
status.textContent = t('screens.registration_email_view.text_022');
|
||||
try {
|
||||
// Подтверждение email идемпотентно на уровне сценария: после первого
|
||||
// успешного ответа повторяем только финальный вход, а не AuthChallenge
|
||||
// регистрации. Иначе предыдущий CreateAuthSession мог оставить сокет
|
||||
// авторизованным, и сервер вернёт ALREADY_AUTHED.
|
||||
if (!draft.dataItemId) {
|
||||
const result = await confirmFreeRegistration(draft.challengeId, code.value.trim());
|
||||
draft.dataItemId = result.dataItemId;
|
||||
}
|
||||
if (!screen.isConnected || disposed) return;
|
||||
status.textContent = t('screens.registration_email_view.text_023');
|
||||
await completeRegistrationLogin({ navigate, keyBundle: draft.preGeneratedKeyBundle });
|
||||
} catch (error) {
|
||||
if (screen.isConnected && !disposed) {
|
||||
status.textContent = t('screens.registration_email_view.text_033', { value1: error.message || t('screens.registration_email_view.text_031') });
|
||||
// Одна и та же кнопка продолжает завершение: отдельная кнопка Retry
|
||||
// создавала два визуально одинаковых действия.
|
||||
confirm.textContent = t('screens.registration_email_view.text_009');
|
||||
}
|
||||
} finally { confirming = false; confirm.disabled = false; }
|
||||
}
|
||||
confirm.addEventListener('click', submit);
|
||||
code.addEventListener('input', () => {
|
||||
code.value = code.value.replace(/\D/g, '').slice(0,6);
|
||||
confirm.textContent = t('screens.registration_email_view.text_008');
|
||||
if (code.value.length === 6) void submit();
|
||||
});
|
||||
input.addEventListener('input', () => {
|
||||
status.textContent = '';
|
||||
input.setCustomValidity('');
|
||||
});
|
||||
if (draft.challengeId && draft.challengeExpiresAtMs > Date.now()) {
|
||||
showCode();
|
||||
status.textContent = t('screens.registration_email_view.text_024');
|
||||
} else {
|
||||
showEmail();
|
||||
}
|
||||
screen.append(createTopBar({ title: t('screens.registration_email_view.text_025'), back: { label: '←', onClick: () => { draft.uiStep = 2; navigate('register-view'); } } }), form);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { state } from '../state.js';
|
||||
|
||||
export const pageMeta = { id: 'registration-faq-view', get title() { return t('screens.registration_faq_view.text_001'); }, showAppChrome: false };
|
||||
|
||||
export const REGISTRATION_FAQ_TOPICS = [
|
||||
{
|
||||
id: 'keys-storage',
|
||||
get shortTitle() { return t('screens.registration_faq_view.text_018'); },
|
||||
get title() { return t('screens.registration_faq_view.text_002'); },
|
||||
get paragraphs() { return [
|
||||
t('screens.registration_faq_view.text_029'),
|
||||
t('screens.registration_faq_view.text_030'),
|
||||
t('screens.registration_faq_view.text_031'),
|
||||
]; },
|
||||
},
|
||||
{
|
||||
id: 'reliability',
|
||||
get shortTitle() { return t('screens.registration_faq_view.text_019'); },
|
||||
get title() { return t('screens.registration_faq_view.text_003'); },
|
||||
get paragraphs() { return [
|
||||
t('screens.registration_faq_view.text_032'),
|
||||
t('screens.registration_faq_view.text_033'),
|
||||
t('screens.registration_faq_view.text_034'),
|
||||
]; },
|
||||
},
|
||||
{
|
||||
id: 'key-derivation',
|
||||
get shortTitle() { return t('screens.registration_faq_view.text_020'); },
|
||||
get title() { return t('screens.registration_faq_view.text_004'); },
|
||||
get paragraphs() { return [
|
||||
t('screens.registration_faq_view.text_035'),
|
||||
t('screens.registration_faq_view.text_036'),
|
||||
t('screens.registration_faq_view.text_037'),
|
||||
]; },
|
||||
},
|
||||
{
|
||||
id: 'three-keys',
|
||||
get shortTitle() { return t('screens.registration_faq_view.text_021'); },
|
||||
get title() { return t('screens.registration_faq_view.text_005'); },
|
||||
get paragraphs() { return [
|
||||
t('screens.registration_faq_view.text_038'),
|
||||
t('screens.registration_faq_view.text_039'),
|
||||
t('screens.registration_faq_view.text_040'),
|
||||
t('screens.registration_faq_view.text_041'),
|
||||
]; },
|
||||
},
|
||||
{
|
||||
id: 'generation-time',
|
||||
get shortTitle() { return t('screens.registration_faq_view.text_022'); },
|
||||
get title() { return t('screens.registration_faq_view.text_006'); },
|
||||
get paragraphs() { return [
|
||||
t('screens.registration_faq_view.text_042'),
|
||||
t('screens.registration_faq_view.text_043'),
|
||||
t('screens.registration_faq_view.text_044'),
|
||||
]; },
|
||||
},
|
||||
{
|
||||
id: 'strong-password',
|
||||
get shortTitle() { return t('screens.registration_faq_view.text_023'); },
|
||||
get title() { return t('screens.registration_faq_view.text_007'); },
|
||||
get paragraphs() { return [
|
||||
t('screens.registration_faq_view.text_045'),
|
||||
t('screens.registration_faq_view.text_046'),
|
||||
t('screens.registration_faq_view.text_047'),
|
||||
]; },
|
||||
},
|
||||
{
|
||||
id: 'why-own-password',
|
||||
get shortTitle() { return t('screens.registration_faq_view.text_024'); },
|
||||
get title() { return t('screens.registration_faq_view.text_008'); },
|
||||
get paragraphs() { return [
|
||||
t('screens.registration_faq_view.text_048'),
|
||||
t('screens.registration_faq_view.text_049'),
|
||||
t('screens.registration_faq_view.text_050'),
|
||||
]; },
|
||||
},
|
||||
{
|
||||
id: 'first-server',
|
||||
get shortTitle() { return t('screens.registration_faq_view.text_025'); },
|
||||
get title() { return t('screens.registration_faq_view.text_009'); },
|
||||
get paragraphs() { return [
|
||||
t('screens.registration_faq_view.text_051'),
|
||||
t('screens.registration_faq_view.text_052'),
|
||||
t('screens.registration_faq_view.text_053'),
|
||||
t('screens.registration_faq_view.text_054'),
|
||||
]; },
|
||||
},
|
||||
{
|
||||
id: 'connect-device',
|
||||
get shortTitle() { return t('screens.registration_faq_view.text_026'); },
|
||||
get title() { return t('screens.registration_faq_view.text_010'); },
|
||||
get paragraphs() { return [
|
||||
t('screens.registration_faq_view.text_055'),
|
||||
t('screens.registration_faq_view.text_056'),
|
||||
t('screens.registration_faq_view.text_057'),
|
||||
]; },
|
||||
},
|
||||
{
|
||||
id: 'hardware-device',
|
||||
shortTitle: 'ESP32',
|
||||
get title() { return t('screens.registration_faq_view.text_011'); },
|
||||
get paragraphs() { return [
|
||||
t('screens.registration_faq_view.text_058'),
|
||||
t('screens.registration_faq_view.text_059'),
|
||||
t('screens.registration_faq_view.text_060'),
|
||||
t('screens.registration_faq_view.text_061'),
|
||||
]; },
|
||||
links: [
|
||||
{
|
||||
get label() { return t('screens.registration_faq_view.text_012'); },
|
||||
href: 'https://docs.waveshare.com/ESP32-S3-Touch-AMOLED-2.16',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'wallet-device',
|
||||
get shortTitle() { return t('screens.registration_faq_view.text_027'); },
|
||||
get title() { return t('screens.registration_faq_view.text_013'); },
|
||||
get paragraphs() { return [
|
||||
t('screens.registration_faq_view.text_062'),
|
||||
t('screens.registration_faq_view.text_063'),
|
||||
t('screens.registration_faq_view.text_064'),
|
||||
]; },
|
||||
},
|
||||
];
|
||||
|
||||
function getTopicById(topicId) {
|
||||
return REGISTRATION_FAQ_TOPICS.find((topic) => topic.id === topicId) || REGISTRATION_FAQ_TOPICS[0];
|
||||
}
|
||||
|
||||
export function openRegistrationFaq(navigate, topicId) {
|
||||
state.registrationHelp.selectedTopic = getTopicById(topicId).id;
|
||||
navigate('registration-faq-view');
|
||||
}
|
||||
|
||||
export function render({ navigate }) {
|
||||
const selectedTopic = getTopicById(state.registrationHelp?.selectedTopic);
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
const heroCard = document.createElement('div');
|
||||
heroCard.className = 'card stack registration-faq-hero';
|
||||
heroCard.innerHTML = `
|
||||
<p class="auth-copy">${th('screens.registration_faq_view.text_028')}</p>
|
||||
`;
|
||||
|
||||
const topicCard = document.createElement('div');
|
||||
topicCard.className = 'card stack registration-faq-topic';
|
||||
|
||||
const question = document.createElement('h2');
|
||||
question.className = 'registration-faq-title';
|
||||
question.textContent = selectedTopic.title;
|
||||
topicCard.append(question);
|
||||
|
||||
selectedTopic.paragraphs.forEach((paragraph) => {
|
||||
const p = document.createElement('p');
|
||||
p.className = 'auth-copy';
|
||||
p.textContent = paragraph;
|
||||
topicCard.append(p);
|
||||
});
|
||||
|
||||
if (Array.isArray(selectedTopic.links) && selectedTopic.links.length > 0) {
|
||||
selectedTopic.links.forEach((linkItem) => {
|
||||
const link = document.createElement('a');
|
||||
link.className = 'link-card';
|
||||
link.href = linkItem.href;
|
||||
link.target = '_blank';
|
||||
link.rel = 'noopener noreferrer';
|
||||
link.textContent = linkItem.label;
|
||||
topicCard.append(link);
|
||||
});
|
||||
}
|
||||
|
||||
const topicsCard = document.createElement('div');
|
||||
topicsCard.className = 'stack';
|
||||
|
||||
const topicsLabel = document.createElement('p');
|
||||
topicsLabel.className = 'nav-list__title';
|
||||
topicsLabel.textContent = t('screens.registration_faq_view.text_014');
|
||||
|
||||
const topicsGrid = document.createElement('div');
|
||||
topicsGrid.className = 'nav-list';
|
||||
|
||||
REGISTRATION_FAQ_TOPICS.filter((topic) => topic.id !== selectedTopic.id).forEach((topic) => {
|
||||
const button = document.createElement('button');
|
||||
button.className = 'nav-row';
|
||||
button.type = 'button';
|
||||
const label = document.createElement('span');
|
||||
label.className = 'nav-row__label';
|
||||
label.textContent = topic.title;
|
||||
button.append(label);
|
||||
button.addEventListener('click', () => {
|
||||
state.registrationHelp.selectedTopic = topic.id;
|
||||
navigate('registration-faq-view');
|
||||
});
|
||||
topicsGrid.append(button);
|
||||
});
|
||||
|
||||
topicsCard.append(topicsLabel, topicsGrid);
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'auth-footer-actions';
|
||||
|
||||
const backButton = document.createElement('button');
|
||||
backButton.className = 'ghost-btn';
|
||||
backButton.type = 'button';
|
||||
backButton.textContent = t('screens.registration_faq_view.text_015');
|
||||
backButton.addEventListener('click', () => navigate('register-view'));
|
||||
|
||||
const registerButton = document.createElement('button');
|
||||
registerButton.className = 'primary-btn';
|
||||
registerButton.type = 'button';
|
||||
registerButton.textContent = t('screens.registration_faq_view.text_016');
|
||||
registerButton.addEventListener('click', () => navigate('register-view'));
|
||||
|
||||
actions.append(backButton, registerButton);
|
||||
|
||||
screen.append(
|
||||
createTopBar({
|
||||
title: t('screens.registration_faq_view.text_017'),
|
||||
back: { label: '←', onClick: () => navigate('register-view') },
|
||||
}),
|
||||
heroCard,
|
||||
topicCard,
|
||||
topicsCard,
|
||||
actions,
|
||||
);
|
||||
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
|
||||
export const pageMeta = { id: 'registration-intro-view', get title() { return t('screens.registration_intro_view.text_001'); }, showAppChrome: false };
|
||||
|
||||
export function render({ navigate }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack registration-screen signup-intro';
|
||||
|
||||
const hero = document.createElement('div');
|
||||
hero.className = 'signup-intro__hero';
|
||||
const artwork = document.createElement('img');
|
||||
artwork.className = 'signup-intro__artwork';
|
||||
artwork.src = './img/registration-sunrise-space.png';
|
||||
artwork.alt = t('screens.registration_intro_view.text_002');
|
||||
const brand = document.createElement('div');
|
||||
brand.className = 'signup-intro__brand';
|
||||
const logo = document.createElement('img');
|
||||
logo.src = './img/shine-logo-transparent-final.png';
|
||||
logo.alt = t('screens.registration_intro_view.text_003');
|
||||
const title = document.createElement('div');
|
||||
title.className = 'signup-intro__wordmark';
|
||||
title.textContent = t('screens.registration_intro_view.text_004');
|
||||
brand.append(logo, title);
|
||||
hero.append(artwork, brand);
|
||||
|
||||
const heading = document.createElement('h1');
|
||||
heading.className = 'signup-title';
|
||||
heading.textContent = t('screens.registration_intro_view.text_005');
|
||||
const intro = document.createElement('p');
|
||||
intro.className = 'signup-lead';
|
||||
intro.textContent = t('screens.registration_intro_view.text_006');
|
||||
|
||||
const benefits = document.createElement('div');
|
||||
benefits.className = 'signup-benefits';
|
||||
const items = [
|
||||
['◇', t('screens.registration_intro_view.text_009'), t('screens.registration_intro_view.text_010')],
|
||||
['☆', t('screens.registration_intro_view.text_011'), t('screens.registration_intro_view.text_012')],
|
||||
['⦿', t('screens.registration_intro_view.text_013'), t('screens.registration_intro_view.text_014')],
|
||||
['∞', t('screens.registration_intro_view.text_015'), t('screens.registration_intro_view.text_016')],
|
||||
];
|
||||
for (const [icon, label, detail] of items) {
|
||||
const item = document.createElement('div');
|
||||
item.className = 'signup-benefit';
|
||||
const iconEl = document.createElement('span');
|
||||
iconEl.className = 'signup-benefit__icon';
|
||||
iconEl.textContent = icon;
|
||||
const copy = document.createElement('div');
|
||||
const strong = document.createElement('strong');
|
||||
strong.textContent = label;
|
||||
const p = document.createElement('p');
|
||||
p.textContent = detail;
|
||||
copy.append(strong, p);
|
||||
item.append(iconEl, copy);
|
||||
benefits.append(item);
|
||||
}
|
||||
const action = document.createElement('button');
|
||||
action.type = 'button';
|
||||
action.className = 'primary-btn signup-next';
|
||||
action.textContent = t('screens.registration_intro_view.text_007');
|
||||
action.addEventListener('click', () => navigate('registration-choice-view'));
|
||||
screen.append(createTopBar({ title: t('screens.registration_intro_view.text_008'), back: { label: '←', onClick: () => navigate('start-view') } }), hero, heading, intro, benefits, action);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,769 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { getSolanaCluster } from '../services/solana-rpc-gateway.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createRegistrationStepper } from '../components/registration-stepper.js';
|
||||
import {
|
||||
authService,
|
||||
authorizeSession,
|
||||
refreshSessions,
|
||||
resetRegistrationFlow,
|
||||
setAuthError,
|
||||
setAuthInfo,
|
||||
state,
|
||||
} from '../state.js';
|
||||
import { clearStoredMessages } from '../services/message-store.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import {
|
||||
createSolanaWalletFromPrivateBase58,
|
||||
formatSol,
|
||||
getBalanceSol,
|
||||
transferSol,
|
||||
} from '../services/solana-wallet-service.js';
|
||||
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
||||
import {
|
||||
checkLoginExistsOnSolana,
|
||||
formatSolanaErrorDetails,
|
||||
isSolanaRpcUnavailableError,
|
||||
isUserAlreadyExistsSolanaError,
|
||||
registerUserOnSolana,
|
||||
} from '../services/solana-register-service.js';
|
||||
import { defaultServerLogin } from '../deploy-config.js';
|
||||
import { getNamespace, normalizeFullLogin } from '../services/shine-namespace-service.js';
|
||||
import { calculateRegistrationFunding, USER_PDA_SPACE, solFromLamports } from '../services/registration-upgrade-helpers.js';
|
||||
|
||||
export const pageMeta = { id: 'registration-payment-view', get title() { return t('screens.registration_payment_view.text_001'); }, showAppChrome: false };
|
||||
const TEST_TOPUP_AMOUNT_SOL = 0.032;
|
||||
const DEVNET_ENDPOINT = 'https://api.devnet.solana.com';
|
||||
const TEST_TOPUP_SENDER_PRIVATE_32_BASE58 = '6xqAuKYvA8qrCdAkcw7Y8aMgvBnYk8JLxWLma5BzbAvu';
|
||||
const AUTO_LOGIN_INITIAL_DELAY_MS = 1000;
|
||||
const AUTO_LOGIN_RETRY_MS = 2000;
|
||||
const REGISTRATION_PROGRESS_DURATION_MS = 12000;
|
||||
const REGISTRATION_POLL_START_DELAY_MS = 4000;
|
||||
const REGISTRATION_POLL_INTERVAL_MS = 2000;
|
||||
const REGISTRATION_CONFIRM_TIMEOUT_MS = 25000;
|
||||
const REGISTRATION_SUCCESS_SETTLE_DELAY_MS = 2000;
|
||||
const EMPTY_PASSWORD_WORDS = Array.from({ length: 12 }, () => '');
|
||||
|
||||
function getExplorerClusterName(endpoint) {
|
||||
const source = String(endpoint || '').trim().toLowerCase();
|
||||
if (!source) return 'mainnet-beta';
|
||||
if (source.includes('devnet')) return 'devnet';
|
||||
if (source.includes('testnet')) return 'testnet';
|
||||
return 'mainnet-beta';
|
||||
}
|
||||
|
||||
function isTestRegistrationContour() {
|
||||
return getSolanaCluster() === 'devnet';
|
||||
}
|
||||
|
||||
function makeSolanaExplorerTxUrl(signature, endpoint) {
|
||||
const cleanSignature = String(signature || '').trim();
|
||||
if (!cleanSignature) return '';
|
||||
const cluster = getSolanaCluster() || getExplorerClusterName(endpoint);
|
||||
const url = new URL(`https://explorer.solana.com/tx/${encodeURIComponent(cleanSignature)}`);
|
||||
if (cluster !== 'mainnet-beta') {
|
||||
url.searchParams.set('cluster', cluster);
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function parseBalanceSol(value) {
|
||||
const parsed = Number.parseFloat(String(value || '').replace(',', '.'));
|
||||
return Number.isFinite(parsed) ? parsed : 0;
|
||||
}
|
||||
|
||||
function registrationAccessServerLogin() {
|
||||
const configured = String(state.entrySettings.shineServerLogin || defaultServerLogin || '').trim().toLowerCase();
|
||||
if (!configured) return '';
|
||||
return normalizeFullLogin(configured.includes('@') ? configured : `${configured}@shine`);
|
||||
}
|
||||
|
||||
function getCryptoRuntimeState() {
|
||||
const hasCrypto = Boolean(globalThis.crypto);
|
||||
const hasGetRandomValues = Boolean(globalThis.crypto && typeof globalThis.crypto.getRandomValues === 'function');
|
||||
const hasSubtle = Boolean(globalThis.crypto && (globalThis.crypto.subtle || globalThis.crypto.webkitSubtle));
|
||||
const secureContext = window.isSecureContext === true;
|
||||
return { hasCrypto, hasGetRandomValues, hasSubtle, secureContext };
|
||||
}
|
||||
|
||||
function clamp(value, min, max) {
|
||||
return Math.max(min, Math.min(max, value));
|
||||
}
|
||||
|
||||
export async function completeRegistrationLogin({ navigate, keyBundle }) {
|
||||
// Финальный вход регистрации нельзя повторять на сокете, который мог
|
||||
// стать авторизованным после частично успешной предыдущей попытки.
|
||||
authService.resetConnection(state.entrySettings.shineServer, { clearSessionContext: true });
|
||||
const result = await authService.createSessionForExistingUser(
|
||||
state.registrationDraft.login,
|
||||
state.registrationDraft.password,
|
||||
);
|
||||
|
||||
// CreateAuthSession уже авторизовал текущий WebSocket. Не запускаем поверх
|
||||
// него второй SessionChallenge/SessionLogin: это не восстановление, а новый
|
||||
// handshake на уже авторизованном соединении. Сначала фиксируем состояние
|
||||
// UI, чтобы локальный сбой IndexedDB не оставлял пользователя «гостем».
|
||||
const resumedLogin = result.login;
|
||||
const resumedSessionId = result.sessionId;
|
||||
const resumedStoragePwd = result.storagePwd;
|
||||
authorizeSession({
|
||||
login: resumedLogin,
|
||||
sessionId: resumedSessionId,
|
||||
storagePwd: resumedStoragePwd,
|
||||
});
|
||||
|
||||
// После регистрации оба рабочих ключа сохраняются автоматически.
|
||||
// Приватный Recovery/root key не записывается на устройство.
|
||||
try {
|
||||
await authService.persistSelectedKeys(result.login, result.storagePwd, keyBundle);
|
||||
} catch (error) {
|
||||
console.warn('Не удалось сохранить рабочие ключи после регистрации; текущая сессия продолжает работать', error);
|
||||
}
|
||||
try {
|
||||
await authService.persistSessionMaterial(result.login, result.sessionMaterial);
|
||||
} catch (error) {
|
||||
console.warn('Не удалось сохранить ключ сессии после регистрации; текущая сессия продолжает работать', error);
|
||||
}
|
||||
await clearStoredMessages(state.registrationDraft.login).catch(() => {});
|
||||
|
||||
// Создаём HEADER сразу после успешной регистрации (Solana и Arweave).
|
||||
// При сбое регистрация остаётся успешной: перед первым блоком AddBlock
|
||||
// повторно создаст отсутствующий HEADER существующим механизмом.
|
||||
try {
|
||||
await authService.ensureBlockchainHeader(resumedLogin, resumedStoragePwd);
|
||||
} catch (error) {
|
||||
console.warn('Не удалось создать HEADER после регистрации; повторим перед первым блоком', error);
|
||||
}
|
||||
|
||||
state.loginDraft.login = resumedLogin;
|
||||
state.loginDraft.password = '';
|
||||
state.loginDraft.passwordMode = 'single';
|
||||
state.loginDraft.passwordWords = EMPTY_PASSWORD_WORDS.slice();
|
||||
|
||||
const completedFlowType = state.registrationDraft.flowType;
|
||||
resetRegistrationFlow();
|
||||
state.registrationSuccess = { flowType: completedFlowType, login: resumedLogin };
|
||||
|
||||
try {
|
||||
await refreshSessions();
|
||||
} catch (error) {
|
||||
console.warn('Не удалось обновить список сессий после регистрации', error);
|
||||
}
|
||||
setAuthInfo(t('screens.registration_payment_view.text_060', { value1: resumedLogin }));
|
||||
|
||||
const nextHash = String(state.authReturnHash || '').trim();
|
||||
state.authReturnHash = '';
|
||||
if (nextHash.startsWith('/')) {
|
||||
navigate(nextHash.slice(1));
|
||||
} else {
|
||||
navigate('registration-success-view');
|
||||
}
|
||||
}
|
||||
|
||||
export function render({ navigate }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack registration-payment-card';
|
||||
let funding = null;
|
||||
let pricingValid = false;
|
||||
|
||||
const status = document.createElement('p');
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.style.display = 'none';
|
||||
|
||||
const walletValue = document.createElement('input');
|
||||
walletValue.className = 'input';
|
||||
walletValue.type = 'text';
|
||||
walletValue.value = state.registrationPayment.walletAddress || '';
|
||||
walletValue.readOnly = true;
|
||||
walletValue.style.width = '100%';
|
||||
|
||||
const walletRow = document.createElement('div');
|
||||
walletRow.className = 'registration-payment-wallet';
|
||||
|
||||
const copyButton = document.createElement('button');
|
||||
copyButton.className = 'secondary-btn registration-payment-action registration-payment-copy-btn';
|
||||
copyButton.type = 'button';
|
||||
copyButton.textContent = t('screens.registration_payment_view.text_002');
|
||||
copyButton.addEventListener('click', async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(walletValue.value);
|
||||
copyButton.textContent = t('screens.registration_payment_view.text_003');
|
||||
window.setTimeout(() => {
|
||||
copyButton.textContent = t('screens.registration_payment_view.text_004');
|
||||
}, 1500);
|
||||
} catch {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = t('screens.registration_payment_view.text_005');
|
||||
status.style.display = '';
|
||||
}
|
||||
});
|
||||
|
||||
const walletHeading = document.createElement('h4');
|
||||
walletHeading.className = 'registration-payment-wallet-heading';
|
||||
walletHeading.textContent = t('screens.registration_payment_view.text_006');
|
||||
const walletHint = document.createElement('p');
|
||||
walletHint.className = 'meta-muted registration-payment-wallet-hint';
|
||||
walletHint.textContent = t('screens.registration_payment_view.text_007');
|
||||
const walletLabel = document.createElement('label');
|
||||
walletLabel.className = 'field-label';
|
||||
walletLabel.textContent = t('screens.registration_payment_view.text_008');
|
||||
walletRow.append(walletHeading, walletHint, walletLabel, walletValue, copyButton);
|
||||
|
||||
const balanceRow = document.createElement('div');
|
||||
balanceRow.className = 'registration-payment-balance';
|
||||
|
||||
const balanceValue = document.createElement('strong');
|
||||
balanceValue.className = 'registration-payment-balance-value';
|
||||
balanceValue.setAttribute('aria-live', 'polite');
|
||||
balanceValue.textContent = `${formatSol(parseBalanceSol(state.registrationPayment.balanceSOL), 6)} SOL`;
|
||||
|
||||
const refreshButton = document.createElement('button');
|
||||
refreshButton.className = 'secondary-btn registration-payment-action registration-payment-refresh-btn';
|
||||
refreshButton.type = 'button';
|
||||
refreshButton.textContent = t('screens.registration_payment_view.text_009');
|
||||
refreshButton.title = t('screens.registration_payment_view.text_010');
|
||||
|
||||
// Коротко и по-человечески; технические подробности — во всплывающей подсказке.
|
||||
const showWalletError = (error, fallback) => {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = error?.code === 'NO_KEYS'
|
||||
? t('screens.registration_payment_view.text_049')
|
||||
: fallback;
|
||||
status.title = error?.message || '';
|
||||
status.style.display = '';
|
||||
};
|
||||
|
||||
const refreshBalance = async ({ showError = true, addressOverride = '' } = {}) => {
|
||||
const address = String(addressOverride || walletValue.value || '').trim();
|
||||
if (!address) return null;
|
||||
refreshButton.disabled = true;
|
||||
refreshButton.textContent = t('screens.registration_payment_view.text_011');
|
||||
try {
|
||||
const balance = await getBalanceSol({
|
||||
endpoint: state.entrySettings.solanaServer,
|
||||
address,
|
||||
});
|
||||
state.registrationPayment.balanceSOL = String(balance.sol);
|
||||
balanceValue.textContent = `${formatSol(balance.sol, 6)} SOL`;
|
||||
return BigInt(balance.lamports);
|
||||
} catch (error) {
|
||||
if (showError) showWalletError(error, t('screens.registration_payment_view.text_046'));
|
||||
return null;
|
||||
} finally {
|
||||
refreshButton.disabled = false;
|
||||
refreshButton.textContent = t('screens.registration_payment_view.text_012');
|
||||
}
|
||||
};
|
||||
|
||||
const deriveUserWalletAddress = async () => {
|
||||
const keyBundle = state.registrationDraft.preGeneratedKeyBundle;
|
||||
if (!keyBundle) throw new Error(t('screens.registration_payment_view.text_051'));
|
||||
const { publicKeyB64 } = keyBundle.blockchainPair;
|
||||
const raw = atob(publicKeyB64);
|
||||
const bytes = new Uint8Array(raw.length);
|
||||
for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);
|
||||
const { PublicKey } = await loadSolanaWeb3();
|
||||
const address = new PublicKey(bytes).toBase58();
|
||||
state.registrationPayment.walletAddress = address;
|
||||
walletValue.value = address;
|
||||
return address;
|
||||
};
|
||||
|
||||
refreshButton.addEventListener('click', () => {
|
||||
void refreshBalance();
|
||||
});
|
||||
|
||||
const balanceInfo = document.createElement('div');
|
||||
balanceInfo.className = 'registration-payment-balance-info';
|
||||
const balanceLabel = document.createElement('span');
|
||||
balanceLabel.className = 'registration-payment-balance-label';
|
||||
balanceLabel.textContent = t('screens.registration_payment_view.text_013');
|
||||
balanceInfo.append(balanceLabel, balanceValue);
|
||||
balanceRow.append(balanceInfo, refreshButton);
|
||||
|
||||
const isTestContour = isTestRegistrationContour();
|
||||
const topupButton = document.createElement('button');
|
||||
topupButton.className = 'secondary-btn registration-payment-action registration-payment-topup-btn';
|
||||
topupButton.type = 'button';
|
||||
topupButton.textContent = t('screens.registration_payment_view.text_061', { value1: TEST_TOPUP_AMOUNT_SOL });
|
||||
topupButton.addEventListener('click', async () => {
|
||||
status.style.display = 'none';
|
||||
topupButton.disabled = true;
|
||||
const defaultText = t('screens.registration_payment_view.text_062', { value1: TEST_TOPUP_AMOUNT_SOL });
|
||||
topupButton.textContent = t('screens.registration_payment_view.text_014');
|
||||
try {
|
||||
const address = await deriveUserWalletAddress();
|
||||
const sender = await createSolanaWalletFromPrivateBase58(TEST_TOPUP_SENDER_PRIVATE_32_BASE58);
|
||||
await transferSol({
|
||||
endpoint: DEVNET_ENDPOINT,
|
||||
fromKeypair: sender.keypair,
|
||||
toAddress: address,
|
||||
amountSol: TEST_TOPUP_AMOUNT_SOL,
|
||||
});
|
||||
const balance = await getBalanceSol({
|
||||
endpoint: DEVNET_ENDPOINT,
|
||||
address,
|
||||
});
|
||||
state.registrationPayment.balanceSOL = String(balance.sol);
|
||||
balanceValue.textContent = `${formatSol(balance.sol, 6)} SOL`;
|
||||
status.className = 'status-line is-available';
|
||||
status.textContent = t('screens.registration_payment_view.text_063', { value1: TEST_TOPUP_AMOUNT_SOL, value2: formatSol(balance.sol, 6) });
|
||||
status.style.display = '';
|
||||
} catch (error) {
|
||||
showWalletError(error, t('screens.registration_payment_view.text_047'));
|
||||
} finally {
|
||||
topupButton.disabled = false;
|
||||
topupButton.textContent = defaultText;
|
||||
}
|
||||
});
|
||||
|
||||
const submitButton = document.createElement('button');
|
||||
submitButton.className = 'primary-btn';
|
||||
submitButton.type = 'button';
|
||||
submitButton.textContent = t('screens.registration_payment_view.text_015');
|
||||
submitButton.addEventListener('click', async () => {
|
||||
status.style.display = 'none';
|
||||
|
||||
const cryptoState = getCryptoRuntimeState();
|
||||
if (!cryptoState.hasCrypto || !cryptoState.hasGetRandomValues || !cryptoState.hasSubtle) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = t('screens.registration_payment_view.text_016');
|
||||
status.style.display = '';
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
submitButton.disabled = true;
|
||||
submitButton.textContent = t('screens.registration_payment_view.text_017');
|
||||
|
||||
if (!pricingValid) throw new Error(t('screens.registration_payment_view.text_052'));
|
||||
const walletAddress = await deriveUserWalletAddress();
|
||||
const currentBalance = await refreshBalance({ showError: true, addressOverride: walletAddress });
|
||||
if (currentBalance == null) return;
|
||||
// Получаем цену из namespace-PDA непосредственно перед отправкой, а не из черновика.
|
||||
funding = await loadFunding();
|
||||
if (currentBalance < funding.requiredLamports) {
|
||||
const shortage = funding.requiredLamports - currentBalance;
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = t('screens.registration_payment_view.text_064', { value1: solFromLamports(shortage), value2: solFromLamports(funding.namespaceFee) });
|
||||
if (isTestContour) status.textContent += t('screens.registration_payment_view.text_065');
|
||||
status.style.display = '';
|
||||
return;
|
||||
}
|
||||
|
||||
const keyBundle = state.registrationDraft.preGeneratedKeyBundle;
|
||||
if (!keyBundle) throw new Error(t('screens.registration_payment_view.text_053'));
|
||||
|
||||
// Перед on-chain регистрацией перепроверяем логин ещё раз:
|
||||
// между экраном выбора логина и оплатой его мог занять кто-то другой.
|
||||
const loginStateBeforeRegister = await checkLoginExistsOnSolana({
|
||||
login: state.registrationDraft.login,
|
||||
solanaEndpoint: state.entrySettings.solanaServer,
|
||||
});
|
||||
if (loginStateBeforeRegister?.exists) {
|
||||
throw new Error(t('screens.registration_payment_view.text_054'));
|
||||
}
|
||||
|
||||
// Регистрация на Solana (смарт контракт)
|
||||
submitButton.textContent = t('screens.registration_payment_view.text_018');
|
||||
let registrationTxId = '';
|
||||
try {
|
||||
const registrationResult = await registerUserOnSolana({
|
||||
login: state.registrationDraft.login,
|
||||
keyBundle,
|
||||
solanaEndpoint: state.entrySettings.solanaServer,
|
||||
accessServers: [registrationAccessServerLogin()],
|
||||
});
|
||||
registrationTxId = String(registrationResult?.signature || '').trim();
|
||||
} catch (solanaError) {
|
||||
const solanaMsg = formatSolanaErrorDetails(solanaError);
|
||||
if (solanaMsg.includes('already') || isUserAlreadyExistsSolanaError(solanaError)) {
|
||||
throw new Error(t('screens.registration_payment_view.text_055'));
|
||||
}
|
||||
if (isSolanaRpcUnavailableError(solanaError)) {
|
||||
throw new Error(t('screens.registration_payment_view.text_056'));
|
||||
}
|
||||
throw new Error(t('screens.registration_payment_view.text_066', { value1: solanaMsg }));
|
||||
}
|
||||
|
||||
renderSolanaRegistrationStage({ navigate, status, keyBundle, registrationTxId });
|
||||
} catch (error) {
|
||||
const message = isSolanaRpcUnavailableError(error)
|
||||
? t('screens.registration_payment_view.text_050')
|
||||
: toUserMessage(error, t('screens.registration_payment_view.text_048'));
|
||||
setAuthError(message);
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = message;
|
||||
status.style.display = '';
|
||||
} finally {
|
||||
submitButton.disabled = false;
|
||||
submitButton.textContent = t('screens.registration_payment_view.text_019');
|
||||
}
|
||||
});
|
||||
|
||||
card.innerHTML = `
|
||||
<h1 class="signup-title">${th('screens.registration_payment_view.text_069')}</h1>
|
||||
<p class="auth-copy">${th('screens.registration_payment_view.text_070')}</p>
|
||||
`;
|
||||
const priceLine = document.createElement('p');
|
||||
priceLine.className = 'registration-payment-fees';
|
||||
priceLine.textContent = t('screens.registration_payment_view.text_020');
|
||||
card.append(priceLine);
|
||||
submitButton.disabled = true;
|
||||
const loadFunding = async () => {
|
||||
const fullLogin = String(state.registrationDraft.login || '').trim();
|
||||
const name = fullLogin.split('@')[1];
|
||||
if (!name) throw new Error(t('screens.registration_payment_view.text_057'));
|
||||
const solanaEndpoint = state.entrySettings.solanaServer;
|
||||
const [namespace, solana] = await Promise.all([
|
||||
getNamespace({ namespace: name, solanaEndpoint }),
|
||||
loadSolanaWeb3(),
|
||||
]);
|
||||
const connection = new solana.Connection(solanaEndpoint, 'confirmed');
|
||||
const rentLamports = await connection.getMinimumBalanceForRentExemption(USER_PDA_SPACE, 'confirmed');
|
||||
const latestFunding = calculateRegistrationFunding({ namespaceFeeLamports: namespace.registrationFeeLamports, rentLamports });
|
||||
funding = latestFunding;
|
||||
priceLine.textContent = t('screens.registration_payment_view.text_067', { value1: solFromLamports(funding.namespaceFee), value2: solFromLamports(funding.requiredLamports) });
|
||||
return funding;
|
||||
};
|
||||
card.append(walletRow, balanceRow);
|
||||
if (isTestContour) {
|
||||
card.append(topupButton);
|
||||
const testHint = document.createElement('p');
|
||||
testHint.className = 'meta-muted registration-payment-test-hint';
|
||||
testHint.textContent = t('screens.registration_payment_view.text_021');
|
||||
card.append(testHint);
|
||||
}
|
||||
card.append(submitButton, status);
|
||||
card.prepend(createRegistrationStepper(3));
|
||||
|
||||
screen.append(
|
||||
createTopBar({
|
||||
title: t('screens.registration_payment_view.text_022'),
|
||||
back: { label: '←', onClick: () => {
|
||||
if (parseBalanceSol(state.registrationPayment.balanceSOL) > 0 && !window.confirm(t('screens.registration_payment_view.text_071'))) return;
|
||||
state.registrationDraft.uiStep = 2; navigate('register-view');
|
||||
} },
|
||||
}),
|
||||
card,
|
||||
);
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const walletAddress = await deriveUserWalletAddress();
|
||||
await refreshBalance({ addressOverride: walletAddress });
|
||||
await loadFunding();
|
||||
pricingValid = true;
|
||||
submitButton.disabled = false;
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = t('screens.registration_payment_view.text_068', { value1: error?.message || 'unknown' });
|
||||
status.style.display = '';
|
||||
}
|
||||
})();
|
||||
|
||||
return screen;
|
||||
}
|
||||
|
||||
function renderSolanaRegistrationStage({ navigate, status, keyBundle, registrationTxId = '' }) {
|
||||
const screen = document.querySelector('section.stack');
|
||||
if (!screen) return;
|
||||
const headerBackButton = screen.querySelector('.topbar .topbar__back');
|
||||
const card = screen.querySelector('.card.stack');
|
||||
if (!card) return;
|
||||
card.classList.add('registration-finish-card');
|
||||
|
||||
let progressTimerId = null;
|
||||
let pollStartTimerId = null;
|
||||
let pollTimerId = null;
|
||||
let successTimerId = null;
|
||||
let confirmationInFlight = false;
|
||||
let stageClosed = false;
|
||||
let successPending = false;
|
||||
let timeoutShown = false;
|
||||
const stageStartedAt = Date.now();
|
||||
const txExplorerUrl = makeSolanaExplorerTxUrl(registrationTxId, state.entrySettings.solanaServer);
|
||||
|
||||
const title = document.createElement('h2');
|
||||
title.className = 'registration-finish-title';
|
||||
title.textContent = t('screens.registration_payment_view.text_023');
|
||||
|
||||
const hint = document.createElement('p');
|
||||
hint.className = 'auth-copy registration-finish-text';
|
||||
hint.textContent = t('screens.registration_payment_view.text_024');
|
||||
|
||||
const txIdLine = document.createElement('p');
|
||||
txIdLine.className = 'meta-muted registration-finish-tx';
|
||||
if (registrationTxId && txExplorerUrl) {
|
||||
const txLabel = document.createElement('span');
|
||||
txLabel.textContent = t('screens.registration_payment_view.text_025');
|
||||
const txLink = document.createElement('a');
|
||||
txLink.className = 'registration-finish-tx-link';
|
||||
txLink.href = txExplorerUrl;
|
||||
txLink.target = '_blank';
|
||||
txLink.rel = 'noopener noreferrer';
|
||||
txLink.textContent = registrationTxId;
|
||||
txIdLine.append(txLabel, txLink);
|
||||
} else {
|
||||
txIdLine.textContent = t('screens.registration_payment_view.text_026');
|
||||
}
|
||||
|
||||
const progressWrap = document.createElement('div');
|
||||
progressWrap.className = 'registration-progress';
|
||||
|
||||
const progressBar = document.createElement('div');
|
||||
progressBar.className = 'registration-progress-bar';
|
||||
progressWrap.append(progressBar);
|
||||
|
||||
const progress = document.createElement('p');
|
||||
progress.className = 'meta-muted registration-finish-progress';
|
||||
progress.textContent = t('screens.registration_payment_view.text_027');
|
||||
|
||||
const pollStatus = document.createElement('p');
|
||||
pollStatus.className = 'meta-muted registration-finish-progress';
|
||||
pollStatus.textContent = t('screens.registration_payment_view.text_028');
|
||||
|
||||
const stopTimers = () => {
|
||||
if (progressTimerId) {
|
||||
window.clearInterval(progressTimerId);
|
||||
progressTimerId = null;
|
||||
}
|
||||
if (pollStartTimerId) {
|
||||
window.clearTimeout(pollStartTimerId);
|
||||
pollStartTimerId = null;
|
||||
}
|
||||
if (pollTimerId) {
|
||||
window.clearInterval(pollTimerId);
|
||||
pollTimerId = null;
|
||||
}
|
||||
if (successTimerId) {
|
||||
window.clearTimeout(successTimerId);
|
||||
successTimerId = null;
|
||||
}
|
||||
};
|
||||
|
||||
const updateVisualProgress = () => {
|
||||
const elapsed = Date.now() - stageStartedAt;
|
||||
let widthPercent = 0;
|
||||
if (elapsed <= REGISTRATION_PROGRESS_DURATION_MS) {
|
||||
const phaseRatio = clamp(elapsed / REGISTRATION_PROGRESS_DURATION_MS, 0, 1);
|
||||
widthPercent = 100 * (1 - ((1 - phaseRatio) ** 1.85));
|
||||
} else {
|
||||
const extraRatio = 1 - Math.exp(-(elapsed - REGISTRATION_PROGRESS_DURATION_MS) / 9000);
|
||||
widthPercent = 88 + (10 * clamp(extraRatio, 0, 1));
|
||||
}
|
||||
progressBar.style.width = `${clamp(widthPercent, 0, 98)}%`;
|
||||
|
||||
if (elapsed < REGISTRATION_POLL_START_DELAY_MS) {
|
||||
progress.textContent = t('screens.registration_payment_view.text_029');
|
||||
return;
|
||||
}
|
||||
if (elapsed < REGISTRATION_CONFIRM_TIMEOUT_MS) {
|
||||
progress.textContent = t('screens.registration_payment_view.text_030');
|
||||
return;
|
||||
}
|
||||
progress.textContent = t('screens.registration_payment_view.text_031');
|
||||
};
|
||||
|
||||
const finalizeSuccess = () => {
|
||||
if (stageClosed || successPending) return;
|
||||
successPending = true;
|
||||
stopTimers();
|
||||
progress.textContent = t('screens.registration_payment_view.text_032');
|
||||
pollStatus.textContent = t('screens.registration_payment_view.text_033');
|
||||
status.style.display = 'none';
|
||||
progressBar.style.transition = `width ${REGISTRATION_SUCCESS_SETTLE_DELAY_MS}ms ease-out`;
|
||||
progressBar.style.width = '100%';
|
||||
successTimerId = window.setTimeout(() => {
|
||||
if (stageClosed) return;
|
||||
stageClosed = true;
|
||||
renderSolanaDoneStage({ navigate, status, keyBundle, registrationTxId });
|
||||
}, REGISTRATION_SUCCESS_SETTLE_DELAY_MS);
|
||||
};
|
||||
|
||||
const showTimeoutState = () => {
|
||||
if (timeoutShown || stageClosed) return;
|
||||
timeoutShown = true;
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = t('screens.registration_payment_view.text_034');
|
||||
status.style.display = '';
|
||||
pollStatus.textContent = t('screens.registration_payment_view.text_035');
|
||||
};
|
||||
|
||||
const tryCheckRegistration = async () => {
|
||||
if (stageClosed || confirmationInFlight) return;
|
||||
confirmationInFlight = true;
|
||||
progress.textContent = t('screens.registration_payment_view.text_036');
|
||||
status.style.display = timeoutShown ? '' : 'none';
|
||||
try {
|
||||
const result = await checkLoginExistsOnSolana({
|
||||
login: state.registrationDraft.login,
|
||||
solanaEndpoint: state.entrySettings.solanaServer,
|
||||
});
|
||||
if (result?.exists) {
|
||||
finalizeSuccess();
|
||||
return;
|
||||
}
|
||||
pollStatus.textContent = t('screens.registration_payment_view.text_037');
|
||||
if ((Date.now() - stageStartedAt) >= REGISTRATION_CONFIRM_TIMEOUT_MS) {
|
||||
showTimeoutState();
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Registration confirmation check failed', toUserMessage(error, 'registration-confirmation'));
|
||||
pollStatus.textContent = t('screens.registration_payment_view.text_038');
|
||||
if ((Date.now() - stageStartedAt) >= REGISTRATION_CONFIRM_TIMEOUT_MS) {
|
||||
showTimeoutState();
|
||||
}
|
||||
} finally {
|
||||
confirmationInFlight = false;
|
||||
}
|
||||
};
|
||||
|
||||
if (headerBackButton) {
|
||||
const replacement = headerBackButton.cloneNode(true);
|
||||
replacement.addEventListener('click', () => {
|
||||
stageClosed = true;
|
||||
stopTimers();
|
||||
resetRegistrationFlow();
|
||||
navigate('start-view');
|
||||
});
|
||||
headerBackButton.replaceWith(replacement);
|
||||
}
|
||||
|
||||
card.innerHTML = '';
|
||||
status.style.display = 'none';
|
||||
card.append(title, hint, txIdLine, progressWrap, progress, pollStatus, status);
|
||||
|
||||
updateVisualProgress();
|
||||
progressTimerId = window.setInterval(() => {
|
||||
if (stageClosed) return;
|
||||
updateVisualProgress();
|
||||
if ((Date.now() - stageStartedAt) >= REGISTRATION_CONFIRM_TIMEOUT_MS) {
|
||||
showTimeoutState();
|
||||
}
|
||||
}, 160);
|
||||
|
||||
pollStartTimerId = window.setTimeout(() => {
|
||||
if (stageClosed) return;
|
||||
void tryCheckRegistration();
|
||||
pollTimerId = window.setInterval(() => {
|
||||
void tryCheckRegistration();
|
||||
}, REGISTRATION_POLL_INTERVAL_MS);
|
||||
}, REGISTRATION_POLL_START_DELAY_MS);
|
||||
}
|
||||
|
||||
function renderSolanaDoneStage({ navigate, status, keyBundle, registrationTxId = '' }) {
|
||||
const screen = document.querySelector('section.stack');
|
||||
if (!screen) return;
|
||||
const headerBackButton = screen.querySelector('.topbar .topbar__back');
|
||||
const card = screen.querySelector('.card.stack');
|
||||
if (!card) return;
|
||||
card.classList.add('registration-finish-card');
|
||||
|
||||
let initialDelayId = null;
|
||||
let retryTimerId = null;
|
||||
let loginInFlight = false;
|
||||
let loginCompleted = false;
|
||||
const txExplorerUrl = makeSolanaExplorerTxUrl(registrationTxId, state.entrySettings.solanaServer);
|
||||
|
||||
const title = document.createElement('h2');
|
||||
title.className = 'registration-finish-title';
|
||||
title.textContent = t('screens.registration_payment_view.text_039');
|
||||
|
||||
const hint = document.createElement('p');
|
||||
hint.className = 'auth-copy registration-finish-text';
|
||||
hint.textContent = t('screens.registration_payment_view.text_040');
|
||||
|
||||
const txIdLine = document.createElement('p');
|
||||
txIdLine.className = 'meta-muted registration-finish-tx';
|
||||
if (registrationTxId && txExplorerUrl) {
|
||||
const txLabel = document.createElement('span');
|
||||
txLabel.textContent = t('screens.registration_payment_view.text_041');
|
||||
const txLink = document.createElement('a');
|
||||
txLink.className = 'registration-finish-tx-link';
|
||||
txLink.href = txExplorerUrl;
|
||||
txLink.target = '_blank';
|
||||
txLink.rel = 'noopener noreferrer';
|
||||
txLink.textContent = registrationTxId;
|
||||
txIdLine.append(txLabel, txLink);
|
||||
} else {
|
||||
txIdLine.textContent = t('screens.registration_payment_view.text_042');
|
||||
}
|
||||
|
||||
const progress = document.createElement('p');
|
||||
progress.className = 'meta-muted registration-finish-progress';
|
||||
progress.textContent = t('screens.registration_payment_view.text_043');
|
||||
|
||||
const stopAutoLogin = () => {
|
||||
if (initialDelayId) {
|
||||
window.clearTimeout(initialDelayId);
|
||||
initialDelayId = null;
|
||||
}
|
||||
if (retryTimerId) {
|
||||
window.clearInterval(retryTimerId);
|
||||
retryTimerId = null;
|
||||
}
|
||||
};
|
||||
|
||||
const tryAutoLogin = async () => {
|
||||
if (loginCompleted || loginInFlight) return;
|
||||
loginInFlight = true;
|
||||
progress.textContent = t('screens.registration_payment_view.text_044');
|
||||
status.style.display = 'none';
|
||||
try {
|
||||
await completeRegistrationLogin({ navigate, keyBundle });
|
||||
loginCompleted = true;
|
||||
stopAutoLogin();
|
||||
} catch (error) {
|
||||
if (!loginCompleted) {
|
||||
progress.textContent = t('screens.registration_payment_view.text_045');
|
||||
console.warn('Auto login after registration is not ready yet', toUserMessage(error, 'auto-login-wait'));
|
||||
}
|
||||
} finally {
|
||||
loginInFlight = false;
|
||||
}
|
||||
};
|
||||
|
||||
if (headerBackButton) {
|
||||
const replacement = headerBackButton.cloneNode(true);
|
||||
replacement.addEventListener('click', () => {
|
||||
loginCompleted = true;
|
||||
stopAutoLogin();
|
||||
resetRegistrationFlow();
|
||||
navigate('start-view');
|
||||
});
|
||||
headerBackButton.replaceWith(replacement);
|
||||
}
|
||||
|
||||
card.innerHTML = '';
|
||||
card.append(title, hint, txIdLine, progress, status);
|
||||
|
||||
initialDelayId = window.setTimeout(() => {
|
||||
if (loginCompleted) return;
|
||||
void tryAutoLogin();
|
||||
retryTimerId = window.setInterval(() => {
|
||||
void tryAutoLogin();
|
||||
}, AUTO_LOGIN_RETRY_MS);
|
||||
}, AUTO_LOGIN_INITIAL_DELAY_MS);
|
||||
}
|
||||
|
||||
/** Тот же тестовый источник +0.032 devnet SOL, что используется обычной регистрацией.
|
||||
* Экспорт добавлен для FREE_CERT → Solana upgrade; поведение обычной регистрации не изменяется.
|
||||
* Никогда не используйте этот встроенный devnet-кошелёк для реальных средств.
|
||||
*/
|
||||
export async function fundDevnetRegistrationWallet(address) {
|
||||
if (!isTestRegistrationContour()) throw new Error(t('screens.registration_payment_view.text_058'));
|
||||
const cleanAddress = String(address || '').trim();
|
||||
if (!cleanAddress) throw new Error(t('screens.registration_payment_view.text_059'));
|
||||
const sender = await createSolanaWalletFromPrivateBase58(TEST_TOPUP_SENDER_PRIVATE_32_BASE58);
|
||||
await transferSol({
|
||||
endpoint: DEVNET_ENDPOINT,
|
||||
fromKeypair: sender.keypair,
|
||||
toAddress: cleanAddress,
|
||||
amountSol: TEST_TOPUP_AMOUNT_SOL,
|
||||
});
|
||||
return getBalanceSol({ endpoint: DEVNET_ENDPOINT, address: cleanAddress });
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { state } from '../state.js';
|
||||
|
||||
export const pageMeta = { id: 'registration-success-view', get title() { return t('screens.registration_success_view.text_001'); }, showAppChrome: false };
|
||||
|
||||
export function render({ navigate }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack signup-success';
|
||||
const paid = state.registrationSuccess?.flowType === 'paid';
|
||||
const login = state.registrationSuccess?.login || state.session.login || '';
|
||||
const symbol = document.createElement('div');
|
||||
symbol.className = 'signup-success__check';
|
||||
symbol.textContent = '✓';
|
||||
const title = document.createElement('h1');
|
||||
title.textContent = t('screens.registration_success_view.text_002');
|
||||
const lead = document.createElement('p');
|
||||
lead.className = 'signup-lead';
|
||||
lead.textContent = t('screens.registration_success_view.text_011', { value1: login });
|
||||
const card = document.createElement('div');
|
||||
card.className = 'signup-success__card';
|
||||
const lines = paid ? [
|
||||
t('screens.registration_success_view.text_004'),
|
||||
t('screens.registration_success_view.text_005'),
|
||||
t('screens.registration_success_view.text_006'),
|
||||
] : [
|
||||
t('screens.registration_success_view.text_007'),
|
||||
t('screens.registration_success_view.text_008'),
|
||||
t('screens.registration_success_view.text_009'),
|
||||
];
|
||||
for (const item of lines) {
|
||||
const p = document.createElement('p');
|
||||
p.textContent = `✓ ${item}`;
|
||||
card.append(p);
|
||||
}
|
||||
const warning = document.createElement('div');
|
||||
warning.className = 'signup-guidance signup-success__warning';
|
||||
warning.innerHTML = t('screens.registration_success_view.text_010');
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'primary-btn signup-next';
|
||||
button.textContent = t('screens.registration_success_view.text_003');
|
||||
button.addEventListener('click', () => {
|
||||
state.registrationSuccess = null;
|
||||
navigate('profile-view');
|
||||
});
|
||||
screen.append(symbol, title, lead, card, warning, button);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { getRegistrationStatus } from '../services/registration-v2-api.js';
|
||||
import { getNamespace } from '../services/shine-namespace-service.js';
|
||||
import { readShineUserPda, upgradeFreeUserOnSolana } from '../services/shine-user-pda-service.js';
|
||||
import { checkLoginExistsOnSolana, formatSolanaErrorDetails } from '../services/solana-register-service.js';
|
||||
import { base64ToBytes, bytesToBase58 } from '../services/crypto-utils.js';
|
||||
import { getSolanaCluster } from '../services/solana-rpc-gateway.js';
|
||||
import { fundDevnetRegistrationWallet } from './registration-payment-view.js';
|
||||
import {
|
||||
getBalanceSol, formatSol,
|
||||
} from '../services/solana-wallet-service.js';
|
||||
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
||||
import {
|
||||
USER_PDA_SPACE, UPGRADE_TEST_TOPUP_SOL, calculateUpgradeFunding,
|
||||
isUpgradeComplete, solFromLamports,
|
||||
} from '../services/registration-upgrade-helpers.js';
|
||||
|
||||
export const pageMeta = { id: 'registration-upgrade-view', get title() { return t('screens.registration_upgrade_view.text_001'); } };
|
||||
const SYNC_INTERVAL_MS = 3000;
|
||||
const SYNC_NOTICE_AFTER_MS = 90000;
|
||||
|
||||
function element(tag, className, content = '') {
|
||||
const node = document.createElement(tag);
|
||||
if (className) node.className = className;
|
||||
node.textContent = content;
|
||||
return node;
|
||||
}
|
||||
function makeButton(label, className = 'primary-btn') {
|
||||
const button = element('button', className, label);
|
||||
button.type = 'button';
|
||||
return button;
|
||||
}
|
||||
function makeExplorerTxLink(signature) {
|
||||
const tx = String(signature || '').trim();
|
||||
if (!tx) return null;
|
||||
const anchor = element('a', '', tx);
|
||||
const url = new URL(`https://explorer.solana.com/tx/${encodeURIComponent(tx)}`);
|
||||
const cluster = getSolanaCluster();
|
||||
if (cluster && cluster !== 'mainnet-beta') url.searchParams.set('cluster', cluster);
|
||||
anchor.href = url.toString();
|
||||
anchor.target = '_blank';
|
||||
anchor.rel = 'noopener noreferrer';
|
||||
anchor.style.overflowWrap = 'anywhere';
|
||||
return anchor;
|
||||
}
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
const login = String(state.session?.login || '');
|
||||
const solanaEndpoint = String(state.entrySettings?.solanaServer || '');
|
||||
const isDevnet = getSolanaCluster() === 'devnet';
|
||||
const screen = element('section', 'stack');
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.registration_upgrade_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigate('settings-view') },
|
||||
}));
|
||||
|
||||
const intro = element('div', 'card stack');
|
||||
intro.append(
|
||||
element('h3', '', t('screens.registration_upgrade_view.text_011')),
|
||||
element('p', 'meta-muted', t('screens.registration_upgrade_view.text_057', { value1: login })),
|
||||
element('p', 'meta-muted', t('screens.registration_upgrade_view.text_012')),
|
||||
element('p', 'meta-muted', t('screens.registration_upgrade_view.text_013')),
|
||||
element('p', 'meta-muted', t('screens.registration_upgrade_view.text_014')),
|
||||
element('p', 'meta-muted', t('screens.registration_upgrade_view.text_015')),
|
||||
);
|
||||
const introStatus = element('p', 'status-line', t('screens.registration_upgrade_view.text_016'));
|
||||
introStatus.setAttribute('aria-live', 'polite');
|
||||
const continueButton = makeButton(t('screens.registration_upgrade_view.text_017'));
|
||||
continueButton.disabled = true;
|
||||
intro.append(continueButton, introStatus);
|
||||
|
||||
const payment = element('div', 'card stack registration-payment-card');
|
||||
payment.append(element('h3', '', t('screens.registration_upgrade_view.text_018')));
|
||||
const walletHeading = element('h4', 'registration-payment-wallet-heading', t('screens.registration_upgrade_view.text_019'));
|
||||
const walletHint = element('p', 'meta-muted registration-payment-wallet-hint', t('screens.registration_upgrade_view.text_020'));
|
||||
const walletLabel = element('label', 'field-label', t('screens.registration_upgrade_view.text_021'));
|
||||
const wallet = document.createElement('input');
|
||||
wallet.className = 'input'; wallet.type = 'text'; wallet.readOnly = true;
|
||||
wallet.style.width = '100%'; wallet.setAttribute('aria-label', t('screens.registration_upgrade_view.text_069'));
|
||||
const copyButton = makeButton(t('screens.registration_upgrade_view.text_022'), 'secondary-btn registration-payment-action registration-payment-copy-btn');
|
||||
const walletSection = element('div', 'registration-payment-wallet');
|
||||
walletSection.append(walletHeading, walletHint, walletLabel, wallet, copyButton);
|
||||
|
||||
const balanceLine = element('strong', 'registration-payment-balance-value', '— SOL');
|
||||
balanceLine.setAttribute('aria-live', 'polite');
|
||||
const balanceLabel = element('span', 'registration-payment-balance-label', t('screens.registration_upgrade_view.text_023'));
|
||||
const balanceInfo = element('div', 'registration-payment-balance-info');
|
||||
balanceInfo.append(balanceLabel, balanceLine);
|
||||
const refreshButton = makeButton(t('screens.registration_upgrade_view.text_024'), 'secondary-btn registration-payment-action registration-payment-refresh-btn');
|
||||
refreshButton.title = t('screens.registration_upgrade_view.text_003');
|
||||
const balanceRow = element('div', 'registration-payment-balance');
|
||||
balanceRow.append(balanceInfo, refreshButton);
|
||||
const topupButton = makeButton(t('screens.registration_upgrade_view.text_058', { value1: UPGRADE_TEST_TOPUP_SOL }), 'secondary-btn registration-payment-action registration-payment-topup-btn');
|
||||
const testHint = element('p', 'meta-muted registration-payment-test-hint', t('screens.registration_upgrade_view.text_025'));
|
||||
const amount = element('div', 'registration-payment-fees', t('screens.registration_upgrade_view.text_026'));
|
||||
const passwordLabel = element('label', 'field-label', t('screens.registration_upgrade_view.text_027'));
|
||||
const password = document.createElement('input');
|
||||
password.className = 'input'; password.type = 'password'; password.autocomplete = 'current-password';
|
||||
password.placeholder = t('screens.registration_upgrade_view.text_004');
|
||||
const payButton = makeButton(t('screens.registration_upgrade_view.text_028'));
|
||||
const payStatus = element('p', 'status-line');
|
||||
payStatus.setAttribute('aria-live', 'polite');
|
||||
payment.append(walletSection, balanceRow);
|
||||
if (isDevnet) payment.append(topupButton, testHint);
|
||||
payment.append(amount, passwordLabel, password, payButton, payStatus);
|
||||
|
||||
const syncing = element('div', 'card stack');
|
||||
syncing.append(element('h3', '', t('screens.registration_upgrade_view.text_029')));
|
||||
const syncInfo = element('p', 'meta-muted', t('screens.registration_upgrade_view.text_030'));
|
||||
const txLine = element('p', 'meta-muted');
|
||||
const syncStatus = element('p', 'status-line');
|
||||
syncStatus.setAttribute('aria-live', 'polite');
|
||||
const checkButton = makeButton(t('screens.registration_upgrade_view.text_031'), 'ghost-btn');
|
||||
syncing.append(syncInfo, txLine, syncStatus, checkButton);
|
||||
|
||||
const done = element('div', 'card stack');
|
||||
done.append(
|
||||
element('h3', '', t('screens.registration_upgrade_view.text_032')),
|
||||
element('p', 'meta-muted', t('screens.registration_upgrade_view.text_059', { value1: login })),
|
||||
element('p', 'meta-muted', t('screens.registration_upgrade_view.text_033')),
|
||||
);
|
||||
const settingsButton = makeButton(t('screens.registration_upgrade_view.text_034'));
|
||||
settingsButton.addEventListener('click', () => navigate('settings-view'));
|
||||
done.append(settingsButton);
|
||||
screen.append(intro, payment, syncing, done);
|
||||
|
||||
let disposed = false;
|
||||
let identity = null;
|
||||
let namespace = null;
|
||||
let funding = null;
|
||||
let walletAddress = '';
|
||||
let pollingTimer = null;
|
||||
let startedPollingAt = 0;
|
||||
let checking = false;
|
||||
let sending = false;
|
||||
|
||||
function show(stageName) {
|
||||
for (const [name, card] of [['intro', intro], ['payment', payment], ['syncing', syncing], ['done', done]]) {
|
||||
card.style.display = name === stageName ? '' : 'none';
|
||||
}
|
||||
}
|
||||
function message(node, value, error = false) {
|
||||
if (disposed) return;
|
||||
node.textContent = value;
|
||||
node.className = `status-line ${error ? 'is-unavailable' : 'is-available'}`;
|
||||
}
|
||||
function stopPolling() {
|
||||
if (pollingTimer !== null) window.clearInterval(pollingTimer);
|
||||
pollingTimer = null;
|
||||
}
|
||||
function succeed() {
|
||||
if (disposed) return;
|
||||
stopPolling();
|
||||
password.value = '';
|
||||
show('done');
|
||||
}
|
||||
async function balanceUpdate(showError = true) {
|
||||
if (!walletAddress) return null;
|
||||
refreshButton.disabled = true;
|
||||
refreshButton.textContent = t('screens.registration_upgrade_view.text_005');
|
||||
try {
|
||||
const balance = await getBalanceSol({ endpoint: solanaEndpoint, address: walletAddress });
|
||||
if (disposed) return null;
|
||||
balanceLine.textContent = `${formatSol(balance.sol, 6)} SOL`;
|
||||
return BigInt(balance.lamports);
|
||||
} catch (error) {
|
||||
if (showError) message(payStatus, t('screens.registration_upgrade_view.text_060', { value1: error.message }), true);
|
||||
return null;
|
||||
} finally {
|
||||
if (!disposed) {
|
||||
refreshButton.disabled = false;
|
||||
refreshButton.textContent = t('screens.registration_upgrade_view.text_006');
|
||||
}
|
||||
}
|
||||
}
|
||||
async function hasVerifiedPda(expectedIdentity = identity) {
|
||||
const presence = await checkLoginExistsOnSolana({ login, solanaEndpoint });
|
||||
if (!presence.exists) return false;
|
||||
const pda = await readShineUserPda({ login, solanaEndpoint });
|
||||
if (pda.login !== login) throw new Error(t('screens.registration_upgrade_view.text_047'));
|
||||
// Если сервер ещё считает аккаунт бесплатным, проверяем совпадение с исходным сертификатом.
|
||||
if (expectedIdentity?.registrationStatus === 'FREE_CERT') {
|
||||
if (bytesToBase58(pda.rootKey) !== expectedIdentity.rootPublicKey ||
|
||||
bytesToBase58(pda.clientKey) !== expectedIdentity.clientPublicKey ||
|
||||
bytesToBase58(pda.forks[0].blockchainKey) !== expectedIdentity.blockchainPublicKey) {
|
||||
throw new Error(t('screens.registration_upgrade_view.text_048'));
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
async function checkSync() {
|
||||
if (disposed || checking) return;
|
||||
checking = true;
|
||||
checkButton.disabled = true;
|
||||
try {
|
||||
const onChainExists = await hasVerifiedPda();
|
||||
if (disposed) return;
|
||||
if (!onChainExists) {
|
||||
message(syncStatus, t('screens.registration_upgrade_view.text_035'));
|
||||
return;
|
||||
}
|
||||
const current = await getRegistrationStatus(login);
|
||||
if (disposed) return;
|
||||
if (isUpgradeComplete(current.registrationStatus)) {
|
||||
succeed();
|
||||
return;
|
||||
}
|
||||
if (current.registrationStatus !== 'FREE_CERT') {
|
||||
message(syncStatus, t('screens.registration_upgrade_view.text_061', { value1: current.registrationStatus }), true);
|
||||
return;
|
||||
}
|
||||
message(syncStatus, t('screens.registration_upgrade_view.text_036'));
|
||||
} catch (error) {
|
||||
message(syncStatus, t('screens.registration_upgrade_view.text_062', { value1: error.message }), true);
|
||||
} finally {
|
||||
checking = false;
|
||||
if (!disposed) checkButton.disabled = false;
|
||||
if (!disposed && Date.now() - startedPollingAt > SYNC_NOTICE_AFTER_MS) {
|
||||
syncInfo.textContent = t('screens.registration_upgrade_view.text_007');
|
||||
}
|
||||
}
|
||||
}
|
||||
function watchSync() {
|
||||
show('syncing');
|
||||
startedPollingAt = Date.now();
|
||||
stopPolling();
|
||||
void checkSync();
|
||||
pollingTimer = window.setInterval(() => void checkSync(), SYNC_INTERVAL_MS);
|
||||
}
|
||||
function markTransaction(signature) {
|
||||
txLine.replaceChildren();
|
||||
const anchor = makeExplorerTxLink(signature);
|
||||
if (anchor) {
|
||||
txLine.append('Tx ID: ', anchor);
|
||||
} else {
|
||||
txLine.textContent = t('screens.registration_upgrade_view.text_008');
|
||||
}
|
||||
}
|
||||
async function initialize() {
|
||||
if (!login.includes('@')) throw new Error(t('screens.registration_upgrade_view.text_049'));
|
||||
const current = await getRegistrationStatus(login);
|
||||
if (disposed) return;
|
||||
// Уже платный аккаунт не должен повторно попадать в мастер покупки.
|
||||
if (isUpgradeComplete(current.registrationStatus)) { navigate('settings-view'); return; }
|
||||
if (current.registrationStatus !== 'FREE_CERT') throw new Error(t('screens.registration_upgrade_view.text_050'));
|
||||
// Проверяем наличие PDA до любых новых платежей. Это также позволяет возобновить проверку после перезагрузки.
|
||||
const onChainExists = await hasVerifiedPda(current);
|
||||
if (disposed) return;
|
||||
if (onChainExists) {
|
||||
markTransaction('');
|
||||
watchSync();
|
||||
return;
|
||||
}
|
||||
const loadedNamespace = await getNamespace({ namespace: login.split('@')[1], solanaEndpoint });
|
||||
if (loadedNamespace.type !== 2) throw new Error(t('screens.registration_upgrade_view.text_051'));
|
||||
if (!current.innerSignature64B64 || !current.blockchainPublicKey) throw new Error(t('screens.registration_upgrade_view.text_052'));
|
||||
const web3 = await loadSolanaWeb3();
|
||||
const connection = new web3.Connection(solanaEndpoint, 'confirmed');
|
||||
const rentLamports = await connection.getMinimumBalanceForRentExemption(USER_PDA_SPACE, 'confirmed');
|
||||
if (disposed) return;
|
||||
identity = current;
|
||||
namespace = loadedNamespace;
|
||||
funding = calculateUpgradeFunding({ namespaceFeeLamports: namespace.registrationFeeLamports, rentLamports });
|
||||
walletAddress = identity.blockchainPublicKey;
|
||||
// Проверяем адрес как настоящий публичный ключ Solana, не используем произвольный текст ответа сервера.
|
||||
const pubkey = new web3.PublicKey(walletAddress);
|
||||
walletAddress = pubkey.toBase58();
|
||||
wallet.value = walletAddress;
|
||||
amount.replaceChildren(element('h4', 'registration-payment-fees-title', t('screens.registration_upgrade_view.text_037')));
|
||||
for (const [label, lamports, emphasized] of [
|
||||
[t('screens.registration_upgrade_view.text_044'), funding.namespaceFee, true],
|
||||
[t('screens.registration_upgrade_view.text_045'), funding.networkReserve, false],
|
||||
[t('screens.registration_upgrade_view.text_046'), funding.requiredLamports, false],
|
||||
]) {
|
||||
const row = element('div', `registration-payment-fee-row${emphasized ? ' registration-payment-fee-row--emphasis' : ''}`);
|
||||
row.append(element('span', '', label), element('strong', '', `${solFromLamports(lamports)} SOL`));
|
||||
amount.append(row);
|
||||
}
|
||||
amount.append(element('p', 'meta-muted', t('screens.registration_upgrade_view.text_038')));
|
||||
continueButton.disabled = false;
|
||||
message(introStatus, t('screens.registration_upgrade_view.text_039'));
|
||||
}
|
||||
|
||||
continueButton.addEventListener('click', () => {
|
||||
show('payment');
|
||||
void balanceUpdate(false);
|
||||
});
|
||||
copyButton.addEventListener('click', async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(walletAddress);
|
||||
copyButton.textContent = t('screens.registration_upgrade_view.text_009');
|
||||
window.setTimeout(() => { if (!disposed) copyButton.textContent = t('screens.registration_upgrade_view.text_010'); }, 1600);
|
||||
message(payStatus, t('screens.registration_upgrade_view.text_040'));
|
||||
} catch {
|
||||
message(payStatus, t('screens.registration_upgrade_view.text_041'), true);
|
||||
}
|
||||
});
|
||||
refreshButton.addEventListener('click', () => void balanceUpdate());
|
||||
topupButton.addEventListener('click', async () => {
|
||||
if (!isDevnet || disposed || !walletAddress) return;
|
||||
topupButton.disabled = true;
|
||||
try {
|
||||
message(payStatus, t('screens.registration_upgrade_view.text_063', { value1: UPGRADE_TEST_TOPUP_SOL }));
|
||||
const result = await fundDevnetRegistrationWallet(walletAddress);
|
||||
if (disposed) return;
|
||||
balanceLine.textContent = `${formatSol(result.sol, 6)} SOL`;
|
||||
message(payStatus, t('screens.registration_upgrade_view.text_064', { value1: UPGRADE_TEST_TOPUP_SOL }));
|
||||
} catch (error) {
|
||||
message(payStatus, t('screens.registration_upgrade_view.text_065', { value1: error.message }), true);
|
||||
} finally {
|
||||
if (!disposed) topupButton.disabled = false;
|
||||
}
|
||||
});
|
||||
payButton.addEventListener('click', async () => {
|
||||
if (disposed || sending) return;
|
||||
sending = true;
|
||||
payButton.disabled = true;
|
||||
try {
|
||||
if (!identity || !namespace || !funding) throw new Error(t('screens.registration_upgrade_view.text_053'));
|
||||
if (!password.value) throw new Error(t('screens.registration_upgrade_view.text_054'));
|
||||
// Повторно сверяем Solana: уже зарегистрированную PDA не оплачиваем второй раз.
|
||||
const pdaExists = await hasVerifiedPda();
|
||||
if (pdaExists) { password.value = ''; markTransaction(''); watchSync(); return; }
|
||||
const balanceLamports = await balanceUpdate();
|
||||
if (balanceLamports === null) return;
|
||||
if (balanceLamports < funding.requiredLamports) {
|
||||
const shortage = funding.requiredLamports - balanceLamports;
|
||||
throw new Error(t('screens.registration_upgrade_view.text_066', { value1: solFromLamports(shortage) }));
|
||||
}
|
||||
message(payStatus, t('screens.registration_upgrade_view.text_042'));
|
||||
const keys = await authService.derivePasswordKeyBundle(login, password.value);
|
||||
if (disposed) return;
|
||||
for (const [pair, expected] of [
|
||||
[keys.rootPair, identity.rootPublicKey],
|
||||
[keys.blockchainPair, identity.blockchainPublicKey],
|
||||
[keys.clientPair, identity.clientPublicKey],
|
||||
]) {
|
||||
if (bytesToBase58(base64ToBytes(pair.publicKeyB64)) !== expected) {
|
||||
throw new Error(t('screens.registration_upgrade_view.text_055'));
|
||||
}
|
||||
}
|
||||
const signature = base64ToBytes(identity.innerSignature64B64);
|
||||
if (signature.length !== 64) throw new Error(t('screens.registration_upgrade_view.text_056'));
|
||||
message(payStatus, t('screens.registration_upgrade_view.text_043'));
|
||||
const result = await upgradeFreeUserOnSolana({
|
||||
login, keyBundle: keys, solanaEndpoint, innerSignature64: signature,
|
||||
accessServers: identity.defaultServerLogin ? [identity.defaultServerLogin] : [],
|
||||
});
|
||||
if (disposed) return;
|
||||
password.value = '';
|
||||
markTransaction(result.signature);
|
||||
watchSync();
|
||||
} catch (error) {
|
||||
// Если Solana успела подтвердить PDA, а HTTP-клиент потерял ответ, нельзя требовать новую оплату.
|
||||
try {
|
||||
const pdaExists = await hasVerifiedPda();
|
||||
if (pdaExists) { password.value = ''; markTransaction(''); watchSync(); return; }
|
||||
} catch { /* Отсутствие связи с RPC не доказывает отсутствие PDA. */ }
|
||||
message(payStatus, t('screens.registration_upgrade_view.text_067', { value1: formatSolanaErrorDetails(error) }), true);
|
||||
} finally {
|
||||
sending = false;
|
||||
if (!disposed) payButton.disabled = false;
|
||||
}
|
||||
});
|
||||
checkButton.addEventListener('click', () => void checkSync());
|
||||
show('intro');
|
||||
void initialize().catch((error) => message(introStatus, t('screens.registration_upgrade_view.text_068', { value1: error.message }), true));
|
||||
screen.cleanup = () => { disposed = true; stopPolling(); password.value = ''; };
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { formatDateTime } from '../i18n/format.js';
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import {
|
||||
isSessionInvalidError,
|
||||
refreshSessions,
|
||||
saveEntrySettings,
|
||||
setAuthError,
|
||||
setAuthInfo,
|
||||
state,
|
||||
terminateCurrentSession,
|
||||
} from '../state.js';
|
||||
|
||||
export const pageMeta = { id: 'remote-addblock-session-view', get title() { return t('screens.remote_addblock_session_view.text_001'); } };
|
||||
|
||||
const SESSION_TYPE_HOMESERVER = 100;
|
||||
|
||||
function formatSessionTime(ms) {
|
||||
return formatDateTime(new Date(ms), {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
});
|
||||
}
|
||||
|
||||
function sessionLabel(session) {
|
||||
const title = String(session?.clientInfoFromClient || '').trim();
|
||||
if (title) return title;
|
||||
return `Homeserver ${String(session?.sessionId || '').slice(0, 12)}`;
|
||||
}
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.remote_addblock_session_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigate('my-blockchain-view') },
|
||||
}));
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'card stack';
|
||||
actions.innerHTML = `
|
||||
<p class="meta-muted">${th('screens.remote_addblock_session_view.text_014')}</p>
|
||||
<button class="primary-btn" type="button" id="remote-addblock-refresh">${th('screens.remote_addblock_session_view.text_015')}</button>
|
||||
<button class="ghost-btn" type="button" id="remote-addblock-clear">${th('screens.remote_addblock_session_view.text_016')}</button>
|
||||
`;
|
||||
|
||||
const listCard = document.createElement('div');
|
||||
listCard.className = 'card stack';
|
||||
|
||||
const buildList = () => {
|
||||
listCard.innerHTML = '';
|
||||
const selectedId = String(state.entrySettings.remoteAddBlockSessionId || '').trim();
|
||||
const sessions = (state.sessions || [])
|
||||
.filter((item) => Number(item?.sessionType || 0) === SESSION_TYPE_HOMESERVER)
|
||||
.sort((a, b) => Number(b?.lastAuthenticatedAtMs || 0) - Number(a?.lastAuthenticatedAtMs || 0));
|
||||
|
||||
if (sessions.length === 0) {
|
||||
const empty = document.createElement('p');
|
||||
empty.className = 'meta-muted';
|
||||
empty.textContent = t('screens.remote_addblock_session_view.text_003');
|
||||
listCard.append(empty);
|
||||
return;
|
||||
}
|
||||
|
||||
sessions.forEach((session) => {
|
||||
const sessionId = String(session?.sessionId || '').trim();
|
||||
const item = document.createElement('button');
|
||||
item.className = 'ui-button session-item';
|
||||
item.type = 'button';
|
||||
const isSelected = sessionId && sessionId === selectedId;
|
||||
item.innerHTML = `
|
||||
<div class="stack" style="gap:4px; text-align:left;">
|
||||
<strong>${sessionLabel(session)}</strong>
|
||||
<span class="meta-muted">${session.geo || 'unknown'} · ${formatSessionTime(session.lastAuthenticatedAtMs || Date.now())}</span>
|
||||
<span class="meta-muted">sessionId: ${sessionId || '-'}</span>
|
||||
<span class="meta-muted">status: ${session.onlineOnThisServer ? 'online' : 'offline on this server'}</span>
|
||||
${isSelected ? t('screens.remote_addblock_session_view.text_010') : ''}
|
||||
</div>
|
||||
`;
|
||||
item.addEventListener('click', async () => {
|
||||
try {
|
||||
await saveEntrySettings({
|
||||
...state.entrySettings,
|
||||
remoteAddBlockSessionId: sessionId,
|
||||
});
|
||||
buildList();
|
||||
setAuthInfo(t('screens.remote_addblock_session_view.text_004'));
|
||||
} catch (error) {
|
||||
if (isSessionInvalidError(error)) {
|
||||
await terminateCurrentSession({
|
||||
infoMessage: t('screens.remote_addblock_session_view.text_011'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
setAuthError(error.message);
|
||||
showToast(toUserMessage(error, t('screens.remote_addblock_session_view.text_005')), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
listCard.append(item);
|
||||
});
|
||||
};
|
||||
|
||||
actions.querySelector('#remote-addblock-refresh')?.addEventListener('click', async () => {
|
||||
try {
|
||||
await refreshSessions();
|
||||
buildList();
|
||||
setAuthInfo(t('screens.remote_addblock_session_view.text_006'));
|
||||
} catch (error) {
|
||||
if (isSessionInvalidError(error)) {
|
||||
await terminateCurrentSession({
|
||||
infoMessage: t('screens.remote_addblock_session_view.text_012'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
setAuthError(error.message);
|
||||
showToast(toUserMessage(error, t('screens.remote_addblock_session_view.text_007')), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
actions.querySelector('#remote-addblock-clear')?.addEventListener('click', async () => {
|
||||
try {
|
||||
await saveEntrySettings({
|
||||
...state.entrySettings,
|
||||
remoteAddBlockSessionId: '',
|
||||
});
|
||||
buildList();
|
||||
setAuthInfo(t('screens.remote_addblock_session_view.text_008'));
|
||||
} catch (error) {
|
||||
if (isSessionInvalidError(error)) {
|
||||
await terminateCurrentSession({
|
||||
infoMessage: t('screens.remote_addblock_session_view.text_013'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
setAuthError(error.message);
|
||||
showToast(toUserMessage(error, t('screens.remote_addblock_session_view.text_009')), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
buildList();
|
||||
screen.append(actions, listCard);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { authService } from '../state.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { renderAvatar } from '../components/avatar-image.js';
|
||||
import { createPersonRow } from '../components/person-row.js';
|
||||
import { createLoadingState, createStateMessage } from '../components/feedback.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { formatChannelAddress, makeShineChannelRoute, makeProfileRoute } from '../services/shine-routes.js';
|
||||
|
||||
export const pageMeta = {
|
||||
id: 'search-view',
|
||||
get title() { return t('screens.search_view.text_001'); },
|
||||
shellMode: { contentWidth: 'wide', topFade: false },
|
||||
};
|
||||
|
||||
const SEARCH_DELAY_MS = 280;
|
||||
|
||||
function channelRow(item, navigate) {
|
||||
const row = document.createElement('button');
|
||||
row.type = 'button';
|
||||
row.className = 'shine-search-result';
|
||||
const displayName = String(item.displayName || item.slug || t('screens.search_view.text_019')).trim();
|
||||
const ownerLogin = String(item.ownerLogin || '').trim();
|
||||
const slug = String(item.slug || '').trim();
|
||||
row.append(renderAvatar({
|
||||
initials: Array.from(displayName)[0] || '#',
|
||||
avatar: item.avatarAr || item.avatarPr
|
||||
? { ar: item.avatarAr || '', pr: item.avatarPr || '' }
|
||||
: null,
|
||||
authorLogin: ownerLogin,
|
||||
size: 'lg',
|
||||
className: 'avatar-plain',
|
||||
title: displayName,
|
||||
alt: t('screens.search_view.text_002'),
|
||||
}));
|
||||
const text = document.createElement('span');
|
||||
text.className = 'shine-search-result__text';
|
||||
const title = document.createElement('strong');
|
||||
title.className = 'shine-search-result__title';
|
||||
title.textContent = displayName;
|
||||
const address = document.createElement('span');
|
||||
address.className = 'shine-search-result__address';
|
||||
address.textContent = t('screens.search_view.text_020', { value1: formatChannelAddress({ ownerLogin, channelName: slug }), value2: Number(item.subscribersCount || 0) });
|
||||
text.append(title, address);
|
||||
const description = String(item.description || '').trim();
|
||||
if (description) {
|
||||
const desc = document.createElement('span');
|
||||
desc.className = 'shine-search-result__description';
|
||||
desc.textContent = description;
|
||||
text.append(desc);
|
||||
}
|
||||
row.append(text);
|
||||
row.addEventListener('click', () => {
|
||||
const route = makeShineChannelRoute({
|
||||
ownerLogin,
|
||||
ownerBlockchainName: String(item.ownerBlockchainName || '').trim(),
|
||||
channelName: slug,
|
||||
});
|
||||
if (route) navigate(route);
|
||||
});
|
||||
return row;
|
||||
}
|
||||
|
||||
// Человек в результатах – той же строкой, что в Связях и чатах; «Написать» – сразу отсюда.
|
||||
function personRow(person, navigate) {
|
||||
const login = String(person?.login || '').trim();
|
||||
const displayName = String(person?.displayName || '').trim();
|
||||
return createPersonRow({
|
||||
login,
|
||||
name: displayName || login,
|
||||
avatar: (person.avatarAr || person.avatarPr) ? { ar: person.avatarAr, pr: person.avatarPr } : null,
|
||||
sub: displayName && displayName !== login ? login : '',
|
||||
onClick: () => navigate(makeProfileRoute(login)),
|
||||
actions: [{ icon: 'message', label: t('screens.search_view.text_003'), onClick: () => navigate(`chat/${encodeURIComponent(login)}`) }],
|
||||
});
|
||||
}
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack shine-search-screen';
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.search_view.text_004'),
|
||||
back: { label: '←', onClick: () => navigate('channels-list') },
|
||||
}));
|
||||
|
||||
const search = document.createElement('input');
|
||||
search.type = 'search';
|
||||
search.className = 'search-field__input shine-search-input';
|
||||
search.placeholder = t('screens.search_view.text_005');
|
||||
search.maxLength = 120;
|
||||
search.autocomplete = 'off';
|
||||
search.enterKeyHint = 'search';
|
||||
search.setAttribute('aria-label', t('screens.search_view.text_021'));
|
||||
const initialQuery = new URLSearchParams(window.location.search).get('q') || '';
|
||||
search.value = initialQuery;
|
||||
|
||||
const tabs = document.createElement('div');
|
||||
tabs.className = 'tabs tabs--three shine-search-tabs';
|
||||
tabs.setAttribute('role', 'radiogroup');
|
||||
const buttons = [['all', t('screens.search_view.text_013')], ['channels', t('screens.search_view.text_014')], ['people', t('screens.search_view.text_015')]].map(([id, label]) => {
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'tab-btn shine-search-tab';
|
||||
btn.textContent = label;
|
||||
btn.dataset.tab = id;
|
||||
btn.setAttribute('role', 'radio');
|
||||
btn.setAttribute('aria-checked', String(id === 'all'));
|
||||
tabs.append(btn);
|
||||
return btn;
|
||||
});
|
||||
|
||||
// Подсказка и итог – одной строкой; загрузка и «ничего не найдено» – общим видом в списке.
|
||||
const status = document.createElement('p');
|
||||
status.className = 'shine-search-status';
|
||||
status.setAttribute('role', 'status');
|
||||
status.textContent = t('screens.search_view.text_006');
|
||||
const field = document.createElement('label');
|
||||
field.className = 'search-field shine-search-field';
|
||||
field.innerHTML = `<span class="search-field__icon" aria-hidden="true">${iconHtml('search')}</span>`;
|
||||
const list = document.createElement('div');
|
||||
list.className = 'shine-search-results';
|
||||
|
||||
let selectedTab = 'all';
|
||||
let channels = [];
|
||||
let people = [];
|
||||
let error = '';
|
||||
let timer = null;
|
||||
let seq = 0;
|
||||
let disposed = false;
|
||||
|
||||
const appendSection = (title, items, factory) => {
|
||||
if (!items.length) return;
|
||||
const header = document.createElement('h3');
|
||||
header.className = 'shine-search-section-heading';
|
||||
header.textContent = `${title} · ${items.length}`;
|
||||
list.append(header);
|
||||
items.forEach((item) => list.append(factory(item, navigate)));
|
||||
};
|
||||
|
||||
const renderResults = () => {
|
||||
buttons.forEach((button) => {
|
||||
button.setAttribute('aria-checked', String(button.dataset.tab === selectedTab));
|
||||
});
|
||||
list.replaceChildren();
|
||||
const query = search.value.trim();
|
||||
if (!query) {
|
||||
status.textContent = t('screens.search_view.text_007');
|
||||
return;
|
||||
}
|
||||
if (selectedTab !== 'people') appendSection(t('screens.search_view.text_011'), channels, channelRow);
|
||||
if (selectedTab !== 'channels') appendSection(t('screens.search_view.text_012'), people, personRow);
|
||||
const shown = (selectedTab === 'people' ? people.length
|
||||
: selectedTab === 'channels' ? channels.length : channels.length + people.length);
|
||||
status.textContent = '';
|
||||
if (error && !shown) {
|
||||
list.append(createStateMessage({ kind: 'error', icon: 'alert', title: t('screens.search_view.text_008'), text: error }));
|
||||
} else if (!shown) {
|
||||
list.append(createStateMessage({ icon: 'search', title: t('screens.search_view.text_009'), text: t('screens.search_view.text_016') }));
|
||||
}
|
||||
};
|
||||
|
||||
const runSearch = async () => {
|
||||
const query = search.value.trim();
|
||||
const currentSeq = ++seq;
|
||||
if (!query) {
|
||||
channels = []; people = []; error = '';
|
||||
renderResults();
|
||||
return;
|
||||
}
|
||||
status.textContent = '';
|
||||
if (!list.childElementCount) list.replaceChildren(createLoadingState({ label: t('screens.search_view.text_010') }));
|
||||
const userQuery = query.replace(/^@/, '').trim();
|
||||
const requests = [authService.searchChannels(query, { limit: 10 })];
|
||||
if (userQuery && !userQuery.includes('/')) requests.push(authService.searchPeople(userQuery, { limit: 10 }));
|
||||
const results = await Promise.allSettled(requests);
|
||||
if (disposed || currentSeq !== seq) return;
|
||||
channels = results[0].status === 'fulfilled' ? results[0].value : [];
|
||||
people = results[1]?.status === 'fulfilled' ? results[1].value : [];
|
||||
error = results.every((result) => result.status === 'rejected')
|
||||
? t('screens.search_view.text_017')
|
||||
: '';
|
||||
renderResults();
|
||||
};
|
||||
|
||||
const rememberQueryInAddress = () => {
|
||||
const url = new URL(window.location.href);
|
||||
if (search.value.trim()) url.searchParams.set('q', search.value.trim());
|
||||
else url.searchParams.delete('q');
|
||||
window.history.replaceState(window.history.state, '', `${url.pathname}${url.search}${url.hash}`);
|
||||
};
|
||||
const scheduleSearch = () => {
|
||||
if (timer) clearTimeout(timer);
|
||||
++seq; // Устаревший ответ не должен подменить новый ввод.
|
||||
channels = []; people = []; error = '';
|
||||
// Прежние результаты остаются до прихода новых – без мелькания на каждую букву.
|
||||
if (!search.value.trim()) list.replaceChildren();
|
||||
status.textContent = search.value.trim() ? '' : t('screens.search_view.text_018');
|
||||
rememberQueryInAddress();
|
||||
timer = setTimeout(() => { timer = null; void runSearch(); }, SEARCH_DELAY_MS);
|
||||
};
|
||||
search.addEventListener('input', scheduleSearch);
|
||||
search.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (timer) clearTimeout(timer);
|
||||
timer = null;
|
||||
void runSearch();
|
||||
}
|
||||
});
|
||||
buttons.forEach((btn) => btn.addEventListener('click', () => {
|
||||
selectedTab = btn.dataset.tab;
|
||||
renderResults();
|
||||
}));
|
||||
field.append(search);
|
||||
screen.append(field, tabs, status, list);
|
||||
screen.cleanup = () => {
|
||||
disposed = true;
|
||||
++seq;
|
||||
if (timer) clearTimeout(timer);
|
||||
};
|
||||
if (initialQuery.trim()) void runSearch();
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { saveEntrySettings, state } from '../state.js';
|
||||
import { checkServerAvailabilityByKey, resolveAndCheckShineServerLogin } from '../services/server-health-service.js';
|
||||
|
||||
export const pageMeta = { id: 'server-settings-view', get title() { return t('screens.server_settings_view.text_001'); } };
|
||||
|
||||
const SERVER_FIELDS = [
|
||||
{ key: 'solanaServer', get label() { return t('screens.server_settings_view.text_002'); } },
|
||||
{ key: 'shineServerLogin', get label() { return t('screens.server_settings_view.text_003'); } },
|
||||
{ key: 'arweaveServer', get label() { return t('screens.server_settings_view.text_004'); } },
|
||||
];
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
const draft = {
|
||||
language: state.entrySettings.language,
|
||||
solanaServer: state.entrySettings.solanaServer,
|
||||
shineServerLogin: state.entrySettings.shineServerLogin,
|
||||
shineServerHttp: state.entrySettings.shineServerHttp,
|
||||
arweaveServer: state.entrySettings.arweaveServer,
|
||||
callPreflightTimeoutMs: Number(state.entrySettings.callPreflightTimeoutMs || 6000),
|
||||
statuses: { ...state.entrySettings.statuses },
|
||||
};
|
||||
|
||||
const timers = new Map();
|
||||
|
||||
const introCard = document.createElement('div');
|
||||
introCard.className = 'settings-intro';
|
||||
introCard.innerHTML = `
|
||||
<p class="meta-muted">${th('screens.server_settings_view.text_019')}</p>
|
||||
`;
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'card stack';
|
||||
|
||||
SERVER_FIELDS.forEach((field) => {
|
||||
const block = document.createElement('div');
|
||||
block.className = 'stack';
|
||||
|
||||
const title = document.createElement('label');
|
||||
title.className = 'field-label';
|
||||
title.textContent = field.label;
|
||||
|
||||
const input = document.createElement('input');
|
||||
input.className = 'input';
|
||||
input.type = 'text';
|
||||
input.value = draft[field.key];
|
||||
|
||||
const controls = document.createElement('div');
|
||||
controls.className = 'row wrap-row';
|
||||
|
||||
const checkButton = document.createElement('button');
|
||||
checkButton.className = 'ghost-btn server-check-btn';
|
||||
checkButton.type = 'button';
|
||||
checkButton.textContent = t('screens.server_settings_view.text_005');
|
||||
|
||||
const status = document.createElement('span');
|
||||
status.className = 'status-line';
|
||||
|
||||
const applyStatus = (value, exactAddress = '') => {
|
||||
draft.statuses[field.key] = value;
|
||||
checkButton.classList.remove('is-available', 'is-unavailable');
|
||||
status.classList.remove('is-available', 'is-unavailable');
|
||||
|
||||
if (value === 'available') {
|
||||
status.textContent = field.key === 'shineServerLogin' && exactAddress
|
||||
? t('screens.server_settings_view.text_017', { value1: exactAddress })
|
||||
: t('screens.server_settings_view.text_015');
|
||||
checkButton.classList.add('is-available');
|
||||
status.classList.add('is-available');
|
||||
} else if (value === 'unavailable') {
|
||||
status.textContent = t('screens.server_settings_view.text_006');
|
||||
checkButton.classList.add('is-unavailable');
|
||||
status.classList.add('is-unavailable');
|
||||
} else {
|
||||
status.textContent = field.key === 'shineServerLogin' && draft.shineServerHttp
|
||||
? t('screens.server_settings_view.text_018', { value1: draft.shineServerHttp })
|
||||
: t('screens.server_settings_view.text_016');
|
||||
}
|
||||
};
|
||||
|
||||
const runCheck = async () => {
|
||||
draft[field.key] = input.value.trim();
|
||||
checkButton.disabled = true;
|
||||
checkButton.textContent = t('screens.server_settings_view.text_007');
|
||||
try {
|
||||
if (field.key === 'shineServerLogin') {
|
||||
const resolved = await resolveAndCheckShineServerLogin(input.value, draft.solanaServer);
|
||||
draft.shineServerHttp = resolved.httpBase;
|
||||
draft.shineServer = resolved.wsUrl;
|
||||
applyStatus(resolved.status, resolved.httpBase);
|
||||
} else {
|
||||
const next = await checkServerAvailabilityByKey(field.key, input.value, {
|
||||
solanaEndpoint: draft.solanaServer,
|
||||
});
|
||||
applyStatus(next);
|
||||
}
|
||||
} finally {
|
||||
checkButton.disabled = false;
|
||||
checkButton.textContent = t('screens.server_settings_view.text_008');
|
||||
}
|
||||
};
|
||||
|
||||
applyStatus(draft.statuses[field.key]);
|
||||
|
||||
checkButton.addEventListener('click', runCheck);
|
||||
input.addEventListener('input', () => {
|
||||
draft[field.key] = input.value;
|
||||
applyStatus('idle');
|
||||
window.clearTimeout(timers.get(field.key));
|
||||
timers.set(field.key, window.setTimeout(() => {
|
||||
void runCheck();
|
||||
}, 3000));
|
||||
});
|
||||
input.addEventListener('blur', () => {
|
||||
void runCheck();
|
||||
});
|
||||
input.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
void runCheck();
|
||||
}
|
||||
});
|
||||
|
||||
controls.append(checkButton, status);
|
||||
block.append(title, input, controls);
|
||||
body.append(block);
|
||||
});
|
||||
|
||||
const callSettings = document.createElement('div');
|
||||
callSettings.className = 'stack';
|
||||
|
||||
const callTimeoutLabel = document.createElement('label');
|
||||
callTimeoutLabel.className = 'field-label';
|
||||
callTimeoutLabel.textContent = t('screens.server_settings_view.text_009');
|
||||
|
||||
const callTimeoutInput = document.createElement('input');
|
||||
callTimeoutInput.className = 'input';
|
||||
callTimeoutInput.type = 'number';
|
||||
callTimeoutInput.min = '1000';
|
||||
callTimeoutInput.max = '20000';
|
||||
callTimeoutInput.step = '500';
|
||||
callTimeoutInput.value = String(Math.max(1000, Math.min(20000, Number(draft.callPreflightTimeoutMs) || 6000)));
|
||||
callTimeoutInput.addEventListener('input', () => {
|
||||
const n = Number(callTimeoutInput.value);
|
||||
if (!Number.isFinite(n)) return;
|
||||
draft.callPreflightTimeoutMs = Math.max(1000, Math.min(20000, Math.round(n)));
|
||||
});
|
||||
|
||||
const callTimeoutHint = document.createElement('p');
|
||||
callTimeoutHint.className = 'meta-muted';
|
||||
callTimeoutHint.textContent = t('screens.server_settings_view.text_010');
|
||||
|
||||
callSettings.append(callTimeoutLabel, callTimeoutInput, callTimeoutHint);
|
||||
body.append(callSettings);
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'action-pair';
|
||||
|
||||
const cancelButton = document.createElement('button');
|
||||
cancelButton.className = 'ghost-btn';
|
||||
cancelButton.type = 'button';
|
||||
cancelButton.textContent = t('screens.server_settings_view.text_011');
|
||||
cancelButton.addEventListener('click', () => navigate('settings-servers-view'));
|
||||
|
||||
const saveButton = document.createElement('button');
|
||||
saveButton.className = 'primary-btn';
|
||||
saveButton.type = 'button';
|
||||
saveButton.textContent = t('screens.server_settings_view.text_012');
|
||||
saveButton.addEventListener('click', async () => {
|
||||
try {
|
||||
await saveEntrySettings(draft);
|
||||
navigate('settings-servers-view');
|
||||
} catch (error) {
|
||||
showToast(toUserMessage(error, t('screens.server_settings_view.text_014')), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
actions.append(cancelButton, saveButton);
|
||||
|
||||
const help = document.createElement('button');
|
||||
help.className = 'ui-button help-fab';
|
||||
help.type = 'button';
|
||||
help.textContent = '?';
|
||||
help.addEventListener('click', () => {
|
||||
window.alert(
|
||||
t('screens.server_settings_view.text_020'),
|
||||
);
|
||||
});
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.server_settings_view.text_013'),
|
||||
back: { label: '←', onClick: () => navigate('settings-servers-view') },
|
||||
}));
|
||||
screen.append(
|
||||
introCard,
|
||||
body,
|
||||
actions,
|
||||
help,
|
||||
);
|
||||
|
||||
screen.cleanup = () => {
|
||||
timers.forEach((timerId) => window.clearTimeout(timerId));
|
||||
};
|
||||
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
|
||||
export const pageMeta = { id: 'settings-servers-view', get title() { return t('screens.settings_servers_view.text_001'); } };
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.settings_servers_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigate('settings-view') },
|
||||
}));
|
||||
const list = document.createElement('div');
|
||||
list.className = 'nav-list';
|
||||
const entries = [
|
||||
[t('screens.settings_servers_view.text_003'), 'access-servers-view'],
|
||||
[t('screens.settings_servers_view.text_004'), 'server-settings-view'],
|
||||
];
|
||||
for (const [label, pageId] of entries) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'nav-row';
|
||||
button.innerHTML = `<span class="nav-row__label">${label}</span>`;
|
||||
button.addEventListener('click', () => navigate(pageId));
|
||||
list.append(button);
|
||||
}
|
||||
screen.append(list);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
import { getLanguageName, t, th } from '../i18n/index.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { getRegistrationStatus } from '../services/registration-v2-api.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { addAppLogEntry, authService, closeSavedProfile, state } from '../state.js';
|
||||
import { openSheet } from '../components/sheet.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { PALETTE_PRESETS, getPaletteSettings, getThemeMode } from '../services/theme-service.js';
|
||||
import {
|
||||
canInstallPwa,
|
||||
isStandalonePwaMode,
|
||||
onPwaInstallAvailabilityChange,
|
||||
promptPwaInstall,
|
||||
} from '../services/pwa-install-service.js';
|
||||
|
||||
export const pageMeta = { id: 'settings-view', get title() { return t('screens.settings_view.text_001'); } };
|
||||
|
||||
// Номер сборки вида 20261013040000 – это дата и время: показываем «13.10.2026, 04:00».
|
||||
function formatBuildStamp(rawValue) {
|
||||
const value = String(rawValue || '').trim();
|
||||
if (!/^\d{14}$/.test(value)) return value;
|
||||
return `${value.slice(6, 8)}.${value.slice(4, 6)}.${value.slice(0, 4)}, ${value.slice(8, 10)}:${value.slice(10, 12)}`;
|
||||
}
|
||||
|
||||
function formatVersionForUi(rawValue) {
|
||||
const value = String(rawValue || '').trim();
|
||||
if (!value) return 'n/a';
|
||||
const formatted = formatBuildStamp(value);
|
||||
if (formatted && formatted !== value) return formatted;
|
||||
return value;
|
||||
}
|
||||
|
||||
// Сервер отвечает версией на Ping (или GetServerInfo у старых серверов).
|
||||
async function loadServerVersion() {
|
||||
try {
|
||||
const pingResp = await authService.ws.request('Ping', { ts: Date.now() }, 7000);
|
||||
const value = String(pingResp?.payload?.serverVersion || pingResp?.serverVersion || '').trim();
|
||||
if (value) return value;
|
||||
} catch {
|
||||
// ниже – запасной запрос
|
||||
}
|
||||
const infoResp = await authService.ws.request('GetServerInfo', {});
|
||||
return String(infoResp?.payload?.version || '').trim();
|
||||
}
|
||||
|
||||
// «О приложении»: версии клиента, сборки и сервера – и кнопка скопировать их для поддержки.
|
||||
function openAboutSheet() {
|
||||
let disposed = false;
|
||||
return openSheet({
|
||||
title: t('dialogs.modals.settings_view.label_001'),
|
||||
className: 'about-sheet',
|
||||
onClose: () => { disposed = true; },
|
||||
content: () => {
|
||||
const list = document.createElement('div');
|
||||
list.className = 'nav-list';
|
||||
const rows = [
|
||||
[t('dialogs.remaining.pages.settings_view.openaboutsheet.versiya_prilozheniya'), formatVersionForUi(window.__SHINE_CLIENT_VERSION__)],
|
||||
[t('dialogs.remaining.pages.settings_view.openaboutsheet.sborka'), formatVersionForUi(window.__SHINE_BUILD_HASH__)],
|
||||
[t('dialogs.remaining.pages.settings_view.openaboutsheet.server'), t('dialogs.remaining.pages.settings_view.openaboutsheet.uznayu')],
|
||||
[t('dialogs.remaining.pages.settings_view.openaboutsheet.server_dostupa'), String(state.entrySettings?.shineServerLogin || '').trim() || '—'],
|
||||
];
|
||||
const values = rows.map(([label, value]) => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'nav-row nav-row--static';
|
||||
row.innerHTML = '<span class="nav-row__hint"></span><span class="nav-row__label"></span>';
|
||||
row.querySelector('.nav-row__hint').textContent = label;
|
||||
row.querySelector('.nav-row__label').textContent = value;
|
||||
list.append(row);
|
||||
return row.querySelector('.nav-row__label');
|
||||
});
|
||||
void loadServerVersion()
|
||||
.then((value) => { if (!disposed) values[2].textContent = formatVersionForUi(value) || '—'; })
|
||||
.catch(() => { if (!disposed) values[2].textContent = t('dialogs.modals.settings_view.label_002'); });
|
||||
const copy = document.createElement('button');
|
||||
copy.type = 'button';
|
||||
copy.className = 'secondary-btn about-sheet__copy';
|
||||
copy.textContent = t('dialogs.modals.settings_view.label_003');
|
||||
copy.addEventListener('click', async () => {
|
||||
const text = rows.map(([label], index) => `${label}: ${values[index].textContent}`).join('\n');
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
showToast(t('dialogs.remaining.pages.settings_view.openaboutsheet.svedeniya_skopirovany'));
|
||||
} catch {
|
||||
showToast(t('dialogs.remaining.pages.settings_view.openaboutsheet.ne_udalos_skopirovat'), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
const box = document.createElement('div');
|
||||
box.className = 'stack';
|
||||
box.append(list, copy);
|
||||
return box;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const THEME_LABELS = { get system() { return t('screens.settings_view.text_026'); }, get light() { return t('screens.settings_view.text_027'); }, get dark() { return t('screens.settings_view.text_028'); } };
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
let isDisposed = false;
|
||||
let aboutSheet = null;
|
||||
|
||||
const topbar = createTopBar({
|
||||
title: t('screens.settings_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigate('profile-view') },
|
||||
});
|
||||
chrome?.setTopbar(topbar);
|
||||
|
||||
// Скрытый вход в «Дополнительные настройки»: пять быстрых нажатий на заголовок.
|
||||
let titleTapCount = 0;
|
||||
let lastTitleTapAt = 0;
|
||||
topbar.querySelector('.topbar__title')?.addEventListener('click', () => {
|
||||
const now = Date.now();
|
||||
titleTapCount = now - lastTitleTapAt <= 900 ? titleTapCount + 1 : 1;
|
||||
lastTitleTapAt = now;
|
||||
if (titleTapCount < 5) return;
|
||||
titleTapCount = 0;
|
||||
navigate('advanced-settings-view');
|
||||
});
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'stack settings-sections';
|
||||
const row = (id, label, hint) => `<button class="nav-row" type="button" id="${id}"><span class="nav-row__label">${label}</span>${hint ? `<span class="nav-row__hint">${hint}</span>` : ''}</button>`;
|
||||
const palette = PALETTE_PRESETS[getPaletteSettings().preset]?.label || '';
|
||||
const appearanceHint = t('screens.settings_view.text_023', {
|
||||
value1: THEME_LABELS[getThemeMode()] || t('screens.settings_view.text_022'),
|
||||
value2: palette ? t('screens.settings_view.text_024', { value1: palette }) : '',
|
||||
});
|
||||
card.innerHTML = `
|
||||
<div class="nav-list" id="settings-account-tier" hidden></div>
|
||||
<div class="nav-list">
|
||||
${row('settings-appearance', t('screens.settings_view.text_004'), appearanceHint)}
|
||||
${row('settings-notifications', t('screens.settings_view.text_005'), t('screens.settings_view.text_006'))}
|
||||
${row('settings-application', t('screens.settings_view.text_007'), t('screens.settings_view.text_008'))}
|
||||
${row('settings-language', t('language.menu'), getLanguageName())}
|
||||
</div>
|
||||
<div class="nav-list">
|
||||
${row('settings-device', t('screens.settings_view.text_009'), t('screens.settings_view.text_010'))}
|
||||
${row('settings-my-blockchain', t('screens.settings_view.text_011'), t('screens.settings_view.text_012'))}
|
||||
${row('settings-servers', t('screens.settings_view.text_013'), t('screens.settings_view.text_014'))}
|
||||
${row('settings-access-keys', t('screens.settings_view.text_015'), t('screens.settings_view.text_016'))}
|
||||
</div>
|
||||
<div class="nav-list" id="settings-install-list" hidden></div>
|
||||
<div class="nav-list">
|
||||
${row('settings-about', t('screens.settings_view.text_017'), t('screens.settings_view.text_025', { value1: window.__SHINE_CLIENT_VERSION__ || '—' }))}
|
||||
${row('settings-developer', t('screens.settings_view.text_018'), t('screens.settings_view.text_019'))}
|
||||
</div>
|
||||
<div class="nav-list">
|
||||
<button class="nav-row nav-row--danger" type="button" id="settings-signout"><span class="nav-row__label">${th('screens.settings_view.text_029')}</span></button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Плашка показывается только FREE_CERT; у всех пользователей с PDA Solana её нет.
|
||||
const accountTier = card.querySelector('#settings-account-tier');
|
||||
const currentLogin = String(state.session?.login || '');
|
||||
if (currentLogin.includes('@')) {
|
||||
void getRegistrationStatus(currentLogin).then(info => {
|
||||
// Не отображаем устаревший ответ после смены аккаунта или размонтирования экрана.
|
||||
if (isDisposed || String(state.session?.login || '') !== currentLogin) return;
|
||||
if (info.registrationStatus !== 'FREE_CERT') return;
|
||||
const button = document.createElement('button');
|
||||
button.id = 'settings-solana-upgrade';
|
||||
button.type = 'button';
|
||||
button.className = 'nav-row';
|
||||
const title = document.createElement('span');
|
||||
title.className = 'nav-row__label';
|
||||
title.textContent = t('dialogs.modals.settings_view.label_004');
|
||||
const hint = document.createElement('span');
|
||||
hint.className = 'nav-row__hint';
|
||||
hint.textContent = t('dialogs.modals.settings_view.label_005');
|
||||
button.append(title, hint);
|
||||
button.addEventListener('click', () => navigate('registration-upgrade-view'));
|
||||
accountTier.replaceChildren(button);
|
||||
accountTier.hidden = false;
|
||||
}).catch(() => {
|
||||
// Если статус неизвестен, нельзя ошибочно предлагать новую оплату.
|
||||
});
|
||||
}
|
||||
card.querySelector('#settings-appearance').addEventListener('click', () => navigate('appearance-view'));
|
||||
card.querySelector('#settings-notifications').addEventListener('click', () => navigate('notification-settings-view'));
|
||||
card.querySelector('#settings-application').addEventListener('click', () => navigate('application-settings-view'));
|
||||
card.querySelector('#settings-about').addEventListener('click', () => {
|
||||
aboutSheet?.close();
|
||||
aboutSheet = openAboutSheet();
|
||||
});
|
||||
card.querySelector('#settings-device').addEventListener('click', () => navigate('device-view'));
|
||||
card.querySelector('#settings-my-blockchain').addEventListener('click', () => navigate('my-blockchain-view'));
|
||||
card.querySelector('#settings-servers').addEventListener('click', () => navigate('settings-servers-view'));
|
||||
card.querySelector('#settings-access-keys').addEventListener('click', () => navigate('access-keys-view'));
|
||||
card.querySelector('#settings-developer').addEventListener('click', () => navigate('developer-settings-view'));
|
||||
card.querySelector('#settings-language').addEventListener('click', () => {
|
||||
sessionStorage.setItem('shine-language-return-page', 'settings-view');
|
||||
navigate('language-view');
|
||||
});
|
||||
|
||||
const installList = card.querySelector('#settings-install-list');
|
||||
const syncInstallAction = () => {
|
||||
const available = !isStandalonePwaMode() && canInstallPwa();
|
||||
installList.hidden = !available;
|
||||
if (!available) {
|
||||
installList.replaceChildren();
|
||||
return;
|
||||
}
|
||||
if (installList.querySelector('#settings-install-pwa')) return;
|
||||
|
||||
installList.innerHTML = row(
|
||||
'settings-install-pwa',
|
||||
t('screens.settings_view.text_020'),
|
||||
t('screens.settings_view.text_021'),
|
||||
);
|
||||
installList.querySelector('#settings-install-pwa')?.addEventListener('click', async (event) => {
|
||||
const button = event.currentTarget;
|
||||
button.disabled = true;
|
||||
try {
|
||||
await promptPwaInstall();
|
||||
} finally {
|
||||
syncInstallAction();
|
||||
}
|
||||
});
|
||||
};
|
||||
const unsubscribeInstallAvailability = onPwaInstallAvailabilityChange(syncInstallAction);
|
||||
syncInstallAction();
|
||||
|
||||
const signOutBtn = card.querySelector('#settings-signout');
|
||||
signOutBtn.addEventListener('click', async () => {
|
||||
const confirmed = await confirmDialog({
|
||||
title: t('dialogs.pages.settings_view.title_001'),
|
||||
text: t('dialogs.pages.settings_view.text_002'),
|
||||
confirmLabel: t('dialogs.pages.settings_view.confirmLabel_003'),
|
||||
danger: true,
|
||||
});
|
||||
if (!confirmed) return;
|
||||
|
||||
signOutBtn.disabled = true;
|
||||
try {
|
||||
addAppLogEntry({
|
||||
level: 'info',
|
||||
source: 'session',
|
||||
message: t('screens.settings_view.text_003'),
|
||||
});
|
||||
const result = await closeSavedProfile(state.session.login);
|
||||
window.location.assign(result?.nextProfile ? '/profile' : '/start');
|
||||
} finally {
|
||||
signOutBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
screen.append(card);
|
||||
|
||||
screen.cleanup = () => {
|
||||
if (isDisposed) return;
|
||||
isDisposed = true;
|
||||
aboutSheet?.close();
|
||||
unsubscribeInstallAvailability();
|
||||
};
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createLoadingState } from '../components/feedback.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { state } from '../state.js';
|
||||
import { bytesToBase58 } from '../services/crypto-utils.js';
|
||||
import { extractSeed32FromPkcs8B64 } from '../services/client-key-utils.js';
|
||||
import { loadEncryptedUserSecrets } from '../services/key-vault.js';
|
||||
|
||||
export const pageMeta = { id: 'show-keys-view', get title() { return t('screens.show_keys_view.text_001'); } };
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
const visible = { blockchain: false, access: false };
|
||||
const keys = { blockchain: '', access: '' };
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.show_keys_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigate('access-keys-view') },
|
||||
}));
|
||||
|
||||
const status = document.createElement('div');
|
||||
status.className = 'meta-muted';
|
||||
status.append(createLoadingState({ label: t('screens.show_keys_view.text_003') }));
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'nav-list key-list';
|
||||
|
||||
const recovery = document.createElement('div');
|
||||
recovery.className = 'key-card stack';
|
||||
recovery.innerHTML = `
|
||||
<div class="row">
|
||||
<span class="field-label">${th('screens.show_keys_view.text_018')}
|
||||
<small class="key-card__hint">${th('screens.show_keys_view.text_019')}</small>
|
||||
</span>
|
||||
</div>
|
||||
<div class="key-value key-value--compact">${th('screens.show_keys_view.text_020')}</div>
|
||||
<p class="meta-muted">${th('screens.show_keys_view.text_021')}</p>
|
||||
`;
|
||||
|
||||
const renderStoredField = (id, label, hint) => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'key-card stack';
|
||||
const eyeIcon = iconHtml('eye', false, 'key-toggle-icon');
|
||||
const eyeOffIcon = iconHtml('eyeOff', false, 'key-toggle-icon');
|
||||
row.innerHTML = `
|
||||
<div class="row">
|
||||
<span class="field-label">${label}<small class="key-card__hint">${hint}</small></span>
|
||||
<button class="icon-btn key-toggle-btn" type="button" data-toggle="${id}" aria-label="${th('remaining.html_show_keys_view.show_key')}" title="${th('remaining.html_show_keys_view.show_key')}">${eyeIcon}</button>
|
||||
</div>
|
||||
<div class="key-value key-value--compact" data-value="${id}">*****</div>
|
||||
`;
|
||||
row._eyeIcon = eyeIcon;
|
||||
row._eyeOffIcon = eyeOffIcon;
|
||||
return row;
|
||||
};
|
||||
|
||||
card.append(
|
||||
recovery,
|
||||
renderStoredField('blockchain', t('screens.show_keys_view.text_007'), t('screens.show_keys_view.text_008')),
|
||||
renderStoredField('access', t('screens.show_keys_view.text_009'), t('screens.show_keys_view.text_010')),
|
||||
);
|
||||
|
||||
const setMissingState = (id) => {
|
||||
const valueEl = card.querySelector(`[data-value="${id}"]`);
|
||||
const btnEl = card.querySelector(`[data-toggle="${id}"]`);
|
||||
const field = btnEl?.closest('.key-card');
|
||||
if (!valueEl || !btnEl) return;
|
||||
valueEl.textContent = t('screens.show_keys_view.text_004');
|
||||
btnEl.disabled = true;
|
||||
btnEl.innerHTML = field?._eyeOffIcon || '';
|
||||
btnEl.setAttribute('aria-label', t('screens.show_keys_view.text_022'));
|
||||
btnEl.title = t('screens.show_keys_view.text_005');
|
||||
};
|
||||
|
||||
const updateField = (id) => {
|
||||
const valueEl = card.querySelector(`[data-value="${id}"]`);
|
||||
const btnEl = card.querySelector(`[data-toggle="${id}"]`);
|
||||
const field = btnEl?.closest('.key-card');
|
||||
if (!valueEl || !btnEl) return;
|
||||
if (!keys[id]) {
|
||||
setMissingState(id);
|
||||
return;
|
||||
}
|
||||
valueEl.textContent = visible[id] ? keys[id] : '*****';
|
||||
btnEl.disabled = false;
|
||||
btnEl.innerHTML = visible[id] ? field?._eyeOffIcon || '' : field?._eyeIcon || '';
|
||||
btnEl.setAttribute('aria-label', visible[id] ? t('screens.show_keys_view.text_011') : t('screens.show_keys_view.text_012'));
|
||||
btnEl.title = visible[id] ? t('screens.show_keys_view.text_013') : t('screens.show_keys_view.text_014');
|
||||
};
|
||||
|
||||
card.querySelectorAll('[data-toggle]').forEach((button) => {
|
||||
button.addEventListener('click', () => {
|
||||
const id = button.dataset.toggle;
|
||||
if (!keys[id]) return;
|
||||
visible[id] = !visible[id];
|
||||
updateField(id);
|
||||
});
|
||||
});
|
||||
|
||||
['blockchain', 'access'].forEach(updateField);
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
if (!state.session.login || !state.session.storagePwdInMemory) {
|
||||
throw new Error(t('screens.show_keys_view.text_017'));
|
||||
}
|
||||
const savedKeys = await loadEncryptedUserSecrets(state.session.login, state.session.storagePwdInMemory);
|
||||
const blockchainSeed32 = savedKeys.blockchainKey ? extractSeed32FromPkcs8B64(savedKeys.blockchainKey) : null;
|
||||
const clientSeed32 = savedKeys.clientKey ? extractSeed32FromPkcs8B64(savedKeys.clientKey) : null;
|
||||
keys.blockchain = blockchainSeed32 ? bytesToBase58(blockchainSeed32) : '';
|
||||
keys.access = clientSeed32 ? bytesToBase58(clientSeed32) : '';
|
||||
status.textContent = keys.blockchain && keys.access
|
||||
? t('screens.show_keys_view.text_015')
|
||||
: t('screens.show_keys_view.text_016');
|
||||
} catch {
|
||||
status.textContent = t('screens.show_keys_view.text_006');
|
||||
}
|
||||
['blockchain', 'access'].forEach(updateField);
|
||||
})();
|
||||
|
||||
screen.append(status, card);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { state } from '../state.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
|
||||
export const pageMeta = { id: 'solana-rpc-check-view', get title() { return t('screens.solana_rpc_check_view.text_001'); } };
|
||||
|
||||
function currentRpcEndpoints() {
|
||||
return [{ name: 'SHiNE SolanaRpcGateway', url: state.entrySettings.solanaServer }];
|
||||
}
|
||||
|
||||
const RPC_PAYLOAD = {
|
||||
jsonrpc: '2.0',
|
||||
id: 1,
|
||||
method: 'getVersion',
|
||||
params: [],
|
||||
};
|
||||
|
||||
function classifyResult(result) {
|
||||
if (!result) return { label: t('screens.solana_rpc_check_view.text_002'), tone: 'neutral' };
|
||||
if (result.ok) return { label: t('screens.solana_rpc_check_view.text_003'), tone: 'ok' };
|
||||
if (result.httpStatus === 402) return { label: t('screens.solana_rpc_check_view.text_004'), tone: 'bad' };
|
||||
if (result.httpStatus === 403) return { label: t('screens.solana_rpc_check_view.text_005'), tone: 'bad' };
|
||||
if (result.httpStatus === 429) return { label: t('screens.solana_rpc_check_view.text_006'), tone: 'warn' };
|
||||
if (result.httpStatus >= 500) return { label: t('screens.solana_rpc_check_view.text_007'), tone: 'bad' };
|
||||
if (result.errorCode === 35) return { label: t('screens.solana_rpc_check_view.text_008'), tone: 'bad' };
|
||||
if (result.networkError) return { label: t('screens.solana_rpc_check_view.text_009'), tone: 'bad' };
|
||||
return { label: t('screens.solana_rpc_check_view.text_010'), tone: 'warn' };
|
||||
}
|
||||
|
||||
function shortenText(value, max = 140) {
|
||||
const text = String(value || '').trim();
|
||||
if (!text) return '–';
|
||||
return text.length > max ? `${text.slice(0, max)}...` : text;
|
||||
}
|
||||
|
||||
async function testEndpoint(url, timeoutMs = 12000) {
|
||||
const startedAt = performance.now();
|
||||
const controller = new AbortController();
|
||||
const timeoutId = window.setTimeout(() => controller.abort(), timeoutMs);
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
mode: 'cors',
|
||||
cache: 'no-store',
|
||||
credentials: 'omit',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(RPC_PAYLOAD),
|
||||
signal: controller.signal,
|
||||
});
|
||||
const elapsedMs = Math.round(performance.now() - startedAt);
|
||||
let data = null;
|
||||
let raw = '';
|
||||
try {
|
||||
raw = await response.text();
|
||||
data = raw ? JSON.parse(raw) : null;
|
||||
} catch {
|
||||
data = null;
|
||||
}
|
||||
return {
|
||||
url,
|
||||
ok: response.ok && !!data?.result,
|
||||
httpStatus: response.status,
|
||||
elapsedMs,
|
||||
result: data?.result || null,
|
||||
errorCode: data?.error?.code ?? null,
|
||||
errorMessage: data?.error?.message || '',
|
||||
raw: shortenText(raw, 180),
|
||||
networkError: '',
|
||||
};
|
||||
} catch (error) {
|
||||
const elapsedMs = Math.round(performance.now() - startedAt);
|
||||
return {
|
||||
url,
|
||||
ok: false,
|
||||
httpStatus: 0,
|
||||
elapsedMs,
|
||||
result: null,
|
||||
errorCode: null,
|
||||
errorMessage: '',
|
||||
raw: '',
|
||||
networkError: error?.name === 'AbortError' ? 'Timeout' : (error?.message || 'Network error'),
|
||||
};
|
||||
} finally {
|
||||
window.clearTimeout(timeoutId);
|
||||
}
|
||||
}
|
||||
|
||||
function makeResultCard(endpoint) {
|
||||
const card = document.createElement('article');
|
||||
card.className = 'card stack solana-rpc-card';
|
||||
|
||||
const head = document.createElement('div');
|
||||
head.className = 'solana-rpc-card-head';
|
||||
|
||||
const title = document.createElement('strong');
|
||||
title.textContent = endpoint.name;
|
||||
|
||||
const badge = document.createElement('span');
|
||||
badge.className = 'badge alt solana-rpc-badge';
|
||||
badge.textContent = t('screens.solana_rpc_check_view.text_011');
|
||||
|
||||
head.append(title, badge);
|
||||
|
||||
const endpointLine = document.createElement('a');
|
||||
endpointLine.className = 'solana-rpc-url';
|
||||
endpointLine.href = endpoint.url;
|
||||
endpointLine.target = '_blank';
|
||||
endpointLine.rel = 'noopener noreferrer';
|
||||
endpointLine.textContent = endpoint.url;
|
||||
|
||||
const meta = document.createElement('div');
|
||||
meta.className = 'solana-rpc-meta';
|
||||
|
||||
const statusLine = document.createElement('div');
|
||||
statusLine.className = 'meta-muted';
|
||||
statusLine.textContent = t('screens.solana_rpc_check_view.text_012');
|
||||
|
||||
const details = document.createElement('div');
|
||||
details.className = 'meta-muted solana-rpc-details';
|
||||
details.textContent = '–';
|
||||
|
||||
meta.append(statusLine, details);
|
||||
card.append(head, endpointLine, meta);
|
||||
|
||||
return { card, badge, statusLine, details };
|
||||
}
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
const intro = document.createElement('div');
|
||||
intro.className = 'card stack';
|
||||
intro.innerHTML = `
|
||||
<strong>${th('screens.solana_rpc_check_view.text_027')}</strong>
|
||||
<p class="meta-muted">
|
||||
${th('screens.solana_rpc_check_view.text_028')}
|
||||
</p>
|
||||
`;
|
||||
|
||||
const controls = document.createElement('div');
|
||||
controls.className = 'auth-footer-actions';
|
||||
|
||||
const runBtn = document.createElement('button');
|
||||
runBtn.className = 'primary-btn';
|
||||
runBtn.type = 'button';
|
||||
runBtn.textContent = t('screens.solana_rpc_check_view.text_013');
|
||||
|
||||
const resetBtn = document.createElement('button');
|
||||
resetBtn.className = 'ghost-btn';
|
||||
resetBtn.type = 'button';
|
||||
resetBtn.textContent = t('screens.solana_rpc_check_view.text_014');
|
||||
|
||||
controls.append(runBtn, resetBtn);
|
||||
intro.append(controls);
|
||||
|
||||
const summary = document.createElement('p');
|
||||
summary.className = 'status-line';
|
||||
summary.textContent = t('screens.solana_rpc_check_view.text_015');
|
||||
|
||||
const grid = document.createElement('div');
|
||||
grid.className = 'stack';
|
||||
|
||||
const cards = currentRpcEndpoints().map((endpoint) => {
|
||||
const ui = makeResultCard(endpoint);
|
||||
grid.append(ui.card);
|
||||
return { endpoint, ui };
|
||||
});
|
||||
|
||||
let runToken = 0;
|
||||
|
||||
const resetState = () => {
|
||||
runToken += 1;
|
||||
summary.className = 'status-line';
|
||||
summary.textContent = t('screens.solana_rpc_check_view.text_016');
|
||||
cards.forEach(({ ui }) => {
|
||||
ui.badge.className = 'badge alt solana-rpc-badge';
|
||||
ui.badge.textContent = t('screens.solana_rpc_check_view.text_017');
|
||||
ui.statusLine.textContent = t('screens.solana_rpc_check_view.text_018');
|
||||
ui.details.textContent = '–';
|
||||
});
|
||||
};
|
||||
|
||||
const runChecks = async () => {
|
||||
const token = ++runToken;
|
||||
runBtn.disabled = true;
|
||||
resetBtn.disabled = true;
|
||||
summary.className = 'status-line';
|
||||
summary.textContent = t('screens.solana_rpc_check_view.text_019');
|
||||
|
||||
let okCount = 0;
|
||||
let warnCount = 0;
|
||||
let badCount = 0;
|
||||
|
||||
const tasks = cards.map(async ({ endpoint, ui }) => {
|
||||
ui.badge.className = 'badge alt solana-rpc-badge';
|
||||
ui.badge.textContent = t('screens.solana_rpc_check_view.text_020');
|
||||
ui.statusLine.textContent = t('screens.solana_rpc_check_view.text_021');
|
||||
ui.details.textContent = t('screens.solana_rpc_check_view.text_022');
|
||||
|
||||
const result = await testEndpoint(endpoint.url);
|
||||
if (token !== runToken) return;
|
||||
|
||||
const verdict = classifyResult(result);
|
||||
if (verdict.tone === 'ok') okCount += 1;
|
||||
else if (verdict.tone === 'warn') warnCount += 1;
|
||||
else if (verdict.tone === 'bad') badCount += 1;
|
||||
|
||||
ui.badge.className = `badge solana-rpc-badge is-${verdict.tone}`;
|
||||
ui.badge.textContent = verdict.label;
|
||||
ui.statusLine.textContent = t('screens.solana_rpc_check_view.text_025', { value1: result.httpStatus || 'ERR', value2: result.elapsedMs });
|
||||
if (result.ok) {
|
||||
ui.details.textContent = `solana-core: ${result.result?.['solana-core'] || 'unknown'} • feature-set: ${result.result?.['feature-set'] || 'unknown'}`;
|
||||
} else if (result.networkError) {
|
||||
ui.details.textContent = `Browser error: ${result.networkError}`;
|
||||
} else if (result.errorMessage) {
|
||||
ui.details.textContent = shortenText(result.errorMessage, 180);
|
||||
} else {
|
||||
ui.details.textContent = result.raw || t('screens.solana_rpc_check_view.text_024');
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(tasks);
|
||||
if (token !== runToken) return;
|
||||
|
||||
summary.className = 'status-line is-available';
|
||||
summary.textContent = t('screens.solana_rpc_check_view.text_026', { value1: okCount, value2: warnCount, value3: badCount });
|
||||
runBtn.disabled = false;
|
||||
resetBtn.disabled = false;
|
||||
};
|
||||
|
||||
runBtn.addEventListener('click', () => {
|
||||
void runChecks();
|
||||
});
|
||||
resetBtn.addEventListener('click', resetState);
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.solana_rpc_check_view.text_023'),
|
||||
back: { label: '←', onClick: () => navigate('developer-settings-view') },
|
||||
}));
|
||||
screen.append(
|
||||
intro,
|
||||
summary,
|
||||
grid,
|
||||
);
|
||||
|
||||
void runChecks();
|
||||
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { confirmSolanaTransactionHttp, getSolanaCluster } from '../services/solana-rpc-gateway.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import {
|
||||
SHINE_USERS_ECONOMY_CONFIG_SEED,
|
||||
SHINE_USERS_PROGRAM_ID,
|
||||
} from '../solana-programs.js';
|
||||
import { state } from '../state.js';
|
||||
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
||||
|
||||
export const pageMeta = { id: 'solana-users-init-view', title: 'Solana Init (users)' };
|
||||
|
||||
let solanaLibPromise = null;
|
||||
function loadSolanaLib() {
|
||||
if (!solanaLibPromise) {
|
||||
solanaLibPromise = loadSolanaWeb3();
|
||||
}
|
||||
return solanaLibPromise;
|
||||
}
|
||||
|
||||
function getProvider() {
|
||||
const p = globalThis?.solana;
|
||||
if (!p || !p.isPhantom) return null;
|
||||
return p;
|
||||
}
|
||||
|
||||
function shortAddr(value = '') {
|
||||
const v = String(value || '').trim();
|
||||
if (v.length < 12) return v;
|
||||
return `${v.slice(0, 6)}...${v.slice(-6)}`;
|
||||
}
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack';
|
||||
|
||||
const status = document.createElement('p');
|
||||
status.className = 'meta-muted';
|
||||
status.textContent = t('screens.solana_users_init_view.text_001');
|
||||
|
||||
const programId = SHINE_USERS_PROGRAM_ID;
|
||||
const programInput = document.createElement('input');
|
||||
programInput.className = 'input';
|
||||
programInput.type = 'text';
|
||||
programInput.readOnly = true;
|
||||
programInput.value = programId;
|
||||
|
||||
const rpcInput = document.createElement('input');
|
||||
rpcInput.className = 'input';
|
||||
rpcInput.type = 'text';
|
||||
rpcInput.readOnly = true;
|
||||
rpcInput.value = String(state.entrySettings.solanaServer || '');
|
||||
|
||||
const walletLine = document.createElement('p');
|
||||
walletLine.className = 'meta-muted';
|
||||
walletLine.textContent = t('screens.solana_users_init_view.text_002');
|
||||
|
||||
const economyPdaLine = document.createElement('p');
|
||||
economyPdaLine.className = 'meta-muted';
|
||||
economyPdaLine.textContent = 'PDA economy config: –';
|
||||
|
||||
const txLine = document.createElement('p');
|
||||
txLine.className = 'meta-muted';
|
||||
txLine.textContent = 'TX: –';
|
||||
|
||||
const connectBtn = document.createElement('button');
|
||||
connectBtn.className = 'text-btn';
|
||||
connectBtn.type = 'button';
|
||||
connectBtn.textContent = t('screens.solana_users_init_view.text_003');
|
||||
|
||||
const initBtn = document.createElement('button');
|
||||
initBtn.className = 'primary-btn';
|
||||
initBtn.type = 'button';
|
||||
initBtn.textContent = t('screens.solana_users_init_view.text_004');
|
||||
initBtn.disabled = true;
|
||||
|
||||
let provider = null;
|
||||
let walletPubkey = null;
|
||||
let economyPda = null;
|
||||
|
||||
async function recomputePda() {
|
||||
const solana = await loadSolanaLib();
|
||||
const pid = new solana.PublicKey(programId);
|
||||
const [pda] = solana.PublicKey.findProgramAddressSync(
|
||||
[new TextEncoder().encode(SHINE_USERS_ECONOMY_CONFIG_SEED)],
|
||||
pid,
|
||||
);
|
||||
economyPda = pda;
|
||||
economyPdaLine.textContent = `PDA economy config: ${pda.toBase58()}`;
|
||||
}
|
||||
|
||||
connectBtn.addEventListener('click', async () => {
|
||||
status.textContent = t('screens.solana_users_init_view.text_005');
|
||||
try {
|
||||
provider = getProvider();
|
||||
if (!provider) throw new Error(t('screens.solana_users_init_view.text_011'));
|
||||
const result = await provider.connect();
|
||||
walletPubkey = result?.publicKey || provider.publicKey;
|
||||
if (!walletPubkey) throw new Error(t('screens.solana_users_init_view.text_012'));
|
||||
walletLine.textContent = t('screens.solana_users_init_view.text_014', { value1: walletPubkey.toBase58(), value2: shortAddr(walletPubkey.toBase58()) });
|
||||
initBtn.disabled = false;
|
||||
status.textContent = t('screens.solana_users_init_view.text_006');
|
||||
} catch (e) {
|
||||
status.textContent = t('screens.solana_users_init_view.text_015', { value1: e?.message || 'unknown' });
|
||||
}
|
||||
});
|
||||
|
||||
initBtn.addEventListener('click', async () => {
|
||||
if (!provider || !walletPubkey || !economyPda) return;
|
||||
initBtn.disabled = true;
|
||||
status.textContent = t('screens.solana_users_init_view.text_007');
|
||||
txLine.textContent = 'TX: –';
|
||||
try {
|
||||
const solana = await loadSolanaLib();
|
||||
const connection = new solana.Connection(String(state.entrySettings.solanaServer || ''), 'confirmed');
|
||||
const programPubkey = new solana.PublicKey(programId);
|
||||
|
||||
const ix = new solana.TransactionInstruction({
|
||||
programId: programPubkey,
|
||||
keys: [
|
||||
{ pubkey: walletPubkey, isSigner: true, isWritable: true },
|
||||
{ pubkey: economyPda, isSigner: false, isWritable: true },
|
||||
{ pubkey: solana.SystemProgram.programId, isSigner: false, isWritable: false },
|
||||
],
|
||||
data: Uint8Array.from([1]),
|
||||
});
|
||||
|
||||
const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
|
||||
const tx = new solana.Transaction({
|
||||
feePayer: walletPubkey,
|
||||
blockhash,
|
||||
lastValidBlockHeight,
|
||||
}).add(ix);
|
||||
|
||||
const signed = await provider.signTransaction(tx);
|
||||
const sig = await connection.sendRawTransaction(signed.serialize(), { skipPreflight: false });
|
||||
await confirmSolanaTransactionHttp(connection, sig, { lastValidBlockHeight });
|
||||
|
||||
txLine.textContent = `TX: ${sig}`;
|
||||
status.textContent = t('screens.solana_users_init_view.text_008');
|
||||
} catch (e) {
|
||||
const message = String(e?.message || 'unknown');
|
||||
txLine.textContent = t('screens.solana_users_init_view.text_009');
|
||||
if (message.toLowerCase().includes('already') || message.includes('1000')) {
|
||||
status.textContent = t('screens.solana_users_init_view.text_010');
|
||||
} else {
|
||||
status.textContent = t('screens.solana_users_init_view.text_016', { value1: message });
|
||||
}
|
||||
} finally {
|
||||
initBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
void recomputePda();
|
||||
|
||||
card.append(
|
||||
(() => {
|
||||
const t = document.createElement('p');
|
||||
t.className = 'meta-muted';
|
||||
t.textContent = `Cluster: ${getSolanaCluster() || t('screens.solana_users_init_view.text_013')}`;
|
||||
return t;
|
||||
})(),
|
||||
(() => {
|
||||
const label = document.createElement('label');
|
||||
label.className = 'field-label';
|
||||
label.textContent = 'Program ID (shine_users)';
|
||||
return label;
|
||||
})(),
|
||||
programInput,
|
||||
(() => {
|
||||
const label = document.createElement('label');
|
||||
label.className = 'field-label';
|
||||
label.textContent = 'RPC endpoint';
|
||||
return label;
|
||||
})(),
|
||||
rpcInput,
|
||||
walletLine,
|
||||
economyPdaLine,
|
||||
txLine,
|
||||
connectBtn,
|
||||
initBtn,
|
||||
status,
|
||||
);
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'Solana Init (users)',
|
||||
back: { label: '←', onClick: () => navigate('developer-settings-view') },
|
||||
}));
|
||||
screen.append(
|
||||
card,
|
||||
);
|
||||
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { clearStartHint } from '../state.js';
|
||||
import { createShineWordmark } from '../components/shine-wordmark.js';
|
||||
|
||||
export const pageMeta = { id: 'start-view', get title() { return t('screens.start_view.text_001'); }, showAppChrome: false };
|
||||
|
||||
export function render({ navigate }) {
|
||||
clearStartHint();
|
||||
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'auth-screen auth-screen--welcome';
|
||||
|
||||
const logoWrap = document.createElement('div');
|
||||
logoWrap.className = 'auth-logo-wrap';
|
||||
// Сияние каждый раз начинается с новой фазы (периоды — как в preauth.css).
|
||||
[83, 7.3, 127, 11.9].forEach((period, i) => {
|
||||
logoWrap.style.setProperty(`--halo-phase-${i + 1}`, `${(-Math.random() * period).toFixed(2)}s`);
|
||||
});
|
||||
|
||||
const logo = document.createElement('img');
|
||||
logo.className = 'auth-logo';
|
||||
logo.src = './img/shine-logo-transparent-final.png';
|
||||
logo.alt = t('screens.start_view.text_002');
|
||||
logoWrap.append(logo);
|
||||
|
||||
const brandBlock = document.createElement('div');
|
||||
brandBlock.className = 'stack auth-brand-block';
|
||||
|
||||
const title = document.createElement('h1');
|
||||
title.className = 'auth-brand';
|
||||
title.append(createShineWordmark());
|
||||
|
||||
const siteName = document.createElement('p');
|
||||
siteName.className = 'meta-muted auth-site-name';
|
||||
siteName.textContent = window.location.host || window.location.hostname || 'shineup.me';
|
||||
|
||||
brandBlock.append(title, siteName);
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'auth-actions shine-actions';
|
||||
|
||||
const loginButton = document.createElement('button');
|
||||
loginButton.className = 'shine-btn shine-btn--primary';
|
||||
loginButton.type = 'button';
|
||||
loginButton.textContent = t('screens.start_view.text_003');
|
||||
loginButton.addEventListener('click', () => navigate('login-view'));
|
||||
|
||||
const registerButton = document.createElement('button');
|
||||
registerButton.className = 'secondary-btn shine-btn--register';
|
||||
registerButton.type = 'button';
|
||||
registerButton.textContent = t('screens.start_view.text_004');
|
||||
registerButton.addEventListener('click', () => navigate('registration-intro-view'));
|
||||
|
||||
const languageButton = document.createElement('button');
|
||||
languageButton.className = 'text-btn start-language-link';
|
||||
languageButton.type = 'button';
|
||||
languageButton.textContent = t('language.menu');
|
||||
languageButton.addEventListener('click', () => {
|
||||
sessionStorage.setItem('shine-language-return-page', 'start-view');
|
||||
navigate('language-view');
|
||||
});
|
||||
|
||||
const settingsButton = document.createElement('button');
|
||||
settingsButton.className = 'text-btn start-settings-link';
|
||||
settingsButton.type = 'button';
|
||||
settingsButton.textContent = t('screens.start_view.text_005');
|
||||
settingsButton.addEventListener('click', () => navigate('entry-settings-view'));
|
||||
|
||||
actions.append(loginButton, registerButton, languageButton, settingsButton);
|
||||
screen.append(logoWrap, brandBlock, actions);
|
||||
// Экран монтируется сразу после render – тогда и подхватываем анимацию знака с заставки.
|
||||
queueMicrotask(() => continueSplashAnimations(logoWrap));
|
||||
return screen;
|
||||
}
|
||||
|
||||
// Заставка рисует тот же знак: продолжаем её сияние с той же фазы, чтобы при смене не было скачка.
|
||||
function continueSplashAnimations(logoWrap) {
|
||||
const splashWrap = document.querySelector('#initial-splash .auth-logo-wrap');
|
||||
if (!splashWrap || !logoWrap.isConnected) return;
|
||||
const keyOf = (animation) => {
|
||||
const target = animation.effect?.target;
|
||||
const part = target?.classList?.contains('auth-logo') ? 'logo' : 'wrap';
|
||||
return `${part}${animation.effect?.pseudoElement || ''}|${animation.animationName || ''}`;
|
||||
};
|
||||
const source = new Map(splashWrap.getAnimations({ subtree: true }).map((animation) => [keyOf(animation), animation]));
|
||||
logoWrap.getAnimations({ subtree: true }).forEach((animation) => {
|
||||
const match = source.get(keyOf(animation));
|
||||
if (match && match.currentTime != null) animation.currentTime = match.currentTime;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { state } from '../state.js';
|
||||
import {
|
||||
formatSol,
|
||||
getBalanceSol,
|
||||
getTopupSiteUrl,
|
||||
} from '../services/solana-wallet-service.js';
|
||||
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
||||
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'topup-view', get title() { return t('screens.topup_view.text_001'); }, showAppChrome: false };
|
||||
const DEVNET_ENDPOINT = 'https://api.devnet.solana.com';
|
||||
const REGISTRATION_TOPUP_AMOUNT_SOL = 0.02;
|
||||
|
||||
// Канонический Solana-кошелёк пользователя = текущий blockchain key.
|
||||
// Тот же адрес используется как fee payer для регистрации и обычных PDA update.
|
||||
async function blockchainWalletAddressFromBundle() {
|
||||
const keyBundle = state.registrationDraft.preGeneratedKeyBundle;
|
||||
if (!keyBundle || !keyBundle.blockchainPair) {
|
||||
throw new Error(t('screens.topup_view.text_013'));
|
||||
}
|
||||
const raw = atob(keyBundle.blockchainPair.publicKeyB64);
|
||||
const bytes = new Uint8Array(raw.length);
|
||||
for (let i = 0; i < raw.length; i += 1) bytes[i] = raw.charCodeAt(i);
|
||||
const { PublicKey } = await loadSolanaWeb3();
|
||||
return new PublicKey(bytes).toBase58();
|
||||
}
|
||||
|
||||
export function render({ navigate }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
const walletValue = document.createElement('input');
|
||||
walletValue.className = 'input';
|
||||
walletValue.type = 'text';
|
||||
walletValue.value = state.registrationPayment.walletAddress || '';
|
||||
walletValue.readOnly = true;
|
||||
walletValue.style.fontSize = '13px';
|
||||
|
||||
const status = document.createElement('p');
|
||||
status.className = 'meta-muted';
|
||||
status.textContent = t('screens.topup_view.text_002');
|
||||
status.style.whiteSpace = 'pre-wrap';
|
||||
status.style.overflowWrap = 'anywhere';
|
||||
status.style.wordBreak = 'break-word';
|
||||
status.style.fontSize = '13px';
|
||||
|
||||
const copyButton = document.createElement('button');
|
||||
copyButton.className = 'ghost-btn';
|
||||
copyButton.type = 'button';
|
||||
copyButton.textContent = t('screens.topup_view.text_003');
|
||||
copyButton.addEventListener('click', async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(walletValue.value);
|
||||
copyButton.textContent = t('screens.topup_view.text_004');
|
||||
window.setTimeout(() => {
|
||||
copyButton.textContent = t('screens.topup_view.text_005');
|
||||
}, 1500);
|
||||
} catch {
|
||||
showToast(t('screens.topup_view.text_011'), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
const walletRow = document.createElement('div');
|
||||
walletRow.className = 'inline-input-row';
|
||||
walletRow.append(walletValue, copyButton);
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack';
|
||||
card.innerHTML = `
|
||||
<p class="auth-copy">${th('screens.topup_view.text_015')}</p>
|
||||
<div class="card stack" style="padding:12px; max-width:320px;">
|
||||
<div class="field-label" style="margin-bottom:6px;">${th('screens.topup_view.text_016')}</div>
|
||||
</div>
|
||||
<div class="stack" style="gap:6px;">
|
||||
<p class="meta-muted">${th('screens.topup_view.text_017')}</p>
|
||||
<a class="link-card" id="topup-site-link" href="${getTopupSiteUrl(state.registrationPayment.walletAddress || '')}" target="_blank" rel="noreferrer">${th('screens.topup_view.text_018')}</a>
|
||||
</div>
|
||||
`;
|
||||
card.children[1].append(walletRow);
|
||||
|
||||
const testButton = document.createElement('button');
|
||||
testButton.className = 'ghost-btn';
|
||||
testButton.type = 'button';
|
||||
testButton.textContent = t('screens.topup_view.text_006');
|
||||
testButton.textContent = t('screens.topup_view.text_007');
|
||||
testButton.addEventListener('click', () => {
|
||||
status.textContent = t('screens.topup_view.text_008');
|
||||
});
|
||||
|
||||
const backButton = document.createElement('button');
|
||||
backButton.className = 'primary-btn';
|
||||
backButton.type = 'button';
|
||||
backButton.textContent = t('screens.topup_view.text_009');
|
||||
backButton.addEventListener('click', () => navigate('registration-payment-view'));
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'auth-footer-actions';
|
||||
actions.append(testButton, backButton);
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
if (!walletValue.value) {
|
||||
const address = await blockchainWalletAddressFromBundle();
|
||||
state.registrationPayment.walletAddress = address;
|
||||
walletValue.value = address;
|
||||
}
|
||||
const topupSiteLink = card.querySelector('#topup-site-link');
|
||||
if (topupSiteLink instanceof HTMLAnchorElement) {
|
||||
topupSiteLink.href = getTopupSiteUrl(walletValue.value);
|
||||
}
|
||||
const balance = await getBalanceSol({
|
||||
endpoint: state.entrySettings.solanaServer,
|
||||
address: walletValue.value,
|
||||
});
|
||||
state.registrationPayment.balanceSOL = String(balance.sol);
|
||||
status.textContent = t('screens.topup_view.text_014', { value1: formatSol(balance.sol, 6) });
|
||||
} catch (error) {
|
||||
status.textContent = actionErrorText(t('screens.topup_view.text_012'), error);
|
||||
}
|
||||
})();
|
||||
|
||||
screen.append(
|
||||
createTopBar({
|
||||
title: t('screens.topup_view.text_010'),
|
||||
back: { label: '←', onClick: () => navigate('registration-payment-view') },
|
||||
}),
|
||||
card,
|
||||
status,
|
||||
actions,
|
||||
);
|
||||
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
// UNUSED FOR NOW: настройка дополнительного пароля для подключения другого устройства
|
||||
// сохранена в коде, но не показывается в активном UI. Текущий UX всегда без пароля.
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createLoadingState } from '../components/feedback.js';
|
||||
import { authService, setAuthError, setAuthInfo, state } from '../state.js';
|
||||
import { deriveEspPairingPasswordHash } from '../services/device-pairing-service.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'trusted-device-login-settings-view', get title() { return t('screens.trusted_device_login_settings_view.text_001'); } };
|
||||
|
||||
function setStatus(statusEl, message, kind = 'info') {
|
||||
statusEl.classList.toggle('is-unavailable', kind === 'error');
|
||||
statusEl.classList.toggle('is-available', kind !== 'error');
|
||||
statusEl.textContent = message;
|
||||
statusEl.style.display = message ? '' : 'none';
|
||||
}
|
||||
|
||||
function describeState(settings) {
|
||||
if (!settings?.enabled) return t('screens.trusted_device_login_settings_view.text_016');
|
||||
if (settings?.hasPassword) return t('screens.trusted_device_login_settings_view.text_017');
|
||||
return t('screens.trusted_device_login_settings_view.text_018');
|
||||
}
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack';
|
||||
|
||||
const summary = document.createElement('div');
|
||||
summary.className = 'auth-copy';
|
||||
summary.append(createLoadingState({ label: t('screens.trusted_device_login_settings_view.text_002') }));
|
||||
|
||||
const hint = document.createElement('p');
|
||||
hint.className = 'meta-muted';
|
||||
hint.textContent = t('screens.trusted_device_login_settings_view.text_003');
|
||||
|
||||
const status = document.createElement('p');
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.style.display = 'none';
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'stack trusted-login-actions';
|
||||
|
||||
const enableToggleBtn = document.createElement('button');
|
||||
enableToggleBtn.className = 'primary-btn';
|
||||
enableToggleBtn.type = 'button';
|
||||
|
||||
const noPasswordBtn = document.createElement('button');
|
||||
noPasswordBtn.className = 'secondary-btn';
|
||||
noPasswordBtn.type = 'button';
|
||||
noPasswordBtn.textContent = t('screens.trusted_device_login_settings_view.text_004');
|
||||
|
||||
const passwordForm = document.createElement('div');
|
||||
passwordForm.className = 'stack';
|
||||
passwordForm.innerHTML = `
|
||||
<label class="stack">
|
||||
<span class="field-label">${th('screens.trusted_device_login_settings_view.text_023')}</span>
|
||||
<input class="input" id="trusted-login-password" type="password" autocomplete="new-password" placeholder="${th('screens.trusted_device_login_settings_view.text_024')}" />
|
||||
</label>
|
||||
<label class="stack">
|
||||
<span class="field-label">${th('screens.trusted_device_login_settings_view.text_025')}</span>
|
||||
<input class="input" id="trusted-login-password-confirm" type="password" autocomplete="new-password" placeholder="${th('screens.trusted_device_login_settings_view.text_026')}" />
|
||||
</label>
|
||||
<button class="primary-btn" type="button" id="trusted-login-password-save">${th('screens.trusted_device_login_settings_view.text_027')}</button>
|
||||
`;
|
||||
|
||||
const passwordInput = passwordForm.querySelector('#trusted-login-password');
|
||||
const passwordConfirmInput = passwordForm.querySelector('#trusted-login-password-confirm');
|
||||
const savePasswordBtn = passwordForm.querySelector('#trusted-login-password-save');
|
||||
|
||||
card.append(summary, hint, actions, passwordForm, status);
|
||||
|
||||
let settings = { enabled: true, hasPassword: false };
|
||||
let busy = false;
|
||||
|
||||
const setBusy = (flag) => {
|
||||
busy = flag;
|
||||
enableToggleBtn.disabled = flag;
|
||||
noPasswordBtn.disabled = flag || !settings.enabled || !settings.hasPassword;
|
||||
noPasswordBtn.hidden = !settings.enabled || !settings.hasPassword;
|
||||
savePasswordBtn.disabled = flag;
|
||||
passwordInput.disabled = flag;
|
||||
passwordConfirmInput.disabled = flag;
|
||||
};
|
||||
|
||||
const renderUi = () => {
|
||||
summary.textContent = describeState(settings);
|
||||
enableToggleBtn.textContent = settings.enabled
|
||||
? t('screens.trusted_device_login_settings_view.text_019')
|
||||
: t('screens.trusted_device_login_settings_view.text_020');
|
||||
enableToggleBtn.className = settings.enabled ? 'destructive-btn' : 'primary-btn';
|
||||
|
||||
actions.innerHTML = '';
|
||||
actions.append(enableToggleBtn);
|
||||
if (settings.enabled) {
|
||||
actions.append(noPasswordBtn);
|
||||
}
|
||||
passwordForm.style.display = settings.enabled ? '' : 'none';
|
||||
noPasswordBtn.disabled = busy || !settings.hasPassword;
|
||||
setBusy(busy);
|
||||
};
|
||||
|
||||
const reloadSettings = async () => {
|
||||
settings = await authService.getTrustedDeviceLoginSettings();
|
||||
renderUi();
|
||||
};
|
||||
|
||||
enableToggleBtn.addEventListener('click', async () => {
|
||||
setStatus(status, '', 'info');
|
||||
setBusy(true);
|
||||
try {
|
||||
settings = await authService.upsertTrustedDeviceLoginSettings({
|
||||
enabled: !settings.enabled,
|
||||
passwordHash: '',
|
||||
});
|
||||
renderUi();
|
||||
setAuthInfo(settings.enabled
|
||||
? t('screens.trusted_device_login_settings_view.text_021')
|
||||
: t('screens.trusted_device_login_settings_view.text_022'));
|
||||
setStatus(status, describeState(settings), 'info');
|
||||
} catch (error) {
|
||||
const message = toUserMessage(error, t('screens.trusted_device_login_settings_view.text_006'));
|
||||
setAuthError(message);
|
||||
setStatus(status, message, 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
});
|
||||
|
||||
noPasswordBtn.addEventListener('click', async () => {
|
||||
setStatus(status, '', 'info');
|
||||
setBusy(true);
|
||||
try {
|
||||
settings = await authService.upsertTrustedDeviceLoginSettings({
|
||||
enabled: true,
|
||||
passwordHash: '',
|
||||
});
|
||||
renderUi();
|
||||
setAuthInfo(t('screens.trusted_device_login_settings_view.text_007'));
|
||||
setStatus(status, t('screens.trusted_device_login_settings_view.text_008'), 'info');
|
||||
} catch (error) {
|
||||
const message = toUserMessage(error, t('screens.trusted_device_login_settings_view.text_009'));
|
||||
setAuthError(message);
|
||||
setStatus(status, message, 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
});
|
||||
|
||||
savePasswordBtn.addEventListener('click', async () => {
|
||||
setStatus(status, '', 'info');
|
||||
const password = String(passwordInput.value || '');
|
||||
const confirm = String(passwordConfirmInput.value || '');
|
||||
if (!password || !confirm) {
|
||||
setStatus(status, t('screens.trusted_device_login_settings_view.text_010'), 'error');
|
||||
return;
|
||||
}
|
||||
if (password !== confirm) {
|
||||
setStatus(status, t('screens.trusted_device_login_settings_view.text_011'), 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
setBusy(true);
|
||||
try {
|
||||
const finalHash = await deriveEspPairingPasswordHash(
|
||||
String(state.session.login || ''),
|
||||
password,
|
||||
);
|
||||
settings = await authService.upsertTrustedDeviceLoginSettings({
|
||||
enabled: true,
|
||||
passwordHash: finalHash,
|
||||
});
|
||||
passwordInput.value = '';
|
||||
passwordConfirmInput.value = '';
|
||||
renderUi();
|
||||
setAuthInfo(t('screens.trusted_device_login_settings_view.text_012'));
|
||||
setStatus(status, t('screens.trusted_device_login_settings_view.text_013'), 'info');
|
||||
} catch (error) {
|
||||
const message = toUserMessage(error, t('screens.trusted_device_login_settings_view.text_014'));
|
||||
setAuthError(message);
|
||||
setStatus(status, message, 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
});
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.trusted_device_login_settings_view.text_005'),
|
||||
back: { label: '←', onClick: () => navigate('device-pairing-view') },
|
||||
}));
|
||||
screen.append(
|
||||
card,
|
||||
);
|
||||
|
||||
void reloadSettings().catch((error) => {
|
||||
const message = toUserMessage(error, t('screens.trusted_device_login_settings_view.text_015'));
|
||||
setAuthError(message);
|
||||
setStatus(status, message, 'error');
|
||||
});
|
||||
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { createErrorState, createLoadingState, createStateMessage } from '../components/feedback.js';
|
||||
import { createPersonRow } from '../components/person-row.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { authService } from '../state.js';
|
||||
import { navigateBack } from '../router.js';
|
||||
import { userDisplayName } from '../services/user-display.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { matchesPeopleQuery } from '../services/people-search.js';
|
||||
import { avatarReferenceToRenderModel, parseAvatarReference } from '../services/avatar-reference.js';
|
||||
|
||||
export const pageMeta = { id: 'user-profile-list-view', get title() { return t('screens.user_profile_list_view.text_001'); } };
|
||||
|
||||
function parseAvatar(raw) {
|
||||
return avatarReferenceToRenderModel(parseAvatarReference(raw));
|
||||
}
|
||||
|
||||
const TITLES = {
|
||||
get friends() { return t('screens.user_profile_list_view.text_017'); }, get close_friends() { return t('screens.user_profile_list_view.text_018'); }, get primary_received() { return t('screens.user_profile_list_view.text_019'); },
|
||||
get primary_given() { return t('screens.user_profile_list_view.text_020'); }, get shine_received() { return t('screens.user_profile_list_view.text_021'); }, get shine_given() { return t('screens.user_profile_list_view.text_022'); },
|
||||
get channels_owned() { return t('screens.user_profile_list_view.text_023'); }, get channels_following() { return t('screens.user_profile_list_view.text_024'); },
|
||||
};
|
||||
|
||||
const EMPTY_TEXT = {
|
||||
get friends() { return t('screens.user_profile_list_view.text_025'); },
|
||||
get close_friends() { return t('screens.user_profile_list_view.text_026'); },
|
||||
get primary_received() { return t('screens.user_profile_list_view.text_027'); },
|
||||
get primary_given() { return t('screens.user_profile_list_view.text_028'); },
|
||||
get shine_received() { return t('screens.user_profile_list_view.text_029'); },
|
||||
get shine_given() { return t('screens.user_profile_list_view.text_030'); },
|
||||
get channels_owned() { return t('screens.user_profile_list_view.text_031'); },
|
||||
get channels_following() { return t('screens.user_profile_list_view.text_032'); },
|
||||
};
|
||||
|
||||
const RELATION_TEXT = { get contact() { return t('screens.user_profile_list_view.text_033'); }, get friend() { return t('screens.user_profile_list_view.text_034'); }, get close_friend() { return t('screens.user_profile_list_view.text_035'); } };
|
||||
const SEARCH_FROM = 12; // с какого размера списка появляется поиск по нему
|
||||
|
||||
function searchText(value) {
|
||||
return String(value || '').toLowerCase().replaceAll('ё', 'е').trim();
|
||||
}
|
||||
|
||||
export function render({ navigate, route, chrome }) {
|
||||
const login = String(route?.params?.login || '').trim();
|
||||
const initialKind = String(route?.params?.kind || '').trim();
|
||||
let activeKind = initialKind;
|
||||
const isFriendsScreen = initialKind === 'friends' || initialKind === 'close_friends';
|
||||
const isChannelsScreen = initialKind === 'channels_owned' || initialKind === 'channels_following';
|
||||
let includeDeleted = false;
|
||||
let disposed = false;
|
||||
let rows = [];
|
||||
let query = '';
|
||||
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack profile-list-screen';
|
||||
const body = document.createElement('div');
|
||||
body.className = 'profile-list-body';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: TITLES[initialKind] || t('screens.user_profile_list_view.text_015'),
|
||||
back: { onClick: () => navigateBack() },
|
||||
}));
|
||||
|
||||
if (isFriendsScreen) {
|
||||
const tabs = document.createElement('div');
|
||||
tabs.className = 'tabs profile-list-kind';
|
||||
tabs.setAttribute('role', 'radiogroup');
|
||||
tabs.setAttribute('aria-label', t('screens.user_profile_list_view.text_039'));
|
||||
for (const [kind, label] of [['friends', t('screens.user_profile_list_view.text_007')], ['close_friends', t('screens.user_profile_list_view.text_008')]]) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'tab-btn';
|
||||
button.dataset.kind = kind;
|
||||
button.setAttribute('role', 'radio');
|
||||
button.setAttribute('aria-checked', String(kind === activeKind));
|
||||
button.textContent = label;
|
||||
button.addEventListener('click', () => {
|
||||
if (kind === activeKind) return;
|
||||
activeKind = kind;
|
||||
tabs.querySelectorAll('.tab-btn').forEach((el) => el.setAttribute('aria-checked', String(el.dataset.kind === activeKind)));
|
||||
void load(activeKind);
|
||||
});
|
||||
tabs.append(button);
|
||||
}
|
||||
screen.append(tabs);
|
||||
}
|
||||
|
||||
if (isChannelsScreen) {
|
||||
const filter = document.createElement('div');
|
||||
filter.className = 'nav-list';
|
||||
filter.innerHTML = `
|
||||
<label class="nav-row nav-row--switch">
|
||||
<span class="nav-row__text"><span class="nav-row__label">${th('screens.user_profile_list_view.text_036')}</span></span>
|
||||
<input class="switch" type="checkbox" />
|
||||
</label>`;
|
||||
filter.querySelector('input').addEventListener('change', (event) => {
|
||||
includeDeleted = Boolean(event.currentTarget.checked);
|
||||
void load(activeKind);
|
||||
});
|
||||
screen.append(filter);
|
||||
}
|
||||
|
||||
// Поиск по списку – когда людей много (у «Друзей» их бывают сотни).
|
||||
const searchWrap = document.createElement('label');
|
||||
searchWrap.className = 'search-field profile-list-search';
|
||||
searchWrap.hidden = true;
|
||||
searchWrap.innerHTML = `<span class="search-field__icon" aria-hidden="true">${iconHtml('search')}</span><input class="search-field__input" type="search" placeholder="${th('screens.user_profile_list_view.text_037')}" autocomplete="off" enterkeyhint="search" aria-label="${th('screens.user_profile_list_view.text_038')}" />`;
|
||||
const searchInput = searchWrap.querySelector('input');
|
||||
searchInput.addEventListener('input', () => {
|
||||
query = searchText(searchInput.value);
|
||||
renderRows();
|
||||
});
|
||||
screen.append(searchWrap, body);
|
||||
|
||||
let loadGeneration = 0;
|
||||
|
||||
function relationRow(row) {
|
||||
const marks = [
|
||||
RELATION_TEXT[row.relationType] || '',
|
||||
row.shineStatus === 'shining' ? t('screens.user_profile_list_view.text_009') : '',
|
||||
row.accountRole === 'primary' ? t('screens.user_profile_list_view.text_010') : '',
|
||||
row.primaryConfirmed ? t('screens.user_profile_list_view.text_011') : '',
|
||||
row.shineConfirmed ? t('screens.user_profile_list_view.text_012') : '',
|
||||
].filter(Boolean);
|
||||
const name = userDisplayName(row);
|
||||
const sub = [name !== row.login ? row.login : '', ...marks].filter(Boolean).join(' · ');
|
||||
return createPersonRow({
|
||||
login: row.login,
|
||||
name,
|
||||
firstName: row.firstName,
|
||||
lastName: row.lastName,
|
||||
avatar: (row.avatarAr || row.avatarPr) ? { ar: String(row.avatarAr || '').trim(), pr: String(row.avatarPr || '').trim() } : null,
|
||||
official: row.accountRole === 'primary',
|
||||
ring: row.shineStatus === 'shining' ? 'shining' : (row.relationType === 'close_friend' ? 'close' : ''),
|
||||
sub,
|
||||
onClick: () => navigate(`SHiNE/${encodeURIComponent(row.login)}`),
|
||||
actions: [{ icon: 'message', label: t('screens.user_profile_list_view.text_002'), onClick: () => navigate(`chat/${encodeURIComponent(row.login)}`) }],
|
||||
});
|
||||
}
|
||||
|
||||
function channelRow(row) {
|
||||
const el = document.createElement('button');
|
||||
el.type = 'button';
|
||||
el.className = 'ui-button card row profile-list-row';
|
||||
el.append(renderUserAvatar({ login: row.ownerLogin, firstName: row.displayName, lastName: '', avatar: (row.avatarAr || row.avatarPr) ? { ar: String(row.avatarAr || ''), pr: String(row.avatarPr || '') } : null, size: 'md' }));
|
||||
const text = document.createElement('div');
|
||||
text.className = 'profile-list-row-text';
|
||||
const title = document.createElement('b');
|
||||
title.textContent = `${String(row.displayName || row.slug || '')}${row.deleted ? t('screens.user_profile_list_view.text_013') : ''}`;
|
||||
const sub = document.createElement('small');
|
||||
sub.textContent = `${String(row.ownerLogin || '')} / ${String(row.slug || '')}`;
|
||||
text.append(title, sub);
|
||||
el.append(text);
|
||||
el.addEventListener('click', () => navigate(`channel/${encodeURIComponent(row.ownerBlockchainName)}/${Number(row.rootBlockNumber || 0)}/${encodeURIComponent(row.rootBlockHashHex || '')}/about`));
|
||||
return el;
|
||||
}
|
||||
|
||||
function renderRows() {
|
||||
body.replaceChildren();
|
||||
const matches = (row) => (isChannelsScreen
|
||||
? !query || searchText(`${row.displayName} ${row.slug} ${row.ownerLogin}`).includes(query)
|
||||
: matchesPeopleQuery(`${userDisplayName(row)} ${row.login}`, query));
|
||||
const visible = rows.filter(matches);
|
||||
if (!rows.length) {
|
||||
body.append(createStateMessage({ icon: isChannelsScreen ? 'channels' : 'network', title: EMPTY_TEXT[activeKind] || t('screens.user_profile_list_view.text_016') }));
|
||||
return;
|
||||
}
|
||||
if (!visible.length) {
|
||||
body.append(createStateMessage({ icon: 'search', title: t('screens.user_profile_list_view.text_003'), text: t('screens.user_profile_list_view.text_014') }));
|
||||
return;
|
||||
}
|
||||
const frag = document.createDocumentFragment();
|
||||
visible.forEach((row) => frag.append(isChannelsScreen ? channelRow(row) : relationRow(row)));
|
||||
body.append(frag);
|
||||
}
|
||||
|
||||
async function load(kind) {
|
||||
const generation = ++loadGeneration;
|
||||
body.replaceChildren(createLoadingState({ label: t('screens.user_profile_list_view.text_004') }));
|
||||
try {
|
||||
const payload = isChannelsScreen
|
||||
? await authService.listUserProfileChannels(login, kind === 'channels_owned' ? 'owned' : 'following', 200, 0, includeDeleted)
|
||||
: await authService.listUserProfileRelations(login, kind, 200, 0);
|
||||
if (disposed || generation !== loadGeneration) return;
|
||||
rows = Array.isArray(isChannelsScreen ? payload?.channels : payload?.users) ? (isChannelsScreen ? payload.channels : payload.users) : [];
|
||||
searchWrap.hidden = rows.length < SEARCH_FROM;
|
||||
renderRows();
|
||||
} catch (error) {
|
||||
if (disposed || generation !== loadGeneration) return;
|
||||
body.replaceChildren(createErrorState({
|
||||
title: t('screens.user_profile_list_view.text_005'),
|
||||
text: toUserMessage(error, t('screens.user_profile_list_view.text_006')),
|
||||
onRetry: () => { void load(activeKind); },
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
screen.cleanup = () => {
|
||||
disposed = true;
|
||||
loadGeneration += 1;
|
||||
};
|
||||
|
||||
void load(activeKind);
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import { openShineSupportDialog } from '../components/shine-support-dialog.js';
|
||||
import { attachSupportStats } from '../components/support-stats.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { SHINE_CONNECTIONS_LOGO_SRC } from '../components/shine-logo.js';
|
||||
import { attachProfileAvatarPreview } from '../components/profile-avatar-preview.js';
|
||||
import { state } from '../state.js';
|
||||
import { loadRelationsForPair, loadUserProfileCard } from '../services/user-connections.js';
|
||||
import { createErrorState, createLoadingState } from '../components/feedback.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { makeProfileLinksRoute } from '../services/shine-routes.js';
|
||||
import { navigateBack } from '../router.js';
|
||||
import { profileCardHtml, profileTileHtml } from '../components/profile-card.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
|
||||
export const pageMeta = { id: 'user', get title() { return t('screens.user_profile_view.text_001'); } };
|
||||
|
||||
function escapeHtml(text) {
|
||||
return String(text || '')
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
|
||||
export function render({ navigate, route, chrome }) {
|
||||
const requestedLogin = String(route?.params?.login || '').trim();
|
||||
const selfLogin = String(state.session.login || '').trim();
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack user-profile-screen';
|
||||
|
||||
const header = createTopBar({
|
||||
title: t('screens.user_profile_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigateBack() },
|
||||
});
|
||||
header.classList.add('user-profile-header');
|
||||
chrome?.setTopbar(header);
|
||||
|
||||
const status = document.createElement('div');
|
||||
status.className = 'user-profile-status';
|
||||
status.append(createLoadingState({ label: t('screens.user_profile_view.text_003') }));
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'user-profile-body';
|
||||
screen.append(status, body);
|
||||
|
||||
let card = null;
|
||||
let relation = null;
|
||||
let avatarPreview = null;
|
||||
let disposed = false;
|
||||
function renderProfile() {
|
||||
if (!card || disposed) return;
|
||||
avatarPreview?.cleanup();
|
||||
avatarPreview = null;
|
||||
const isSelf = card.login.toLowerCase() === selfLogin.toLowerCase();
|
||||
|
||||
body.innerHTML = profileCardHtml({
|
||||
card,
|
||||
login: requestedLogin,
|
||||
isSelf,
|
||||
tilesHtml: isSelf ? '' : [
|
||||
profileTileHtml({ icon: 'user-plus', label: t('screens.user_profile_view.text_004'), attrs: 'data-profile-action="add"' }),
|
||||
profileTileHtml({ label: t('screens.user_profile_view.text_005'), attrs: 'data-profile-action="links"', iconMarkup: `<img class="pf-tile-mandala" src="${SHINE_CONNECTIONS_LOGO_SRC}" alt="" aria-hidden="true">` }),
|
||||
profileTileHtml({ icon: 'message', label: t('screens.user_profile_view.text_006'), attrs: 'data-profile-action="chat"' }),
|
||||
profileTileHtml({ icon: 'heart', label: t('screens.support_phase2.donate'), attrs: 'data-profile-action="support"' }),
|
||||
].join(''),
|
||||
});
|
||||
|
||||
attachSupportStats(body, { login: card.login, isActive: () => !disposed });
|
||||
syncRelationTile();
|
||||
|
||||
avatarPreview = attachProfileAvatarPreview(body.querySelector('.user-profile-avatar-slot'), card);
|
||||
|
||||
status.replaceChildren();
|
||||
}
|
||||
|
||||
// Плитка показывает текущую связь («Друг ✓») или предлагает ответить, если человек
|
||||
// добавил вас первым; нажатие – как раньше, в управление связью.
|
||||
function syncRelationTile() {
|
||||
const tile = body.querySelector('[data-profile-action="add"]');
|
||||
if (!tile || !relation) return;
|
||||
const r = relation;
|
||||
const theyFriend = r.inFriend || r.inCloseFriend;
|
||||
let icon = 'user-plus';
|
||||
let label = t('remaining.profile.add_connection');
|
||||
let hint = '';
|
||||
if (r.outCloseFriend) { icon = 'check'; label = t('screens.user_profile_view.text_013'); }
|
||||
else if (r.outFriend) { icon = 'check'; label = t('screens.user_profile_view.text_014'); }
|
||||
else if (r.outContact) { icon = 'check'; label = t('screens.user_profile_view.text_015'); }
|
||||
else if (theyFriend) { label = t('screens.user_profile_view.text_016'); hint = t('screens.user_profile_view.text_017'); }
|
||||
else if (r.inContact) {
|
||||
label = t('screens.user_profile_view.text_018');
|
||||
hint = t('screens.user_profile_view.text_019', { value1: card.gender === 'female' ? t('screens.user_profile_view.text_010') : card.gender === 'male' ? t('screens.user_profile_view.text_011') : t('screens.user_profile_view.text_012') });
|
||||
}
|
||||
tile.innerHTML = `${iconHtml(icon)}<span></span>`;
|
||||
tile.querySelector('span').textContent = label;
|
||||
tile.classList.toggle('is-related', icon === 'check');
|
||||
tile.setAttribute('aria-label', icon === 'check' ? t('screens.user_profile_view.text_020', { value1: label }) : label);
|
||||
body.querySelector('.user-profile-relation-hint')?.remove();
|
||||
if (hint) {
|
||||
const note = document.createElement('p');
|
||||
note.className = 'user-profile-relation-hint';
|
||||
note.textContent = `${[card.firstName, card.lastName].map((v) => String(v || '').trim()).filter(Boolean).join(' ') || card.login} ${hint}`;
|
||||
body.querySelector('.pf-tiles-wrap')?.before(note);
|
||||
}
|
||||
}
|
||||
|
||||
body.addEventListener('click', (event) => {
|
||||
if (!card) return;
|
||||
const listButton = event.target.closest('[data-profile-list]');
|
||||
if (listButton) {
|
||||
const kind = listButton.dataset.profileList;
|
||||
if (kind) navigate(`SHiNE/${encodeURIComponent(card.login)}/list/${encodeURIComponent(kind)}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const actionButton = event.target.closest('[data-profile-action]');
|
||||
const action = actionButton?.dataset.profileAction;
|
||||
if (action === 'add') {
|
||||
navigate(`SHiNE/${encodeURIComponent(card.login)}/manage`);
|
||||
return;
|
||||
}
|
||||
if (action === 'links') {
|
||||
navigate(makeProfileLinksRoute(card.login));
|
||||
return;
|
||||
}
|
||||
if (action === 'support') {
|
||||
openShineSupportDialog({ recipientLogin: card.login, onSuccess: () => { if (!disposed) renderProfile(); } });
|
||||
return;
|
||||
}
|
||||
if (action === 'chat') {
|
||||
navigate(`chat/${encodeURIComponent(card.login)}`);
|
||||
}
|
||||
});
|
||||
|
||||
screen.cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
avatarPreview?.cleanup();
|
||||
avatarPreview = null;
|
||||
};
|
||||
|
||||
async function refresh() {
|
||||
const loaded = await loadUserProfileCard(requestedLogin);
|
||||
if (disposed) return;
|
||||
card = loaded;
|
||||
renderProfile();
|
||||
if (selfLogin && card.login.toLowerCase() !== selfLogin.toLowerCase()) {
|
||||
loadRelationsForPair({ currentLogin: selfLogin, targetLogin: card.login })
|
||||
.then((flags) => {
|
||||
if (disposed) return;
|
||||
relation = flags;
|
||||
syncRelationTile();
|
||||
})
|
||||
.catch(() => { /* без сведений о связи плитка остаётся «Добавить связь» */ });
|
||||
}
|
||||
}
|
||||
|
||||
const showLoadError = (error) => {
|
||||
if (disposed) return;
|
||||
status.replaceChildren(createErrorState({
|
||||
title: t('screens.user_profile_view.text_007'),
|
||||
text: toUserMessage(error, t('screens.user_profile_view.text_009')),
|
||||
onRetry: () => {
|
||||
status.replaceChildren(createLoadingState({ label: t('screens.user_profile_view.text_008'), delayMs: 0 }));
|
||||
refresh().catch(showLoadError);
|
||||
},
|
||||
}));
|
||||
};
|
||||
refresh().catch(showLoadError);
|
||||
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
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 { createErrorState, createLoadingState } from '../components/feedback.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { loadRelationsForPair, loadUserProfileCard } from '../services/user-connections.js';
|
||||
import { navigateBack } from '../router.js';
|
||||
import { escapeProfileHtml } from '../components/profile-card.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'user-relation-manage-view', get title() { return t('screens.user_relation_manage_view.text_001'); } };
|
||||
|
||||
const SOCIAL_LABELS = {
|
||||
get none() { return t('screens.user_relation_manage_view.text_037'); },
|
||||
get contact() { return t('screens.user_relation_manage_view.text_038'); },
|
||||
get friend() { return t('screens.user_relation_manage_view.text_039'); },
|
||||
get close_friend() { return t('screens.user_relation_manage_view.text_040'); },
|
||||
};
|
||||
|
||||
const MUTUAL_LABELS = {
|
||||
get contact() { return t('screens.user_relation_manage_view.text_041'); },
|
||||
get friend() { return t('screens.user_relation_manage_view.text_042'); },
|
||||
get close_friend() { return t('screens.user_relation_manage_view.text_043'); },
|
||||
};
|
||||
|
||||
function effectiveSocial(flags = {}, direction = 'out') {
|
||||
const prefix = direction === 'in' ? 'in' : 'out';
|
||||
if (flags[`${prefix}CloseFriend`]) return 'close_friend';
|
||||
if (flags[`${prefix}Friend`]) return 'friend';
|
||||
if (flags[`${prefix}Contact`]) return 'contact';
|
||||
return 'none';
|
||||
}
|
||||
|
||||
function relationSummaryHtml(flags = {}) {
|
||||
const outgoing = effectiveSocial(flags, 'out');
|
||||
const incoming = effectiveSocial(flags, 'in');
|
||||
|
||||
if (outgoing !== 'none' && outgoing === incoming) {
|
||||
return `
|
||||
<div class="relation-manage-mutual">
|
||||
<span class="relation-manage-mutual-label">${th('screens.user_relation_manage_view.text_044')}</span>
|
||||
<strong>${escapeProfileHtml(MUTUAL_LABELS[outgoing])}</strong>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="relation-manage-current">
|
||||
<div class="relation-manage-current-row">
|
||||
<span>${th('screens.user_relation_manage_view.text_045')}</span>
|
||||
<strong>${escapeProfileHtml(SOCIAL_LABELS[outgoing])}</strong>
|
||||
</div>
|
||||
${incoming !== 'none' ? `
|
||||
<div class="relation-manage-current-row">
|
||||
<span>${th('screens.user_relation_manage_view.text_046')}</span>
|
||||
<strong>${escapeProfileHtml(SOCIAL_LABELS[incoming])}</strong>
|
||||
</div>` : ''}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function socialButtonsHtml(flags = {}) {
|
||||
const current = effectiveSocial(flags, 'out');
|
||||
const kinds = ['none', 'contact', 'friend', 'close_friend'];
|
||||
return kinds.map((kind) => `
|
||||
<button type="button" class="secondary-btn relation-manage-choice${current === kind ? ' is-active' : ''}" data-social-kind="${kind}">
|
||||
${escapeProfileHtml(SOCIAL_LABELS[kind])}
|
||||
</button>`).join('');
|
||||
}
|
||||
|
||||
function officialBlockHtml(flags = {}, targetIsOfficial = false) {
|
||||
return `
|
||||
<section class="card stack relation-manage-card relation-manage-card--official">
|
||||
<div class="relation-manage-card-head">
|
||||
<strong>${th('screens.user_relation_manage_view.text_047')}</strong>
|
||||
<span>${targetIsOfficial ? t('screens.user_relation_manage_view.text_009') : t('screens.user_relation_manage_view.text_010')}</span>
|
||||
</div>
|
||||
<div class="relation-manage-confirmations">
|
||||
${flags.outOfficialAccount ? t('screens.user_relation_manage_view.text_011') : ''}
|
||||
${flags.inOfficialAccount ? t('screens.user_relation_manage_view.text_012') : ''}
|
||||
</div>
|
||||
<button type="button" class="secondary-btn relation-manage-confirm-btn" data-confirm="official_account">
|
||||
${flags.outOfficialAccount ? t('screens.user_relation_manage_view.text_013') : t('screens.user_relation_manage_view.text_014')}
|
||||
</button>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function shineBlockHtml(flags = {}, targetIsShining = false) {
|
||||
return `
|
||||
<section class="card stack relation-manage-card relation-manage-card--shine">
|
||||
<div class="relation-manage-card-head">
|
||||
<strong>${th('screens.user_relation_manage_view.text_048')}</strong>
|
||||
<span>${targetIsShining ? t('screens.user_relation_manage_view.text_015') : t('screens.user_relation_manage_view.text_016')}</span>
|
||||
</div>
|
||||
<div class="relation-manage-confirmations">
|
||||
${flags.outShineConfirmed ? t('screens.user_relation_manage_view.text_017') : ''}
|
||||
${flags.inShineConfirmed ? t('screens.user_relation_manage_view.text_018') : ''}
|
||||
</div>
|
||||
<button type="button" class="secondary-btn relation-manage-confirm-btn" data-confirm="shine_confirmed">
|
||||
${flags.outShineConfirmed ? t('screens.user_relation_manage_view.text_019') : t('screens.user_relation_manage_view.text_020')}
|
||||
</button>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
export function render({ route, chrome }) {
|
||||
const targetLogin = String(route?.params?.login || '').trim();
|
||||
const selfLogin = String(state.session.login || '').trim();
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack relation-manage-screen';
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'stack relation-manage-body';
|
||||
const status = document.createElement('div');
|
||||
status.className = 'status-line relation-manage-status';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.user_relation_manage_view.text_002'),
|
||||
back: { label: '←', onClick: () => navigateBack() },
|
||||
}));
|
||||
screen.append(status, body);
|
||||
|
||||
let flags = {};
|
||||
let selfCard = null;
|
||||
let targetCard = null;
|
||||
let busy = false;
|
||||
|
||||
async function setKind(kind, enabled) {
|
||||
await authService.setUserRelation({
|
||||
login: selfLogin,
|
||||
toLogin: targetLogin,
|
||||
kind,
|
||||
enabled,
|
||||
storagePwd: state.session.storagePwdInMemory,
|
||||
});
|
||||
}
|
||||
|
||||
async function changeSocial(next) {
|
||||
const current = effectiveSocial(flags, 'out');
|
||||
if (current === next) return;
|
||||
|
||||
if (next === 'none') {
|
||||
if (flags.outCloseFriend) await setKind('close_friend', false);
|
||||
if (flags.outFriend) await setKind('friend', false);
|
||||
if (flags.outContact) await setKind('contact', false);
|
||||
}
|
||||
if (next === 'contact') {
|
||||
if (flags.outCloseFriend) await setKind('close_friend', false);
|
||||
if (flags.outFriend) await setKind('friend', false);
|
||||
if (!flags.outContact) await setKind('contact', true);
|
||||
}
|
||||
if (next === 'friend') {
|
||||
if (flags.outCloseFriend) await setKind('close_friend', false);
|
||||
if (!flags.outFriend) await setKind('friend', true);
|
||||
}
|
||||
if (next === 'close_friend' && !flags.outCloseFriend) {
|
||||
await setKind('close_friend', true);
|
||||
}
|
||||
}
|
||||
|
||||
function renderBody() {
|
||||
// Те же правила, что проверяет сервер (validateConnectionVotingRights): голосует официальный аккаунт,
|
||||
// за сияние – основной и сам сияющий; цель не должна отказываться от подтверждений.
|
||||
const selfPrimary = selfCard?.accountRole === 'primary';
|
||||
const canPrimary = selfPrimary && targetCard?.accountRole !== 'non_voting';
|
||||
const canShine = selfPrimary && selfCard?.shineStatus === 'shining' && targetCard?.shineStatus !== 'not_interested';
|
||||
|
||||
body.innerHTML = `
|
||||
<section class="card stack relation-manage-card relation-manage-card--social">
|
||||
<div class="relation-manage-card-head">
|
||||
<strong>${th('screens.user_relation_manage_view.text_049')}</strong>
|
||||
<span>${escapeProfileHtml(targetCard?.login || targetLogin)}</span>
|
||||
</div>
|
||||
${relationSummaryHtml(flags)}
|
||||
<div class="relation-manage-choices" aria-label="${th('screens.user_relation_manage_view.text_050')}">
|
||||
${socialButtonsHtml(flags)}
|
||||
</div>
|
||||
</section>
|
||||
${canPrimary ? officialBlockHtml(flags, targetCard?.accountRole === 'primary') : ''}
|
||||
${canShine ? shineBlockHtml(flags, targetCard?.shineStatus === 'shining') : ''}
|
||||
`;
|
||||
}
|
||||
|
||||
async function refresh({ loading = true } = {}) {
|
||||
// Спиннер – только если ответ задержался, иначе он мелькает и сдвигает экран.
|
||||
const loadingTimer = loading ? window.setTimeout(() => {
|
||||
if (screen.isConnected && !body.childElementCount) status.replaceChildren(createLoadingState({ label: t('screens.user_relation_manage_view.text_003'), delayMs: 0 }));
|
||||
}, 500) : 0;
|
||||
[selfCard, targetCard, flags] = await Promise.all([
|
||||
loadUserProfileCard(selfLogin),
|
||||
loadUserProfileCard(targetLogin),
|
||||
loadRelationsForPair({ currentLogin: selfLogin, targetLogin }),
|
||||
]);
|
||||
window.clearTimeout(loadingTimer);
|
||||
renderBody();
|
||||
status.className = 'status-line relation-manage-status';
|
||||
status.textContent = '';
|
||||
}
|
||||
|
||||
const SOCIAL_DONE = {
|
||||
none: t('screens.user_relation_manage_view.text_021'),
|
||||
contact: t('screens.user_relation_manage_view.text_022'),
|
||||
friend: t('screens.user_relation_manage_view.text_023'),
|
||||
close_friend: t('screens.user_relation_manage_view.text_024'),
|
||||
};
|
||||
|
||||
// Выбор сохраняется прямо на нажатой кнопке (без строки статуса, которая сдвигала экран),
|
||||
// после сохранения – короткое сообщение и возврат на страницу пользователя.
|
||||
body.addEventListener('click', async (event) => {
|
||||
const button = event.target.closest('button');
|
||||
if (!button || busy) return;
|
||||
|
||||
const social = button.dataset.socialKind;
|
||||
const confirm = button.dataset.confirm;
|
||||
if (!social && !confirm) return;
|
||||
if (social && effectiveSocial(flags, 'out') === social) { navigateBack(); return; }
|
||||
|
||||
const isAttestation = confirm === 'official_account' || confirm === 'shine_confirmed';
|
||||
const withdrawing = (confirm === 'official_account' && flags.outOfficialAccount)
|
||||
|| (confirm === 'shine_confirmed' && flags.outShineConfirmed);
|
||||
const accepted = await (isAttestation ? confirmDialog : confirmPublicHistoryAction)({
|
||||
title: isAttestation ? t('screens.user_relation_manage_view.text_025') : t('screens.user_relation_manage_view.text_026'),
|
||||
text: isAttestation
|
||||
? t('screens.user_relation_manage_view.text_027')
|
||||
: t('screens.user_relation_manage_view.text_028'),
|
||||
confirmLabel: isAttestation ? (withdrawing ? t('screens.user_relation_manage_view.text_029') : t('screens.user_relation_manage_view.text_030')) : t('screens.user_relation_manage_view.text_031'),
|
||||
});
|
||||
if (!accepted || !screen.isConnected || busy) return;
|
||||
busy = true;
|
||||
body.classList.add('is-busy');
|
||||
body.querySelectorAll('button').forEach((item) => { item.disabled = true; });
|
||||
const label = button.textContent;
|
||||
button.classList.add('is-pending');
|
||||
button.textContent = t('screens.user_relation_manage_view.text_004');
|
||||
|
||||
try {
|
||||
let done = '';
|
||||
if (social) {
|
||||
await changeSocial(social);
|
||||
done = SOCIAL_DONE[social] || t('screens.user_relation_manage_view.text_036');
|
||||
} else if (confirm === 'official_account') {
|
||||
await setKind('official_account', !flags.outOfficialAccount);
|
||||
done = flags.outOfficialAccount ? t('screens.user_relation_manage_view.text_032') : t('screens.user_relation_manage_view.text_033');
|
||||
} else if (confirm === 'shine_confirmed') {
|
||||
await setKind('shine_confirmed', !flags.outShineConfirmed);
|
||||
done = flags.outShineConfirmed ? t('screens.user_relation_manage_view.text_034') : t('screens.user_relation_manage_view.text_035');
|
||||
}
|
||||
if (!screen.isConnected) return;
|
||||
showToast(done);
|
||||
navigateBack();
|
||||
} catch (error) {
|
||||
if (!screen.isConnected) return;
|
||||
showToast(toUserMessage(error, t('screens.user_relation_manage_view.text_007')), { kind: 'error', timeoutMs: 4000 });
|
||||
button.textContent = label;
|
||||
button.classList.remove('is-pending');
|
||||
body.querySelectorAll('button').forEach((item) => { item.disabled = false; });
|
||||
} finally {
|
||||
busy = false;
|
||||
body.classList.remove('is-busy');
|
||||
}
|
||||
});
|
||||
|
||||
if (!selfLogin || !targetLogin) {
|
||||
status.className = 'status-line relation-manage-status is-unavailable';
|
||||
status.textContent = t('screens.user_relation_manage_view.text_005');
|
||||
return screen;
|
||||
}
|
||||
|
||||
const showLoadError = (error) => {
|
||||
status.className = 'relation-manage-status';
|
||||
status.replaceChildren(createErrorState({
|
||||
title: t('screens.user_relation_manage_view.text_006'),
|
||||
text: toUserMessage(error, t('screens.user_relation_manage_view.text_008')),
|
||||
onRetry: () => {
|
||||
status.replaceChildren();
|
||||
refresh().catch(showLoadError);
|
||||
},
|
||||
}));
|
||||
};
|
||||
refresh().catch(showLoadError);
|
||||
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
/** SHiNE wallet beta swap — in-app Jupiter routing, user's blockchainKey signs locally. */
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { state } from '../state.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
import { getBalanceSol, getWalletFromStoredBlockchainKey } from '../services/solana-wallet-service.js';
|
||||
import { getUsdtBalance, formatAtomicAmount } from '../services/solana-usdt-service.js';
|
||||
import { getSolanaCluster } from '../services/solana-rpc-gateway.js';
|
||||
import { requestSwapBuild, validateSwapInput, validateSwapBuildResponse, executeJupiterSwap, getPendingSwapSignature } from '../services/jupiter-swap-service.js';
|
||||
|
||||
export const pageMeta = { id: 'wallet-swap-view', get title() { return t('wallet_swap.title'); } };
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
chrome?.setTopbar(createTopBar({ title: t('wallet_swap.title'), back: { label: '←', onClick: () => navigate('wallet') } }));
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack wallet-transfer-screen wallet-swap-screen';
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack wallet-transfer-card wallet-swap-card';
|
||||
card.innerHTML = `
|
||||
<h2 data-heading></h2>
|
||||
<p class="wallet-swap-beta-tag" data-beta></p>
|
||||
<p class="wallet-swap-warning" data-warning></p>
|
||||
<div class="wallet-transfer-balances">
|
||||
<div class="wallet-transfer-balance"><span>SOL</span><strong data-balance-sol>—</strong></div>
|
||||
<div class="wallet-transfer-balance"><span>USDT</span><strong data-balance-usdt>—</strong></div>
|
||||
</div>
|
||||
<label class="wallet-transfer-field"><span data-from-label></span><select class="input wallet-transfer-select" data-from><option value="SOL">SOL → USDT</option><option value="USDT">USDT → SOL</option></select></label>
|
||||
<label class="wallet-transfer-field"><span data-amount-label></span><input class="input" inputmode="decimal" autocomplete="off" data-amount type="text" placeholder="0.01" /></label>
|
||||
<p class="meta-muted wallet-swap-limit" data-limit></p>
|
||||
<button type="button" class="secondary-btn wallet-swap-quote-button" data-quote></button>
|
||||
<div class="wallet-swap-quote-box" data-preview hidden>
|
||||
<div><span data-receive-label></span><strong data-receive>—</strong></div>
|
||||
<div><span data-min-label></span><strong data-min>—</strong></div>
|
||||
<div><span data-route-label></span><strong>Jupiter Metis</strong></div>
|
||||
<p class="meta-muted" data-preview-hint></p>
|
||||
</div>
|
||||
<label class="wallet-transfer-notice wallet-swap-consent" data-consent-row hidden><input type="checkbox" data-consent /><span data-consent-label></span></label>
|
||||
<button type="button" class="primary-btn wallet-swap-confirm" data-confirm hidden disabled></button>
|
||||
<p class="meta-muted wallet-transfer-status" data-status role="status" aria-live="polite"></p>
|
||||
<a data-explorer target="_blank" rel="noopener noreferrer" class="wallet-swap-explorer" hidden></a>
|
||||
<button type="button" class="secondary-btn wallet-swap-check" data-check hidden></button>
|
||||
`;
|
||||
const el = (name) => card.querySelector(`[data-${name}]`);
|
||||
el('heading').textContent = t('wallet_swap.title');
|
||||
el('beta').textContent = t('wallet_swap.beta');
|
||||
el('warning').textContent = t('wallet_swap.warning');
|
||||
el('from-label').textContent = t('wallet_swap.direction');
|
||||
el('amount-label').textContent = t('wallet_swap.amount');
|
||||
el('quote').textContent = t('wallet_swap.get_quote');
|
||||
el('receive-label').textContent = t('wallet_swap.expected');
|
||||
el('min-label').textContent = t('wallet_swap.minimum');
|
||||
el('route-label').textContent = t('wallet_swap.route');
|
||||
el('preview-hint').textContent = t('wallet_swap.quote_note');
|
||||
el('consent-label').textContent = t('wallet_swap.accept_risk');
|
||||
el('confirm').textContent = t('wallet_swap.execute');
|
||||
el('check').textContent = t('wallet_swap.check_status');
|
||||
screen.append(card);
|
||||
const mainnet = getSolanaCluster() === 'mainnet-beta';
|
||||
const endpoint = state.entrySettings.solanaServer;
|
||||
let destroyed = false;
|
||||
let busy = false;
|
||||
let walletAddress = '';
|
||||
let balances = { solLamports: null, usdtAtomic: null };
|
||||
let lastQuote = null;
|
||||
let lastAmount = '';
|
||||
let lastCurrency = '';
|
||||
let blocked = false;
|
||||
|
||||
const status = (s) => { if (!destroyed) el('status').textContent = s || ''; };
|
||||
const showExplorer = (signature) => {
|
||||
const link = el('explorer');
|
||||
if (!signature || !/^[1-9A-HJ-NP-Za-km-z]{80,100}$/.test(signature)) { link.hidden = true; return; }
|
||||
link.href = `https://solscan.io/tx/${encodeURIComponent(signature)}`;
|
||||
link.textContent = `${t('wallet_swap.transaction')}: ${signature}`;
|
||||
link.hidden = false;
|
||||
};
|
||||
const resetQuote = () => {
|
||||
lastQuote = null;
|
||||
el('preview').hidden = true;
|
||||
el('consent-row').hidden = true;
|
||||
el('consent').checked = false;
|
||||
el('confirm').hidden = true;
|
||||
el('confirm').disabled = true;
|
||||
};
|
||||
const setBusy = (value) => {
|
||||
busy = value;
|
||||
el('amount').disabled = value || !mainnet;
|
||||
el('from').disabled = value || !mainnet;
|
||||
el('quote').disabled = value || !mainnet || blocked;
|
||||
el('confirm').disabled = value || !lastQuote || blocked || !el('consent').checked;
|
||||
};
|
||||
const updateLimit = () => {
|
||||
el('limit').textContent = el('from').value === 'SOL' ? t('wallet_swap.sol_limit') : t('wallet_swap.usdt_limit');
|
||||
resetQuote();
|
||||
};
|
||||
el('from').addEventListener('change', updateLimit);
|
||||
el('amount').addEventListener('input', resetQuote);
|
||||
el('consent').addEventListener('change', () => { el('confirm').disabled = !el('consent').checked || blocked || busy; });
|
||||
updateLimit();
|
||||
|
||||
async function refreshBalances() {
|
||||
const login = state.session.login;
|
||||
const storagePwd = state.session.storagePwdInMemory;
|
||||
if (!login || !storagePwd) throw new Error(t('wallet_swap.session_required'));
|
||||
const wallet = await getWalletFromStoredBlockchainKey({ login, storagePwd });
|
||||
walletAddress = wallet.address;
|
||||
const [sol, usdt] = await Promise.all([getBalanceSol({ endpoint, address: walletAddress }), getUsdtBalance({ endpoint, address: walletAddress })]);
|
||||
if (destroyed) return;
|
||||
balances = { solLamports: BigInt(sol.lamports), usdtAtomic: usdt.atomic };
|
||||
el('balance-sol').textContent = `${sol.sol.toFixed(6)} SOL`;
|
||||
el('balance-usdt').textContent = `${usdt.text} USDT`;
|
||||
}
|
||||
|
||||
async function checkPrevious() {
|
||||
const pending = await getPendingSwapSignature(endpoint);
|
||||
if (destroyed) return;
|
||||
const wasBlocked = blocked;
|
||||
blocked = Boolean(pending);
|
||||
el('check').hidden = !pending;
|
||||
if (pending) {
|
||||
status(t('wallet_swap.pending'));
|
||||
showExplorer(pending);
|
||||
} else if (wasBlocked) {
|
||||
status(t('wallet_swap.pending_resolved'));
|
||||
}
|
||||
setBusy(false);
|
||||
}
|
||||
el('check').addEventListener('click', () => { void checkPrevious().catch((error) => status(error.message || String(error))); });
|
||||
if (!mainnet) {
|
||||
status(t('wallet_swap.devnet_unavailable'));
|
||||
setBusy(false);
|
||||
} else {
|
||||
void (async () => {
|
||||
try { await refreshBalances(); await checkPrevious(); }
|
||||
catch (error) { status(error.message || String(error)); }
|
||||
})();
|
||||
}
|
||||
|
||||
el('quote').addEventListener('click', async () => {
|
||||
if (busy || destroyed || blocked || !mainnet) return;
|
||||
resetQuote();
|
||||
showExplorer('');
|
||||
try {
|
||||
const { pair, amount } = validateSwapInput(el('from').value, el('amount').value, balances);
|
||||
setBusy(true);
|
||||
status(t('wallet_swap.fetching'));
|
||||
if (!walletAddress) throw new Error(t('wallet_swap.session_required'));
|
||||
const prepared = await requestSwapBuild({ inputCurrency: pair.inputCurrency, amountAtomic: amount, walletAddress });
|
||||
if (destroyed) return;
|
||||
const checked = validateSwapBuildResponse(prepared.response, pair, amount);
|
||||
lastQuote = prepared;
|
||||
lastAmount = el('amount').value;
|
||||
lastCurrency = el('from').value;
|
||||
el('receive').textContent = `${formatAtomicAmount(checked.expected, pair.outputDecimals)} ${pair.outputCurrency}`;
|
||||
el('min').textContent = `${formatAtomicAmount(checked.minimum, pair.outputDecimals)} ${pair.outputCurrency}`;
|
||||
el('preview').hidden = false;
|
||||
el('consent-row').hidden = false;
|
||||
el('confirm').hidden = false;
|
||||
status(t('wallet_swap.review'));
|
||||
} catch (error) { status(error.message || String(error)); }
|
||||
finally { if (!destroyed) setBusy(false); }
|
||||
});
|
||||
|
||||
el('confirm').addEventListener('click', async () => {
|
||||
if (busy || blocked || !lastQuote || !el('consent').checked || destroyed) return;
|
||||
if (lastCurrency !== el('from').value || lastAmount !== el('amount').value) { resetQuote(); return; }
|
||||
if (Date.now() - lastQuote.fetchedAt > 30_000) { resetQuote(); status(t('wallet_swap.stale')); return; }
|
||||
const checked = validateSwapBuildResponse(lastQuote.response, lastQuote.pair, lastQuote.amount);
|
||||
const info = `${formatAtomicAmount(lastQuote.amount, lastQuote.pair.inputDecimals)} ${lastQuote.pair.inputCurrency} → ${formatAtomicAmount(checked.expected, lastQuote.pair.outputDecimals)} ${lastQuote.pair.outputCurrency}\n${t('wallet_swap.minimum')}: ${formatAtomicAmount(checked.minimum, lastQuote.pair.outputDecimals)} ${lastQuote.pair.outputCurrency}`;
|
||||
if (!window.confirm(`${t('wallet_swap.final_warning')}\n\n${info}\n\n${t('wallet_swap.final_question')}`)) return;
|
||||
const confirmedQuote = lastQuote;
|
||||
resetQuote(); // One-shot, even if signing or RPC fails.
|
||||
setBusy(true);
|
||||
status(t('wallet_swap.executing'));
|
||||
try {
|
||||
if (await getPendingSwapSignature(endpoint)) throw new Error(t('wallet_swap.pending'));
|
||||
const wallet = await getWalletFromStoredBlockchainKey({ login: state.session.login, storagePwd: state.session.storagePwdInMemory });
|
||||
if (wallet.address !== walletAddress) throw new Error(t('wallet_swap.wallet_changed'));
|
||||
const result = await executeJupiterSwap({ endpoint, fromKeypair: wallet.keypair, prepared: confirmedQuote });
|
||||
if (!destroyed) {
|
||||
showExplorer(result.signature);
|
||||
blocked = true; // No one-click repeat from this page after success.
|
||||
status(t('wallet_swap.success'));
|
||||
await refreshBalances();
|
||||
}
|
||||
} catch (error) {
|
||||
if (!destroyed) {
|
||||
status(error.message || String(error));
|
||||
if (error.signature) { blocked = true; showExplorer(error.signature); el('check').hidden = false; }
|
||||
}
|
||||
} finally { if (!destroyed) setBusy(false); }
|
||||
});
|
||||
screen.cleanup = () => { destroyed = true; };
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
/** One dedicated transfer screen, opened from Wallet or an existing DM contact. */
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { getBalanceSol, getWalletFromStoredBlockchainKey, transferSolLamports, solanaAddressFromPublicKeyBase64 } from '../services/solana-wallet-service.js';
|
||||
import { getUsdtAsset, getUsdtBalance, toAtomicAmount, formatAtomicAmount, transferUsdt } from '../services/solana-usdt-service.js';
|
||||
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
||||
import { readShineUserPda } from '../services/shine-user-pda-service.js';
|
||||
import { bytesToBase58 } from '../services/crypto-utils.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
import { makeSolanaExplorerTxUrl } from '../services/solana-rpc-gateway.js';
|
||||
|
||||
export const pageMeta = { id: 'wallet-transfer-view', get title() { return t('wallet_multi.transfer_title'); } };
|
||||
|
||||
/** Use the blockchain public key, never clientKey (DM) or rootKey. */
|
||||
export async function resolveContactBlockchainAddress(login, endpoint) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
if (!cleanLogin) throw new Error('Не указан получатель');
|
||||
try {
|
||||
const pda = await readShineUserPda({ login: cleanLogin, solanaEndpoint: endpoint });
|
||||
const latest = pda?.forks?.at(-1)?.blockchainKey;
|
||||
if (latest?.length === 32) return bytesToBase58(latest);
|
||||
} catch { /* A Free account may not have a paid Solana PDA. */ }
|
||||
const user = await authService.getUser(cleanLogin);
|
||||
if (!user?.exists || !user.blockchainKey) throw new Error('Не удалось получить blockchainKey получателя');
|
||||
return solanaAddressFromPublicKeyBase64(user.blockchainKey);
|
||||
}
|
||||
|
||||
export function render({ navigate, chrome, route }) {
|
||||
const recipientFromRoute = String(route?.params?.recipientLogin || '').trim();
|
||||
const backTarget = recipientFromRoute ? `chat/${encodeURIComponent(recipientFromRoute)}` : 'wallet';
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('wallet_multi.transfer_title'),
|
||||
back: { label: '←', onClick: () => navigate(backTarget) },
|
||||
}));
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack wallet-transfer-screen';
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack wallet-transfer-card';
|
||||
card.innerHTML = `
|
||||
<h2 class="wallet-transfer-heading"></h2>
|
||||
<div class="wallet-transfer-balances">
|
||||
<div class="wallet-transfer-balance"><span>SOL</span><strong data-balance-sol>—</strong></div>
|
||||
<div class="wallet-transfer-balance"><span data-usdt-name>USDT</span><strong data-balance-usdt>—</strong></div>
|
||||
</div>
|
||||
<label class="wallet-transfer-field"><span data-currency-label></span><select class="input wallet-transfer-select" data-currency><option value="SOL">SOL</option><option value="USDT">USDT</option></select></label>
|
||||
<label class="wallet-transfer-field"><span data-amount-label></span><input class="input" data-amount type="text" inputmode="decimal" autocomplete="off" placeholder="0.01" /></label>
|
||||
<div class="wallet-transfer-selected" data-selected hidden></div>
|
||||
<label class="wallet-transfer-field"><span data-recipient-label></span><input class="input" data-recipient type="text" spellcheck="false" autocomplete="off" placeholder="Solana address (Base58)" /></label>
|
||||
<label class="wallet-transfer-notice" data-notify-row hidden><input type="checkbox" data-notify /><span data-notify-label></span></label>
|
||||
<p class="meta-muted wallet-transfer-hint" data-hint></p>
|
||||
<button type="button" class="primary-btn wallet-transfer-submit" data-send></button>
|
||||
<p class="meta-muted wallet-transfer-status" data-status role="status" aria-live="polite"></p>
|
||||
`;
|
||||
const q = (selector) => card.querySelector(`[data-${selector}]`);
|
||||
q('currency-label').textContent = t('wallet_multi.asset');
|
||||
q('amount-label').textContent = t('wallet_multi.amount');
|
||||
q('recipient-label').textContent = t('wallet_multi.recipient');
|
||||
q('notify-label').textContent = t('wallet_multi.notify');
|
||||
q('notify-row').hidden = !recipientFromRoute;
|
||||
q('send').textContent = t('wallet_multi.send');
|
||||
q('hint').textContent = t('wallet_multi.no_stars');
|
||||
q('selected').textContent = '';
|
||||
card.querySelector('.wallet-transfer-heading').textContent = t('wallet_multi.transfer_title');
|
||||
screen.append(card);
|
||||
let disposed = false;
|
||||
let busy = false;
|
||||
// A chat-bound transfer has exactly one recipient; the wallet flow accepts only an address.
|
||||
const recipientLogin = recipientFromRoute;
|
||||
let selectedAddress = '';
|
||||
let resolvingRecipient = Boolean(recipientLogin);
|
||||
let address = '';
|
||||
let usdt = { available: false, atomic: 0n, asset: getUsdtAsset() };
|
||||
const endpoint = state.entrySettings.solanaServer;
|
||||
const setStatus = (value) => { if (!disposed) q('status').textContent = value; };
|
||||
const setBusy = (value) => {
|
||||
busy = value;
|
||||
q('currency').disabled = value;
|
||||
q('amount').disabled = value;
|
||||
q('recipient').disabled = value;
|
||||
q('notify').disabled = value;
|
||||
q('send').disabled = value || resolvingRecipient || (Boolean(recipientLogin) && !selectedAddress) || q('send').dataset.completed === 'true';
|
||||
};
|
||||
if (recipientLogin) {
|
||||
q('selected').hidden = false;
|
||||
q('selected').textContent = `${t('wallet_multi.contact')}: ${recipientLogin}`;
|
||||
q('recipient').readOnly = true;
|
||||
q('recipient').value = t('wallet_multi.resolving');
|
||||
q('send').disabled = true;
|
||||
void resolveContactBlockchainAddress(recipientLogin, endpoint)
|
||||
.then((resolved) => {
|
||||
if (disposed) return;
|
||||
selectedAddress = resolved;
|
||||
q('recipient').value = resolved;
|
||||
setStatus('');
|
||||
})
|
||||
.catch((error) => {
|
||||
if (disposed) return;
|
||||
q('recipient').value = '';
|
||||
setStatus(error.message || String(error));
|
||||
})
|
||||
.finally(() => {
|
||||
if (disposed) return;
|
||||
resolvingRecipient = false;
|
||||
q('send').disabled = busy || !selectedAddress;
|
||||
});
|
||||
}
|
||||
|
||||
const refreshBalances = async () => {
|
||||
try {
|
||||
const wallet = await getWalletFromStoredBlockchainKey({
|
||||
login: state.session.login, storagePwd: state.session.storagePwdInMemory,
|
||||
});
|
||||
if (disposed) return;
|
||||
address = wallet.address;
|
||||
const [sol, usdtResult] = await Promise.allSettled([
|
||||
getBalanceSol({ endpoint, address }), getUsdtBalance({ endpoint, address }),
|
||||
]);
|
||||
if (disposed) return;
|
||||
if (sol.status === 'fulfilled') q('balance-sol').textContent = `${sol.value.sol.toFixed(6)} SOL`;
|
||||
if (usdtResult.status === 'fulfilled') {
|
||||
usdt = usdtResult.value;
|
||||
q('balance-usdt').textContent = usdt.available ? `${usdt.text} ${usdt.asset.label}` : t('wallet_multi.test_mint_missing');
|
||||
} else q('balance-usdt').textContent = t('wallet_multi.balance_unavailable');
|
||||
q('usdt-name').textContent = usdt.asset.label;
|
||||
if (!usdt.available) q('currency').querySelector('option[value="USDT"]').disabled = true;
|
||||
q('hint').textContent = usdt.asset.test ? `${t('wallet_multi.no_stars')} ${t('wallet_multi.devnet_disclaimer')}` : t('wallet_multi.no_stars');
|
||||
} catch (error) { setStatus(error.message || String(error)); }
|
||||
};
|
||||
void refreshBalances();
|
||||
|
||||
q('send').addEventListener('click', async () => {
|
||||
if (busy || disposed) return;
|
||||
const currency = q('currency').value;
|
||||
const amountText = q('amount').value;
|
||||
const messageWanted = q('notify').checked;
|
||||
let toAddress = String(q('recipient').value || '').trim();
|
||||
let atomic;
|
||||
try {
|
||||
atomic = toAtomicAmount(amountText, currency === 'SOL' ? 9 : 6);
|
||||
if (!state.session.login || !state.session.storagePwdInMemory) throw new Error('Не найдена авторизованная сессия SHiNE');
|
||||
if (currency === 'SOL' && atomic > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error('Сумма SOL слишком большая');
|
||||
if (recipientLogin) {
|
||||
if (!selectedAddress || resolvingRecipient) throw new Error('Адрес получателя ещё не получен');
|
||||
// Refresh the binding at signing time, protect against stale/rotated blockchain keys.
|
||||
toAddress = await resolveContactBlockchainAddress(recipientLogin, endpoint);
|
||||
if (selectedAddress && toAddress !== selectedAddress) {
|
||||
q('recipient').value = toAddress;
|
||||
selectedAddress = toAddress;
|
||||
throw new Error('Блокчейн-ключ получателя изменился. Проверьте новый адрес и повторите отправку.');
|
||||
}
|
||||
}
|
||||
const solana = await loadSolanaWeb3();
|
||||
const target = new solana.PublicKey(toAddress).toBase58();
|
||||
if (address && target === address) throw new Error('Нельзя переводить самому себе');
|
||||
// A wallet-to-wallet payment must never be sent to a mint, token account or executable program.
|
||||
if (!solana.PublicKey.isOnCurve(new solana.PublicKey(target).toBytes())) {
|
||||
throw new Error('Получатель должен быть обычным кошельком Solana (не PDA программы)');
|
||||
}
|
||||
const recipientInfo = await new solana.Connection(endpoint, 'confirmed').getAccountInfo(new solana.PublicKey(target), 'confirmed');
|
||||
if (recipientInfo && (recipientInfo.executable || !recipientInfo.owner.equals(solana.SystemProgram.programId))) {
|
||||
throw new Error('Адрес получателя не является обычным кошельком Solana');
|
||||
}
|
||||
if (currency === 'USDT' && !usdt.available) throw new Error('USDT в этой сети не настроен');
|
||||
const display = `${formatAtomicAmount(atomic, currency === 'SOL' ? 9 : 6)} ${currency === 'SOL' ? 'SOL' : usdt.asset.label}`;
|
||||
const contactLabel = recipientLogin ? `${recipientLogin}\n${target}` : target;
|
||||
if (!window.confirm(`${t('wallet_multi.confirm')}\n${display}\n${contactLabel}`)) return;
|
||||
setBusy(true);
|
||||
setStatus(t('wallet_multi.sending'));
|
||||
const wallet = await getWalletFromStoredBlockchainKey({ login: state.session.login, storagePwd: state.session.storagePwdInMemory });
|
||||
if (wallet.address === target) throw new Error('Нельзя переводить самому себе');
|
||||
const result = currency === 'SOL'
|
||||
? await transferSolLamports({ endpoint, fromKeypair: wallet.keypair, toAddress: target, amountLamports: atomic })
|
||||
: await transferUsdt({ endpoint, fromKeypair: wallet.keypair, toAddress: target, amountAtomic: atomic });
|
||||
// The transfer is confirmed even if the user navigated away. Send requested DM anyway.
|
||||
if (!disposed) {
|
||||
setStatus(`${t('wallet_multi.success')}\n${result.signature}`);
|
||||
q('send').textContent = t('wallet_multi.sent');
|
||||
q('send').dataset.completed = 'true';
|
||||
}
|
||||
if (messageWanted && recipientLogin) {
|
||||
try {
|
||||
await authService.sendDirectMessage({
|
||||
login: state.session.login, toLogin: recipientLogin,
|
||||
storagePwd: state.session.storagePwdInMemory,
|
||||
text: `${t('wallet_multi.dm_prefix')} ${display}\n${t('wallet_multi.dm_signature')}: ${result.signature}\n${t('wallet_multi.dm_explorer')}: ${makeSolanaExplorerTxUrl(result.signature, endpoint)}`,
|
||||
});
|
||||
if (!disposed) setStatus(`${t('wallet_multi.success')}\n${result.signature}\n${t('wallet_multi.notice_sent')}`);
|
||||
} catch (error) {
|
||||
if (!disposed) setStatus(`${t('wallet_multi.success')}\n${result.signature}\n${t('wallet_multi.notice_failed')}: ${error.message || error}`);
|
||||
}
|
||||
}
|
||||
// Prevent accidental re-send on the success screen; user must navigate away to make another transfer.
|
||||
if (!disposed) {
|
||||
q('send').disabled = true;
|
||||
q('send').dataset.completed = 'true';
|
||||
void refreshBalances();
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error?.message || String(error);
|
||||
if (/timed out|timeout|expired|confirmation/i.test(message)) {
|
||||
// RPC timeout is not evidence that funds were not moved. Avoid duplicate send.
|
||||
setStatus(`${t('wallet_multi.uncertain')}\n${message}`);
|
||||
q('send').dataset.completed = 'true';
|
||||
} else setStatus(message);
|
||||
} finally {
|
||||
if (!disposed) {
|
||||
setBusy(false);
|
||||
if (q('send').dataset.completed === 'true') q('send').disabled = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
screen.cleanup = () => { disposed = true; };
|
||||
return screen;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user