SHA256
CORE/CONTENT test5593 и адаптация UI
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,980 @@
|
||||
import { preparePublicFile } from '../services/file-preparation-service.js';
|
||||
import { formatDateTime, formatNumber } from '../i18n/format.js';
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import {
|
||||
buildArweaveDataUrl,
|
||||
getArweaveUploadPrice,
|
||||
loadArweaveFileMetadata,
|
||||
sha256HexFromArrayBuffer,
|
||||
uploadArweaveFile,
|
||||
validateArweaveTxId,
|
||||
} from '../services/arweave-file-service.js';
|
||||
import { addArweaveWalletSecret, getArweaveBalance, getArweaveWalletChoices } from '../services/arweave-wallet-service.js';
|
||||
import { escapeHtml, formatBytes, normalizeAttachment } from '../services/attachment-format.js';
|
||||
import { getStoredSolanaWalletChoices } from '../services/solana-wallet-service.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
import {
|
||||
estimateTurboUploadPrice,
|
||||
formatTurboCredits,
|
||||
getFreeTurboUploadBytesLimit,
|
||||
getTurboBalanceForStoredSolanaKey,
|
||||
topUpTurboWithSolana,
|
||||
uploadFileWithTurbo,
|
||||
} from '../services/turbo-upload-service.js';
|
||||
|
||||
const HISTORY_KEY = 'shine-ui-arweave-attachment-history-v1';
|
||||
const LAST_WALLET_KEY_PREFIX = 'shine-ui-arweave-last-wallet-v1:';
|
||||
const MAX_HISTORY_ITEMS = 100;
|
||||
const RECENT_UPLOAD_MS = 20 * 60 * 1000;
|
||||
|
||||
function normalizeHistoryItem(input = {}) {
|
||||
const item = normalizeAttachment(input);
|
||||
const placedInShineAtMs = Number(input.placedInShineAtMs || 0) || 0;
|
||||
const purpose = String(input.purpose || '').trim() === 'avatar' ? 'avatar' : 'attachment';
|
||||
return {
|
||||
...item,
|
||||
purpose,
|
||||
pendingPlacement: input.pendingPlacement === true && !placedInShineAtMs,
|
||||
placedInShineAtMs,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
export function readArweaveAttachmentHistory(login) {
|
||||
try {
|
||||
const raw = sessionStorage.getItem(HISTORY_KEY);
|
||||
const parsed = raw ? JSON.parse(raw) : {};
|
||||
const key = String(login || '').trim().toLowerCase();
|
||||
const rows = Array.isArray(parsed?.[key]) ? parsed[key] : [];
|
||||
return rows.map((item) => normalizeHistoryItem(item)).filter(Boolean);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function saveArweaveAttachmentHistory(login, rows) {
|
||||
try {
|
||||
const key = String(login || '').trim().toLowerCase();
|
||||
const raw = sessionStorage.getItem(HISTORY_KEY);
|
||||
const parsed = raw ? JSON.parse(raw) : {};
|
||||
parsed[key] = (Array.isArray(rows) ? rows : [])
|
||||
.map((item) => normalizeHistoryItem(item))
|
||||
.slice(0, MAX_HISTORY_ITEMS);
|
||||
sessionStorage.setItem(HISTORY_KEY, JSON.stringify(parsed));
|
||||
} catch {
|
||||
// ignore sessionStorage errors
|
||||
}
|
||||
}
|
||||
|
||||
export function clearArweaveAttachmentHistory(login) {
|
||||
saveArweaveAttachmentHistory(login, []);
|
||||
}
|
||||
|
||||
export function addArweaveAttachmentToHistory(login, attachment, { pendingPlacement = undefined, markPlaced = false } = {}) {
|
||||
const item = normalizeHistoryItem(attachment);
|
||||
const rows = readArweaveAttachmentHistory(login);
|
||||
const existing = rows.find((row) => row.ar === item.ar) || {};
|
||||
const placedInShineAtMs = markPlaced
|
||||
? Date.now()
|
||||
: Number(existing.placedInShineAtMs || item.placedInShineAtMs || 0) || 0;
|
||||
const nextPendingPlacement = pendingPlacement === undefined
|
||||
? (existing.pendingPlacement === true && !placedInShineAtMs)
|
||||
: (!!pendingPlacement && !placedInShineAtMs);
|
||||
const nextItem = {
|
||||
...item,
|
||||
pendingPlacement: nextPendingPlacement,
|
||||
placedInShineAtMs,
|
||||
};
|
||||
const nextRows = rows.filter((row) => row.ar !== item.ar);
|
||||
nextRows.unshift(nextItem);
|
||||
saveArweaveAttachmentHistory(login, nextRows);
|
||||
return nextItem;
|
||||
}
|
||||
|
||||
export function markArweaveAttachmentPlaced(login, attachment) {
|
||||
const item = normalizeHistoryItem(attachment);
|
||||
const rows = readArweaveAttachmentHistory(login);
|
||||
const existing = rows.find((row) => row.ar === item.ar) || {};
|
||||
const nextItem = {
|
||||
...item,
|
||||
uploadedAtMs: item.uploadedAtMs || existing.uploadedAtMs || Date.now(),
|
||||
pendingPlacement: false,
|
||||
placedInShineAtMs: Number(existing.placedInShineAtMs || 0) || Date.now(),
|
||||
};
|
||||
const nextRows = rows.filter((row) => row.ar !== item.ar);
|
||||
nextRows.unshift(nextItem);
|
||||
saveArweaveAttachmentHistory(login, nextRows);
|
||||
return nextItem;
|
||||
}
|
||||
|
||||
export function formatArweaveHistoryTime(ms) {
|
||||
const value = Number(ms || 0);
|
||||
if (!Number.isFinite(value) || value <= 0) return '–';
|
||||
const diffMs = Date.now() - value;
|
||||
if (diffMs >= 0 && diffMs < RECENT_UPLOAD_MS) {
|
||||
const minutes = Math.max(1, Math.floor(diffMs / 60000));
|
||||
return t('screens.arweave_attachment_manager.text_065', { value1: minutes });
|
||||
}
|
||||
return formatDateTime(new Date(value));
|
||||
}
|
||||
|
||||
export function formatArweaveHistoryDateTime(ms) {
|
||||
const value = Number(ms || 0);
|
||||
if (!Number.isFinite(value) || value <= 0) return '–';
|
||||
return formatDateTime(new Date(value));
|
||||
}
|
||||
|
||||
export async function getArweaveAttachmentAvailability({ gateway, attachment } = {}) {
|
||||
const item = normalizeAttachment(attachment);
|
||||
const url = buildArweaveDataUrl({ gateway, txId: item.ar });
|
||||
try {
|
||||
const response = await fetch(url, { method: 'HEAD', cache: 'no-store' });
|
||||
if (response.ok) return { status: 'available', label: t('screens.arweave_attachment_manager.text_001'), url };
|
||||
} catch {
|
||||
// gateway может временно не отвечать или блокировать HEAD; для UI это всё равно недоступно.
|
||||
}
|
||||
const ageMs = Date.now() - Number(item.uploadedAtMs || 0);
|
||||
if (Number.isFinite(ageMs) && ageMs >= 0 && ageMs < RECENT_UPLOAD_MS) {
|
||||
return { status: 'pending', label: t('screens.arweave_attachment_manager.text_002'), url };
|
||||
}
|
||||
return { status: 'unavailable', label: t('screens.arweave_attachment_manager.text_003'), url };
|
||||
}
|
||||
|
||||
function setText(node, text) {
|
||||
if (node) node.textContent = String(text || '');
|
||||
}
|
||||
|
||||
function shortAddress(value) {
|
||||
const raw = String(value || '').trim();
|
||||
if (raw.length <= 16) return raw;
|
||||
return `${raw.slice(0, 8)}...${raw.slice(-6)}`;
|
||||
}
|
||||
|
||||
function lastWalletStorageKey(login) {
|
||||
return `${LAST_WALLET_KEY_PREFIX}${String(login || '').trim().toLowerCase() || 'anonymous'}`;
|
||||
}
|
||||
|
||||
function readLastWalletId(login) {
|
||||
try {
|
||||
return sessionStorage.getItem(lastWalletStorageKey(login)) || '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function writeLastWalletId(login, walletId) {
|
||||
try {
|
||||
const clean = String(walletId || '').trim();
|
||||
if (clean) sessionStorage.setItem(lastWalletStorageKey(login), clean);
|
||||
} catch {
|
||||
// Если sessionStorage недоступен, выбор сохраняется хотя бы в текущем окне менеджера.
|
||||
}
|
||||
}
|
||||
|
||||
export async function prepareAvatarImageFile(file) {
|
||||
const source = file instanceof File ? file : null;
|
||||
if (!source) throw new Error(t('screens.arweave_attachment_manager.text_045'));
|
||||
const dataUrl = await new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(String(reader.result || ''));
|
||||
reader.onerror = () => reject(new Error(t('screens.arweave_attachment_manager.text_046')));
|
||||
reader.readAsDataURL(source);
|
||||
});
|
||||
const image = await new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
img.onload = () => resolve(img);
|
||||
img.onerror = () => reject(new Error(t('screens.arweave_attachment_manager.text_047')));
|
||||
img.src = dataUrl;
|
||||
});
|
||||
const side = Math.min(image.naturalWidth || image.width, image.naturalHeight || image.height);
|
||||
if (!side || side <= 0) throw new Error(t('screens.arweave_attachment_manager.text_048'));
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 512;
|
||||
canvas.height = 512;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) throw new Error(t('screens.arweave_attachment_manager.text_049'));
|
||||
const sx = Math.max(0, ((image.naturalWidth || image.width) - side) / 2);
|
||||
const sy = Math.max(0, ((image.naturalHeight || image.height) - side) / 2);
|
||||
ctx.drawImage(image, sx, sy, side, side, 0, 0, 512, 512);
|
||||
const blob = await new Promise((resolve) => canvas.toBlob(resolve, 'image/jpeg', 0.9));
|
||||
if (!blob) throw new Error(t('screens.arweave_attachment_manager.text_050'));
|
||||
return new File([blob], 'avatar.jpg', { type: 'image/jpeg', lastModified: Date.now() });
|
||||
}
|
||||
|
||||
export function openArweaveAttachmentManager({
|
||||
login,
|
||||
storagePwd,
|
||||
gateway,
|
||||
onSelect,
|
||||
selectedTxIds = [],
|
||||
historyOnly = false,
|
||||
persistToHistory = true,
|
||||
allowHistorySelection = true,
|
||||
allowExistingTxInput = true,
|
||||
mode = 'attachment',
|
||||
historyPurpose = '',
|
||||
uploadTransport = 'turbo',
|
||||
turboKeySource = 'blockchain',
|
||||
dialogTitle = '',
|
||||
uploadButtonLabel = '',
|
||||
initialFile = null,
|
||||
initialSha256 = '',
|
||||
initialName = '',
|
||||
fixedFile = false,
|
||||
autoOpenFileDialog = false,
|
||||
shineType = '',
|
||||
extraUploadTags = [],
|
||||
signal = null,
|
||||
hostElement = null,
|
||||
embedded = false,
|
||||
} = {}) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const cleanStoragePwd = String(storagePwd || '').trim();
|
||||
const cleanGateway = String(gateway || 'https://arweave.net').trim();
|
||||
if (!cleanLogin || !cleanStoragePwd) return Promise.reject(new Error(t('screens.arweave_attachment_manager.text_051')));
|
||||
|
||||
const embeddedHost = hostElement instanceof HTMLElement ? hostElement : null;
|
||||
const isEmbedded = Boolean(embeddedHost || embedded);
|
||||
const root = embeddedHost || document.createElement('div');
|
||||
if (!embeddedHost) {
|
||||
root.className = 'ar-attachment-manager-root';
|
||||
document.body.append(root);
|
||||
} else {
|
||||
root.classList.add('ar-attachment-manager-embedded-root');
|
||||
}
|
||||
|
||||
let closed = false;
|
||||
let wallets = [];
|
||||
let turboKeyChoices = [];
|
||||
let selectedWalletId = readLastWalletId(cleanLogin) || 'derived-blockchain-key';
|
||||
const selectedTurboKeySource = 'blockchain';
|
||||
let selectedUploadTransport = String(uploadTransport || '').trim().toLowerCase() === 'arweave' ? 'arweave' : 'turbo';
|
||||
let selectedFile = null;
|
||||
let selectedSha256 = '';
|
||||
let selectedPrepared = null;
|
||||
let priceInfo = null;
|
||||
let balanceInfo = null;
|
||||
let autoOpenedFileDialogOnce = false;
|
||||
const isAvatarMode = String(mode || '') === 'avatar';
|
||||
if (isAvatarMode && !String(uploadTransport || '').trim()) {
|
||||
selectedUploadTransport = 'turbo';
|
||||
}
|
||||
const historyPurposeMode = String(historyPurpose || '').trim();
|
||||
const purposeFilter = isAvatarMode || historyPurposeMode === 'avatar' ? 'avatar' : 'attachment';
|
||||
const selectedTxIdSet = new Set((Array.isArray(selectedTxIds) ? selectedTxIds : []).map((item) => String(item || '').trim()).filter(Boolean));
|
||||
const effectiveDialogTitle = String(dialogTitle || '').trim();
|
||||
const effectiveUploadButtonLabel = String(uploadButtonLabel || '').trim();
|
||||
const forcedShineType = String(shineType || '').trim();
|
||||
const normalizedExtraUploadTags = Array.isArray(extraUploadTags)
|
||||
? extraUploadTags.filter((item) => item?.name && item?.value)
|
||||
: [];
|
||||
if (initialFile instanceof File) {
|
||||
selectedFile = initialFile;
|
||||
if (initialSha256) selectedSha256 = String(initialSha256 || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function isTurboUpload() {
|
||||
return selectedUploadTransport === 'turbo';
|
||||
}
|
||||
|
||||
function selectedWallet() {
|
||||
return wallets.find((item) => String(item.id) === String(selectedWalletId)) || wallets[0] || null;
|
||||
}
|
||||
|
||||
function close(resolve, result = null) {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (embeddedHost) root.replaceChildren();
|
||||
else root.remove();
|
||||
resolve(result);
|
||||
}
|
||||
|
||||
function finish(resolve, attachment, { pendingPlacement = undefined } = {}) {
|
||||
if (closed) return;
|
||||
const item = persistToHistory
|
||||
? addArweaveAttachmentToHistory(cleanLogin, attachment, {
|
||||
pendingPlacement,
|
||||
markPlaced: false,
|
||||
})
|
||||
: {
|
||||
...attachment,
|
||||
...normalizeAttachment(attachment),
|
||||
};
|
||||
if (!pendingPlacement && typeof onSelect === 'function') onSelect(item);
|
||||
close(resolve, item);
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const onAbort = () => close(resolve, null);
|
||||
if (signal?.aborted) { onAbort(); return; }
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
const shellOpen = (extraClass = '') => isEmbedded
|
||||
? `<div class="stack ar-attachment-manager-card ar-attachment-manager-card--embedded ${extraClass}">`
|
||||
: `<div class="modal" data-ar-attach-modal="true"><div class="modal-card stack ar-attachment-manager-card ${extraClass}">`;
|
||||
const shellClose = () => isEmbedded ? '</div>' : '</div></div>';
|
||||
const bindBackdrop = () => {
|
||||
if (isEmbedded) return;
|
||||
const modal = root.querySelector('[data-ar-attach-modal="true"]');
|
||||
modal?.addEventListener('click', (event) => {
|
||||
if (event.target === modal) close(resolve, null);
|
||||
});
|
||||
};
|
||||
|
||||
const renderWalletOptions = () => wallets.map((wallet) => (
|
||||
`<option value="${escapeHtml(wallet.id)}">${escapeHtml(wallet.isDefault ? t('screens.arweave_attachment_manager.text_013') : wallet.label)} · ${escapeHtml(shortAddress(wallet.address))}</option>`
|
||||
)).join('');
|
||||
|
||||
const loadWallets = async (errorEl = null) => {
|
||||
try {
|
||||
wallets = await getArweaveWalletChoices({ login: cleanLogin, storagePwd: cleanStoragePwd });
|
||||
if (!wallets.some((item) => String(item.id) === String(selectedWalletId))) {
|
||||
selectedWalletId = String(wallets[0]?.id || 'derived-blockchain-key');
|
||||
}
|
||||
writeLastWalletId(cleanLogin, selectedWalletId);
|
||||
} catch (error) {
|
||||
setText(errorEl, error?.message || t('screens.arweave_attachment_manager.text_052'));
|
||||
}
|
||||
};
|
||||
|
||||
const loadTurboKeyChoices = async (errorEl = null) => {
|
||||
try {
|
||||
turboKeyChoices = await getStoredSolanaWalletChoices({
|
||||
login: cleanLogin,
|
||||
storagePwd: cleanStoragePwd,
|
||||
});
|
||||
if (!turboKeyChoices.some((item) => String(item.keySource) === 'blockchain')) {
|
||||
throw new Error(t('screens.arweave_attachment_manager.text_053'));
|
||||
}
|
||||
} catch (error) {
|
||||
setText(errorEl, error?.message || t('screens.arweave_attachment_manager.text_054'));
|
||||
}
|
||||
};
|
||||
|
||||
const updateBalanceButton = () => {
|
||||
const button = root.querySelector('[data-action="check-balance"]');
|
||||
if (!button) return;
|
||||
if (isTurboUpload()) {
|
||||
button.textContent = balanceInfo
|
||||
? t('screens.arweave_attachment_manager.text_066', { value1: formatTurboCredits(balanceInfo.effectiveCredits, 6) })
|
||||
: t('screens.arweave_attachment_manager.text_014');
|
||||
return;
|
||||
}
|
||||
button.textContent = balanceInfo
|
||||
? t('screens.arweave_attachment_manager.text_067', { value1: formatNumber(Number(balanceInfo.ar || 0), { maximumFractionDigits: 6 }) })
|
||||
: t('screens.arweave_attachment_manager.text_015');
|
||||
};
|
||||
|
||||
const renderTurboMeta = (mainMetaEl) => {
|
||||
updateBalanceButton();
|
||||
if (!mainMetaEl) return;
|
||||
if (!selectedFile) {
|
||||
mainMetaEl.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
const uploadPrice = priceInfo ? `${formatTurboCredits(priceInfo.credits, 6)} credits` : '';
|
||||
const fileSize = formatBytes(selectedFile.size);
|
||||
const isFreeSize = Number(selectedFile.size || 0) <= getFreeTurboUploadBytesLimit();
|
||||
mainMetaEl.innerHTML = `
|
||||
<div class="ar-attachment-summary">${th('remaining.file_upload.size')}${escapeHtml(fileSize)} · ${isFreeSize
|
||||
? t('screens.arweave_attachment_manager.text_016')
|
||||
: (uploadPrice ? t('screens.arweave_attachment_manager.text_068', { value1: escapeHtml(uploadPrice) }) : t('screens.arweave_attachment_manager.text_017'))}</div>
|
||||
<details class="ar-attachment-details">
|
||||
<summary>${th('screens.arweave_attachment_manager.text_070')}</summary>
|
||||
<div>SHA-256: ${escapeHtml(selectedSha256 || '–')}</div>
|
||||
${uploadPrice ? `<div>${th('remaining.file_upload.turbo_price')}${escapeHtml(uploadPrice)}</div>` : ''}
|
||||
<div>${th('remaining.file_upload.free_up_to')}${escapeHtml(formatBytes(getFreeTurboUploadBytesLimit()))}</div>
|
||||
</details>
|
||||
`;
|
||||
};
|
||||
|
||||
const refreshTurboBalance = async (mainMetaEl, errorEl) => {
|
||||
try {
|
||||
balanceInfo = await getTurboBalanceForStoredSolanaKey({
|
||||
login: cleanLogin,
|
||||
storagePwd: cleanStoragePwd,
|
||||
keySource: selectedTurboKeySource,
|
||||
});
|
||||
renderTurboMeta(mainMetaEl);
|
||||
if (errorEl && String(errorEl.textContent || '').includes('Turbo balance')) {
|
||||
setText(errorEl, '');
|
||||
}
|
||||
} catch (error) {
|
||||
setText(errorEl, error?.message || t('screens.arweave_attachment_manager.text_055'));
|
||||
}
|
||||
};
|
||||
|
||||
const promptTurboTopUp = async (mainMetaEl, errorEl) => {
|
||||
await refreshTurboBalance(mainMetaEl, errorEl);
|
||||
const previous = document.getElementById('turbo-topup-modal');
|
||||
previous?.remove();
|
||||
const overlay = document.createElement('div');
|
||||
overlay.id = 'turbo-topup-modal';
|
||||
overlay.className = 'modal ar-balance-modal';
|
||||
const sol = String(balanceInfo?.solBalance ?? '–');
|
||||
const credits = balanceInfo ? formatTurboCredits(balanceInfo.effectiveCredits, 6) : '–';
|
||||
const address = String(balanceInfo?.address || '').trim();
|
||||
overlay.innerHTML = `
|
||||
<div class="modal-card stack ar-balance-modal__card" role="dialog" aria-modal="true">
|
||||
<h3 class="modal-title">${t('dialogs.modals.arweave_attachment_manager.label_001')}</h3>
|
||||
<p class="ar-attachment-note">${t('dialogs.modals.arweave_attachment_manager.label_002')}</p>
|
||||
<div class="ar-balance-grid">
|
||||
<div><span>${t('dialogs.modals.arweave_attachment_manager.label_003')}</span><strong>${escapeHtml(shortAddress(address || '–'))}</strong></div>
|
||||
<div><span>${t('dialogs.modals.arweave_attachment_manager.label_004')}</span><strong>${escapeHtml(sol)} SOL</strong></div>
|
||||
<div><span>${t('dialogs.modals.arweave_attachment_manager.label_005')}</span><strong>${escapeHtml(credits)}</strong></div>
|
||||
</div>
|
||||
<label class="form-field"><span>${t('dialogs.modals.arweave_attachment_manager.label_006')}</span><input class="input" data-role="amount" inputmode="decimal" value="0.01" /></label>
|
||||
<p class="inline-error" data-role="topup-error"></p>
|
||||
<div class="form-actions-grid">
|
||||
<button class="secondary-btn" type="button" data-action="cancel">${t('dialogs.modals.arweave_attachment_manager.label_007')}</button>
|
||||
<button class="primary-btn" type="button" data-action="confirm">${t('dialogs.modals.arweave_attachment_manager.label_008')}</button>
|
||||
</div>
|
||||
</div>`;
|
||||
document.body.append(overlay);
|
||||
await new Promise((done) => {
|
||||
const finish = () => { overlay.remove(); done(); };
|
||||
overlay.querySelector('[data-action="cancel"]')?.addEventListener('click', finish);
|
||||
overlay.addEventListener('click', (event) => { if (event.target === overlay) finish(); });
|
||||
overlay.querySelector('[data-action="confirm"]')?.addEventListener('click', async () => {
|
||||
const amount = String(overlay.querySelector('[data-role="amount"]')?.value || '').trim();
|
||||
const localError = overlay.querySelector('[data-role="topup-error"]');
|
||||
const btn = overlay.querySelector('[data-action="confirm"]');
|
||||
if (btn) btn.disabled = true;
|
||||
setText(localError, t('screens.arweave_attachment_manager.text_004'));
|
||||
try {
|
||||
const result = await topUpTurboWithSolana({
|
||||
login: cleanLogin,
|
||||
storagePwd: cleanStoragePwd,
|
||||
keySource: selectedTurboKeySource,
|
||||
amountSol: amount,
|
||||
});
|
||||
await refreshTurboBalance(mainMetaEl, errorEl);
|
||||
setText(errorEl, t('screens.arweave_attachment_manager.text_069', { value1: result.txId || t('screens.arweave_attachment_manager.text_056') }));
|
||||
finish();
|
||||
} catch (error) {
|
||||
setText(localError, error?.message || t('screens.arweave_attachment_manager.text_057'));
|
||||
if (btn) btn.disabled = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const showArweaveTopUp = async (mainMetaEl, errorEl) => {
|
||||
const wallet = selectedWallet();
|
||||
if (!wallet?.address) {
|
||||
setText(errorEl, t('screens.arweave_attachment_manager.text_005'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
balanceInfo = await getArweaveBalance({ gateway: cleanGateway, address: wallet.address });
|
||||
renderArweaveMeta(mainMetaEl);
|
||||
} catch {
|
||||
// Адрес всё равно можно показать для пополнения.
|
||||
}
|
||||
const previous = document.getElementById('arweave-topup-modal');
|
||||
previous?.remove();
|
||||
const overlay = document.createElement('div');
|
||||
overlay.id = 'arweave-topup-modal';
|
||||
overlay.className = 'modal ar-balance-modal';
|
||||
overlay.innerHTML = `
|
||||
<div class="modal-card stack ar-balance-modal__card" role="dialog" aria-modal="true">
|
||||
<h3 class="modal-title">${t('dialogs.modals.arweave_attachment_manager.label_009')}</h3>
|
||||
<p class="ar-attachment-note">${t('dialogs.modals.arweave_attachment_manager.label_010')}</p>
|
||||
<div class="ar-wallet-address" data-role="address">${escapeHtml(wallet.address)}</div>
|
||||
<div class="ar-balance-grid"><div><span>${t('dialogs.modals.arweave_attachment_manager.label_011')}</span><strong>${escapeHtml(formatNumber(Number(balanceInfo?.ar || 0), { maximumFractionDigits: 6 }))} AR</strong></div></div>
|
||||
<div class="form-actions-grid">
|
||||
<button class="secondary-btn" type="button" data-action="copy">${t('dialogs.modals.arweave_attachment_manager.label_012')}</button>
|
||||
<button class="primary-btn" type="button" data-action="close">${t('dialogs.modals.arweave_attachment_manager.label_013')}</button>
|
||||
</div>
|
||||
</div>`;
|
||||
document.body.append(overlay);
|
||||
overlay.querySelector('[data-action="copy"]')?.addEventListener('click', async () => {
|
||||
try { await navigator.clipboard.writeText(wallet.address); } catch { /* ignore */ }
|
||||
});
|
||||
const closeOverlay = () => overlay.remove();
|
||||
overlay.querySelector('[data-action="close"]')?.addEventListener('click', closeOverlay);
|
||||
overlay.addEventListener('click', (event) => { if (event.target === overlay) closeOverlay(); });
|
||||
};
|
||||
|
||||
const renderArweaveMeta = (mainMetaEl) => {
|
||||
updateBalanceButton();
|
||||
if (!mainMetaEl) return;
|
||||
if (!selectedFile) {
|
||||
mainMetaEl.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
mainMetaEl.innerHTML = `
|
||||
${isAvatarMode ? '' : `<div>${th('remaining.file_upload.name')}${escapeHtml(selectedFile.name || 'file')}</div>`}
|
||||
<div>${th('remaining.file_upload.size_label')}${escapeHtml(formatBytes(selectedFile.size || 0))}</div>
|
||||
<div>SHA-256: ${escapeHtml(selectedSha256 || '–')}</div>
|
||||
${priceInfo ? `<div>${th('remaining.file_upload.price')}${escapeHtml(formatNumber(Number(priceInfo.ar || 0), { maximumFractionDigits: 6 }))} AR</div>` : ''}
|
||||
`;
|
||||
};
|
||||
|
||||
const recalculateArweaveState = async (mainMetaEl, errorEl, uploadBtn) => {
|
||||
uploadBtn.disabled = true;
|
||||
priceInfo = null;
|
||||
balanceInfo = null;
|
||||
setText(errorEl, '');
|
||||
if (!selectedFile || !selectedSha256) {
|
||||
setText(mainMetaEl, '');
|
||||
return;
|
||||
}
|
||||
const wallet = selectedWallet();
|
||||
if (!wallet?.address) throw new Error(t('screens.arweave_attachment_manager.text_058'));
|
||||
const mainPrice = await getArweaveUploadPrice({ gateway: cleanGateway, byteLength: selectedFile.size });
|
||||
const totalWinston = BigInt(mainPrice.winston);
|
||||
balanceInfo = await getArweaveBalance({ gateway: cleanGateway, address: wallet.address });
|
||||
priceInfo = {
|
||||
ar: Number(totalWinston) / 1e12,
|
||||
winston: totalWinston.toString(),
|
||||
};
|
||||
renderArweaveMeta(mainMetaEl);
|
||||
const hasFunds = BigInt(balanceInfo.winston) >= totalWinston;
|
||||
if (!hasFunds) {
|
||||
setText(errorEl, t('screens.arweave_attachment_manager.text_006'));
|
||||
return;
|
||||
}
|
||||
uploadBtn.disabled = false;
|
||||
};
|
||||
|
||||
const refreshTurboStateForCurrentFile = async (mainMetaEl, errorEl, uploadBtn) => {
|
||||
uploadBtn.disabled = true;
|
||||
priceInfo = null;
|
||||
balanceInfo = null;
|
||||
setText(errorEl, '');
|
||||
if (!selectedFile || !selectedSha256) {
|
||||
renderTurboMeta(mainMetaEl);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const mainPrice = await estimateTurboUploadPrice({
|
||||
login: cleanLogin,
|
||||
storagePwd: cleanStoragePwd,
|
||||
keySource: selectedTurboKeySource,
|
||||
byteLength: selectedFile.size,
|
||||
});
|
||||
const totalWinc = BigInt(mainPrice.winc);
|
||||
priceInfo = {
|
||||
...mainPrice,
|
||||
byteLength: Number(selectedFile.size || 0),
|
||||
isFree: Number(selectedFile.size || 0) <= getFreeTurboUploadBytesLimit(),
|
||||
winc: totalWinc.toString(),
|
||||
credits: Number(totalWinc) / 1_000_000_000_000,
|
||||
};
|
||||
balanceInfo = await getTurboBalanceForStoredSolanaKey({
|
||||
login: cleanLogin,
|
||||
storagePwd: cleanStoragePwd,
|
||||
keySource: selectedTurboKeySource,
|
||||
});
|
||||
renderTurboMeta(mainMetaEl);
|
||||
if (!priceInfo.isFree && BigInt(balanceInfo.effectiveWinc) < BigInt(priceInfo.winc)) {
|
||||
setText(errorEl, t('screens.arweave_attachment_manager.text_007'));
|
||||
return;
|
||||
}
|
||||
uploadBtn.disabled = false;
|
||||
} catch (error) {
|
||||
setText(errorEl, error?.message || t('screens.arweave_attachment_manager.text_059'));
|
||||
}
|
||||
};
|
||||
|
||||
const showUpload = async () => {
|
||||
const turboMode = isTurboUpload();
|
||||
const titleText = effectiveDialogTitle
|
||||
|| (isAvatarMode ? t('screens.arweave_attachment_manager.text_018') : (historyOnly ? t('screens.arweave_attachment_manager.text_019') : t('screens.arweave_attachment_manager.text_020')));
|
||||
const uploadText = effectiveUploadButtonLabel || (historyOnly ? t('screens.arweave_attachment_manager.text_021') : t('screens.arweave_attachment_manager.text_022'));
|
||||
const canShowHistory = allowHistorySelection;
|
||||
const canShowExisting = allowExistingTxInput;
|
||||
root.innerHTML = `${shellOpen()}
|
||||
${isEmbedded ? '' : `<div class="ar-attachment-manager-head">
|
||||
<h3 class="modal-title">${escapeHtml(titleText)}</h3>
|
||||
<button class="icon-btn ar-attachment-manager-close" type="button" data-action="cancel" aria-label="${t('dialogs.remaining.components.arweave_attachment_manager.markup.zakryt')}">${iconHtml('close')}</button>
|
||||
</div>`}
|
||||
<div class="tabs tabs--auto" role="radiogroup" aria-label="${t('dialogs.remaining.components.arweave_attachment_manager.markup.sposob_zagruzki')}">
|
||||
<button class="tab-btn" role="radio" aria-checked="${turboMode}" type="button" data-action="switch-turbo">Turbo</button>
|
||||
<button class="tab-btn" role="radio" aria-checked="${!turboMode}" type="button" data-action="switch-arweave">${t('dialogs.remaining.components.arweave_attachment_manager.markup.napryamuyu_v_arweave')}</button>
|
||||
</div>
|
||||
${turboMode
|
||||
? `
|
||||
<p class="ar-attachment-note"><strong>Turbo</strong> ${th('screens.arweave_attachment_manager.text_071')}</p>
|
||||
`
|
||||
: `
|
||||
<div class="form-field">
|
||||
<label for="ar-attach-wallet">${th('screens.arweave_attachment_manager.text_072')}</label>
|
||||
<select class="select ar-attachment-wallet-select" id="ar-attach-wallet"></select>
|
||||
<button class="text-btn ar-attachment-link" type="button" data-action="add-wallet">${th('screens.arweave_attachment_manager.text_073')}</button>
|
||||
</div>
|
||||
<p class="ar-attachment-note">${th('screens.arweave_attachment_manager.text_074')}</p>${isAvatarMode ? t('screens.arweave_attachment_manager.text_023') : ''}
|
||||
`}
|
||||
${canShowHistory || canShowExisting ? `
|
||||
<div class="ar-attachment-alt-sources">
|
||||
${canShowHistory ? `<button class="text-btn ar-attachment-link" type="button" data-action="history-top">${isAvatarMode ? t('screens.arweave_attachment_manager.text_024') : t('screens.arweave_attachment_manager.text_025')}</button>` : ''}
|
||||
${canShowExisting ? `<button class="text-btn ar-attachment-link" type="button" data-action="existing-top">${isAvatarMode ? t('screens.arweave_attachment_manager.text_026') : t('screens.arweave_attachment_manager.text_027')}</button>` : ''}
|
||||
</div>` : ''}
|
||||
${fixedFile ? '' : `<label class="ar-attachment-file-picker">
|
||||
<input class="ar-attachment-file-input" id="ar-attach-file" type="file" ${isAvatarMode ? 'accept="image/*"' : ''} />
|
||||
<span class="ar-attachment-file-btn">${th('screens.arweave_attachment_manager.text_075')}</span>
|
||||
<span class="ar-attachment-file-name" data-file-name="true">${th('screens.arweave_attachment_manager.text_076')}</span>
|
||||
</label>`}
|
||||
<div class="ar-attachment-meta" data-meta-main="true"></div>
|
||||
<p class="meta-muted inline-error" data-error="true"></p>
|
||||
<div class="form-actions-grid">
|
||||
${turboMode ? t('screens.arweave_attachment_manager.text_028') : t('screens.arweave_attachment_manager.text_029')}
|
||||
<button class="primary-btn" type="button" data-action="upload" disabled>${escapeHtml(uploadText)}</button>
|
||||
</div>
|
||||
${shellClose()}
|
||||
`;
|
||||
bindBackdrop();
|
||||
const walletEl = root.querySelector('#ar-attach-wallet');
|
||||
const fileEl = root.querySelector('#ar-attach-file');
|
||||
const mainMetaEl = root.querySelector('[data-meta-main="true"]');
|
||||
const errorEl = root.querySelector('[data-error="true"]');
|
||||
const uploadBtn = root.querySelector('[data-action="upload"]');
|
||||
|
||||
root.querySelector('[data-action="switch-arweave"]')?.addEventListener('click', async () => {
|
||||
if (selectedUploadTransport === 'arweave') return;
|
||||
selectedUploadTransport = 'arweave';
|
||||
selectedFile = null;
|
||||
selectedSha256 = '';
|
||||
selectedPrepared = null;
|
||||
priceInfo = null;
|
||||
balanceInfo = null;
|
||||
await showUpload();
|
||||
});
|
||||
root.querySelector('[data-action="switch-turbo"]')?.addEventListener('click', async () => {
|
||||
if (selectedUploadTransport === 'turbo') return;
|
||||
selectedUploadTransport = 'turbo';
|
||||
selectedFile = null;
|
||||
selectedSha256 = '';
|
||||
selectedPrepared = null;
|
||||
priceInfo = null;
|
||||
balanceInfo = null;
|
||||
await showUpload();
|
||||
});
|
||||
root.querySelector('[data-action="history-top"]')?.addEventListener('click', showHistory);
|
||||
root.querySelector('[data-action="existing-top"]')?.addEventListener('click', showExisting);
|
||||
|
||||
if (turboMode) {
|
||||
await loadTurboKeyChoices(errorEl);
|
||||
await refreshTurboStateForCurrentFile(mainMetaEl, errorEl, uploadBtn);
|
||||
} else {
|
||||
await loadWallets(errorEl);
|
||||
if (walletEl) {
|
||||
walletEl.innerHTML = renderWalletOptions();
|
||||
walletEl.value = selectedWalletId;
|
||||
walletEl.addEventListener('change', () => {
|
||||
selectedWalletId = String(walletEl.value || '');
|
||||
writeLastWalletId(cleanLogin, selectedWalletId);
|
||||
uploadBtn.disabled = true;
|
||||
selectedFile = null;
|
||||
selectedSha256 = '';
|
||||
priceInfo = null;
|
||||
balanceInfo = null;
|
||||
if (fileEl) fileEl.value = '';
|
||||
setText(mainMetaEl, '');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
root.querySelectorAll('[data-action="cancel"]').forEach((btn) => btn.addEventListener('click', () => close(resolve, null)));
|
||||
root.querySelector('[data-action="topup"]')?.addEventListener('click', async () => {
|
||||
await promptTurboTopUp(mainMetaEl, errorEl);
|
||||
if (turboMode && selectedFile && selectedSha256) {
|
||||
await refreshTurboStateForCurrentFile(mainMetaEl, errorEl, uploadBtn);
|
||||
}
|
||||
});
|
||||
root.querySelector('[data-action="check-balance"]')?.addEventListener('click', async () => {
|
||||
if (turboMode) {
|
||||
await refreshTurboBalance(mainMetaEl, errorEl);
|
||||
if (selectedFile && selectedSha256) await refreshTurboStateForCurrentFile(mainMetaEl, errorEl, uploadBtn);
|
||||
} else {
|
||||
const wallet = selectedWallet();
|
||||
if (!wallet?.address) { setText(errorEl, t('screens.arweave_attachment_manager.text_008')); return; }
|
||||
try {
|
||||
balanceInfo = await getArweaveBalance({ gateway: cleanGateway, address: wallet.address });
|
||||
renderArweaveMeta(mainMetaEl);
|
||||
setText(errorEl, '');
|
||||
} catch (error) {
|
||||
setText(errorEl, error?.message || t('screens.arweave_attachment_manager.text_060'));
|
||||
}
|
||||
}
|
||||
});
|
||||
root.querySelector('[data-action="arweave-topup"]')?.addEventListener('click', async () => {
|
||||
await showArweaveTopUp(mainMetaEl, errorEl);
|
||||
});
|
||||
if (!turboMode) {
|
||||
root.querySelector('[data-action="add-wallet"]')?.addEventListener('click', showAddWallet);
|
||||
}
|
||||
|
||||
fileEl?.addEventListener('change', () => {
|
||||
const nameEl = root.querySelector('[data-file-name="true"]');
|
||||
if (nameEl) nameEl.textContent = fileEl.files?.[0]?.name || t('dialogs.modals.arweave_attachment_manager.label_014');
|
||||
});
|
||||
fileEl?.addEventListener('change', async () => {
|
||||
selectedFile = fileEl.files?.[0] || null;
|
||||
selectedSha256 = '';
|
||||
selectedPrepared = null;
|
||||
priceInfo = null;
|
||||
balanceInfo = null;
|
||||
uploadBtn.disabled = true;
|
||||
setText(errorEl, '');
|
||||
setText(mainMetaEl, '');
|
||||
if (!selectedFile) return;
|
||||
|
||||
try {
|
||||
if (isAvatarMode && !String(selectedFile.type || '').startsWith('image/')) {
|
||||
throw new Error(t('screens.arweave_attachment_manager.text_061'));
|
||||
}
|
||||
if (isAvatarMode) {
|
||||
selectedFile = await prepareAvatarImageFile(selectedFile);
|
||||
}
|
||||
const buffer = await selectedFile.arrayBuffer();
|
||||
selectedSha256 = await sha256HexFromArrayBuffer(buffer);
|
||||
selectedPrepared = await preparePublicFile(selectedFile);
|
||||
if (turboMode) {
|
||||
await refreshTurboStateForCurrentFile(mainMetaEl, errorEl, uploadBtn);
|
||||
} else {
|
||||
await recalculateArweaveState(mainMetaEl, errorEl, uploadBtn);
|
||||
}
|
||||
} catch (error) {
|
||||
setText(errorEl, error?.message || t('screens.arweave_attachment_manager.text_062'));
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
uploadBtn?.addEventListener('click', async () => {
|
||||
if (!selectedFile || !selectedSha256) {
|
||||
setText(errorEl, t('screens.arweave_attachment_manager.text_009'));
|
||||
return;
|
||||
}
|
||||
if (!turboMode) {
|
||||
const wallet = selectedWallet();
|
||||
if (!wallet?.jwk) {
|
||||
setText(errorEl, t('screens.arweave_attachment_manager.text_010'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
uploadBtn.disabled = true;
|
||||
setText(errorEl, turboMode ? t('screens.arweave_attachment_manager.text_030') : t('screens.arweave_attachment_manager.text_031'));
|
||||
try {
|
||||
const uploaded = turboMode
|
||||
? await uploadFileWithTurbo({
|
||||
login: cleanLogin,
|
||||
storagePwd: cleanStoragePwd,
|
||||
keySource: selectedTurboKeySource,
|
||||
file: selectedFile,
|
||||
shineType: forcedShineType || (isAvatarMode ? 'avatar' : 'attachment'),
|
||||
tags: [
|
||||
{ name: 'SHiNE-Login', value: cleanLogin },
|
||||
{ name: isAvatarMode ? 'SHiNE-Avatar' : 'SHiNE-Attachment-Name', value: isAvatarMode ? '1' : (selectedFile.name || 'file') },
|
||||
...normalizedExtraUploadTags,
|
||||
],
|
||||
})
|
||||
: await uploadArweaveFile({
|
||||
gateway: cleanGateway,
|
||||
jwk: selectedWallet()?.jwk,
|
||||
file: selectedFile,
|
||||
shineType: forcedShineType || (isAvatarMode ? 'avatar' : 'attachment'),
|
||||
tags: [
|
||||
{ name: 'SHiNE-Login', value: cleanLogin },
|
||||
{ name: isAvatarMode ? 'SHiNE-Avatar' : 'SHiNE-Attachment-Name', value: isAvatarMode ? '1' : (selectedFile.name || 'file') },
|
||||
...normalizedExtraUploadTags,
|
||||
],
|
||||
});
|
||||
const prepared = selectedPrepared || await preparePublicFile(selectedFile);
|
||||
finish(resolve, {
|
||||
pr: prepared.pr, mm: prepared.mm,
|
||||
name: isAvatarMode ? t('screens.arweave_attachment_manager.text_032') : (initialName || selectedFile.name || 'file'),
|
||||
size: selectedFile.size,
|
||||
sha256: selectedSha256,
|
||||
ar: uploaded.id,
|
||||
uploadTransport: turboMode ? 'turbo' : 'arweave',
|
||||
uploadedAtMs: Date.now(),
|
||||
purpose: isAvatarMode ? 'avatar' : 'attachment',
|
||||
}, { pendingPlacement: historyOnly && !isAvatarMode });
|
||||
} catch (error) {
|
||||
uploadBtn.disabled = false;
|
||||
setText(errorEl, error?.message || (turboMode ? t('screens.arweave_attachment_manager.text_033') : t('screens.arweave_attachment_manager.text_034')));
|
||||
}
|
||||
});
|
||||
|
||||
if (selectedFile && selectedSha256) {
|
||||
if (turboMode) {
|
||||
await refreshTurboStateForCurrentFile(mainMetaEl, errorEl, uploadBtn);
|
||||
} else {
|
||||
await recalculateArweaveState(mainMetaEl, errorEl, uploadBtn);
|
||||
}
|
||||
}
|
||||
|
||||
if (!fixedFile && autoOpenFileDialog && !autoOpenedFileDialogOnce) {
|
||||
autoOpenedFileDialogOnce = true;
|
||||
window.setTimeout(() => fileEl?.click(), 0);
|
||||
}
|
||||
};
|
||||
|
||||
const showExisting = () => {
|
||||
root.innerHTML = `${shellOpen()}
|
||||
<h3 class="modal-title">${isAvatarMode ? t('screens.arweave_attachment_manager.text_035') : t('screens.arweave_attachment_manager.text_036')}</h3>
|
||||
<label class="meta-muted" for="ar-existing-txid">Transaction ID</label>
|
||||
<input class="input" id="ar-existing-txid" type="text" maxlength="64" placeholder="${t('dialogs.remaining.components.arweave_attachment_manager.markup.43_simvola_txid')}" />
|
||||
${isAvatarMode ? '' : `
|
||||
<label class="meta-muted" for="ar-existing-name">${th('screens.arweave_attachment_manager.text_077')}</label>
|
||||
<input class="input" id="ar-existing-name" type="text" maxlength="180" placeholder="${th('screens.arweave_attachment_manager.text_078')}" />
|
||||
`}
|
||||
<div class="ar-attachment-meta" data-meta="true"></div>
|
||||
<p class="meta-muted inline-error" data-error="true"></p>
|
||||
<div class="form-actions-grid">
|
||||
<button class="secondary-btn" type="button" data-action="back">${t('dialogs.remaining.components.arweave_attachment_manager.markup.nazad')}</button>
|
||||
<button class="primary-btn" type="button" data-action="check">${t('dialogs.remaining.components.arweave_attachment_manager.markup.skachat_i_proverit')}</button>
|
||||
</div>
|
||||
${shellClose()}
|
||||
`;
|
||||
bindBackdrop();
|
||||
const txEl = root.querySelector('#ar-existing-txid');
|
||||
const nameEl = root.querySelector('#ar-existing-name');
|
||||
const metaEl = root.querySelector('[data-meta="true"]');
|
||||
const errorEl = root.querySelector('[data-error="true"]');
|
||||
const checkBtn = root.querySelector('[data-action="check"]');
|
||||
root.querySelector('[data-action="back"]')?.addEventListener('click', showUpload);
|
||||
checkBtn?.addEventListener('click', async () => {
|
||||
const txId = String(txEl?.value || '').trim();
|
||||
const name = isAvatarMode ? t('screens.arweave_attachment_manager.text_037') : (String(nameEl?.value || '').trim() || 'arweave-file');
|
||||
if (!validateArweaveTxId(txId)) {
|
||||
setText(errorEl, t('screens.arweave_attachment_manager.text_011'));
|
||||
return;
|
||||
}
|
||||
checkBtn.disabled = true;
|
||||
setText(errorEl, t('screens.arweave_attachment_manager.text_012'));
|
||||
setText(metaEl, '');
|
||||
try {
|
||||
const meta = await loadArweaveFileMetadata({ gateway: cleanGateway, txId });
|
||||
const item = normalizeAttachment({
|
||||
name,
|
||||
size: meta.sizeBytes,
|
||||
sha256: meta.sha256Hex,
|
||||
ar: txId,
|
||||
uploadedAtMs: Date.now(),
|
||||
purpose: isAvatarMode ? 'avatar' : 'attachment',
|
||||
});
|
||||
metaEl.innerHTML = `
|
||||
<div>${th('remaining.file_upload.size_label')}${escapeHtml(formatBytes(item.size))}</div>
|
||||
<div>SHA-256: ${escapeHtml(item.sha256)}</div>
|
||||
`;
|
||||
setText(errorEl, '');
|
||||
const addBtn = document.createElement('button');
|
||||
addBtn.className = 'primary-btn';
|
||||
addBtn.type = 'button';
|
||||
addBtn.textContent = isAvatarMode ? t('dialogs.modals.arweave_attachment_manager.label_015') : (historyOnly ? t('screens.arweave_attachment_manager.text_038') : t('screens.arweave_attachment_manager.text_039'));
|
||||
addBtn.addEventListener('click', () => finish(resolve, item, { pendingPlacement: historyOnly && !isAvatarMode }));
|
||||
metaEl.append(addBtn);
|
||||
} catch (error) {
|
||||
setText(errorEl, error?.message || t('screens.arweave_attachment_manager.text_063'));
|
||||
checkBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
window.setTimeout(() => txEl?.focus(), 0);
|
||||
};
|
||||
|
||||
const showHistory = () => {
|
||||
const rows = readArweaveAttachmentHistory(cleanLogin)
|
||||
.filter((item) => purposeFilter === 'avatar' ? item.purpose === 'avatar' : item.purpose !== 'avatar')
|
||||
.slice()
|
||||
.reverse();
|
||||
root.innerHTML = `${shellOpen('ar-attachment-manager-card--wide')}
|
||||
<h3 class="modal-title">${t('dialogs.remaining.components.arweave_attachment_manager.markup.zhurnal_zagruzhennyh_faylov')}</h3>
|
||||
<p class="meta-muted">${t('dialogs.remaining.components.arweave_attachment_manager.markup.zhurnal_hranitsya_tolko_v_etoy_brauzernoy_sessii')}</p>
|
||||
<div class="ar-attachment-history-tiles" data-history-scroll="true">
|
||||
${rows.length ? rows.map((item, index) => {
|
||||
const isSelected = selectedTxIdSet.has(item.ar);
|
||||
return `
|
||||
<article class="ar-attachment-history-tile${isSelected ? ' is-selected' : ''}" data-history-tile="${index}">
|
||||
<strong class="ar-attachment-history-name">${escapeHtml(item.name)}${item.purpose === 'avatar' ? t('screens.arweave_attachment_manager.text_040') : ''}</strong>
|
||||
<div class="ar-attachment-history-meta-row">
|
||||
<span>${escapeHtml(formatBytes(item.size))}</span>
|
||||
<span>${escapeHtml(formatArweaveHistoryTime(item.uploadedAtMs))}</span>
|
||||
<span class="ar-attachment-status ar-attachment-status--pending" data-status="${index}">${th('screens.arweave_attachment_manager.text_079')}</span>
|
||||
${item.pendingPlacement ? t('screens.arweave_attachment_manager.text_041') : ''}
|
||||
</div>
|
||||
<div class="mono-cell ar-attachment-history-txid">${escapeHtml(item.ar)}</div>
|
||||
<button class="${isSelected ? 'secondary-btn' : 'ghost-btn'}" type="button" data-pick="${index}" ${isSelected ? 'disabled' : ''}>${isSelected ? t('screens.arweave_attachment_manager.text_042') : t('screens.arweave_attachment_manager.text_043')}</button>
|
||||
</article>
|
||||
`;
|
||||
}).join('') : t('screens.arweave_attachment_manager.text_044')}
|
||||
</div>
|
||||
<div class="form-actions-grid">
|
||||
<button class="secondary-btn" type="button" data-action="back">${t('dialogs.remaining.components.arweave_attachment_manager.markup.nazad')}</button>
|
||||
</div>
|
||||
${shellClose()}
|
||||
`;
|
||||
bindBackdrop();
|
||||
const scrollEl = root.querySelector('[data-history-scroll="true"]');
|
||||
window.setTimeout(() => {
|
||||
if (scrollEl) scrollEl.scrollTop = scrollEl.scrollHeight;
|
||||
}, 0);
|
||||
root.querySelector('[data-action="back"]')?.addEventListener('click', showUpload);
|
||||
root.querySelectorAll('[data-pick]').forEach((button) => {
|
||||
button.addEventListener('click', () => {
|
||||
const index = Number(button.getAttribute('data-pick'));
|
||||
const item = rows[index];
|
||||
if (item) finish(resolve, item);
|
||||
});
|
||||
});
|
||||
rows.forEach((item, index) => {
|
||||
const statusEl = root.querySelector(`[data-status="${index}"]`);
|
||||
void getArweaveAttachmentAvailability({ gateway: cleanGateway, attachment: item })
|
||||
.then((result) => {
|
||||
if (!statusEl) return;
|
||||
statusEl.className = `ar-attachment-status ar-attachment-status--${result.status}`;
|
||||
statusEl.textContent = result.label;
|
||||
})
|
||||
.catch(() => {
|
||||
if (!statusEl) return;
|
||||
statusEl.className = 'ar-attachment-status ar-attachment-status--unavailable';
|
||||
statusEl.textContent = t('dialogs.modals.arweave_attachment_manager.label_016');
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const showAddWallet = () => {
|
||||
root.innerHTML = `${shellOpen()}
|
||||
<h3 class="modal-title">${t('dialogs.remaining.components.arweave_attachment_manager.markup.dobavit_arweave_koshelyok')}</h3>
|
||||
<p class="meta-muted">${t('dialogs.remaining.components.arweave_attachment_manager.markup.vstavte_json_jwk_ili_korotkuyu_stroku_base64url_json_jwk_kly')}</p>
|
||||
<label class="meta-muted" for="ar-wallet-label">${t('dialogs.remaining.components.arweave_attachment_manager.markup.nazvanie')}</label>
|
||||
<input class="input" id="ar-wallet-label" type="text" maxlength="80" placeholder="${t('dialogs.remaining.components.arweave_attachment_manager.markup.naprimer_osnovnoy_ar')}" />
|
||||
<label class="meta-muted" for="ar-wallet-secret">${t('dialogs.remaining.components.arweave_attachment_manager.markup.sekret_arweave')}</label>
|
||||
<textarea class="input" id="ar-wallet-secret" rows="7" placeholder="${t('dialogs.remaining.components.arweave_attachment_manager.markup.json_jwk_ili_base64url_json')}"></textarea>
|
||||
<p class="meta-muted inline-error" data-error="true"></p>
|
||||
<div class="form-actions-grid">
|
||||
<button class="secondary-btn" type="button" data-action="back">${t('dialogs.remaining.components.arweave_attachment_manager.markup.nazad')}</button>
|
||||
<button class="primary-btn" type="button" data-action="save">${t('dialogs.remaining.components.arweave_attachment_manager.markup.dobavit')}</button>
|
||||
</div>
|
||||
${shellClose()}
|
||||
`;
|
||||
bindBackdrop();
|
||||
const labelEl = root.querySelector('#ar-wallet-label');
|
||||
const secretEl = root.querySelector('#ar-wallet-secret');
|
||||
const errorEl = root.querySelector('[data-error="true"]');
|
||||
const saveBtn = root.querySelector('[data-action="save"]');
|
||||
root.querySelector('[data-action="back"]')?.addEventListener('click', showUpload);
|
||||
saveBtn?.addEventListener('click', async () => {
|
||||
saveBtn.disabled = true;
|
||||
setText(errorEl, '');
|
||||
try {
|
||||
const wallet = await addArweaveWalletSecret({
|
||||
login: cleanLogin,
|
||||
storagePwd: cleanStoragePwd,
|
||||
label: String(labelEl?.value || '').trim(),
|
||||
secret: String(secretEl?.value || '').trim(),
|
||||
});
|
||||
selectedWalletId = wallet.id;
|
||||
writeLastWalletId(cleanLogin, selectedWalletId);
|
||||
await showUpload();
|
||||
} catch (error) {
|
||||
saveBtn.disabled = false;
|
||||
setText(errorEl, error?.message || t('screens.arweave_attachment_manager.text_064'));
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
void showUpload();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { state } from '../state.js';
|
||||
import { buildArweaveDataUrl, validateArweaveTxId } from '../services/arweave-file-service.js';
|
||||
import { getCachedAvatarObjectUrl } from '../services/arweave-avatar-cache-service.js';
|
||||
import { resolvePublicFileUrl } from '../services/public-file-service.js';
|
||||
import { updatedUserFileUrlAfterError } from '../services/user-file-server-service.js';
|
||||
import { validatePublicPiecesRoot } from '../services/public-pieces-root.js';
|
||||
|
||||
function normalizeLogin(value) {
|
||||
return String(value || '').trim();
|
||||
}
|
||||
|
||||
function pickSizeClass(size) {
|
||||
const raw = String(size || '').trim().toLowerCase();
|
||||
if (raw === 'node') return 'node-dot';
|
||||
if (raw === 'xs' || raw === 'xsmall' || raw === 'tiny') return 'avatar-xs';
|
||||
if (raw === 'sm' || raw === 'small') return 'avatar-sm';
|
||||
if (raw === 'md' || raw === 'medium' || raw === '') return 'avatar-md';
|
||||
if (raw === 'lg' || raw === 'big') return 'avatar-lg';
|
||||
if (raw === 'xl' || raw === 'xlarge' || raw === 'large' || raw === 'very-large') return 'avatar-xl';
|
||||
return raw || '';
|
||||
}
|
||||
|
||||
export function buildAvatarInitials({ login, firstName = '', lastName = '' } = {}) {
|
||||
const first = String(firstName || '').trim();
|
||||
const last = String(lastName || '').trim();
|
||||
if (first || last) {
|
||||
const initials = `${(first[0] || '').toUpperCase()}${(last[0] || '').toUpperCase()}`.trim();
|
||||
if (initials) return initials;
|
||||
}
|
||||
const cleanLogin = normalizeLogin(login);
|
||||
return (cleanLogin[0] || '?').toUpperCase();
|
||||
}
|
||||
|
||||
export function renderAvatar({
|
||||
initials = '?',
|
||||
avatar = null,
|
||||
size = 'xl',
|
||||
className = '',
|
||||
title = '',
|
||||
alt = t('remaining.avatar.avatar'),
|
||||
glow = false,
|
||||
official = false,
|
||||
authorLogin = '',
|
||||
} = {}) {
|
||||
const wrap = document.createElement('div');
|
||||
const classes = new Set(['avatar', 'avatar-image', 'avatar-framed']);
|
||||
const sizeClass = pickSizeClass(size);
|
||||
if (sizeClass) classes.add(sizeClass);
|
||||
const extraClass = String(className || '').trim();
|
||||
if (extraClass) extraClass.split(/\s+/g).filter(Boolean).forEach((value) => classes.add(value));
|
||||
if (glow) classes.add('avatar-glow');
|
||||
wrap.className = Array.from(classes).join(' ');
|
||||
if (title) wrap.title = String(title);
|
||||
|
||||
const fallback = document.createElement('span');
|
||||
fallback.className = 'avatar-fallback';
|
||||
fallback.textContent = String(initials || '?').trim().slice(0, 2).toUpperCase() || '?';
|
||||
wrap.append(fallback);
|
||||
|
||||
if (official) {
|
||||
const badge = document.createElement('img');
|
||||
badge.className = 'avatar-official-badge';
|
||||
badge.src = '/assets/shine-official-badge.svg?v=2';
|
||||
badge.alt = '';
|
||||
badge.setAttribute('aria-hidden', 'true');
|
||||
wrap.append(badge);
|
||||
}
|
||||
|
||||
const txId = String(avatar?.ar || '').trim();
|
||||
const pr = String(avatar?.pr || '').trim();
|
||||
const expectedPr = validatePublicPiecesRoot(pr) ? pr : '';
|
||||
const hasArweave = validateArweaveTxId(txId);
|
||||
const hasServerAvatar = !txId && expectedPr;
|
||||
if (!hasArweave && !hasServerAvatar) return wrap;
|
||||
|
||||
const img = document.createElement('img');
|
||||
img.className = 'avatar-photo';
|
||||
img.alt = String(alt || t('screens.avatar_image.text_002'));
|
||||
img.loading = 'lazy';
|
||||
img.decoding = 'async';
|
||||
img.referrerPolicy = 'no-referrer';
|
||||
wrap.append(img);
|
||||
|
||||
const setLoadedState = (loaded) => {
|
||||
wrap.classList.toggle('has-image', Boolean(loaded));
|
||||
};
|
||||
setLoadedState(false);
|
||||
|
||||
if (hasServerAvatar) {
|
||||
// All public avatars use exactly the same PR/Base58 R2 object key as attachments.
|
||||
img.onload = () => setLoadedState(true);
|
||||
let attemptedRefresh = false;
|
||||
img.onerror = async () => {
|
||||
const previousUrl = img.src;
|
||||
if (!attemptedRefresh && authorLogin) {
|
||||
attemptedRefresh = true;
|
||||
try {
|
||||
const updated = await updatedUserFileUrlAfterError({
|
||||
login: authorLogin, id: expectedPr, previousUrl,
|
||||
});
|
||||
if (updated && img.parentElement === wrap) { img.src = updated; return; }
|
||||
} catch { /* старый адрес останется недоступным */ }
|
||||
}
|
||||
img.removeAttribute('src'); setLoadedState(false);
|
||||
};
|
||||
void resolvePublicFileUrl({ pr: expectedPr, authorLogin }).then((url) => {
|
||||
if (img.parentElement === wrap) img.src = url;
|
||||
}).catch(() => { img.removeAttribute('src'); setLoadedState(false); });
|
||||
return wrap;
|
||||
}
|
||||
|
||||
const gateway = state?.entrySettings?.arweaveServer;
|
||||
void getCachedAvatarObjectUrl({ gateway, txId, expectedPr })
|
||||
.then((objectUrl) => {
|
||||
const directUrl = buildArweaveDataUrl({ gateway, txId });
|
||||
let triedDirectUrl = false;
|
||||
let objectUrlReleased = false;
|
||||
const releaseObjectUrl = () => {
|
||||
if (objectUrlReleased) return;
|
||||
objectUrlReleased = true;
|
||||
if (objectUrl.startsWith('blob:')) {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
};
|
||||
img.onload = () => {
|
||||
setLoadedState(true);
|
||||
releaseObjectUrl();
|
||||
};
|
||||
img.onerror = () => {
|
||||
if (!triedDirectUrl) {
|
||||
if (expectedPr) {
|
||||
releaseObjectUrl();
|
||||
img.removeAttribute('src');
|
||||
setLoadedState(false);
|
||||
return;
|
||||
}
|
||||
triedDirectUrl = true;
|
||||
releaseObjectUrl();
|
||||
img.src = directUrl;
|
||||
return;
|
||||
}
|
||||
releaseObjectUrl();
|
||||
img.removeAttribute('src');
|
||||
setLoadedState(false);
|
||||
};
|
||||
img.src = objectUrl;
|
||||
})
|
||||
.catch(() => {
|
||||
if (expectedPr) {
|
||||
img.removeAttribute('src');
|
||||
setLoadedState(false);
|
||||
return;
|
||||
}
|
||||
let directUrl = '';
|
||||
try {
|
||||
directUrl = buildArweaveDataUrl({ gateway, txId });
|
||||
} catch {
|
||||
directUrl = '';
|
||||
}
|
||||
if (!directUrl) {
|
||||
img.removeAttribute('src');
|
||||
setLoadedState(false);
|
||||
return;
|
||||
}
|
||||
img.onload = () => {
|
||||
setLoadedState(true);
|
||||
};
|
||||
img.onerror = () => {
|
||||
img.removeAttribute('src');
|
||||
setLoadedState(false);
|
||||
};
|
||||
img.src = directUrl;
|
||||
});
|
||||
|
||||
return wrap;
|
||||
}
|
||||
|
||||
export function renderUserAvatar({
|
||||
login,
|
||||
firstName = '',
|
||||
lastName = '',
|
||||
avatar = null,
|
||||
size = 'xl',
|
||||
className = '',
|
||||
title = '',
|
||||
glow = false,
|
||||
official = false,
|
||||
authorLogin = '',
|
||||
} = {}) {
|
||||
return renderAvatar({
|
||||
initials: buildAvatarInitials({ login, firstName, lastName }),
|
||||
avatar,
|
||||
size,
|
||||
className,
|
||||
title,
|
||||
alt: t('screens.avatar_image.text_001'),
|
||||
glow,
|
||||
official,
|
||||
authorLogin: login,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { openChannelAttachmentManager } from './channel-attachment-manager.js';
|
||||
import { saveProfileAvatar } from '../services/user-profile-params.js';
|
||||
|
||||
export async function openAvatarWizard({
|
||||
login,
|
||||
storagePwd,
|
||||
gateway,
|
||||
navigate,
|
||||
onAvatarSaved,
|
||||
onStatus,
|
||||
} = {}) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const cleanStoragePwd = String(storagePwd || '').trim();
|
||||
const cleanGateway = String(gateway || '').trim();
|
||||
if (!cleanLogin || !cleanStoragePwd) {
|
||||
throw new Error(t('screens.avatar_wizard.text_001'));
|
||||
}
|
||||
|
||||
const item = await openChannelAttachmentManager({
|
||||
login: cleanLogin,
|
||||
storagePwd: cleanStoragePwd,
|
||||
gateway: cleanGateway,
|
||||
mode: 'avatar',
|
||||
});
|
||||
|
||||
if (!item?.pr || !item?.size) return false;
|
||||
|
||||
if (typeof onStatus === 'function') {
|
||||
onStatus(t('screens.avatar_wizard.text_002'));
|
||||
}
|
||||
|
||||
await saveProfileAvatar(cleanLogin, item);
|
||||
|
||||
if (typeof onAvatarSaved === 'function') {
|
||||
await onAvatarSaved(item);
|
||||
}
|
||||
|
||||
if (typeof onStatus === 'function') {
|
||||
onStatus('');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { formatDateTime } from '../i18n/format.js';
|
||||
import { escapeHtml } from '../services/attachment-format.js';
|
||||
import { arweaveBlockUrl, checkArweavePayload, checkSolanaAuthor, readSignedBlock, signedDataItemFilename } from '../services/blockchain-proof-service.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
|
||||
const validHash = (value) => /^[0-9a-f]{64}$/iu.test(String(value || ''));
|
||||
const label = (key) => t(`blockchain_details.${key}`);
|
||||
const safe = (value) => escapeHtml(String(value ?? ''));
|
||||
const shortened = (value) => String(value || '').length > 24
|
||||
? `${String(value).slice(0, 12)}…${String(value).slice(-8)}` : String(value || '');
|
||||
|
||||
function asVersions(details) {
|
||||
const raw = Array.isArray(details?.raw?.versions) ? details.raw.versions : [];
|
||||
if (raw.length) return raw.map((v, i) => ({ ...v, versionIndex: Number(v.versionIndex || i + 1) }));
|
||||
return [{ versionIndex: 1, blockNumber: details.blockNumber, blockHash: details.blockHash,
|
||||
createdAtMs: details.createdAtMs, arweaveDataItemId: details.raw?.arweaveDataItemId || '',
|
||||
arweavePublishPending: details.raw?.arweavePublishPending,
|
||||
arweavePublishedAtMs: details.raw?.arweavePublishedAtMs,
|
||||
signedDataItemBytes: details.raw?.signedDataItemBytes }];
|
||||
}
|
||||
function field(title, value, { code = false } = {}) {
|
||||
const valueHtml = code ? `<code title="${safe(value)}">${safe(value)}</code>` : `<strong>${safe(value)}</strong>`;
|
||||
return `<div class="block-proof-row"><span>${safe(title)}</span>${valueHtml}</div>`;
|
||||
}
|
||||
function statusFor(version) {
|
||||
if (version?.arweavePublishedAtMs > 0) return { color: 'success', text: label('published') };
|
||||
if (version?.arweavePublishPending === true) return { color: 'pending', text: label('pending') };
|
||||
return { color: 'unknown', text: label('unknown') };
|
||||
}
|
||||
async function copy(value) {
|
||||
const text = String(value || '');
|
||||
if (!text) return;
|
||||
if (navigator.clipboard?.writeText) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} else {
|
||||
const input = document.createElement('textarea');
|
||||
input.value = text; input.style.position = 'fixed'; input.style.opacity = '0';
|
||||
document.body.append(input); input.select(); document.execCommand('copy'); input.remove();
|
||||
}
|
||||
showToast(label('copied'));
|
||||
}
|
||||
function resultRow(name, status, reason = '') {
|
||||
const mark = status === 'valid' ? '✓' : status === 'invalid' ? '✕' : '—';
|
||||
const description = status === 'valid' ? label('verified') : status === 'invalid' ? label('failed') : label('not_verified');
|
||||
return `<div class="block-proof-check block-proof-check--${status}"><span aria-hidden="true">${mark}</span><div><strong>${safe(name)}: ${safe(description)}</strong>${reason ? `<small>${safe(reason)}</small>` : ''}</div></div>`;
|
||||
}
|
||||
|
||||
/** Единый диалог для ленты канала и страницы обсуждения. */
|
||||
export function openBlockchainDetailsModal(details, { authService, solanaEndpoint, isActive = () => true } = {}) {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!root) return;
|
||||
const versions = asVersions(details);
|
||||
let current = versions.length - 1;
|
||||
let busy = false;
|
||||
const rawText = JSON.stringify(details.raw || {}, null, 2);
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="blockchain-details-modal">
|
||||
<section class="modal-card stack blockchain-details-card block-proof-card" role="dialog" aria-modal="true" aria-label="${safe(label('title'))}">
|
||||
<header class="block-proof-header">
|
||||
<span class="block-proof-icon" aria-hidden="true">⛓</span>
|
||||
<div><h3 class="modal-title">${safe(label('title'))}</h3><p class="meta-muted">${safe(label('description'))}</p></div>
|
||||
</header>
|
||||
${versions.length > 1 ? `<label class="field-label" for="block-proof-version">${safe(label('version'))}</label>
|
||||
<select class="input" id="block-proof-version">${versions.map((v, i) => `<option value="${i}" ${i === current ? 'selected' : ''}>${safe(label('version'))} ${i + 1} · #${safe(v.blockNumber)}</option>`).join('')}</select>` : ''}
|
||||
<div id="block-proof-content"></div>
|
||||
<div class="block-proof-actions">
|
||||
<a class="secondary-btn block-proof-link" id="block-proof-open" target="_blank" rel="noopener noreferrer">↗ ${safe(label('open_arweave'))}</a>
|
||||
<button class="secondary-btn" type="button" id="block-proof-copy-url">${safe(label('copy_url'))}</button>
|
||||
<button class="secondary-btn" type="button" id="block-proof-download">↓ ${safe(label('download_signed'))}</button>
|
||||
<button class="secondary-btn block-proof-verify" type="button" id="block-proof-verify">🛡 ${safe(label('verify'))}</button>
|
||||
</div>
|
||||
<div id="block-proof-results" class="block-proof-results" hidden aria-live="polite"></div>
|
||||
<details class="block-proof-raw"><summary>${safe(label('technical'))}</summary>
|
||||
<pre class="blockchain-raw-block">${safe(rawText)}</pre>
|
||||
<button class="secondary-btn" id="block-proof-copy-raw" type="button">${safe(label('copy_raw'))}</button>
|
||||
</details>
|
||||
<button class="secondary-btn" id="block-proof-close" type="button">${safe(label('close'))}</button>
|
||||
</section>
|
||||
</div>`;
|
||||
const get = (id) => root.querySelector(`#${id}`);
|
||||
const currentVersion = () => versions[current];
|
||||
const content = get('block-proof-content');
|
||||
const results = get('block-proof-results');
|
||||
const button = get('block-proof-download');
|
||||
const verify = get('block-proof-verify');
|
||||
const close = () => { if (get('blockchain-details-modal')) root.innerHTML = ''; };
|
||||
function renderVersion() {
|
||||
const v = currentVersion();
|
||||
const archive = statusFor(v);
|
||||
const hash = validHash(v.blockHash) ? v.blockHash : '';
|
||||
const url = arweaveBlockUrl(v.arweaveDataItemId);
|
||||
const date = Number(v.createdAtMs || details.createdAtMs);
|
||||
content.innerHTML = `
|
||||
<div class="block-proof-facts">
|
||||
${field(label('author'), details.authorLogin || '—')}
|
||||
${field(label('blockchain'), details.authorBlockchainName || '—', { code: true })}
|
||||
${field(label('block_number'), v.blockNumber)}
|
||||
${field(label('created'), date > 0 ? formatDateTime(new Date(date)) : '—')}
|
||||
${field(label('storage'), 'Arweave')}
|
||||
${field(label('signed_size'), Number.isInteger(v.signedDataItemBytes) ? `${v.signedDataItemBytes} ${label('bytes')}` : '—')}
|
||||
</div>
|
||||
${v.attachmentMetadataValid === false ? `<p class="block-proof-warning">${safe(label('invalid_attachment'))}</p>` : ''}
|
||||
<div class="block-proof-status block-proof-status--${archive.color}"><span class="block-proof-dot"></span>${safe(archive.text)}</div>
|
||||
<div class="block-proof-hash"><span>${safe(label('hash'))}</span><div><code title="${safe(hash)}">${safe(shortened(hash) || '—')}</code><button type="button" class="block-proof-copy-icon" id="block-proof-copy-hash" ${hash ? '' : 'disabled'} aria-label="${safe(label('copy_hash'))}" title="${safe(label('copy_hash'))}">⧉</button></div></div>
|
||||
${url ? `<div class="block-proof-hash"><span>Arweave DataItem ID</span><div><code title="${safe(v.arweaveDataItemId)}">${safe(shortened(v.arweaveDataItemId))}</code><button type="button" class="block-proof-copy-icon" id="block-proof-copy-id" aria-label="${safe(label('copy_id'))}" title="${safe(label('copy_id'))}">⧉</button></div></div>` : ''}`;
|
||||
get('block-proof-open').href = url || '#';
|
||||
get('block-proof-open').hidden = !url;
|
||||
get('block-proof-copy-url').disabled = !url;
|
||||
get('block-proof-copy-hash')?.addEventListener('click', () => { void copy(hash); });
|
||||
get('block-proof-copy-id')?.addEventListener('click', () => { void copy(v.arweaveDataItemId); });
|
||||
results.hidden = true;
|
||||
results.replaceChildren();
|
||||
}
|
||||
async function signedBlock() {
|
||||
const v = currentVersion();
|
||||
if (!validHash(v.blockHash)) throw new Error(label('missing_hash'));
|
||||
return readSignedBlock({ authService, blockchainName: details.authorBlockchainName,
|
||||
blockNumber: v.blockNumber, blockHash: v.blockHash, dataItemId: v.arweaveDataItemId });
|
||||
}
|
||||
get('block-proof-version')?.addEventListener('change', (event) => {
|
||||
if (busy) { event.target.value = String(current); return; }
|
||||
current = Number(event.target.value); renderVersion();
|
||||
});
|
||||
get('block-proof-copy-url')?.addEventListener('click', () => { void copy(arweaveBlockUrl(currentVersion().arweaveDataItemId)); });
|
||||
get('block-proof-copy-raw')?.addEventListener('click', () => { void copy(rawText); });
|
||||
get('block-proof-close')?.addEventListener('click', close);
|
||||
button.addEventListener('click', async () => {
|
||||
if (busy) return;
|
||||
busy = true; button.disabled = true; verify.disabled = true;
|
||||
try {
|
||||
const proof = await signedBlock();
|
||||
if (!isActive() || !get('blockchain-details-modal')) return;
|
||||
const blobUrl = URL.createObjectURL(new Blob([proof.bytes], { type: 'application/octet-stream' }));
|
||||
const link = document.createElement('a');
|
||||
link.href = blobUrl;
|
||||
link.download = signedDataItemFilename(details.authorBlockchainName, currentVersion().blockNumber);
|
||||
document.body.append(link); link.click(); link.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(blobUrl), 30000);
|
||||
} catch (error) { if (isActive()) showToast(String(error?.message || error), { kind: 'error' }); }
|
||||
finally { busy = false; button.disabled = false; verify.disabled = false; }
|
||||
});
|
||||
verify.addEventListener('click', async () => {
|
||||
if (busy) return;
|
||||
busy = true; verify.disabled = true; button.disabled = true;
|
||||
const select = get('block-proof-version'); if (select) select.disabled = true;
|
||||
results.hidden = false; results.textContent = label('checking');
|
||||
try {
|
||||
const proof = await signedBlock();
|
||||
const id = currentVersion().arweaveDataItemId || proof.actualId;
|
||||
const [arweave, solana] = await Promise.all([
|
||||
checkArweavePayload(id, proof.data),
|
||||
checkSolanaAuthor({ authorLogin: details.authorLogin, blockchainName: details.authorBlockchainName,
|
||||
owner32: proof.owner32, solanaEndpoint }),
|
||||
]);
|
||||
if (!isActive() || !get('blockchain-details-modal')) return;
|
||||
results.innerHTML = [
|
||||
resultRow(label('signature'), 'valid'),
|
||||
resultRow(label('integrity'), 'valid'),
|
||||
resultRow(label('arweave_check'), arweave.status, arweave.reason),
|
||||
resultRow(label('solana_check'), solana.status, solana.reason),
|
||||
`<p class="meta-muted">${safe(label('proof_note'))}</p>`,
|
||||
].join('');
|
||||
} catch (error) {
|
||||
if (!isActive() || !get('blockchain-details-modal')) return;
|
||||
results.innerHTML = resultRow(label('signed_check'), 'unavailable', String(error?.message || error));
|
||||
} finally {
|
||||
busy = false;
|
||||
if (get('blockchain-details-modal')) { verify.disabled = false; button.disabled = false; if (select) select.disabled = false; }
|
||||
}
|
||||
});
|
||||
renderVersion();
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { openArweaveAttachmentManager, prepareAvatarImageFile } from './arweave-attachment-manager.js';
|
||||
import { formatBytes } from '../services/attachment-format.js';
|
||||
import { uploadPublicFile } from '../services/public-file-service.js';
|
||||
import { state } from '../state.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
|
||||
export function openChannelAttachmentManager({
|
||||
login,
|
||||
storagePwd = '',
|
||||
gateway = '',
|
||||
selectedTxIds = [],
|
||||
signal = null,
|
||||
mode = 'attachment',
|
||||
} = {}) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const isAvatarMode = String(mode || '').trim() === 'avatar';
|
||||
const root = document.createElement('div');
|
||||
root.className = 'public-attachment-manager-root';
|
||||
document.body.append(root);
|
||||
|
||||
let closed = false;
|
||||
let selectedFile = null;
|
||||
let uploading = false;
|
||||
let arweaveStarted = false;
|
||||
const arweaveAbortController = new AbortController();
|
||||
if (signal) signal.addEventListener('abort', () => arweaveAbortController.abort(), { once: true });
|
||||
|
||||
const close = (resolve, value = null) => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
arweaveAbortController.abort();
|
||||
root.remove();
|
||||
resolve(value);
|
||||
};
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const onAbort = () => close(resolve, null);
|
||||
if (signal?.aborted) { onAbort(); return; }
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
|
||||
root.innerHTML = `
|
||||
<div class="modal public-attachment-manager" data-public-attachment-modal="true">
|
||||
<div class="modal-card stack public-attachment-manager__card" role="dialog" aria-modal="true" aria-labelledby="public-attachment-title">
|
||||
<div class="public-attachment-manager__header">
|
||||
<h3 class="modal-title" id="public-attachment-title">${isAvatarMode ? t('screens.channel_attachment_manager.text_003') : t('screens.channel_attachment_manager.text_004')}</h3>
|
||||
<button class="icon-btn" type="button" data-action="close" aria-label="${th('screens.channel_attachment_manager.text_008')}">×</button>
|
||||
</div>
|
||||
|
||||
<div class="public-attachment-manager__sources" role="radiogroup" aria-label="${th('screens.channel_attachment_manager.text_009')}">
|
||||
<label class="public-attachment-manager__source is-selected">
|
||||
<input type="radio" name="attachment-storage" value="server" checked />
|
||||
<span><strong>${th('screens.channel_attachment_manager.text_010')}</strong><small>${th('screens.channel_attachment_manager.text_011')}</small></span>
|
||||
</label>
|
||||
<label class="public-attachment-manager__source">
|
||||
<input type="radio" name="attachment-storage" value="arweave" />
|
||||
<span><strong>ARWEAVE</strong><small>${th('screens.channel_attachment_manager.text_012')}</small></span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="public-attachment-manager__server" data-panel="server">
|
||||
<div class="public-attachment-manager__notice">
|
||||
<strong>${th('screens.channel_attachment_manager.text_013')}</strong>
|
||||
<p>${th('screens.channel_attachment_manager.text_014')}</p>
|
||||
<p>${th('screens.channel_attachment_manager.text_015')}</p>
|
||||
<p>${th('screens.channel_attachment_manager.text_016')}</p>
|
||||
<p>${th('screens.channel_attachment_manager.text_017')}</p>
|
||||
</div>
|
||||
<label class="ar-attachment-file-picker public-attachment-manager__file-picker">
|
||||
<input class="ar-attachment-file-input" type="file" data-role="file" ${isAvatarMode ? 'accept="image/*"' : ''} />
|
||||
<span class="ar-attachment-file-btn">${th('screens.channel_attachment_manager.text_018')}</span>
|
||||
<span class="ar-attachment-file-name" data-role="selected">${th('screens.channel_attachment_manager.text_019')}</span>
|
||||
</label>
|
||||
<div class="public-attachment-manager__status meta-muted" data-role="status"></div>
|
||||
<div class="public-attachment-manager__error inline-error" data-role="error"></div>
|
||||
<button class="primary-btn" type="button" data-action="upload" disabled>${isAvatarMode ? t('screens.channel_attachment_manager.text_005') : t('screens.channel_attachment_manager.text_006')}</button>
|
||||
</div>
|
||||
|
||||
<div class="public-attachment-manager__arweave" data-panel="arweave" hidden>
|
||||
<p class="meta-muted">${th('screens.channel_attachment_manager.text_020')}</p>
|
||||
<div class="public-attachment-manager__arweave-loading meta-muted">${th('screens.channel_attachment_manager.text_021')}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const modal = root.querySelector('[data-public-attachment-modal="true"]');
|
||||
const fileInput = root.querySelector('[data-role="file"]');
|
||||
const selectedEl = root.querySelector('[data-role="selected"]');
|
||||
const statusEl = root.querySelector('[data-role="status"]');
|
||||
const errorEl = root.querySelector('[data-role="error"]');
|
||||
const uploadButton = root.querySelector('[data-action="upload"]');
|
||||
const radios = [...root.querySelectorAll('input[name="attachment-storage"]')];
|
||||
|
||||
const setSource = (value) => {
|
||||
root.querySelectorAll('.public-attachment-manager__source').forEach((label) => {
|
||||
label.classList.toggle('is-selected', label.querySelector('input')?.value === value);
|
||||
});
|
||||
root.querySelector('[data-panel="server"]').hidden = value !== 'server';
|
||||
root.querySelector('[data-panel="arweave"]').hidden = value !== 'arweave';
|
||||
};
|
||||
|
||||
const openArweaveFlow = async () => {
|
||||
if (arweaveStarted || closed) return;
|
||||
arweaveStarted = true;
|
||||
const hostElement = root.querySelector('[data-panel="arweave"]');
|
||||
if (!(hostElement instanceof HTMLElement)) { arweaveStarted = false; return; }
|
||||
try {
|
||||
const item = await openArweaveAttachmentManager({
|
||||
login: cleanLogin,
|
||||
storagePwd,
|
||||
gateway,
|
||||
selectedTxIds,
|
||||
signal: arweaveAbortController.signal,
|
||||
mode: isAvatarMode ? 'avatar' : 'attachment',
|
||||
historyPurpose: isAvatarMode ? 'avatar' : '',
|
||||
autoOpenFileDialog: false,
|
||||
hostElement,
|
||||
embedded: true,
|
||||
});
|
||||
if (item && !closed) close(resolve, item);
|
||||
} catch (error) {
|
||||
arweaveStarted = false;
|
||||
if (!closed && hostElement) {
|
||||
hostElement.replaceChildren();
|
||||
const message = document.createElement('p');
|
||||
message.className = 'inline-error';
|
||||
message.textContent = toUserMessage(error, t('screens.channel_attachment_manager.text_001'));
|
||||
hostElement.append(message);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
radios.forEach((radio) => radio.addEventListener('change', () => {
|
||||
setSource(radio.value);
|
||||
if (radio.value === 'arweave' && radio.checked) void openArweaveFlow();
|
||||
}));
|
||||
root.querySelector('[data-action="close"]')?.addEventListener('click', () => close(resolve, null));
|
||||
modal?.addEventListener('click', (event) => {
|
||||
if (event.target === modal && !uploading) close(resolve, null);
|
||||
});
|
||||
|
||||
fileInput?.addEventListener('change', () => {
|
||||
selectedFile = fileInput.files?.[0] || null;
|
||||
if (selectedEl) selectedEl.textContent = selectedFile
|
||||
? `${selectedFile.name} · ${formatBytes(selectedFile.size)}`
|
||||
: t('screens.channel_attachment_manager.text_007');
|
||||
if (errorEl) errorEl.textContent = '';
|
||||
if (statusEl) statusEl.textContent = '';
|
||||
if (uploadButton) uploadButton.disabled = !selectedFile;
|
||||
});
|
||||
|
||||
uploadButton?.addEventListener('click', async () => {
|
||||
if (!selectedFile || uploading) return;
|
||||
uploading = true;
|
||||
uploadButton.disabled = true;
|
||||
fileInput.disabled = true;
|
||||
if (errorEl) errorEl.textContent = '';
|
||||
try {
|
||||
const uploadFile = isAvatarMode ? await prepareAvatarImageFile(selectedFile) : selectedFile;
|
||||
const item = await uploadPublicFile({
|
||||
file: uploadFile,
|
||||
purpose: isAvatarMode ? 'avatar' : 'attachment',
|
||||
login: cleanLogin,
|
||||
sessionId: state.session.sessionId,
|
||||
wsUrl: state.entrySettings.shineServer,
|
||||
onStatus: (message) => { if (statusEl) statusEl.textContent = message; },
|
||||
});
|
||||
close(resolve, { ...item, purpose: isAvatarMode ? 'avatar' : 'attachment' });
|
||||
} catch (error) {
|
||||
if (errorEl) errorEl.textContent = toUserMessage(error, t('screens.channel_attachment_manager.text_002'));
|
||||
if (statusEl) statusEl.textContent = '';
|
||||
uploading = false;
|
||||
fileInput.disabled = false;
|
||||
uploadButton.disabled = !selectedFile;
|
||||
}
|
||||
});
|
||||
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
import { confirmPublicHistoryAction } from '../services/public-history-consent.js';
|
||||
import { markArweaveAttachmentPlaced } from './arweave-attachment-manager.js';
|
||||
import { openChannelAttachmentManager } from './channel-attachment-manager.js';
|
||||
import { composeMessageWithAttachments, MAX_MESSAGE_ATTACHMENTS } from '../services/attachment-format.js';
|
||||
import { state } from '../state.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { renderUserAvatar } from './avatar-image.js';
|
||||
import { openAuthRequiredModal } from '../services/auth-required-modal.js';
|
||||
import { openHistoryLayer } from '../router.js';
|
||||
|
||||
const drafts = new Map();
|
||||
|
||||
function draftKey(key) {
|
||||
const login = String(state.session.login || 'guest').trim().toLowerCase();
|
||||
return `${login}:${String(key || 'editor')}`;
|
||||
}
|
||||
|
||||
// MVP: вложения показываются только строкой с именем, без запросов миниатюр.
|
||||
function attachmentLabel(item) {
|
||||
const name = String(item?.name || t('screens.channel_editor.text_012'));
|
||||
const size = Number(item?.size || 0);
|
||||
if (!size) return name;
|
||||
if (size < 1024) return t('screens.channel_editor.text_017', { value1: name, value2: size });
|
||||
if (size < 1024 * 1024) return t('screens.channel_editor.text_018', { value1: name, value2: Math.ceil(size / 1024) });
|
||||
return t('screens.channel_editor.text_019', { value1: name, value2: (size / 1024 / 1024).toFixed(1) });
|
||||
}
|
||||
|
||||
export function openChannelEditor({
|
||||
id = 'channel-editor',
|
||||
title = t('remaining.channel_editor.reply'),
|
||||
submitLabel = t('remaining.channel_editor.reply_2'),
|
||||
placeholder = t('remaining.channel_editor.write_a_reply'),
|
||||
context = null,
|
||||
destination = '',
|
||||
key = 'reply',
|
||||
extraControl = null,
|
||||
initialText = '',
|
||||
allowEmptyText = false,
|
||||
allowAttachments = true,
|
||||
rawText = false,
|
||||
openAttachOnStart = false,
|
||||
onSubmit,
|
||||
isActive = () => true,
|
||||
} = {}) {
|
||||
if (!state.session.isAuthorized) {
|
||||
openAuthRequiredModal({ title: t('dialogs.components.channel_editor.title_001'), text: t('dialogs.components.channel_editor.text_002') });
|
||||
return null;
|
||||
}
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!root || typeof onSubmit !== 'function') return null;
|
||||
if (root.querySelector('.channel-editor-overlay')) return null;
|
||||
|
||||
const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||
const storageKey = draftKey(key);
|
||||
const login = state.session.login;
|
||||
const saved = drafts.get(storageKey) || { text: initialText, attachments: [] };
|
||||
const attachments = Array.isArray(saved.attachments) ? [...saved.attachments] : [];
|
||||
const extraFields = extraControl ? [...extraControl.querySelectorAll('select,input')] : [];
|
||||
extraFields.forEach((field, index) => {
|
||||
if (saved.controls?.[index] !== undefined) field.value = saved.controls[index];
|
||||
});
|
||||
let inFlight = false;
|
||||
let composing = false;
|
||||
let closed = false;
|
||||
let picking = false;
|
||||
let completed = false;
|
||||
const attachmentController = new AbortController();
|
||||
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'channel-editor-overlay';
|
||||
overlay.id = id;
|
||||
overlay.setAttribute('role', 'dialog');
|
||||
overlay.setAttribute('aria-modal', 'true');
|
||||
overlay.setAttribute('aria-labelledby', `${id}-title`);
|
||||
|
||||
const dialog = document.createElement('div');
|
||||
dialog.className = 'channel-editor';
|
||||
|
||||
const header = document.createElement('header');
|
||||
header.className = 'channel-editor__header';
|
||||
const closeButton = document.createElement('button');
|
||||
closeButton.type = 'button';
|
||||
closeButton.className = 'icon-btn channel-editor__close';
|
||||
closeButton.setAttribute('aria-label', t('screens.channel_editor.text_025'));
|
||||
closeButton.innerHTML = iconHtml('close');
|
||||
const heading = document.createElement('h2');
|
||||
heading.id = `${id}-title`;
|
||||
heading.textContent = title;
|
||||
// Закрытие не теряет текст: черновик хранится до отправки
|
||||
const draftMark = document.createElement('span');
|
||||
draftMark.className = 'channel-editor__draft';
|
||||
draftMark.textContent = t('screens.channel_editor.text_001');
|
||||
const headerEnd = document.createElement('div');
|
||||
headerEnd.className = 'channel-editor__header-end';
|
||||
header.append(closeButton, heading, headerEnd);
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'channel-editor__body';
|
||||
|
||||
// Цепочка как в Threads: исходная запись и ответы до той, на которую отвечаем, сверху вниз, соединены линией.
|
||||
// Поле ввода – последним звеном; к началу цепочки – прокруткой вверх.
|
||||
const chain = Array.isArray(context?.chain) ? context.chain.filter(Boolean) : [];
|
||||
if (chain.length) {
|
||||
const chainBox = document.createElement('ol');
|
||||
chainBox.className = 'channel-editor__chain';
|
||||
chainBox.setAttribute('aria-label', t('screens.channel_editor.text_026'));
|
||||
chain.forEach((item) => {
|
||||
const row = document.createElement('li');
|
||||
row.className = 'channel-editor__chain-item';
|
||||
const avatar = item.avatar instanceof Node ? item.avatar : renderUserAvatar({ login: item.author || 'unknown', className: 'avatar-plain', size: 'sm' });
|
||||
avatar.classList.add('channel-editor__chain-avatar');
|
||||
const main = document.createElement('div');
|
||||
main.className = 'channel-editor__chain-main';
|
||||
const head = document.createElement('div');
|
||||
head.className = 'channel-editor__chain-head';
|
||||
const name = document.createElement('strong');
|
||||
name.textContent = String(item.title || item.author || '');
|
||||
head.append(name);
|
||||
if (item.time) {
|
||||
const time = document.createElement('span');
|
||||
time.textContent = item.time;
|
||||
head.append(time);
|
||||
}
|
||||
const text = document.createElement('p');
|
||||
text.textContent = String(item.text || item.attachmentLabel || t('screens.channel_editor.text_013'));
|
||||
main.append(head, text);
|
||||
row.append(avatar, main);
|
||||
chainBox.append(row);
|
||||
});
|
||||
body.append(chainBox);
|
||||
} else if (context && (context.author || context.text || context.attachmentLabel)) {
|
||||
const contextBox = document.createElement('div');
|
||||
contextBox.className = 'channel-editor__context';
|
||||
const contextTitle = document.createElement('strong');
|
||||
contextTitle.textContent = context.author ? t('screens.channel_editor.text_020', { value1: context.author }) : t('screens.channel_editor.text_009');
|
||||
const quote = document.createElement('p');
|
||||
quote.textContent = String(context.text || context.attachmentLabel || t('screens.channel_editor.text_014'));
|
||||
const expand = document.createElement('button');
|
||||
expand.type = 'button';
|
||||
expand.className = 'text-btn channel-editor__context-toggle';
|
||||
expand.textContent = t('screens.channel_editor.text_002');
|
||||
expand.setAttribute('aria-expanded', 'false');
|
||||
expand.addEventListener('click', () => {
|
||||
const expanded = contextBox.classList.toggle('is-expanded');
|
||||
expand.textContent = expanded ? t('screens.channel_editor.text_010') : t('screens.channel_editor.text_011');
|
||||
expand.setAttribute('aria-expanded', String(expanded));
|
||||
});
|
||||
contextBox.append(contextTitle, quote, expand);
|
||||
body.append(contextBox);
|
||||
}
|
||||
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.className = 'channel-editor__input';
|
||||
textarea.rows = 1;
|
||||
textarea.maxLength = 2000;
|
||||
textarea.placeholder = placeholder;
|
||||
textarea.setAttribute('aria-label', placeholder);
|
||||
textarea.value = String(saved.text || '');
|
||||
|
||||
const attachmentsBox = document.createElement('div');
|
||||
attachmentsBox.className = 'channel-editor__attachments';
|
||||
attachmentsBox.setAttribute('aria-live', 'polite');
|
||||
|
||||
const error = document.createElement('p');
|
||||
error.className = 'channel-editor__error';
|
||||
error.setAttribute('role', 'alert');
|
||||
|
||||
const clearButton = document.createElement('button');
|
||||
clearButton.type = 'button';
|
||||
clearButton.className = 'text-btn channel-editor__clear';
|
||||
clearButton.textContent = t('screens.channel_editor.text_003');
|
||||
|
||||
const author = document.createElement('div');
|
||||
author.className = 'channel-editor__author';
|
||||
author.append(renderUserAvatar({ login: login || 'guest', className: 'avatar-plain', size: 'md' }));
|
||||
const authorText = document.createElement('span');
|
||||
authorText.className = 'channel-editor__author-text';
|
||||
const authorName = document.createElement('strong');
|
||||
authorName.textContent = login || t('screens.channel_editor.text_015');
|
||||
authorText.append(authorName);
|
||||
if (destination) {
|
||||
const where = document.createElement('small');
|
||||
where.textContent = destination;
|
||||
authorText.append(where);
|
||||
}
|
||||
author.append(authorText);
|
||||
if (chain.length) author.classList.add('is-chained');
|
||||
body.append(author);
|
||||
|
||||
const footer = document.createElement('footer');
|
||||
footer.className = 'channel-editor__footer';
|
||||
const attachButton = document.createElement('button');
|
||||
attachButton.type = 'button';
|
||||
attachButton.className = 'icon-btn channel-editor__attach';
|
||||
attachButton.innerHTML = `${iconHtml('image')}<span class="sr-only">${th('screens.channel_editor.text_024')}</span>`;
|
||||
attachButton.title = t('screens.channel_editor.text_004');
|
||||
attachButton.hidden = !allowAttachments;
|
||||
// Как в Threads: текст пишется прямо под именем, без рамки; под ним – вложения.
|
||||
// «Прикрепить» – в нижней панели у кнопки отправки, «Очистить» – в шапке, пока есть что очищать.
|
||||
const compose = document.createElement('div');
|
||||
compose.className = 'channel-editor__compose';
|
||||
compose.append(textarea, attachmentsBox, error);
|
||||
authorText.append(compose);
|
||||
headerEnd.append(clearButton, draftMark);
|
||||
const counter = document.createElement('span');
|
||||
counter.className = 'channel-editor__counter';
|
||||
const submitButton = document.createElement('button');
|
||||
submitButton.type = 'button';
|
||||
submitButton.className = 'primary-btn channel-editor__submit';
|
||||
submitButton.textContent = submitLabel;
|
||||
submitButton.title = t('screens.channel_editor.text_005');
|
||||
footer.append(attachButton);
|
||||
if (extraControl instanceof Node) {
|
||||
footer.classList.add('has-extra');
|
||||
footer.append(extraControl);
|
||||
}
|
||||
footer.append(counter, submitButton);
|
||||
dialog.append(header, body, footer);
|
||||
overlay.append(dialog);
|
||||
root.replaceChildren(overlay);
|
||||
|
||||
const saveDraft = () => {
|
||||
const value = { text: textarea.value, attachments: [...attachments], controls: extraFields.map((field) => field.value) };
|
||||
if (completed) { drafts.delete(storageKey); return; }
|
||||
if (value.text || value.attachments.length) drafts.set(storageKey, value);
|
||||
else drafts.delete(storageKey);
|
||||
};
|
||||
|
||||
const sync = () => {
|
||||
textarea.style.height = 'auto';
|
||||
textarea.style.height = `${Math.max(24, textarea.scrollHeight)}px`;
|
||||
const length = textarea.value.length;
|
||||
counter.textContent = `${length} / 2000`;
|
||||
counter.classList.toggle('is-near-limit', length >= 1800);
|
||||
// Счётчик нужен только у предела, пустой «0 / 2000» лишь шумит.
|
||||
counter.classList.toggle('is-hidden', length < 1500);
|
||||
submitButton.disabled = inFlight || picking || length > textarea.maxLength || (!allowEmptyText && !textarea.value.trim() && attachments.length === 0);
|
||||
dialog.setAttribute('aria-busy', String(inFlight || picking));
|
||||
clearButton.hidden = !textarea.value && attachments.length === 0;
|
||||
draftMark.hidden = !clearButton.hidden;
|
||||
attachmentsBox.replaceChildren();
|
||||
attachments.forEach((item, index) => {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'channel-editor__attachment';
|
||||
const label = document.createElement('span');
|
||||
label.textContent = attachmentLabel(item);
|
||||
const remove = document.createElement('button');
|
||||
remove.type = 'button';
|
||||
remove.className = 'icon-btn';
|
||||
remove.setAttribute('aria-label', t('screens.channel_editor.text_022', { value1: item?.name || '' }));
|
||||
remove.textContent = '×';
|
||||
remove.disabled = inFlight;
|
||||
remove.addEventListener('click', () => {
|
||||
attachments.splice(index, 1);
|
||||
saveDraft();
|
||||
sync();
|
||||
});
|
||||
card.append(label, remove);
|
||||
attachmentsBox.append(card);
|
||||
});
|
||||
};
|
||||
|
||||
// «Назад» закрывает редактор, а не уводит со страницы; слой в истории ведёт роутер.
|
||||
const historyLayer = openHistoryLayer(() => close({ fromHistory: true }));
|
||||
const viewport = window.visualViewport;
|
||||
const updateViewport = () => {
|
||||
overlay.style.setProperty('--editor-height', `${viewport?.height || window.innerHeight}px`);
|
||||
overlay.style.setProperty('--editor-top', `${viewport?.offsetTop || 0}px`);
|
||||
};
|
||||
const observer = new MutationObserver(() => {
|
||||
if (!overlay.isConnected) close({ restoreFocus: false });
|
||||
});
|
||||
const close = ({ fromHistory = false, restoreFocus = true } = {}) => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
saveDraft();
|
||||
observer.disconnect();
|
||||
attachmentController.abort();
|
||||
document.removeEventListener('keydown', onDocumentKeydown);
|
||||
viewport?.removeEventListener('resize', updateViewport);
|
||||
viewport?.removeEventListener('scroll', updateViewport);
|
||||
window.removeEventListener('resize', updateViewport);
|
||||
overlay.remove();
|
||||
if (!fromHistory) historyLayer.close();
|
||||
if (restoreFocus && opener?.isConnected) opener.focus({ preventScroll: true });
|
||||
};
|
||||
overlay.cleanup = () => close({ restoreFocus: false });
|
||||
|
||||
const submit = async () => {
|
||||
if (inFlight || submitButton.disabled) return;
|
||||
inFlight = true;
|
||||
error.textContent = '';
|
||||
textarea.disabled = true;
|
||||
attachButton.disabled = true;
|
||||
clearButton.disabled = true;
|
||||
if (extraControl) extraControl.querySelectorAll('select,button,input').forEach((el) => { el.disabled = true; });
|
||||
submitButton.textContent = t('screens.channel_editor.text_006');
|
||||
sync();
|
||||
try {
|
||||
const accepted = await confirmPublicHistoryAction({
|
||||
title: t('dialogs.final.consent.publish_title'),
|
||||
aboveEditor: true,
|
||||
text: t('dialogs.final.consent.publish_warning'),
|
||||
confirmLabel: t('dialogs.final.consent.publish_accept'),
|
||||
cancelLabel: t('dialogs.final.consent.return_to_draft'),
|
||||
});
|
||||
if (!isActive() || closed) return;
|
||||
if (!accepted) {
|
||||
inFlight = false;
|
||||
textarea.disabled = false;
|
||||
attachButton.disabled = false;
|
||||
clearButton.disabled = false;
|
||||
if (extraControl) extraControl.querySelectorAll('select,button,input').forEach((el) => { el.disabled = false; });
|
||||
submitButton.textContent = submitLabel;
|
||||
saveDraft();
|
||||
sync();
|
||||
return;
|
||||
}
|
||||
await onSubmit({
|
||||
text: rawText ? textarea.value.trim() : composeMessageWithAttachments(textarea.value.trim(), attachments),
|
||||
attachments: [...attachments],
|
||||
});
|
||||
completed = true;
|
||||
attachments.filter((item) => item?.ar).forEach((item) => markArweaveAttachmentPlaced(login, item));
|
||||
// Не удаляем новый черновик, открытый после закрытия отправляющего редактора.
|
||||
if (!closed || drafts.get(storageKey)?.text === textarea.value) drafts.delete(storageKey);
|
||||
if (!isActive() || closed) return;
|
||||
close();
|
||||
} catch (submitError) {
|
||||
if (!isActive() || closed) return;
|
||||
inFlight = false;
|
||||
textarea.disabled = false;
|
||||
attachButton.disabled = false;
|
||||
clearButton.disabled = false;
|
||||
if (extraControl) extraControl.querySelectorAll('select,button,input').forEach((el) => { el.disabled = false; });
|
||||
submitButton.textContent = submitLabel;
|
||||
error.textContent = toUserMessage(submitError, t('screens.channel_editor.text_007'));
|
||||
saveDraft();
|
||||
sync();
|
||||
}
|
||||
};
|
||||
|
||||
const onDocumentKeydown = (event) => {
|
||||
if (!overlay.isConnected || document.querySelector('.ar-attachment-manager-root, .public-attachment-manager-root')) return;
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
close();
|
||||
return;
|
||||
}
|
||||
if (event.key === 'Enter' && (event.ctrlKey || event.metaKey) && !composing && !event.isComposing) {
|
||||
event.preventDefault();
|
||||
void submit();
|
||||
return;
|
||||
}
|
||||
if (event.key !== 'Tab') return;
|
||||
const focusable = [...overlay.querySelectorAll('button:not(:disabled), textarea:not(:disabled), select:not(:disabled)')].filter((el) => !el.hidden);
|
||||
if (!focusable.length) return;
|
||||
const first = focusable[0];
|
||||
const last = focusable[focusable.length - 1];
|
||||
if (event.shiftKey && document.activeElement === first) {
|
||||
event.preventDefault();
|
||||
last.focus();
|
||||
} else if (!event.shiftKey && document.activeElement === last) {
|
||||
event.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
};
|
||||
|
||||
closeButton.addEventListener('click', () => close());
|
||||
clearButton.addEventListener('click', () => {
|
||||
textarea.value = '';
|
||||
attachments.splice(0);
|
||||
drafts.delete(storageKey);
|
||||
error.textContent = '';
|
||||
sync();
|
||||
textarea.focus();
|
||||
});
|
||||
textarea.addEventListener('input', () => {
|
||||
error.textContent = '';
|
||||
saveDraft();
|
||||
sync();
|
||||
});
|
||||
textarea.addEventListener('compositionstart', () => { composing = true; });
|
||||
extraFields.forEach((field) => field.addEventListener('change', saveDraft));
|
||||
textarea.addEventListener('compositionend', () => { composing = false; });
|
||||
attachButton.addEventListener('click', async () => {
|
||||
if (picking || inFlight) return;
|
||||
if (attachments.length >= MAX_MESSAGE_ATTACHMENTS) {
|
||||
error.textContent = t('screens.channel_editor.text_023', { value1: MAX_MESSAGE_ATTACHMENTS });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
picking = true;
|
||||
dialog.inert = true;
|
||||
sync();
|
||||
const item = await openChannelAttachmentManager({
|
||||
login,
|
||||
storagePwd: state.session.storagePwdInMemory,
|
||||
gateway: state.entrySettings.arweaveServer,
|
||||
selectedTxIds: attachments.map((attachment) => attachment.ar),
|
||||
signal: attachmentController.signal,
|
||||
});
|
||||
if (!isActive() || !overlay.isConnected || !item) return;
|
||||
attachments.push(item);
|
||||
saveDraft();
|
||||
sync();
|
||||
} catch (attachError) {
|
||||
if (isActive() && overlay.isConnected) {
|
||||
error.textContent = toUserMessage(attachError, t('screens.channel_editor.text_008'));
|
||||
}
|
||||
} finally {
|
||||
picking = false;
|
||||
dialog.inert = false;
|
||||
if (!closed) { sync(); attachButton.focus(); }
|
||||
}
|
||||
});
|
||||
submitButton.addEventListener('click', () => void submit());
|
||||
document.addEventListener('keydown', onDocumentKeydown);
|
||||
viewport?.addEventListener('resize', updateViewport);
|
||||
viewport?.addEventListener('scroll', updateViewport);
|
||||
window.addEventListener('resize', updateViewport);
|
||||
observer.observe(root, { childList: true });
|
||||
updateViewport();
|
||||
sync();
|
||||
requestAnimationFrame(() => {
|
||||
if (closed || !isActive()) return;
|
||||
const quote = overlay.querySelector('.channel-editor__context p');
|
||||
const expand = overlay.querySelector('.channel-editor__context-toggle');
|
||||
if (quote && expand && quote.clientHeight > 0) expand.hidden = quote.scrollHeight <= quote.clientHeight;
|
||||
sync();
|
||||
if (chain.length) body.scrollTop = author.offsetTop - body.offsetTop - 120;
|
||||
textarea.focus({ preventScroll: chain.length > 0 });
|
||||
if (openAttachOnStart && allowAttachments) attachButton.click();
|
||||
textarea.setSelectionRange(textarea.value.length, textarea.value.length);
|
||||
});
|
||||
return { close };
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
// Возвращает Promise<boolean>: true — подтвердили, false — отмена, Escape или тап мимо.
|
||||
export function confirmDialog({
|
||||
title = t('remaining.confirmation.confirm_action'),
|
||||
text = '',
|
||||
confirmLabel = t('remaining.confirmation.yes'),
|
||||
cancelLabel = t('remaining.confirmation.cancel'),
|
||||
danger = false,
|
||||
aboveEditor = false,
|
||||
rememberChoice = null,
|
||||
} = {}) {
|
||||
return new Promise((resolve) => {
|
||||
const opener = document.activeElement;
|
||||
const modal = document.createElement('div');
|
||||
modal.className = `modal confirm-dialog${aboveEditor ? ' confirm-dialog--above-editor' : ''}`;
|
||||
modal.innerHTML = `
|
||||
<div class="modal-card confirm-dialog__card" role="alertdialog" aria-modal="true" aria-labelledby="confirm-dialog-title">
|
||||
<h2 class="modal-title" id="confirm-dialog-title"></h2>
|
||||
<p class="confirm-dialog__text"></p>
|
||||
<div class="form-actions-grid">
|
||||
<button type="button" class="secondary-btn" data-answer="no"></button>
|
||||
<button type="button" class="${danger ? 'destructive-btn confirm-dialog__danger' : 'primary-btn'}" data-answer="yes"></button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
modal.querySelector('.modal-title').textContent = title;
|
||||
const textEl = modal.querySelector('.confirm-dialog__text');
|
||||
textEl.textContent = text;
|
||||
textEl.hidden = !text;
|
||||
let rememberCheckbox = null;
|
||||
if (rememberChoice?.label) {
|
||||
const label = document.createElement('label');
|
||||
label.className = 'confirm-dialog__remember';
|
||||
rememberCheckbox = document.createElement('input');
|
||||
rememberCheckbox.type = 'checkbox';
|
||||
const explanation = document.createElement('span');
|
||||
explanation.textContent = rememberChoice.label;
|
||||
label.append(rememberCheckbox, explanation);
|
||||
modal.querySelector('.form-actions-grid').before(label);
|
||||
}
|
||||
modal.querySelector('[data-answer="no"]').textContent = cancelLabel;
|
||||
modal.querySelector('[data-answer="yes"]').textContent = confirmLabel;
|
||||
|
||||
const finish = (answer) => {
|
||||
document.removeEventListener('keydown', onKeydown, true);
|
||||
modal.remove();
|
||||
opener?.focus?.();
|
||||
if (answer && rememberCheckbox?.checked) rememberChoice?.onConfirm?.();
|
||||
resolve(answer);
|
||||
};
|
||||
const onKeydown = (event) => {
|
||||
if (event.key === 'Escape') { event.stopPropagation(); finish(false); }
|
||||
};
|
||||
modal.addEventListener('click', (event) => {
|
||||
if (event.target === modal) { finish(false); return; }
|
||||
const answer = event.target.closest('[data-answer]')?.dataset.answer;
|
||||
if (answer) finish(answer === 'yes');
|
||||
});
|
||||
document.addEventListener('keydown', onKeydown, true);
|
||||
document.body.append(modal);
|
||||
modal.querySelector('[data-answer="no"]').focus();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { openSheet } from './sheet.js';
|
||||
|
||||
// Пошаговое подтверждение перед публичной записью. Ни один шаг не выполняет сетевых запросов.
|
||||
// Текст задаёт вызывающий экран; запись начинается только после прохождения всех шагов.
|
||||
export function confirmConsentSteps({ title = t('remaining.consent.confirmation'), steps = [] } = {}) {
|
||||
if (!steps.length) return Promise.resolve(false);
|
||||
return new Promise((resolve) => {
|
||||
let completed = false;
|
||||
let stepIndex = 0;
|
||||
const content = document.createElement('div');
|
||||
content.className = 'stack profile-consent-flow';
|
||||
const progress = document.createElement('div');
|
||||
progress.className = 'meta-muted profile-consent-progress';
|
||||
const heading = document.createElement('h3');
|
||||
heading.className = 'profile-consent-heading';
|
||||
const paragraph = document.createElement('p');
|
||||
paragraph.className = 'profile-consent-description';
|
||||
const checkboxLabel = document.createElement('label');
|
||||
checkboxLabel.className = 'profile-consent-accept';
|
||||
const checkbox = document.createElement('input');
|
||||
checkbox.type = 'checkbox';
|
||||
const checkboxText = document.createElement('span');
|
||||
checkboxLabel.append(checkbox, checkboxText);
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'form-actions-grid';
|
||||
const cancelBtn = document.createElement('button');
|
||||
cancelBtn.type = 'button';
|
||||
cancelBtn.className = 'secondary-btn';
|
||||
cancelBtn.textContent = t('screens.consent_steps.text_001');
|
||||
const nextBtn = document.createElement('button');
|
||||
nextBtn.type = 'button';
|
||||
nextBtn.className = 'primary-btn';
|
||||
actions.append(cancelBtn, nextBtn);
|
||||
content.append(progress, heading, paragraph, checkboxLabel, actions);
|
||||
|
||||
const sheet = openSheet({
|
||||
title,
|
||||
className: 'profile-consent-sheet',
|
||||
content,
|
||||
onClose: () => resolve(completed),
|
||||
});
|
||||
function renderStep() {
|
||||
const step = steps[stepIndex];
|
||||
progress.textContent = `${stepIndex + 1} / ${steps.length}`;
|
||||
heading.textContent = step.title;
|
||||
paragraph.textContent = step.text;
|
||||
checkbox.checked = false;
|
||||
checkboxLabel.hidden = !step.accept;
|
||||
checkboxText.textContent = step.accept || '';
|
||||
nextBtn.disabled = Boolean(step.accept);
|
||||
nextBtn.textContent = step.button || (stepIndex === steps.length - 1 ? t('screens.consent_steps.text_002') : t('screens.consent_steps.text_003'));
|
||||
}
|
||||
checkbox.addEventListener('change', () => { nextBtn.disabled = !checkbox.checked; });
|
||||
cancelBtn.addEventListener('click', () => sheet.close());
|
||||
nextBtn.addEventListener('click', () => {
|
||||
if (steps[stepIndex].accept && !checkbox.checked) return;
|
||||
if (stepIndex === steps.length - 1) {
|
||||
completed = true;
|
||||
sheet.close();
|
||||
} else {
|
||||
stepIndex += 1;
|
||||
renderStep();
|
||||
}
|
||||
});
|
||||
renderStep();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
// Вложения личных сообщений: превью картинок и видео после расшифровки и карточка файла со «Скачать».
|
||||
// Общие для ленты чата и экрана «Медиа и файлы».
|
||||
import { decryptDmFileToBlob, downloadAndDecryptDmFile, isDmFileExpired } from '../services/dm-file-service.js';
|
||||
import { formatBytes, getAttachmentKind } from '../services/attachment-format.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
import { createSpinner } from './feedback.js';
|
||||
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||
|
||||
// Картинки и видео в личке показываются так же, как в каналах (карусель + просмотрщик),
|
||||
// только файл сначала расшифровывается. Большие файлы остаются карточками со «Скачать»,
|
||||
// чтобы не тратить трафик на автозагрузку.
|
||||
const DM_INLINE_MEDIA_MAX_BYTES = 20 * 1024 * 1024;
|
||||
const DM_MEDIA_MIME = { jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif', webp: 'image/webp', avif: 'image/avif', bmp: 'image/bmp', svg: 'image/svg+xml', mp4: 'video/mp4', m4v: 'video/mp4', webm: 'video/webm', mov: 'video/quicktime', ogv: 'video/ogg' };
|
||||
const dmMediaBlobs = new Map();
|
||||
const DM_MEDIA_CACHE_LIMIT = 40;
|
||||
|
||||
export function isDmInlineMedia(attachment) {
|
||||
if (attachment?.kind === 'voice' || isDmFileExpired(attachment)) return false;
|
||||
const size = Number(attachment?.size || 0);
|
||||
if (!(size > 0 && size <= DM_INLINE_MEDIA_MAX_BYTES)) return false;
|
||||
const kind = getAttachmentKind(attachment);
|
||||
return kind === 'image' || kind === 'video';
|
||||
}
|
||||
|
||||
// Расшифрованный файл держим в памяти: лента перерисовывается на каждое новое сообщение,
|
||||
// и без кэша картинка расшифровывалась бы и мигала заново.
|
||||
export function resolveDmMediaUrl(attachment) {
|
||||
if (isDmFileExpired(attachment)) return Promise.reject(new Error('DM_FILE_EXPIRED'));
|
||||
const key = String(attachment?.id || attachment?.url || '');
|
||||
let pending = dmMediaBlobs.get(key);
|
||||
if (!pending) {
|
||||
const ext = String(attachment?.name || '').split('.').pop().toLowerCase();
|
||||
pending = decryptDmFileToBlob(attachment)
|
||||
.then((blob) => new Blob([blob], { type: DM_MEDIA_MIME[ext] || blob.type || 'application/octet-stream' }));
|
||||
pending.catch(() => dmMediaBlobs.delete(key));
|
||||
dmMediaBlobs.set(key, pending);
|
||||
if (dmMediaBlobs.size > DM_MEDIA_CACHE_LIMIT) dmMediaBlobs.delete(dmMediaBlobs.keys().next().value);
|
||||
}
|
||||
return pending.then((blob) => ({ url: URL.createObjectURL(blob), objectUrl: true }));
|
||||
}
|
||||
|
||||
export function createDmExpiredAttachmentCard(attachment) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'dm-file-card';
|
||||
const copy = document.createElement('span');
|
||||
copy.className = 'dm-file-card__copy';
|
||||
const name = document.createElement('strong');
|
||||
name.className = 'dm-file-card__name';
|
||||
name.textContent = attachment?.name || 'file';
|
||||
const info = document.createElement('span');
|
||||
info.className = 'dm-file-card__meta';
|
||||
info.textContent = t('screens.dm_attachments.file_expired');
|
||||
copy.append(name, info);
|
||||
card.append(copy);
|
||||
return card;
|
||||
}
|
||||
|
||||
export function createDmFileAttachmentCard(attachment) {
|
||||
if (isDmFileExpired(attachment)) return createDmExpiredAttachmentCard(attachment);
|
||||
const fileCard = document.createElement('div');
|
||||
fileCard.className = 'dm-file-card';
|
||||
|
||||
const fileIcon = document.createElement('span');
|
||||
fileIcon.className = 'dm-file-card__icon';
|
||||
fileIcon.setAttribute('aria-hidden', 'true');
|
||||
fileIcon.innerHTML = iconHtml('doc');
|
||||
|
||||
const fileCopy = document.createElement('span');
|
||||
fileCopy.className = 'dm-file-card__copy';
|
||||
const fileName = document.createElement('strong');
|
||||
fileName.className = 'dm-file-card__name';
|
||||
fileName.textContent = attachment.name || 'file';
|
||||
const fileMeta = document.createElement('span');
|
||||
fileMeta.className = 'dm-file-card__meta';
|
||||
const metaParts = [formatBytes(attachment.size)];
|
||||
if (Number(attachment?.version || 1) === 2) metaParts.push('BitTorrent v2');
|
||||
fileMeta.textContent = metaParts.join(' · ');
|
||||
fileCopy.append(fileName, fileMeta);
|
||||
|
||||
// Круглая кнопка со стрелкой; пока файл качается и расшифровывается – проценты в ней же.
|
||||
const downloadBtn = document.createElement('button');
|
||||
downloadBtn.type = 'button';
|
||||
downloadBtn.className = 'dm-file-card__download';
|
||||
downloadBtn.title = t('screens.dm_attachments.text_001');
|
||||
downloadBtn.setAttribute('aria-label', t('screens.dm_attachments.text_007', { value1: attachment.name || t('screens.dm_attachments.text_006') }));
|
||||
const showDownloadIcon = () => {
|
||||
downloadBtn.classList.remove('is-busy');
|
||||
downloadBtn.innerHTML = iconHtml('download');
|
||||
};
|
||||
showDownloadIcon();
|
||||
downloadBtn.addEventListener('click', async (event) => {
|
||||
event.stopPropagation();
|
||||
if (downloadBtn.disabled) return;
|
||||
downloadBtn.disabled = true;
|
||||
downloadBtn.classList.add('is-busy');
|
||||
downloadBtn.replaceChildren(createSpinner({ size: 'sm', label: t('screens.dm_attachments.text_002') }));
|
||||
try {
|
||||
const result = await downloadAndDecryptDmFile(attachment, {
|
||||
onProgress: ({ processedBytes, totalBytes }) => {
|
||||
if (!totalBytes) return;
|
||||
const percent = Math.min(100, Math.max(0, Math.round((processedBytes / totalBytes) * 100)));
|
||||
downloadBtn.textContent = `${percent}%`;
|
||||
},
|
||||
});
|
||||
if (!result?.cancelled) {
|
||||
// Сохранён сразу на диск (по частям) или отдан браузеру – для человека это одно и то же.
|
||||
showToast(result?.streamed ? t('screens.dm_attachments.text_004') : t('screens.dm_attachments.text_005'), { timeoutMs: 1600 });
|
||||
}
|
||||
} catch (error) {
|
||||
showToast(actionErrorText(t('screens.dm_attachments.text_003'), error), { kind: 'error' });
|
||||
} finally {
|
||||
downloadBtn.disabled = false;
|
||||
showDownloadIcon();
|
||||
}
|
||||
});
|
||||
|
||||
fileCard.append(fileIcon, fileCopy, downloadBtn);
|
||||
return fileCard;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
// Пункт меню чата «Без звука» со сроком – общий для шапки чата и меню строки в списке чатов.
|
||||
// Срок выбирается во вложенном списке того же меню; включённый звук возвращается одним нажатием.
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
import { formatDmMuteUntil, getDmChatMutedUntil, setDmChatMuted } from '../services/dm-chat-prefs.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
|
||||
const HOUR = 60 * 60 * 1000;
|
||||
const DURATIONS = () => [
|
||||
[t('screens.dm_mute_menu.text_007'), HOUR],
|
||||
[t('screens.dm_mute_menu.text_008'), 8 * HOUR],
|
||||
[t('screens.dm_mute_menu.text_009'), 24 * HOUR],
|
||||
[t('screens.dm_mute_menu.text_010'), 7 * 24 * HOUR],
|
||||
[t('screens.dm_mute_menu.text_011'), 0],
|
||||
];
|
||||
|
||||
export function createDmMuteMenuItem(chatId, { iconClass = '', onChange = null } = {}) {
|
||||
const until = getDmChatMutedUntil(chatId);
|
||||
if (until !== null) {
|
||||
return {
|
||||
label: t('screens.dm_mute_menu.text_001'),
|
||||
hint: until ? t('screens.dm_mute_menu.text_005', { value1: formatDmMuteUntil(until) }) : '',
|
||||
iconHtml: iconHtml('bell', false, iconClass),
|
||||
action: () => {
|
||||
setDmChatMuted(chatId, false);
|
||||
showToast(t('screens.dm_mute_menu.text_003'), { timeoutMs: 1400 });
|
||||
onChange?.(false);
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
label: t('screens.dm_mute_menu.text_002'),
|
||||
iconHtml: iconHtml('bell-off', false, iconClass),
|
||||
submenu: DURATIONS().map(([label, ms]) => ({
|
||||
label,
|
||||
action: () => {
|
||||
const untilMs = ms ? Date.now() + ms : 0;
|
||||
setDmChatMuted(chatId, true, { untilMs });
|
||||
showToast(untilMs ? t('screens.dm_mute_menu.text_006', { value1: formatDmMuteUntil(untilMs) }) : t('screens.dm_mute_menu.text_004'), { timeoutMs: 1800 });
|
||||
onChange?.(true);
|
||||
},
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
|
||||
let activeDropdown = null;
|
||||
|
||||
function normalizeItems(items) {
|
||||
const value = typeof items === 'function' ? items() : items;
|
||||
return Array.isArray(value) ? value.filter(Boolean) : [];
|
||||
}
|
||||
|
||||
function resolvePlacement({ placement, align }) {
|
||||
if (placement === 'bottom-start' || placement === 'top-start') return 'left';
|
||||
if (placement === 'bottom-end' || placement === 'top-end') return 'right';
|
||||
return align === 'left' ? 'left' : 'right';
|
||||
}
|
||||
|
||||
export function createDropdownMenu({
|
||||
anchorEl,
|
||||
items = [],
|
||||
renderContent = null,
|
||||
className = '',
|
||||
minWidth = 210,
|
||||
offset = 7,
|
||||
placement = 'bottom-end',
|
||||
align = null,
|
||||
leftShift = 0,
|
||||
transparent = false,
|
||||
dimBackground = true,
|
||||
keepAnchorPressed = true,
|
||||
onOpen = null,
|
||||
onClose = null,
|
||||
} = {}) {
|
||||
let portal = null;
|
||||
let menuEl = null;
|
||||
let destroyed = false;
|
||||
|
||||
const setAnchorOpen = (isOpen) => {
|
||||
if (!anchorEl) return;
|
||||
anchorEl.setAttribute('aria-haspopup', 'menu');
|
||||
anchorEl.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
|
||||
if (keepAnchorPressed && isOpen) anchorEl.dataset.open = 'true';
|
||||
else delete anchorEl.dataset.open;
|
||||
};
|
||||
|
||||
const close = ({ focusAnchor = false } = {}) => {
|
||||
if (!portal) return;
|
||||
portal.remove();
|
||||
portal = null;
|
||||
menuEl = null;
|
||||
if (activeDropdown === api) activeDropdown = null;
|
||||
setAnchorOpen(false);
|
||||
onClose?.();
|
||||
if (focusAnchor) anchorEl?.focus?.();
|
||||
};
|
||||
|
||||
const position = () => {
|
||||
if (!portal || !menuEl || !anchorEl) return;
|
||||
const rect = anchorEl.getBoundingClientRect();
|
||||
const margin = 10;
|
||||
const menuWidth = menuEl.offsetWidth || minWidth;
|
||||
const side = resolvePlacement({ placement, align });
|
||||
const baseLeft = side === 'left' ? rect.left : rect.right - menuWidth;
|
||||
const desiredLeft = baseLeft - Number(leftShift || 0);
|
||||
const left = Math.max(margin, Math.min(window.innerWidth - menuWidth - margin, desiredLeft));
|
||||
|
||||
const menuHeight = menuEl.offsetHeight || 180;
|
||||
const prefersTop = String(placement || '').startsWith('top-');
|
||||
let top = prefersTop ? rect.top - menuHeight - offset : rect.bottom + offset;
|
||||
if (!prefersTop && top + menuHeight > window.innerHeight - margin) {
|
||||
top = Math.max(margin, rect.top - menuHeight - offset);
|
||||
} else if (prefersTop && top < margin) {
|
||||
top = Math.min(window.innerHeight - menuHeight - margin, rect.bottom + offset);
|
||||
}
|
||||
|
||||
menuEl.style.left = `${Math.round(left)}px`;
|
||||
menuEl.style.top = `${Math.round(top)}px`;
|
||||
};
|
||||
|
||||
// Пункт с submenu не закрывает меню, а показывает вложенный список на том же месте
|
||||
// (сверху – «назад»): так выбирают, например, срок «без звука».
|
||||
const appendItems = (levelItems = items, parentTitle = '') => {
|
||||
if (parentTitle) {
|
||||
const back = document.createElement('button');
|
||||
back.type = 'button';
|
||||
back.className = 'dropdown-menu__item dropdown-menu__back';
|
||||
back.setAttribute('aria-label', t('screens.dropdown_menu.text_001', { value1: parentTitle }));
|
||||
back.innerHTML = `<span class="dropdown-menu__icon">${iconHtml('back')}</span>`;
|
||||
const backLabel = document.createElement('span');
|
||||
backLabel.textContent = parentTitle;
|
||||
back.append(backLabel);
|
||||
back.addEventListener('click', (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
showLevel(items, '');
|
||||
});
|
||||
const divider = document.createElement('div');
|
||||
divider.className = 'dropdown-menu__divider';
|
||||
divider.setAttribute('role', 'separator');
|
||||
menuEl.append(back, divider);
|
||||
}
|
||||
normalizeItems(levelItems).forEach((item) => {
|
||||
if (item.divider) {
|
||||
const divider = document.createElement('div');
|
||||
divider.className = 'dropdown-menu__divider';
|
||||
divider.setAttribute('role', 'separator');
|
||||
menuEl.append(divider);
|
||||
return;
|
||||
}
|
||||
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = `dropdown-menu__item${item.selected ? ' is-selected' : ''}${item.danger ? ' is-danger' : ''}${item.className ? ` ${item.className}` : ''}`;
|
||||
button.setAttribute('role', 'menuitem');
|
||||
button.disabled = Boolean(item.disabled);
|
||||
|
||||
if (item.iconHtml) {
|
||||
const icon = document.createElement('span');
|
||||
icon.className = 'dropdown-menu__icon';
|
||||
icon.innerHTML = item.iconHtml;
|
||||
button.append(icon);
|
||||
} else if (item.iconSrc) {
|
||||
const icon = document.createElement('img');
|
||||
icon.className = 'dropdown-menu__icon';
|
||||
icon.src = item.iconSrc;
|
||||
icon.alt = '';
|
||||
icon.setAttribute('aria-hidden', 'true');
|
||||
button.append(icon);
|
||||
}
|
||||
|
||||
const label = document.createElement('span');
|
||||
label.textContent = String(item.label || '');
|
||||
if (item.hint) {
|
||||
const text = document.createElement('span');
|
||||
text.className = 'dropdown-menu__text';
|
||||
const hint = document.createElement('small');
|
||||
hint.className = 'dropdown-menu__hint';
|
||||
hint.textContent = String(item.hint);
|
||||
text.append(label, hint);
|
||||
button.append(text);
|
||||
} else {
|
||||
button.append(label);
|
||||
}
|
||||
if (item.submenu) {
|
||||
button.setAttribute('aria-haspopup', 'menu');
|
||||
const chevron = document.createElement('span');
|
||||
chevron.className = 'dropdown-menu__chevron';
|
||||
chevron.setAttribute('aria-hidden', 'true');
|
||||
chevron.innerHTML = iconHtml('chevron');
|
||||
button.append(chevron);
|
||||
}
|
||||
button.addEventListener('click', async (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (button.disabled) return;
|
||||
if (item.submenu) {
|
||||
showLevel(item.submenu, String(item.submenuTitle || item.label || ''));
|
||||
return;
|
||||
}
|
||||
close({ focusAnchor: true });
|
||||
await item.action?.();
|
||||
});
|
||||
menuEl.append(button);
|
||||
});
|
||||
};
|
||||
|
||||
const showLevel = (levelItems, parentTitle) => {
|
||||
if (!menuEl) return;
|
||||
menuEl.replaceChildren();
|
||||
appendItems(levelItems, parentTitle);
|
||||
position();
|
||||
// Во вложенном списке фокус – на первый вариант, а не на «назад».
|
||||
(menuEl.querySelector('button:not(:disabled):not(.dropdown-menu__back)')
|
||||
|| menuEl.querySelector('button:not(:disabled)'))?.focus();
|
||||
};
|
||||
|
||||
const open = () => {
|
||||
if (destroyed || !anchorEl || portal) return;
|
||||
if (activeDropdown && activeDropdown !== api) activeDropdown.close();
|
||||
|
||||
portal = document.createElement('div');
|
||||
portal.className = `dropdown-portal${dimBackground ? ' dropdown-portal--dim' : ''}`;
|
||||
|
||||
if (dimBackground) {
|
||||
const backdrop = document.createElement('div');
|
||||
backdrop.className = 'dropdown-backdrop';
|
||||
backdrop.setAttribute('aria-hidden', 'true');
|
||||
backdrop.addEventListener('pointerdown', (event) => {
|
||||
if (event.target === backdrop) close();
|
||||
});
|
||||
portal.append(backdrop);
|
||||
}
|
||||
|
||||
menuEl = document.createElement('div');
|
||||
menuEl.className = `dropdown-menu${transparent ? ' dropdown-menu--transparent' : ''}${className ? ` ${className}` : ''}`;
|
||||
menuEl.setAttribute('role', 'menu');
|
||||
menuEl.style.minWidth = `${minWidth}px`;
|
||||
|
||||
if (typeof renderContent === 'function') {
|
||||
const content = renderContent({ close, menuEl });
|
||||
if (content instanceof Node) menuEl.append(content);
|
||||
} else {
|
||||
appendItems();
|
||||
}
|
||||
|
||||
menuEl.addEventListener('pointerdown', (event) => event.stopPropagation());
|
||||
menuEl.addEventListener('click', (event) => event.stopPropagation());
|
||||
portal.append(menuEl);
|
||||
document.body.append(portal);
|
||||
activeDropdown = api;
|
||||
setAnchorOpen(true);
|
||||
onOpen?.();
|
||||
position();
|
||||
menuEl.querySelector('button:not(:disabled)')?.focus();
|
||||
};
|
||||
|
||||
const toggle = () => {
|
||||
if (portal) close();
|
||||
else open();
|
||||
};
|
||||
|
||||
const onAnchorClick = (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
toggle();
|
||||
};
|
||||
const onOutsidePointerDown = (event) => {
|
||||
if (!portal) return;
|
||||
if (menuEl?.contains(event.target) || anchorEl?.contains(event.target)) return;
|
||||
close();
|
||||
};
|
||||
const onKeydown = (event) => {
|
||||
if (!portal) return;
|
||||
if (event.key === 'Escape' || event.key === 'Tab') {
|
||||
if (event.key === 'Escape') event.preventDefault();
|
||||
close({ focusAnchor: true });
|
||||
return;
|
||||
}
|
||||
if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) return;
|
||||
const buttons = [...menuEl.querySelectorAll('button:not(:disabled)')];
|
||||
if (!buttons.length) return;
|
||||
event.preventDefault();
|
||||
const index = buttons.indexOf(document.activeElement);
|
||||
const next = event.key === 'Home' ? 0 : event.key === 'End' ? buttons.length - 1 : (index + (event.key === 'ArrowUp' ? -1 : 1) + buttons.length) % buttons.length;
|
||||
buttons[next].focus();
|
||||
};
|
||||
const onNavigation = () => close();
|
||||
const onViewportChange = () => position();
|
||||
|
||||
setAnchorOpen(false);
|
||||
anchorEl?.addEventListener('click', onAnchorClick);
|
||||
document.addEventListener('pointerdown', onOutsidePointerDown, true);
|
||||
document.addEventListener('keydown', onKeydown);
|
||||
window.addEventListener('popstate', onNavigation);
|
||||
window.addEventListener('hashchange', onNavigation);
|
||||
window.addEventListener('resize', onViewportChange, { passive: true });
|
||||
window.addEventListener('scroll', onViewportChange, { passive: true, capture: true });
|
||||
|
||||
const api = {
|
||||
open,
|
||||
close,
|
||||
toggle,
|
||||
position,
|
||||
get isOpen() {
|
||||
return Boolean(portal);
|
||||
},
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
destroyed = true;
|
||||
close();
|
||||
anchorEl?.removeEventListener('click', onAnchorClick);
|
||||
document.removeEventListener('pointerdown', onOutsidePointerDown, true);
|
||||
document.removeEventListener('keydown', onKeydown);
|
||||
window.removeEventListener('popstate', onNavigation);
|
||||
window.removeEventListener('hashchange', onNavigation);
|
||||
window.removeEventListener('resize', onViewportChange);
|
||||
window.removeEventListener('scroll', onViewportChange, true);
|
||||
setAnchorOpen(false);
|
||||
},
|
||||
};
|
||||
|
||||
return api;
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
import {
|
||||
TWEMOJI_GROUPS,
|
||||
getTwemojiAssetUrl,
|
||||
getTwemojiPreviewUrl,
|
||||
} from './twemoji-catalog.js?v=202607151545';
|
||||
|
||||
const RECENT_STORAGE_KEY = 'shine-ui-recent-emojis-v1';
|
||||
const MAX_RECENT = 28;
|
||||
const ALL_EMOJI_ITEMS = TWEMOJI_GROUPS.flatMap((group) => group.items);
|
||||
const EMOJI_ASSET_BY_CHAR = new Map(ALL_EMOJI_ITEMS.map((item) => [item.emoji, item]));
|
||||
const TWEMOJI_MATCHER = new RegExp(
|
||||
[...EMOJI_ASSET_BY_CHAR.keys()]
|
||||
.sort((left, right) => right.length - left.length)
|
||||
.map((emoji) => emoji.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&'))
|
||||
.join('|'),
|
||||
'gu',
|
||||
);
|
||||
const DEFAULT_RECENT = ALL_EMOJI_ITEMS.slice(0, 7).map((item) => item.emoji);
|
||||
let activeAnimation = null;
|
||||
|
||||
function loadRecent() {
|
||||
try {
|
||||
const parsed = JSON.parse(localStorage.getItem(RECENT_STORAGE_KEY) || '[]');
|
||||
return Array.isArray(parsed)
|
||||
? parsed.filter((item) => typeof item === 'string' && item).slice(0, MAX_RECENT)
|
||||
: [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function saveRecent(items) {
|
||||
try {
|
||||
localStorage.setItem(RECENT_STORAGE_KEY, JSON.stringify(items.slice(0, MAX_RECENT)));
|
||||
} catch {
|
||||
// Selection remains usable when browser storage is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
function appendAnimatedAsset(root, item) {
|
||||
const previewUrl = item.previewUrl || getTwemojiPreviewUrl(item.emoji);
|
||||
const animatedUrl = item.animatedUrl || getTwemojiAssetUrl(item.emoji);
|
||||
const hasAnimation = animatedUrl && animatedUrl !== previewUrl;
|
||||
const image = document.createElement('img');
|
||||
image.className = 'twemoji-image';
|
||||
image.alt = '';
|
||||
image.decoding = 'async';
|
||||
image.setAttribute('aria-hidden', 'true');
|
||||
|
||||
// Без отдельного анимационного ассета — просто статичная картинка,
|
||||
// без hover/tap-подмены src и pointer capture (лишние запросы и «моргание»).
|
||||
if (!hasAnimation) {
|
||||
image.src = previewUrl;
|
||||
image.onerror = () => {
|
||||
root.classList.add('is-error');
|
||||
image.removeAttribute('src');
|
||||
};
|
||||
root.append(image);
|
||||
return;
|
||||
}
|
||||
|
||||
let isActive = false;
|
||||
let sourceVersion = 0;
|
||||
|
||||
const setSource = (source) => {
|
||||
const requestedVersion = sourceVersion + 1;
|
||||
sourceVersion = requestedVersion;
|
||||
root.classList.remove('is-error');
|
||||
image.onload = () => {
|
||||
if (requestedVersion !== sourceVersion) return;
|
||||
if (isActive) root.classList.remove('is-loading');
|
||||
};
|
||||
image.onerror = () => {
|
||||
if (requestedVersion !== sourceVersion) return;
|
||||
if (isActive) {
|
||||
isActive = false;
|
||||
root.classList.remove('is-active', 'is-loading');
|
||||
if (activeAnimation?.root === root) activeAnimation = null;
|
||||
setSource(previewUrl);
|
||||
return;
|
||||
}
|
||||
root.classList.add('is-error');
|
||||
image.removeAttribute('src');
|
||||
};
|
||||
image.src = source;
|
||||
};
|
||||
|
||||
const deactivate = () => {
|
||||
isActive = false;
|
||||
root.classList.remove('is-active', 'is-loading', 'is-error');
|
||||
if (activeAnimation?.root === root) activeAnimation = null;
|
||||
setSource(previewUrl);
|
||||
};
|
||||
|
||||
const activate = () => {
|
||||
if (activeAnimation?.root && activeAnimation.root !== root) {
|
||||
activeAnimation.deactivate();
|
||||
}
|
||||
activeAnimation = { root, deactivate };
|
||||
isActive = true;
|
||||
root.classList.add('is-active', 'is-loading');
|
||||
setSource(animatedUrl);
|
||||
};
|
||||
|
||||
const onPointerOver = (event) => {
|
||||
if (event.relatedTarget && root.contains(event.relatedTarget)) return;
|
||||
if (event.pointerType === 'mouse') activate();
|
||||
};
|
||||
|
||||
const onPointerOut = (event) => {
|
||||
if (event.relatedTarget && root.contains(event.relatedTarget)) return;
|
||||
if (event.pointerType === 'mouse') deactivate();
|
||||
};
|
||||
|
||||
const onPointerDown = (event) => {
|
||||
if (event.pointerType === 'mouse') return;
|
||||
root.setPointerCapture?.(event.pointerId);
|
||||
activate();
|
||||
};
|
||||
|
||||
const onPointerEnd = (event) => {
|
||||
if (event.pointerType === 'mouse') return;
|
||||
if (root.hasPointerCapture?.(event.pointerId)) root.releasePointerCapture?.(event.pointerId);
|
||||
deactivate();
|
||||
};
|
||||
|
||||
root.addEventListener('pointerover', onPointerOver);
|
||||
root.addEventListener('pointerout', onPointerOut);
|
||||
root.addEventListener('pointerdown', onPointerDown);
|
||||
root.addEventListener('pointerup', onPointerEnd);
|
||||
root.addEventListener('pointercancel', onPointerEnd);
|
||||
root.addEventListener('lostpointercapture', deactivate);
|
||||
setSource(previewUrl);
|
||||
root.append(image);
|
||||
}
|
||||
|
||||
export function stopAllTwemojiAnimations() {
|
||||
activeAnimation?.deactivate();
|
||||
activeAnimation = null;
|
||||
}
|
||||
|
||||
function createEmojiButton(item, onSelect) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'emoji-picker-item';
|
||||
button.setAttribute('aria-label', `Add ${item.emoji}`);
|
||||
button.title = item.emoji;
|
||||
button.addEventListener('pointerdown', (event) => event.preventDefault());
|
||||
button.addEventListener('click', () => onSelect(item.emoji));
|
||||
|
||||
const preview = document.createElement('span');
|
||||
preview.className = 'emoji-picker-preview';
|
||||
appendAnimatedAsset(preview, item);
|
||||
button.append(preview);
|
||||
return button;
|
||||
}
|
||||
|
||||
export function hasTwemojiAsset(emoji) {
|
||||
return EMOJI_ASSET_BY_CHAR.has(emoji);
|
||||
}
|
||||
|
||||
export function createTwemojiAsset(emoji, { className = '' } = {}) {
|
||||
const item = EMOJI_ASSET_BY_CHAR.get(emoji);
|
||||
const root = document.createElement('span');
|
||||
root.className = `twemoji ${className}`.trim();
|
||||
root.setAttribute('aria-label', emoji);
|
||||
root.setAttribute('role', 'img');
|
||||
|
||||
if (!item) {
|
||||
root.textContent = emoji;
|
||||
return root;
|
||||
}
|
||||
|
||||
appendAnimatedAsset(root, item);
|
||||
return root;
|
||||
}
|
||||
|
||||
export function appendTwemojiText(root, text, { className = '' } = {}) {
|
||||
const source = String(text || '');
|
||||
let cursor = 0;
|
||||
let found = false;
|
||||
|
||||
TWEMOJI_MATCHER.lastIndex = 0;
|
||||
for (const match of source.matchAll(TWEMOJI_MATCHER)) {
|
||||
const index = Number(match.index || 0);
|
||||
if (index > cursor) root.append(document.createTextNode(source.slice(cursor, index)));
|
||||
root.append(createTwemojiAsset(match[0], { className }));
|
||||
cursor = index + match[0].length;
|
||||
found = true;
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
root.textContent = source;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (cursor < source.length) root.append(document.createTextNode(source.slice(cursor)));
|
||||
return true;
|
||||
}
|
||||
|
||||
export function createEmojiPicker({ onSelect }) {
|
||||
const root = document.createElement('section');
|
||||
root.className = 'emoji-picker';
|
||||
root.setAttribute('aria-label', 'Emoji picker');
|
||||
|
||||
const recentSection = document.createElement('section');
|
||||
recentSection.className = 'emoji-picker-section emoji-picker-recent';
|
||||
const recentTitle = document.createElement('strong');
|
||||
recentTitle.className = 'emoji-picker-section-title';
|
||||
recentTitle.textContent = 'Recent';
|
||||
const recentGrid = document.createElement('div');
|
||||
recentGrid.className = 'emoji-picker-grid';
|
||||
recentSection.append(recentTitle, recentGrid);
|
||||
|
||||
const categoryTabs = document.createElement('div');
|
||||
categoryTabs.className = 'emoji-picker-tabs';
|
||||
categoryTabs.setAttribute('role', 'tablist');
|
||||
|
||||
const categorySection = document.createElement('section');
|
||||
categorySection.className = 'emoji-picker-section';
|
||||
const categoryTitle = document.createElement('strong');
|
||||
categoryTitle.className = 'emoji-picker-section-title';
|
||||
const categoryGrid = document.createElement('div');
|
||||
categoryGrid.className = 'emoji-picker-grid';
|
||||
categorySection.append(categoryTitle, categoryGrid);
|
||||
|
||||
let activeGroup = TWEMOJI_GROUPS[0];
|
||||
const tabs = new Map();
|
||||
|
||||
const rememberAndSelect = (emoji) => {
|
||||
const recent = [emoji, ...loadRecent().filter((item) => item !== emoji)];
|
||||
saveRecent(recent);
|
||||
renderRecent();
|
||||
onSelect?.(emoji);
|
||||
};
|
||||
|
||||
const renderRecent = () => {
|
||||
const recentItems = (loadRecent().length ? loadRecent() : DEFAULT_RECENT)
|
||||
.map((emoji) => EMOJI_ASSET_BY_CHAR.get(emoji))
|
||||
.filter(Boolean);
|
||||
stopAllTwemojiAnimations();
|
||||
recentGrid.replaceChildren(...recentItems.map((item) => createEmojiButton(item, rememberAndSelect)));
|
||||
};
|
||||
|
||||
const renderGroup = () => {
|
||||
categoryTitle.textContent = activeGroup.label;
|
||||
stopAllTwemojiAnimations();
|
||||
categoryGrid.replaceChildren(...activeGroup.items.map((item) => createEmojiButton(item, rememberAndSelect)));
|
||||
tabs.forEach((tab, groupId) => {
|
||||
const active = groupId === activeGroup.id;
|
||||
tab.classList.toggle('is-active', active);
|
||||
tab.setAttribute('aria-selected', String(active));
|
||||
});
|
||||
};
|
||||
|
||||
TWEMOJI_GROUPS.forEach((group) => {
|
||||
const tab = document.createElement('button');
|
||||
tab.type = 'button';
|
||||
tab.className = 'emoji-picker-tab';
|
||||
tab.textContent = group.icon;
|
||||
tab.title = group.label;
|
||||
tab.setAttribute('aria-label', group.label);
|
||||
tab.setAttribute('role', 'tab');
|
||||
tab.addEventListener('click', () => {
|
||||
activeGroup = group;
|
||||
renderGroup();
|
||||
});
|
||||
tabs.set(group.id, tab);
|
||||
categoryTabs.append(tab);
|
||||
});
|
||||
|
||||
root.append(recentSection, categoryTabs, categorySection);
|
||||
renderRecent();
|
||||
renderGroup();
|
||||
return root;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
// Общие состояния экрана: загрузка, «пусто» и ошибка – один вид на всё приложение.
|
||||
// Индикатор загрузки появляется с задержкой (CSS): если данные пришли быстро, его не видно
|
||||
// вовсе, и экран не мелькает.
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
|
||||
export function createSpinner({ size = 'md', label = t('remaining.feedback.loading') } = {}) {
|
||||
const el = document.createElement('span');
|
||||
el.className = `spinner spinner--${size}`;
|
||||
el.setAttribute('role', 'status');
|
||||
el.setAttribute('aria-label', label);
|
||||
return el;
|
||||
}
|
||||
|
||||
export function createLoadingState({ label = t('remaining.feedback.loading'), delayMs = 350, className = '' } = {}) {
|
||||
const el = document.createElement('div');
|
||||
el.className = `loading-state${className ? ` ${className}` : ''}`;
|
||||
el.style.setProperty('--loading-delay', `${Math.max(0, Number(delayMs) || 0)}ms`);
|
||||
el.append(createSpinner({ label }));
|
||||
return el;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сообщение вместо содержимого: пусто или ошибка, с необязательным действием.
|
||||
* @param {{ kind?: 'empty'|'error', icon?: string, title?: string, text?: string,
|
||||
* actionLabel?: string, onAction?: Function, className?: string }} opts
|
||||
*/
|
||||
export function createStateMessage({
|
||||
kind = 'empty', icon = '', title = '', text = '', actionLabel = '', onAction = null, className = '',
|
||||
} = {}) {
|
||||
const el = document.createElement('div');
|
||||
el.className = `state-message state-message--${kind}${className ? ` ${className}` : ''}`;
|
||||
if (kind === 'error') el.setAttribute('role', 'alert');
|
||||
if (icon) {
|
||||
const badge = document.createElement('span');
|
||||
badge.className = 'state-message__icon';
|
||||
badge.innerHTML = iconHtml(icon);
|
||||
el.append(badge);
|
||||
}
|
||||
if (title) {
|
||||
const heading = document.createElement('p');
|
||||
heading.className = 'state-message__title';
|
||||
heading.textContent = title;
|
||||
el.append(heading);
|
||||
}
|
||||
if (text) {
|
||||
const body = document.createElement('p');
|
||||
body.className = 'state-message__text';
|
||||
body.textContent = text;
|
||||
el.append(body);
|
||||
}
|
||||
if (actionLabel && typeof onAction === 'function') {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = `${kind === 'error' ? 'secondary-btn' : 'primary-btn'} state-message__action`;
|
||||
button.textContent = actionLabel;
|
||||
button.addEventListener('click', onAction);
|
||||
el.append(button);
|
||||
}
|
||||
return el;
|
||||
}
|
||||
|
||||
export function createErrorState({
|
||||
title = t('remaining.feedback.could_not_load'),
|
||||
text = t('remaining.feedback.check_your_connection_and_try_again'),
|
||||
onRetry = null,
|
||||
className = '',
|
||||
} = {}) {
|
||||
return createStateMessage({
|
||||
kind: 'error', icon: 'alert', title, text, actionLabel: onRetry ? t('screens.feedback.text_001') : '', onAction: onRetry, className,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { getShowPublicHistoryWarning, setShowPublicHistoryWarning, getPublicHistoryRememberLabel } from '../services/public-history-consent.js';
|
||||
import { openSheet } from './sheet.js';
|
||||
|
||||
function safeCount(raw, maximum = Infinity) {
|
||||
const count = Number(raw);
|
||||
return Number.isFinite(count) ? Math.max(0, Math.min(maximum, Math.trunc(count))) : 0;
|
||||
}
|
||||
|
||||
// Значения счётчиков получены от сервера, это не криптографическая аттестация личности.
|
||||
export function confirmLikeAction(options = {}) {
|
||||
if (!getShowPublicHistoryWarning()) return Promise.resolve(true);
|
||||
return openLikeSheet(options);
|
||||
}
|
||||
|
||||
// Просмотр счётчиков не является действием в блокчейне и не спрашивает согласие.
|
||||
export function showLikeStatistics({ counts = {}, onViewList = null } = {}) {
|
||||
return openLikeSheet({ counts, onViewList, readOnly: true });
|
||||
}
|
||||
|
||||
function openLikeSheet({ liked = false, counts = {}, onViewList = null, readOnly = false } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
let accepted = false;
|
||||
const all = safeCount(counts.all ?? counts.likesCount);
|
||||
const official = safeCount(counts.official ?? counts.primaryLikesCount, all);
|
||||
const shining = safeCount(counts.shining ?? counts.shiningLikesCount, official);
|
||||
const body = document.createElement('div');
|
||||
body.className = 'stack like-consent';
|
||||
const intro = document.createElement('p');
|
||||
intro.textContent = t('dialogs.modals.like_action_sheet.label_001');
|
||||
const grid = document.createElement('div');
|
||||
grid.className = 'like-consent-counters';
|
||||
const categories = [
|
||||
{ label: t('dialogs.remaining.components.like_action_sheet.openlikesheet.ofitsialnye_siyayuschie'), count: shining, type: 'shining' },
|
||||
{ label: t('dialogs.remaining.components.like_action_sheet.openlikesheet.vse_ofitsialnye'), count: official, type: 'official' },
|
||||
{ label: t('dialogs.remaining.components.like_action_sheet.openlikesheet.vse_akkaunty'), count: all, type: 'all' },
|
||||
];
|
||||
categories.forEach(({ label, count, type }) => {
|
||||
const item = document.createElement(onViewList ? 'button' : 'div');
|
||||
item.className = 'like-consent-count';
|
||||
if (onViewList) {
|
||||
item.type = 'button';
|
||||
item.addEventListener('click', () => {
|
||||
sheet.close();
|
||||
onViewList(type);
|
||||
});
|
||||
}
|
||||
const number = document.createElement('strong');
|
||||
number.textContent = String(count);
|
||||
const name = document.createElement('span');
|
||||
name.textContent = label;
|
||||
item.append(number, name);
|
||||
grid.append(item);
|
||||
});
|
||||
const warning = document.createElement('p');
|
||||
warning.className = 'meta-muted';
|
||||
warning.textContent = t('dialogs.modals.like_action_sheet.label_002');
|
||||
const rememberLabel = document.createElement('label');
|
||||
rememberLabel.className = 'confirm-dialog__remember';
|
||||
const remember = document.createElement('input');
|
||||
remember.type = 'checkbox';
|
||||
const rememberText = document.createElement('span');
|
||||
rememberText.textContent = getPublicHistoryRememberLabel();
|
||||
rememberLabel.append(remember, rememberText);
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'form-actions-grid';
|
||||
const cancel = document.createElement('button');
|
||||
cancel.type = 'button';
|
||||
cancel.className = 'secondary-btn';
|
||||
cancel.textContent = readOnly ? t('dialogs.modals.like_action_sheet.label_003') : t('dialogs.remaining.components.like_action_sheet.openlikesheet.ne_menyat');
|
||||
const confirm = document.createElement('button');
|
||||
confirm.type = 'button';
|
||||
confirm.className = 'primary-btn';
|
||||
confirm.textContent = liked ? t('dialogs.modals.like_action_sheet.label_004') : t('dialogs.remaining.components.like_action_sheet.openlikesheet.dobavit_moy_layk');
|
||||
if (readOnly) actions.append(cancel);
|
||||
else actions.append(cancel, confirm);
|
||||
body.append(intro, grid);
|
||||
if (!readOnly) body.append(warning, rememberLabel);
|
||||
body.append(actions);
|
||||
const sheet = openSheet({ title: t('dialogs.modals.like_action_sheet.label_005'), className: 'like-consent-sheet', content: body, onClose: () => resolve(accepted) });
|
||||
cancel.addEventListener('click', () => sheet.close());
|
||||
confirm.addEventListener('click', () => { if (remember.checked) setShowPublicHistoryWarning(false); accepted = true; sheet.close(); });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
// Полноэкранный просмотр фото и видео из вложений: листание, «Скачать».
|
||||
// Закрывается крестиком, Esc, смахиванием вниз или переходом назад.
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
|
||||
let activeClose = null;
|
||||
|
||||
function safeFileName(name, kind) {
|
||||
const clean = String(name || '').trim().replace(/[\\/:*?"<>|]+/g, '_');
|
||||
if (clean) return clean;
|
||||
return kind === 'video' ? 'video.mp4' : 'image.jpg';
|
||||
}
|
||||
|
||||
// Arweave отдаёт файл с другого адреса: атрибут download там не работает, поэтому скачиваем через blob.
|
||||
async function downloadMedia(item) {
|
||||
const name = safeFileName(item.name, item.kind);
|
||||
try {
|
||||
const response = await fetch(item.url);
|
||||
if (!response.ok) throw new Error(String(response.status));
|
||||
const blobUrl = URL.createObjectURL(await response.blob());
|
||||
const link = document.createElement('a');
|
||||
link.href = blobUrl;
|
||||
link.download = name;
|
||||
document.body.append(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
window.setTimeout(() => URL.revokeObjectURL(blobUrl), 30000);
|
||||
} catch {
|
||||
window.open(item.url, '_blank', 'noopener');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* items: [{ url, kind: 'image' | 'video', name }], index – с какого начать.
|
||||
*/
|
||||
export function openMediaViewer(items = [], index = 0) {
|
||||
const list = items.filter((item) => item?.url && (item.kind === 'image' || item.kind === 'video'));
|
||||
if (!list.length) return;
|
||||
activeClose?.();
|
||||
|
||||
let current = Math.max(0, Math.min(list.length - 1, index));
|
||||
const root = document.getElementById('modal-root') || document.body;
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'media-viewer';
|
||||
overlay.setAttribute('role', 'dialog');
|
||||
overlay.setAttribute('aria-modal', 'true');
|
||||
overlay.setAttribute('aria-label', t('screens.media_viewer.text_006'));
|
||||
// Сверху – только «закрыть»; счётчик и «Скачать» – сразу под фото, по центру.
|
||||
overlay.innerHTML = `
|
||||
<div class="media-viewer__bar">
|
||||
<button class="media-viewer__btn" type="button" data-action="close" aria-label="${th('screens.media_viewer.text_001')}">${iconHtml('close')}</button>
|
||||
</div>
|
||||
<div class="media-viewer__stage">
|
||||
<div class="media-viewer__frame"></div>
|
||||
<div class="media-viewer__controls">
|
||||
<span class="media-viewer__counter"></span>
|
||||
<button class="media-viewer__btn media-viewer__btn--round" type="button" data-action="download" aria-label="${th('screens.media_viewer.text_002')}" title="${th('screens.media_viewer.text_003')}">${iconHtml('download')}</button>
|
||||
</div>
|
||||
</div>
|
||||
<button class="media-viewer__nav media-viewer__nav--prev" type="button" data-action="prev" aria-label="${th('screens.media_viewer.text_004')}">${iconHtml('back')}</button>
|
||||
<button class="media-viewer__nav media-viewer__nav--next" type="button" data-action="next" aria-label="${th('screens.media_viewer.text_005')}">${iconHtml('open')}</button>
|
||||
`;
|
||||
const stage = overlay.querySelector('.media-viewer__stage');
|
||||
const frame = overlay.querySelector('.media-viewer__frame');
|
||||
const counter = overlay.querySelector('.media-viewer__counter');
|
||||
const prevBtn = overlay.querySelector('[data-action="prev"]');
|
||||
const nextBtn = overlay.querySelector('[data-action="next"]');
|
||||
|
||||
const render = () => {
|
||||
stage.querySelectorAll('video').forEach((video) => video.pause());
|
||||
const item = list[current];
|
||||
let media;
|
||||
if (item.kind === 'video') {
|
||||
media = document.createElement('video');
|
||||
media.controls = true;
|
||||
media.autoplay = true;
|
||||
media.playsInline = true;
|
||||
} else {
|
||||
media = document.createElement('img');
|
||||
media.alt = item.name || '';
|
||||
media.decoding = 'async';
|
||||
}
|
||||
media.className = 'media-viewer__media';
|
||||
media.src = item.url;
|
||||
frame.replaceChildren(media);
|
||||
counter.textContent = list.length > 1 ? `${current + 1}/${list.length}` : '';
|
||||
counter.hidden = list.length <= 1;
|
||||
prevBtn.hidden = current <= 0;
|
||||
nextBtn.hidden = current >= list.length - 1;
|
||||
};
|
||||
|
||||
const go = (delta) => {
|
||||
const next = current + delta;
|
||||
if (next < 0 || next >= list.length) return;
|
||||
current = next;
|
||||
render();
|
||||
};
|
||||
|
||||
const onKey = (event) => {
|
||||
if (event.key === 'Escape') close();
|
||||
else if (event.key === 'ArrowLeft') go(-1);
|
||||
else if (event.key === 'ArrowRight') go(1);
|
||||
};
|
||||
const onPopState = () => close();
|
||||
|
||||
const close = () => {
|
||||
if (activeClose !== close) return;
|
||||
activeClose = null;
|
||||
document.removeEventListener('keydown', onKey);
|
||||
window.removeEventListener('popstate', onPopState);
|
||||
stage.querySelectorAll('video').forEach((video) => video.pause());
|
||||
overlay.remove();
|
||||
};
|
||||
|
||||
let swiped = false;
|
||||
overlay.addEventListener('click', (event) => {
|
||||
// Клик, который браузер присылает после смахивания, не должен прятать панель или закрывать просмотр.
|
||||
if (swiped) { swiped = false; return; }
|
||||
const action = event.target.closest('[data-action]')?.dataset.action;
|
||||
if (action === 'close') close();
|
||||
else if (action === 'prev') go(-1);
|
||||
else if (action === 'next') go(1);
|
||||
else if (action === 'download') void downloadMedia(list[current]);
|
||||
else if (event.target.closest('.media-viewer__media')?.tagName === 'IMG') overlay.classList.toggle('is-bare');
|
||||
else if (event.target === stage || event.target === frame || event.target === overlay) close();
|
||||
});
|
||||
|
||||
// Смахивание: вбок – листать, вниз – закрыть.
|
||||
let startX = 0;
|
||||
let startY = 0;
|
||||
let tracking = false;
|
||||
stage.addEventListener('pointerdown', (event) => {
|
||||
if (event.target.tagName === 'VIDEO') return;
|
||||
tracking = true;
|
||||
startX = event.clientX;
|
||||
startY = event.clientY;
|
||||
});
|
||||
stage.addEventListener('pointermove', (event) => {
|
||||
if (!tracking) return;
|
||||
const dy = event.clientY - startY;
|
||||
if (dy > 0 && Math.abs(dy) > Math.abs(event.clientX - startX)) {
|
||||
stage.style.transform = `translateY(${dy}px)`;
|
||||
overlay.style.setProperty('--viewer-dim', String(Math.max(0.4, 1 - dy / 400)));
|
||||
}
|
||||
});
|
||||
const endSwipe = (event) => {
|
||||
if (!tracking) return;
|
||||
tracking = false;
|
||||
const dx = event.clientX - startX;
|
||||
const dy = event.clientY - startY;
|
||||
swiped = Math.hypot(dx, dy) > 10;
|
||||
stage.style.transform = '';
|
||||
overlay.style.removeProperty('--viewer-dim');
|
||||
if (dy > 90 && dy > Math.abs(dx)) close();
|
||||
else if (Math.abs(dx) > 50 && Math.abs(dx) > Math.abs(dy)) go(dx < 0 ? 1 : -1);
|
||||
};
|
||||
stage.addEventListener('pointerup', endSwipe);
|
||||
stage.addEventListener('pointercancel', endSwipe);
|
||||
|
||||
document.addEventListener('keydown', onKey);
|
||||
window.addEventListener('popstate', onPopState);
|
||||
activeClose = close;
|
||||
render();
|
||||
root.append(overlay);
|
||||
overlay.querySelector('[data-action="close"]')?.focus({ preventScroll: true });
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { createDropdownMenu } from './dropdown-menu.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
|
||||
export function attachMessageMenu(card, head, items) {
|
||||
const trigger = document.createElement('button');
|
||||
trigger.type = 'button';
|
||||
trigger.className = 'icon-btn channel-message-more';
|
||||
trigger.innerHTML = iconHtml('more');
|
||||
trigger.setAttribute('aria-label', t('screens.message_menu.text_001'));
|
||||
head.append(trigger);
|
||||
const menu = createDropdownMenu({ anchorEl: trigger, items });
|
||||
const previousCleanup = card.cleanup;
|
||||
card.cleanup = () => {
|
||||
previousCleanup?.();
|
||||
menu.destroy();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export function createOverflowDots({ className = '' } = {}) {
|
||||
const dots = document.createElement('span');
|
||||
const extra = String(className || '').trim();
|
||||
dots.className = `app-overflow-dots${extra ? ` ${extra}` : ''}`;
|
||||
dots.setAttribute('aria-hidden', 'true');
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
dots.append(document.createElement('i'));
|
||||
}
|
||||
return dots;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
export function renderPageLabel(titleRu, pageId, collapsed, onToggle) {
|
||||
const label = document.createElement('div');
|
||||
label.className = `page-label${collapsed ? ' is-collapsed' : ''}`;
|
||||
|
||||
const toggle = document.createElement('button');
|
||||
toggle.type = 'button';
|
||||
toggle.className = 'page-label-toggle';
|
||||
toggle.title = collapsed ? t('screens.page_label.text_002') : t('screens.page_label.text_003');
|
||||
toggle.setAttribute(
|
||||
'aria-label',
|
||||
collapsed ? t('screens.page_label.text_004') : t('screens.page_label.text_005'),
|
||||
);
|
||||
toggle.addEventListener('click', onToggle);
|
||||
|
||||
if (!collapsed) {
|
||||
label.append(toggle);
|
||||
|
||||
const content = document.createElement('div');
|
||||
content.className = 'page-label-content';
|
||||
|
||||
const hint = document.createElement('div');
|
||||
hint.className = 'page-label-hint';
|
||||
hint.textContent = t('screens.page_label.text_001');
|
||||
|
||||
const caption = document.createElement('div');
|
||||
caption.className = 'page-label-caption';
|
||||
caption.textContent = `${titleRu} (${pageId})`;
|
||||
|
||||
content.append(hint, caption);
|
||||
label.append(content);
|
||||
} else {
|
||||
label.append(toggle);
|
||||
}
|
||||
|
||||
return label;
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
// Редактор точной настройки палитры.
|
||||
import {
|
||||
PALETTE_PRESETS,
|
||||
PALETTE_ROLES,
|
||||
exportPalette,
|
||||
getPaletteSettings,
|
||||
importPalette,
|
||||
resolvePalette,
|
||||
resolveThemeMode,
|
||||
setPaletteSettings,
|
||||
} from '../services/theme-service.js';
|
||||
|
||||
export function openPaletteEditor({ theme = resolveThemeMode(), onClose } = {}) {
|
||||
let editTheme = theme === 'light' ? 'light' : 'dark';
|
||||
const opener = document.activeElement;
|
||||
|
||||
const modal = document.createElement('div');
|
||||
modal.className = 'modal palette-editor';
|
||||
modal.innerHTML = `
|
||||
<div class="modal-card palette-editor__card" role="dialog" aria-modal="true" aria-labelledby="palette-editor-title">
|
||||
<div class="palette-editor__head">
|
||||
<h2 class="modal-title" id="palette-editor-title">${th('screens.palette_editor.text_003')}</h2>
|
||||
<button class="icon-btn palette-editor__close" type="button" aria-label="${th('screens.palette_editor.text_004')}">✕</button>
|
||||
</div>
|
||||
<div class="palette-editor__section">
|
||||
<span class="palette-editor__label">${th('screens.palette_editor.text_005')}</span>
|
||||
<select class="input palette-editor__presets" aria-label="${th('screens.palette_editor.text_006')}"></select>
|
||||
<div class="palette-editor__preview" aria-hidden="true"><span></span><span></span><span></span><span></span></div>
|
||||
</div>
|
||||
<div class="palette-editor__section">
|
||||
<span class="palette-editor__label">${th('screens.palette_editor.text_007')}</span>
|
||||
<div class="tabs tabs--auto" role="radiogroup" aria-label="${th('screens.palette_editor.text_008')}">
|
||||
<button type="button" class="tab-btn" role="radio" data-edit-theme="light">${th('screens.palette_editor.text_009')}</button>
|
||||
<button type="button" class="tab-btn" role="radio" data-edit-theme="dark">${th('screens.palette_editor.text_010')}</button>
|
||||
</div>
|
||||
<p class="palette-editor__hint">${th('screens.palette_editor.text_011')}</p>
|
||||
</div>
|
||||
<div class="palette-editor__roles"></div>
|
||||
<details class="palette-editor__share">
|
||||
<summary>${th('screens.palette_editor.text_012')}</summary>
|
||||
<p class="palette-editor__hint">${th('screens.palette_editor.text_013')}</p>
|
||||
<textarea class="input palette-editor__json" rows="8" spellcheck="false"></textarea>
|
||||
<p class="palette-editor__error" role="alert" hidden></p>
|
||||
<div class="palette-editor__actions">
|
||||
<button type="button" class="secondary-btn" data-action="copy">${th('screens.palette_editor.text_014')}</button>
|
||||
<button type="button" class="secondary-btn" data-action="import">${th('screens.palette_editor.text_015')}</button>
|
||||
</div>
|
||||
</details>
|
||||
<div class="palette-editor__actions">
|
||||
<button type="button" class="secondary-btn" data-action="reset-theme">${th('screens.palette_editor.text_016')}</button>
|
||||
<button type="button" class="primary-btn" data-action="done">${th('screens.palette_editor.text_017')}</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const card = modal.querySelector('.palette-editor__card');
|
||||
const presetsEl = modal.querySelector('.palette-editor__presets');
|
||||
const rolesEl = modal.querySelector('.palette-editor__roles');
|
||||
const jsonEl = modal.querySelector('.palette-editor__json');
|
||||
const errorEl = modal.querySelector('.palette-editor__error');
|
||||
|
||||
for (const [id, preset] of Object.entries(PALETTE_PRESETS)) {
|
||||
const option = document.createElement('option');
|
||||
option.value = id;
|
||||
option.textContent = preset.label;
|
||||
presetsEl.append(option);
|
||||
}
|
||||
|
||||
const update = (mutate) => {
|
||||
const settings = getPaletteSettings();
|
||||
const next = { preset: settings.preset, custom: { dark: { ...settings.custom.dark }, light: { ...settings.custom.light } } };
|
||||
mutate(next);
|
||||
setPaletteSettings(next);
|
||||
render();
|
||||
};
|
||||
|
||||
function render() {
|
||||
const settings = getPaletteSettings();
|
||||
const colors = resolvePalette(editTheme, settings);
|
||||
const custom = settings.custom[editTheme];
|
||||
presetsEl.value = settings.preset;
|
||||
modal.querySelectorAll('.palette-editor__preview span').forEach((swatch, index) => {
|
||||
swatch.style.backgroundColor = [colors.background, colors.surface, colors.accent, colors['surface-selected']][index];
|
||||
});
|
||||
modal.querySelectorAll('[data-edit-theme]').forEach((btn) => {
|
||||
btn.setAttribute('aria-checked', String(btn.dataset.editTheme === editTheme));
|
||||
});
|
||||
rolesEl.replaceChildren(...PALETTE_ROLES.map((role) => {
|
||||
const row = document.createElement('label');
|
||||
row.className = 'palette-editor__role';
|
||||
const changed = Boolean(custom[role.id]);
|
||||
row.innerHTML = `
|
||||
<input type="color" value="${colors[role.id]}" aria-label="${role.label}">
|
||||
<span class="palette-editor__role-name">${role.label}${changed ? t('screens.palette_editor.text_002') : ''}</span>
|
||||
<code class="palette-editor__role-value">${colors[role.id]}</code>
|
||||
`;
|
||||
const input = row.querySelector('input');
|
||||
input.addEventListener('input', () => {
|
||||
document.documentElement.style.setProperty(`--${role.id}`, input.value);
|
||||
row.querySelector('code').textContent = input.value;
|
||||
});
|
||||
input.addEventListener('change', () => update((next) => { next.custom[editTheme][role.id] = input.value; }));
|
||||
return row;
|
||||
}));
|
||||
jsonEl.value = exportPalette();
|
||||
errorEl.hidden = true;
|
||||
}
|
||||
|
||||
const close = () => {
|
||||
document.removeEventListener('keydown', onKeydown);
|
||||
modal.remove();
|
||||
opener?.focus?.();
|
||||
onClose?.();
|
||||
};
|
||||
const onKeydown = (event) => { if (event.key === 'Escape') close(); };
|
||||
|
||||
modal.addEventListener('click', async (event) => {
|
||||
if (event.target === modal) { close(); return; }
|
||||
// data-edit-theme, а не data-theme: data-theme стоит на <html>, и closest() находил бы его при любом клике.
|
||||
const themeBtn = event.target.closest('[data-edit-theme]');
|
||||
if (themeBtn) { editTheme = themeBtn.dataset.editTheme; render(); return; }
|
||||
if (event.target.closest('.palette-editor__close')) { close(); return; }
|
||||
const action = event.target.closest('[data-action]')?.dataset.action;
|
||||
if (action === 'done') close();
|
||||
if (action === 'reset-theme') update((next) => { next.custom[editTheme] = {}; });
|
||||
if (action === 'copy') {
|
||||
try {
|
||||
await navigator.clipboard.writeText(jsonEl.value);
|
||||
} catch {
|
||||
jsonEl.select();
|
||||
}
|
||||
}
|
||||
if (action === 'import') {
|
||||
try {
|
||||
importPalette(jsonEl.value);
|
||||
render();
|
||||
} catch {
|
||||
errorEl.textContent = t('screens.palette_editor.text_001');
|
||||
errorEl.hidden = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
presetsEl.addEventListener('change', () => update((next) => {
|
||||
next.preset = presetsEl.value;
|
||||
next.custom = { dark: {}, light: {} };
|
||||
}));
|
||||
document.addEventListener('keydown', onKeydown);
|
||||
|
||||
render();
|
||||
document.body.append(modal);
|
||||
card.querySelector('.palette-editor__close').focus();
|
||||
return close;
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
// Шторка «Заметка о человеке»: текст и цветная метка, видны только владельцу аккаунта.
|
||||
// Открывается с карты связей и из профиля человека; хранение – services/people-notes.js.
|
||||
import { openSheet } from './sheet.js';
|
||||
import { NOTE_MARKS, PERSON_NOTE_MAX_TEXT, getPersonNote, setPersonNote } from '../services/people-notes.js';
|
||||
|
||||
export function openPersonNoteSheet({ login, name = '', onClose = null } = {}) {
|
||||
const current = getPersonNote(login);
|
||||
let mark = current?.mark || '';
|
||||
return openSheet({
|
||||
title: t('dialogs.remaining.components.person_note_sheet.openpersonnotesheet.zametka_value1', { value1: name || login }),
|
||||
className: 'person-note-sheet',
|
||||
onClose,
|
||||
content: (sheet) => {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'stack person-note';
|
||||
const hint = document.createElement('p');
|
||||
hint.className = 'meta-muted person-note__hint';
|
||||
hint.textContent = t('dialogs.modals.person_note_sheet.label_001');
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.className = 'input person-note__text';
|
||||
textarea.rows = 5;
|
||||
textarea.maxLength = PERSON_NOTE_MAX_TEXT;
|
||||
textarea.placeholder = t('dialogs.modals.person_note_sheet.label_002');
|
||||
textarea.value = current?.text || '';
|
||||
textarea.setAttribute('aria-label', t('dialogs.modals.person_note_sheet.label_003'));
|
||||
textarea.autofocus = true;
|
||||
|
||||
const marksLabel = document.createElement('div');
|
||||
marksLabel.className = 'person-note__label';
|
||||
marksLabel.id = `person-note-marks-${Math.random().toString(36).slice(2, 8)}`;
|
||||
marksLabel.textContent = t('dialogs.modals.person_note_sheet.label_004');
|
||||
const marks = document.createElement('div');
|
||||
marks.className = 'person-note__marks';
|
||||
marks.setAttribute('role', 'radiogroup');
|
||||
marks.setAttribute('aria-labelledby', marksLabel.id);
|
||||
const markButtons = [];
|
||||
const syncMarks = () => markButtons.forEach((button) => button.setAttribute('aria-checked', String(button.dataset.mark === mark)));
|
||||
for (const option of [{ id: '', label: t('dialogs.remaining.components.person_note_sheet.openpersonnotesheet.bez_metki') }, ...NOTE_MARKS]) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'person-note__mark';
|
||||
button.dataset.mark = option.id;
|
||||
button.setAttribute('role', 'radio');
|
||||
button.setAttribute('aria-label', option.label);
|
||||
button.title = option.label;
|
||||
button.addEventListener('click', () => { mark = option.id; syncMarks(); });
|
||||
markButtons.push(button);
|
||||
marks.append(button);
|
||||
}
|
||||
syncMarks();
|
||||
wrap.append(hint, textarea, marksLabel, marks);
|
||||
|
||||
if (current) {
|
||||
const remove = document.createElement('button');
|
||||
remove.type = 'button';
|
||||
remove.className = 'ghost-btn person-note__remove';
|
||||
remove.textContent = t('dialogs.modals.person_note_sheet.label_005');
|
||||
remove.addEventListener('click', () => {
|
||||
setPersonNote(login, { text: '', mark: '' });
|
||||
sheet.close();
|
||||
});
|
||||
sheet.footer.append(remove);
|
||||
}
|
||||
const save = document.createElement('button');
|
||||
save.type = 'button';
|
||||
save.className = 'primary-btn person-note__save';
|
||||
save.textContent = t('dialogs.modals.person_note_sheet.label_006');
|
||||
save.addEventListener('click', () => {
|
||||
setPersonNote(login, { text: textarea.value, mark });
|
||||
sheet.close();
|
||||
});
|
||||
sheet.footer.append(save);
|
||||
return wrap;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Готовый блок заметки (для карточки на карте и профиля); null, если заметки нет.
|
||||
export function createPersonNotePreview(note, { className = '', onClick = null } = {}) {
|
||||
if (!note) return null;
|
||||
const el = document.createElement(onClick ? 'button' : 'div');
|
||||
if (onClick) {
|
||||
el.type = 'button';
|
||||
el.title = t('screens.person_note_sheet.text_001');
|
||||
el.addEventListener('click', onClick);
|
||||
}
|
||||
el.className = `person-note-preview${className ? ` ${className}` : ''}`;
|
||||
if (note.mark) el.dataset.mark = note.mark;
|
||||
el.textContent = note.text.trim() || t('dialogs.modals.person_note_sheet.label_007');
|
||||
return el;
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// Строка человека в списках (связи, поиск людей, списки профиля): аватар, имя, строка под
|
||||
// ним и действия справа. Вид совпадает со строками списка чатов.
|
||||
import { renderUserAvatar } from './avatar-image.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
import { createSpinner } from './feedback.js';
|
||||
|
||||
/**
|
||||
* @param {Object} opts
|
||||
* @param {string} opts.login
|
||||
* @param {string} [opts.name] – как показывать (по умолчанию логин)
|
||||
* @param {string} [opts.firstName] [opts.lastName] – для инициалов
|
||||
* @param {Object|null} [opts.avatar]
|
||||
* @param {string} [opts.sub] – строка под именем
|
||||
* @param {string} [opts.note] – личная заметка (третья строка, курсивом)
|
||||
* @param {string} [opts.markColor] – метка заметки: green/yellow/red/blue/violet, 'note' – без цвета, '' – нет
|
||||
* @param {'close'|'shining'|''} [opts.ring] – цветное кольцо вокруг аватара
|
||||
* @param {boolean} [opts.official]
|
||||
* @param {string} [opts.tag] – короткая пометка цветом в начале второй строки («ждёт ответа»)
|
||||
* @param {Function} [opts.onClick]
|
||||
* @param {Array<{icon:string,label:string,onClick:Function,primary?:boolean,busy?:boolean}>} [opts.actions]
|
||||
* primary – главное действие строки (цветом), busy – идёт сохранение (спиннер, кнопка неактивна)
|
||||
*/
|
||||
export function createPersonRow({
|
||||
login, name = '', firstName = '', lastName = '', avatar = null, sub = '', note = '', markColor = '',
|
||||
ring = '', official = false, tag = '', onClick = null, actions = [],
|
||||
} = {}) {
|
||||
const row = document.createElement('div');
|
||||
row.className = `person-row${ring ? ` person-row--${ring}` : ''}`;
|
||||
row.dataset.login = String(login || '');
|
||||
|
||||
const main = document.createElement('button');
|
||||
main.type = 'button';
|
||||
main.className = 'person-row__main';
|
||||
const avatarWrap = document.createElement('span');
|
||||
avatarWrap.className = 'person-row__avatar';
|
||||
// Имя и фамилию отдельно знают не все источники (поиск по сети отдаёт одно «displayName») –
|
||||
// тогда инициалы берутся из показанного имени, а не из логина.
|
||||
const nameParts = name && name !== login ? String(name).trim().split(/\s+/) : [];
|
||||
const initialsFirst = firstName || nameParts[0] || '';
|
||||
const initialsLast = lastName || (nameParts.length > 1 ? nameParts[nameParts.length - 1] : '');
|
||||
avatarWrap.append(renderUserAvatar({ login, firstName: initialsFirst, lastName: initialsLast, avatar, size: 'md', official }));
|
||||
if (markColor) {
|
||||
// Метка заметки – та же цветная точка, что на карте связей; 'note' – заметка без цвета.
|
||||
const mark = document.createElement('span');
|
||||
mark.className = 'person-row__mark';
|
||||
mark.dataset.mark = markColor;
|
||||
mark.setAttribute('aria-hidden', 'true');
|
||||
avatarWrap.append(mark);
|
||||
}
|
||||
const text = document.createElement('span');
|
||||
text.className = 'person-row__text';
|
||||
const title = document.createElement('span');
|
||||
title.className = 'person-row__name';
|
||||
const titleText = document.createElement('span');
|
||||
titleText.className = 'person-row__name-text';
|
||||
titleText.textContent = name || login;
|
||||
title.append(titleText);
|
||||
text.append(title);
|
||||
if (sub || tag) {
|
||||
// Пометка («ждёт ответа») – в начале второй строки, чтобы не съедать место у имени.
|
||||
const subEl = document.createElement('span');
|
||||
subEl.className = 'person-row__sub';
|
||||
if (tag) {
|
||||
const tagEl = document.createElement('span');
|
||||
tagEl.className = 'person-row__tag';
|
||||
tagEl.textContent = tag;
|
||||
subEl.append(tagEl);
|
||||
if (sub) subEl.append(' · ');
|
||||
}
|
||||
if (sub) subEl.append(sub);
|
||||
text.append(subEl);
|
||||
}
|
||||
if (note) {
|
||||
const noteEl = document.createElement('span');
|
||||
noteEl.className = 'person-row__note';
|
||||
noteEl.textContent = note;
|
||||
text.append(noteEl);
|
||||
}
|
||||
main.append(avatarWrap, text);
|
||||
if (typeof onClick === 'function') main.addEventListener('click', onClick);
|
||||
row.append(main);
|
||||
|
||||
for (const action of actions) {
|
||||
if (!action) continue;
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = `icon-btn person-row__action${action.primary ? ' person-row__action--primary' : ''}`;
|
||||
if (action.busy) {
|
||||
button.disabled = true;
|
||||
button.append(createSpinner({ size: 'sm', label: action.label }));
|
||||
} else {
|
||||
button.innerHTML = iconHtml(action.icon);
|
||||
}
|
||||
button.setAttribute('aria-label', action.label);
|
||||
button.title = action.label;
|
||||
button.addEventListener('click', (event) => action.onClick?.(event, button));
|
||||
row.append(button);
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
// Заголовок группы в списке («Друзья · 58», «А»).
|
||||
export function createListSection(text) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'person-list-section';
|
||||
el.textContent = text;
|
||||
return el;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { renderUserAvatar } from './avatar-image.js';
|
||||
|
||||
let activeClose = null;
|
||||
|
||||
/**
|
||||
* Тот же экземпляр Avatar переносится во всплывающее окно, а затем обратно.
|
||||
* Так сохраняются уже загруженная фотография и blob URL, который может быть
|
||||
* отозван загрузчиком после onload; клонировать img/src здесь нельзя.
|
||||
*/
|
||||
export function attachProfileAvatarPreview(slot, card) {
|
||||
if (!slot || !card) return { cleanup() {} };
|
||||
const trigger = document.createElement('button');
|
||||
trigger.type = 'button';
|
||||
trigger.className = 'user-profile-avatar-trigger';
|
||||
trigger.setAttribute('aria-label', t('screens.profile_avatar_preview.open'));
|
||||
|
||||
const avatar = renderUserAvatar({
|
||||
login: card.login,
|
||||
firstName: card.firstName,
|
||||
lastName: card.lastName,
|
||||
avatar: card.avatar,
|
||||
size: 'xl',
|
||||
className: 'user-profile-hero-avatar',
|
||||
official: card.accountRole === 'primary',
|
||||
});
|
||||
trigger.append(avatar);
|
||||
slot.append(trigger);
|
||||
|
||||
let closePreview = null;
|
||||
trigger.addEventListener('click', () => {
|
||||
if (closePreview) return;
|
||||
activeClose?.({ restoreFocus: false });
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'profile-avatar-preview';
|
||||
overlay.setAttribute('role', 'dialog');
|
||||
overlay.setAttribute('aria-modal', 'true');
|
||||
overlay.setAttribute('aria-label', t('screens.profile_avatar_preview.dialog'));
|
||||
|
||||
const largeButton = document.createElement('button');
|
||||
largeButton.type = 'button';
|
||||
largeButton.className = 'profile-avatar-preview__image';
|
||||
largeButton.setAttribute('aria-label', t('screens.profile_avatar_preview.close'));
|
||||
largeButton.append(avatar);
|
||||
overlay.append(largeButton);
|
||||
|
||||
const onKey = (event) => {
|
||||
if (event.key === 'Escape') close();
|
||||
};
|
||||
const onPopState = () => close({ restoreFocus: false });
|
||||
const close = ({ restoreFocus = true } = {}) => {
|
||||
if (closePreview !== close) return;
|
||||
closePreview = null;
|
||||
if (activeClose === close) activeClose = null;
|
||||
document.removeEventListener('keydown', onKey);
|
||||
window.removeEventListener('popstate', onPopState);
|
||||
// При обновлении карточки или уходе со страницы прежний trigger уже может быть удалён.
|
||||
if (trigger.isConnected) trigger.append(avatar);
|
||||
overlay.remove();
|
||||
if (restoreFocus && trigger.isConnected) trigger.focus({ preventScroll: true });
|
||||
};
|
||||
closePreview = close;
|
||||
activeClose = close;
|
||||
overlay.addEventListener('click', (event) => {
|
||||
if (event.target === overlay || event.target.closest('.profile-avatar-preview__image')) close();
|
||||
});
|
||||
document.addEventListener('keydown', onKey);
|
||||
window.addEventListener('popstate', onPopState);
|
||||
(document.getElementById('modal-root') || document.body).append(overlay);
|
||||
largeButton.focus({ preventScroll: true });
|
||||
});
|
||||
|
||||
return {
|
||||
cleanup() { closePreview?.({ restoreFocus: false }); },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
// data-profile-list / data-self-profile-action / data-profile-action обрабатывают profile-view.js и user-profile-view.js.
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
import { displayCity } from '../services/cities.js';
|
||||
|
||||
export function escapeProfileHtml(text) {
|
||||
return String(text || '')
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
|
||||
const esc = escapeProfileHtml;
|
||||
|
||||
// Карточка статуса у аватара: кто подтвердил этот аккаунт и кого подтвердил он сам.
|
||||
function statusSideHtml({ kind, title, active, received, given, verb }) {
|
||||
const isOfficial = kind === 'primary';
|
||||
const receivedKind = isOfficial ? 'primary_received' : 'shine_received';
|
||||
const givenKind = isOfficial ? 'primary_given' : 'shine_given';
|
||||
return `
|
||||
<section class="pf-sc pf-sc--${esc(kind)}${active ? ' is-active' : ' is-empty'}" aria-label="${esc(title)}">
|
||||
<div class="pf-sc__title">${esc(title)}</div>
|
||||
<button type="button" class="pf-sc__row" data-profile-list="${receivedKind}" aria-label="${esc(title)}${th('remaining.html_profile_card.confirmed_by')}${Number(received || 0)}">
|
||||
<strong>${Number(received || 0)}</strong><span>${th('screens.profile_card.text_017')}</span>
|
||||
</button>
|
||||
<button type="button" class="pf-sc__row" data-profile-list="${givenKind}" aria-label="${esc(title)}: ${esc(verb)} ${Number(given || 0)}">
|
||||
<strong>${Number(given || 0)}</strong><span>${esc(verb)}</span>
|
||||
</button>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function statHtml({ kind, label, valueHtml, ariaLabel }) {
|
||||
return `
|
||||
<button type="button" class="pf-stat" data-profile-list="${esc(kind)}" aria-label="${esc(ariaLabel)}">
|
||||
<span class="pf-stat-value">${valueHtml}</span>
|
||||
<span class="pf-stat-label">${esc(label)}</span>
|
||||
</button>`;
|
||||
}
|
||||
|
||||
function contactRows(card) {
|
||||
return [
|
||||
[t('screens.profile_card.text_006'), card?.web],
|
||||
[t('screens.profile_card.text_007'), card?.phone],
|
||||
[t('screens.profile_card.text_008'), card?.address],
|
||||
]
|
||||
.filter(([, value]) => String(value || '').trim())
|
||||
.map(([label, value]) => `
|
||||
<div class="pf-row">
|
||||
<span class="pf-row-label">${esc(label)}</span>
|
||||
<span class="pf-row-value">${esc(value)}</span>
|
||||
</div>`)
|
||||
.join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} opts
|
||||
* @param {object} opts.card карточка профиля (loadUserProfileCard)
|
||||
* @param {string} opts.login логин на случай, если в карточке его нет
|
||||
* @param {string} opts.tilesHtml плитки действий (свои/чужие)
|
||||
* @param {string} [opts.tilesWrapClass] доп. класс обёртки плиток (для меню «Добавить»)
|
||||
* @param {string} [opts.beforeTilesHtml] разметка внутри обёртки перед плитками
|
||||
*/
|
||||
export function profileCardHtml({ card, login = '', tilesHtml = '', tilesWrapClass = '', beforeTilesHtml = '', isSelf = true }) {
|
||||
const stats = card?.stats || {};
|
||||
const official = card?.accountRole === 'primary';
|
||||
const shining = card?.shineStatus === 'shining';
|
||||
const cardLogin = String(card?.login || login || '').trim().replace(/^@+/, '');
|
||||
const city = displayCity(card?.city);
|
||||
const fullName = [card?.firstName, card?.lastName].map((v) => String(v || '').trim()).filter(Boolean).join(' ');
|
||||
const displayName = fullName || cardLogin || t('screens.profile_card.text_012');
|
||||
const about = String(card?.about || '').trim();
|
||||
const spiritualPath = String(card?.spiritualPath || '').trim();
|
||||
const contacts = contactRows(card);
|
||||
const aboutRow = (about || isSelf) ? `
|
||||
<div class="pf-row pf-row--block">
|
||||
<span class="pf-row-label">${th('screens.profile_card.text_018')}</span>
|
||||
<p class="pf-row-text${about ? '' : ' is-empty'}">${esc(about || t('screens.profile_card.text_013'))}</p>
|
||||
</div>` : '';
|
||||
const pathRow = spiritualPath ? `
|
||||
<div class="pf-row pf-row--block">
|
||||
<span class="pf-row-label">${th('screens.profile_card.text_019')}</span>
|
||||
<p class="pf-row-text">${esc(spiritualPath)}</p>
|
||||
</div>` : '';
|
||||
const listInner = aboutRow + contacts + pathRow;
|
||||
const listHtml = listInner.trim() ? `<div class="pf-list">${listInner}</div>` : '';
|
||||
const friends = Number(stats.friendsCount || 0);
|
||||
const closeFriends = Number(stats.closeFriendsCount || 0);
|
||||
|
||||
const shineReceived = Number(stats.shineReceivedCount || 0);
|
||||
const shineGiven = Number(stats.shineGivenCount || 0);
|
||||
const primaryReceived = Number(stats.primaryReceivedCount || 0);
|
||||
const primaryGiven = Number(stats.primaryGivenCount || 0);
|
||||
// Статусы по бокам аватара: слева «Официальный», справа «Сияние». На своём профиле – всегда
|
||||
// (пустая сторона бледнее), на чужом – если статус есть или уже есть подтверждения.
|
||||
const verb = card?.gender === 'female' ? t('screens.profile_card.text_009') : card?.gender === 'male' ? t('screens.profile_card.text_010') : t('screens.profile_card.text_011');
|
||||
const officialSide = (isSelf || official || primaryReceived || primaryGiven)
|
||||
? statusSideHtml({ kind: 'primary', title: t('screens.profile_card.text_001'), active: official, received: primaryReceived, given: primaryGiven, verb })
|
||||
: '';
|
||||
const shineSide = (isSelf || shining || shineReceived || shineGiven)
|
||||
? statusSideHtml({ kind: 'shine', title: t('screens.profile_card.text_002'), active: shining, received: shineReceived, given: shineGiven, verb })
|
||||
: '';
|
||||
|
||||
return `
|
||||
<div class="pf-hero" aria-label="${th('remaining.html_profile_card.profile')}${esc(cardLogin)}">
|
||||
<div class="pf-identity">
|
||||
<div class="pf-side pf-side--left">${officialSide}</div>
|
||||
<div class="pf-avatar user-profile-avatar-slot${shining ? ' is-shining' : ''}"></div>
|
||||
<div class="pf-side pf-side--right">${shineSide}</div>
|
||||
</div>
|
||||
<h2 class="pf-name">${esc(displayName)}</h2>
|
||||
<div class="pf-login">${esc(cardLogin)}</div>
|
||||
${city ? `<div class="pf-city">${iconHtml('place')}<span>${esc(city)}</span></div>` : ''}
|
||||
</div>
|
||||
|
||||
<div class="pf-stats">
|
||||
${statHtml({ kind: 'friends', label: t('screens.profile_card.text_003'), valueHtml: closeFriends ? `${friends}<small> · ${closeFriends}${th('remaining.html_profile_card.close')}</small>` : String(friends), ariaLabel: t('screens.profile_card.text_014', { value1: friends, value2: closeFriends }) })}
|
||||
${statHtml({ kind: 'channels_owned', label: t('screens.profile_card.text_004'), valueHtml: String(Number(stats.ownedPublicChannelsCount || 0)), ariaLabel: t('screens.profile_card.text_015', { value1: Number(stats.ownedPublicChannelsCount || 0) }) })}
|
||||
${statHtml({ kind: 'channels_following', label: t('screens.profile_card.text_005'), valueHtml: String(Number(stats.followingChannelsCount || 0)), ariaLabel: t('screens.profile_card.text_016', { value1: Number(stats.followingChannelsCount || 0) }) })}
|
||||
</div>
|
||||
|
||||
${tilesHtml ? `
|
||||
<div class="pf-tiles-wrap user-profile-actions-wrap ${esc(tilesWrapClass)}">
|
||||
${beforeTilesHtml}
|
||||
<div class="pf-tiles user-profile-actions">${tilesHtml}</div>
|
||||
</div>` : ''}
|
||||
|
||||
${listHtml}`;
|
||||
}
|
||||
|
||||
export function profileTileHtml({ icon, label, attrs = '', iconMarkup = '' }) {
|
||||
return `<button type="button" class="pf-tile user-profile-action-btn" ${attrs}>${iconMarkup || iconHtml(icon)}<span>${esc(label)}</span></button>`;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
/** В выборе тарифа счётчик не показываем: он начинается с логина. */
|
||||
export function createRegistrationStepper(step) {
|
||||
const current = Math.max(1, Math.min(3, Number(step) || 1));
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.className = 'signup-stepper';
|
||||
wrapper.setAttribute('aria-label', t('screens.registration_stepper.text_001', { value1: current }));
|
||||
const dots = document.createElement('div');
|
||||
dots.className = 'signup-stepper__dots';
|
||||
for (let i = 1; i <= 3; i += 1) {
|
||||
const dot = document.createElement('span');
|
||||
dot.className = `signup-stepper__dot${i === current ? ' is-active' : ''}${i < current ? ' is-complete' : ''}`;
|
||||
dots.append(dot);
|
||||
}
|
||||
const label = document.createElement('span');
|
||||
label.className = 'signup-stepper__label';
|
||||
label.textContent = t('screens.registration_stepper.text_002', { value1: current });
|
||||
wrapper.append(dots, label);
|
||||
return wrapper;
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
function resolveElement(value) {
|
||||
return typeof value === 'function' ? value() : value;
|
||||
}
|
||||
|
||||
function buildArrowIcon() {
|
||||
const icon = document.createElement('span');
|
||||
icon.className = 'scroll-to-bottom-btn__icon';
|
||||
icon.setAttribute('aria-hidden', 'true');
|
||||
icon.innerHTML = iconHtml('down');
|
||||
return icon;
|
||||
}
|
||||
|
||||
export function attachScrollToBottomButton({
|
||||
scrollContainer,
|
||||
mountTarget = document.querySelector('.app-shell'),
|
||||
thresholdPx = 160,
|
||||
title = t('remaining.scroll.scroll_down'),
|
||||
} = {}) {
|
||||
const target = resolveElement(mountTarget);
|
||||
if (!(target instanceof Element)) {
|
||||
return {
|
||||
button: null,
|
||||
refresh() {},
|
||||
cleanup() {},
|
||||
};
|
||||
}
|
||||
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'scroll-to-bottom-btn';
|
||||
button.title = title;
|
||||
button.setAttribute('aria-label', t('screens.scroll_to_bottom_button.text_001'));
|
||||
button.tabIndex = -1;
|
||||
button.append(buildArrowIcon());
|
||||
target.append(button);
|
||||
|
||||
let disposed = false;
|
||||
let boundContainer = null;
|
||||
let resizeObserver = null;
|
||||
let mutationObserver = null;
|
||||
let refreshFrame = 0;
|
||||
|
||||
const hide = () => {
|
||||
button.classList.remove('is-visible');
|
||||
button.setAttribute('aria-hidden', 'true');
|
||||
button.tabIndex = -1;
|
||||
};
|
||||
|
||||
const scheduleRefresh = () => {
|
||||
if (disposed || refreshFrame) return;
|
||||
refreshFrame = window.requestAnimationFrame(() => {
|
||||
refreshFrame = 0;
|
||||
refresh();
|
||||
});
|
||||
};
|
||||
|
||||
const unbindContainer = () => {
|
||||
boundContainer?.removeEventListener('scroll', scheduleRefresh);
|
||||
resizeObserver?.disconnect();
|
||||
mutationObserver?.disconnect();
|
||||
resizeObserver = null;
|
||||
mutationObserver = null;
|
||||
boundContainer = null;
|
||||
};
|
||||
|
||||
const bindContainer = () => {
|
||||
const nextContainer = resolveElement(scrollContainer);
|
||||
if (!(nextContainer instanceof Element)) {
|
||||
if (boundContainer) unbindContainer();
|
||||
return null;
|
||||
}
|
||||
if (nextContainer === boundContainer) return boundContainer;
|
||||
|
||||
unbindContainer();
|
||||
boundContainer = nextContainer;
|
||||
boundContainer.addEventListener('scroll', scheduleRefresh, { passive: true });
|
||||
|
||||
if (typeof ResizeObserver === 'function') {
|
||||
resizeObserver = new ResizeObserver(scheduleRefresh);
|
||||
resizeObserver.observe(boundContainer);
|
||||
}
|
||||
|
||||
if (typeof MutationObserver === 'function') {
|
||||
mutationObserver = new MutationObserver(scheduleRefresh);
|
||||
mutationObserver.observe(boundContainer, { childList: true, subtree: true });
|
||||
}
|
||||
|
||||
return boundContainer;
|
||||
};
|
||||
|
||||
function refresh() {
|
||||
if (disposed) return;
|
||||
const container = bindContainer();
|
||||
if (!container) {
|
||||
hide();
|
||||
return;
|
||||
}
|
||||
|
||||
const scrollHeight = Number(container.scrollHeight || 0);
|
||||
const clientHeight = Number(container.clientHeight || 0);
|
||||
const scrollTop = Number(container.scrollTop || 0);
|
||||
const maxScrollTop = Math.max(0, scrollHeight - clientHeight);
|
||||
const distanceToBottom = Math.max(0, maxScrollTop - scrollTop);
|
||||
const shouldShow = maxScrollTop > 8 && distanceToBottom > Math.max(24, Number(thresholdPx || 0));
|
||||
|
||||
button.classList.toggle('is-visible', shouldShow);
|
||||
button.setAttribute('aria-hidden', shouldShow ? 'false' : 'true');
|
||||
button.tabIndex = shouldShow ? 0 : -1;
|
||||
}
|
||||
|
||||
const scrollToBottom = () => {
|
||||
const container = bindContainer();
|
||||
if (!container) return;
|
||||
if (typeof container.scrollTo === 'function') {
|
||||
container.scrollTo({ top: container.scrollHeight, behavior: 'smooth' });
|
||||
} else {
|
||||
container.scrollTop = container.scrollHeight;
|
||||
}
|
||||
scheduleRefresh();
|
||||
};
|
||||
|
||||
button.addEventListener('click', scrollToBottom);
|
||||
window.addEventListener('resize', scheduleRefresh);
|
||||
window.visualViewport?.addEventListener('resize', scheduleRefresh);
|
||||
window.requestAnimationFrame(refresh);
|
||||
|
||||
return {
|
||||
button,
|
||||
refresh: scheduleRefresh,
|
||||
cleanup() {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
if (refreshFrame) {
|
||||
window.cancelAnimationFrame(refreshFrame);
|
||||
refreshFrame = 0;
|
||||
}
|
||||
unbindContainer();
|
||||
window.removeEventListener('resize', scheduleRefresh);
|
||||
window.visualViewport?.removeEventListener('resize', scheduleRefresh);
|
||||
button.removeEventListener('click', scrollToBottom);
|
||||
button.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
|
||||
/** Общий экран ожидания локальной генерации ключей. Без ложного процента выполнения. */
|
||||
export function createSecretGenerationOverlay() {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'secret-generation-overlay';
|
||||
overlay.hidden = true;
|
||||
overlay.setAttribute('role', 'status');
|
||||
overlay.setAttribute('aria-live', 'polite');
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'secret-generation-card stack';
|
||||
|
||||
const spinner = document.createElement('div');
|
||||
spinner.className = 'secret-generation-spinner';
|
||||
spinner.setAttribute('aria-hidden', 'true');
|
||||
|
||||
const title = document.createElement('div');
|
||||
title.className = 'secret-generation-title';
|
||||
title.textContent = t('components.secret_generation_overlay.title');
|
||||
|
||||
const description = document.createElement('p');
|
||||
description.className = 'secret-generation-description';
|
||||
description.textContent = t('components.secret_generation_overlay.description');
|
||||
|
||||
card.append(spinner, title, description);
|
||||
overlay.append(card);
|
||||
return {
|
||||
overlay,
|
||||
show() { overlay.hidden = false; },
|
||||
hide() { overlay.hidden = true; },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { openSheet } from './sheet.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
|
||||
// «Поделиться записью / комментарием»: что именно отправляется, ссылка и «Скопировать ссылку».
|
||||
// Системное меню «Поделиться» — вторым действием, если браузер его умеет.
|
||||
export function openShareSheet({ title = t('dialogs.remaining.components.share_sheet.opensharesheet.podelitsya'), kicker = '', text = '', url = '' } = {}) {
|
||||
return openSheet({
|
||||
title,
|
||||
className: 'share-sheet',
|
||||
content: (sheet) => {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'share-sheet__content';
|
||||
|
||||
const preview = document.createElement('div');
|
||||
preview.className = 'share-sheet__preview';
|
||||
const k = document.createElement('strong');
|
||||
k.textContent = kicker;
|
||||
const previewText = document.createElement('p');
|
||||
previewText.textContent = text;
|
||||
preview.append(k, previewText);
|
||||
|
||||
const label = document.createElement('label');
|
||||
label.className = 'share-sheet__label';
|
||||
label.textContent = t('dialogs.modals.share_sheet.label_001');
|
||||
const field = document.createElement('input');
|
||||
field.className = 'share-sheet__link';
|
||||
field.readOnly = true;
|
||||
field.value = url;
|
||||
field.addEventListener('focus', () => field.select());
|
||||
label.append(field);
|
||||
|
||||
const copy = document.createElement('button');
|
||||
copy.type = 'button';
|
||||
copy.className = 'primary-btn share-sheet__copy';
|
||||
copy.innerHTML = `${iconHtml('copy')}<span>${t('dialogs.remaining.components.share_sheet.markup.skopirovat_ssylku')}</span>`;
|
||||
copy.addEventListener('click', async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(url);
|
||||
showToast(t('dialogs.remaining.components.share_sheet.opensharesheet.ssylka_skopirovana'));
|
||||
sheet.close();
|
||||
} catch {
|
||||
field.focus();
|
||||
field.select();
|
||||
showToast(t('dialogs.remaining.components.share_sheet.opensharesheet.ssylka_vydelena_skopiruyte_eyo_vruchnuyu'), { kind: 'info' });
|
||||
}
|
||||
});
|
||||
wrap.append(preview, label, copy);
|
||||
|
||||
if (navigator.share) {
|
||||
const system = document.createElement('button');
|
||||
system.type = 'button';
|
||||
system.className = 'secondary-btn share-sheet__system';
|
||||
system.innerHTML = `${iconHtml('share')}<span>${t('dialogs.remaining.components.share_sheet.markup.drugoe_prilozhenie')}</span>`;
|
||||
system.addEventListener('click', async () => {
|
||||
try { await navigator.share({ title: kicker, text, url }); sheet.close(); } catch { /* отменили */ }
|
||||
});
|
||||
wrap.append(system);
|
||||
}
|
||||
return wrap;
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
|
||||
// Шторка снизу (на широком экране — окно по центру) с заголовком и «✕».
|
||||
// Закрывается по «✕», Escape и тапу мимо; фокус возвращается туда, откуда открыли.
|
||||
// Возвращает { root, body, footer, close }. content — Node или функция (sheet) => Node.
|
||||
export function openSheet({ title = '', content = null, className = '', onClose = null } = {}) {
|
||||
const opener = document.activeElement;
|
||||
const modal = document.createElement('div');
|
||||
modal.className = `modal sheet${className ? ` ${className}` : ''}`;
|
||||
const card = document.createElement('div');
|
||||
card.className = 'modal-card sheet__card';
|
||||
card.setAttribute('role', 'dialog');
|
||||
card.setAttribute('aria-modal', 'true');
|
||||
|
||||
const head = document.createElement('div');
|
||||
head.className = 'sheet__head';
|
||||
const heading = document.createElement('h2');
|
||||
heading.className = 'modal-title sheet__title';
|
||||
heading.textContent = title;
|
||||
heading.id = `sheet-title-${Math.random().toString(36).slice(2, 8)}`;
|
||||
card.setAttribute('aria-labelledby', heading.id);
|
||||
const closeBtn = document.createElement('button');
|
||||
closeBtn.type = 'button';
|
||||
closeBtn.className = 'icon-btn sheet__close';
|
||||
closeBtn.setAttribute('aria-label', t('screens.sheet.text_001'));
|
||||
closeBtn.innerHTML = iconHtml('close');
|
||||
head.append(heading, closeBtn);
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'sheet__body';
|
||||
const footer = document.createElement('div');
|
||||
footer.className = 'sheet__footer';
|
||||
footer.hidden = true;
|
||||
card.append(head, body, footer);
|
||||
modal.append(card);
|
||||
|
||||
let closed = false;
|
||||
const close = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
document.removeEventListener('keydown', onKeydown, true);
|
||||
modal.remove();
|
||||
opener?.focus?.();
|
||||
onClose?.();
|
||||
};
|
||||
const onKeydown = (event) => {
|
||||
if (event.key === 'Escape') { event.stopPropagation(); close(); }
|
||||
};
|
||||
modal.addEventListener('click', (event) => { if (event.target === modal) close(); });
|
||||
closeBtn.addEventListener('click', close);
|
||||
document.addEventListener('keydown', onKeydown, true);
|
||||
|
||||
const sheet = { root: modal, body, footer, close };
|
||||
const node = typeof content === 'function' ? content(sheet) : content;
|
||||
if (node instanceof Node) body.append(node);
|
||||
if (footer.childElementCount) footer.hidden = false;
|
||||
document.body.append(modal);
|
||||
(card.querySelector('[autofocus]') || closeBtn).focus();
|
||||
return sheet;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export const SHINE_CONNECTIONS_LOGO_SRC = '/assets/SHiNE_connections_blue.svg?v=2026082601';
|
||||
|
||||
export function createShineConnectionsLogo({ className = '' } = {}) {
|
||||
const img = document.createElement('img');
|
||||
img.src = SHINE_CONNECTIONS_LOGO_SRC;
|
||||
img.alt = '';
|
||||
img.setAttribute('aria-hidden', 'true');
|
||||
img.className = String(className || '').trim();
|
||||
return img;
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { readShineUserPda, supportShineUserOnSolana, supportShineDaoOnSolana } from '../services/shine-user-pda-service.js';
|
||||
import { loadEncryptedUserSecrets } from '../services/key-vault.js';
|
||||
import { getWalletFromStoredBlockchainKey, transferSolLamports, solanaAddressFromPublicKeyBase64 } from '../services/solana-wallet-service.js';
|
||||
import { bytesToBase58 } from '../services/crypto-utils.js';
|
||||
import { parseStarCents, formatStars, splitStarCents, starCentsToLamports, formatLamportsSol } from '../services/shine-support-amount.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { getStarsQuoteFromRpc } from '../services/shine-stars-pyth.js';
|
||||
|
||||
/** One shared payment dialog for profiles, posts and donations to the SHiNE economy. */
|
||||
export function openShineSupportDialog({ recipientLogin = '', target = { type: 0 }, onSuccess = () => {} } = {}) {
|
||||
const dao = !recipientLogin;
|
||||
const login = String(state.session.login || '').trim();
|
||||
if (!login) { window.alert(t('screens.support_phase2.login_required')); return; }
|
||||
if (!dao && login.toLowerCase() === String(recipientLogin).trim().toLowerCase()) {
|
||||
window.alert(t('screens.support_phase2.self_support')); return;
|
||||
}
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'shine-support-dialog-overlay';
|
||||
overlay.style.cssText = 'position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,.66);display:flex;align-items:center;justify-content:center;padding:16px;';
|
||||
const panel = document.createElement('section');
|
||||
panel.className = 'card stack shine-support-dialog';
|
||||
panel.style.cssText = 'width:min(100%,440px);max-height:90vh;overflow:auto;padding:20px;gap:12px;';
|
||||
const header = document.createElement('h2');
|
||||
header.textContent = dao ? t('screens.support_phase2.donate_shine') : t('screens.support_phase2.donate');
|
||||
const description = document.createElement('p');
|
||||
description.className = 'meta-muted';
|
||||
description.textContent = dao ? t('screens.support_phase2.dao_info') : `${t('screens.support_phase2.to')} ${recipientLogin}`;
|
||||
const amountLabel = document.createElement('label');
|
||||
amountLabel.textContent = t('screens.support_phase2.amount');
|
||||
const input = document.createElement('input');
|
||||
input.className = 'input';
|
||||
input.type = 'text';
|
||||
input.inputMode = 'decimal';
|
||||
input.autocomplete = 'off';
|
||||
input.placeholder = '0.10';
|
||||
const details = document.createElement('p');
|
||||
details.className = 'meta-muted';
|
||||
const status = document.createElement('p');
|
||||
status.setAttribute('role', 'status');
|
||||
status.className = 'meta-muted';
|
||||
const donate = document.createElement('button');
|
||||
donate.type = 'button';
|
||||
donate.className = 'primary-btn';
|
||||
donate.textContent = t('screens.support_phase2.donate');
|
||||
const direct = document.createElement('button');
|
||||
direct.type = 'button';
|
||||
direct.className = 'secondary-btn';
|
||||
direct.textContent = t('screens.support_phase2.direct');
|
||||
const cancel = document.createElement('button');
|
||||
cancel.type = 'button';
|
||||
cancel.className = 'text-btn';
|
||||
cancel.textContent = t('screens.support_phase2.close');
|
||||
panel.append(header, description, amountLabel, input, details, status, donate);
|
||||
// Direct transfers bypass Stars accounting and must not appear in the support dialog.
|
||||
panel.append(cancel);
|
||||
overlay.append(panel);
|
||||
document.body.append(overlay);
|
||||
let quote = null;
|
||||
let busy = false;
|
||||
let closed = false;
|
||||
const close = () => { if (busy) return; closed = true; overlay.remove(); };
|
||||
cancel.addEventListener('click', close);
|
||||
overlay.addEventListener('click', (event) => { if (event.target === overlay) close(); });
|
||||
const update = () => {
|
||||
try {
|
||||
const cents = parseStarCents(input.value);
|
||||
const split = splitStarCents(cents);
|
||||
const sol = quote ? ` · ≈ ${formatLamportsSol(starCentsToLamports(cents, quote.solUsdE8, quote.usdtUsdE8))} SOL` : '';
|
||||
details.textContent = dao ? `${formatStars(cents)}${sol}` :
|
||||
`${t('screens.support_phase2.recipient')}: ${formatStars(split.author)} · ${t('screens.support_phase2.fund')}: ${formatStars(split.dao)}${sol}`;
|
||||
} catch { details.textContent = 'Минимум 0,10 ⭐'; }
|
||||
};
|
||||
input.addEventListener('input', update);
|
||||
amountLabel.textContent = 'Сумма поддержки, ⭐';
|
||||
update();
|
||||
void getStarsQuoteFromRpc({ solanaEndpoint: state.entrySettings.solanaServer }).then((value) => { quote = value; if (!closed) update(); })
|
||||
.catch(() => { if (!closed) details.textContent = 'Курс недоступен. Повторите попытку позднее.'; });
|
||||
const send = async (isDirect) => {
|
||||
if (busy || closed) return;
|
||||
let amount, cents;
|
||||
try {
|
||||
cents = parseStarCents(input.value);
|
||||
if (isDirect) throw new Error('Прямой перевод не учитывается в Stars');
|
||||
} catch (error) { status.textContent = error.message; return; }
|
||||
if (isDirect && !window.confirm(t('screens.support_phase2.direct_warning'))) return;
|
||||
busy = true;
|
||||
donate.disabled = direct.disabled = cancel.disabled = input.disabled = true;
|
||||
status.textContent = t('screens.support_phase2.sending');
|
||||
try {
|
||||
// Fetch a fresh quote immediately before signing; Pyth on-chain check is authoritative.
|
||||
quote = await getStarsQuoteFromRpc({ solanaEndpoint: state.entrySettings.solanaServer });
|
||||
amount = starCentsToLamports(cents, quote.solUsdE8, quote.usdtUsdE8);
|
||||
const { storagePwdInMemory: password } = state.session;
|
||||
const endpoint = state.entrySettings.solanaServer;
|
||||
let result;
|
||||
if (isDirect) {
|
||||
let address = '';
|
||||
try {
|
||||
const pda = await readShineUserPda({ login: recipientLogin, solanaEndpoint: endpoint });
|
||||
address = bytesToBase58(pda.forks.at(-1).blockchainKey);
|
||||
} catch {
|
||||
const recipient = await authService.getUser(recipientLogin);
|
||||
if (!recipient?.exists) throw new Error(t('screens.support_phase2.unavailable'));
|
||||
address = solanaAddressFromPublicKeyBase64(recipient.blockchainKey);
|
||||
}
|
||||
const wallet = await getWalletFromStoredBlockchainKey({ login, storagePwd: password });
|
||||
result = await transferSolLamports({ endpoint, fromKeypair: wallet.keypair, toAddress: address, amountLamports: amount });
|
||||
} else {
|
||||
const secrets = await loadEncryptedUserSecrets(login, password);
|
||||
if (!secrets?.blockchainKey || !secrets?.clientKey) throw new Error(t('screens.support_phase2.keys_required'));
|
||||
const args = { senderLogin: login, amountLamports: amount, starCents: cents,
|
||||
oracleAccounts: { solUsd: quote.solOracleAccount, usdtUsd: quote.usdtOracleAccount },
|
||||
solanaEndpoint: endpoint, blockchainPrivatePkcs8B64: secrets.blockchainKey, clientPrivatePkcs8B64: secrets.clientKey };
|
||||
result = dao ? await supportShineDaoOnSolana(args) : await supportShineUserOnSolana({ ...args, recipientLogin, target });
|
||||
}
|
||||
status.textContent = `${t('screens.support_phase2.success')} ${result.signature || ''}`;
|
||||
try { onSuccess(result); } catch { /* page may have been closed */ }
|
||||
donate.hidden = true;
|
||||
direct.hidden = true;
|
||||
cancel.disabled = false;
|
||||
cancel.textContent = t('screens.support_phase2.close');
|
||||
} catch (error) {
|
||||
status.textContent = toUserMessage(error, t('screens.support_phase2.failed'));
|
||||
} finally {
|
||||
busy = false;
|
||||
donate.disabled = direct.disabled = cancel.disabled = input.disabled = false;
|
||||
}
|
||||
};
|
||||
donate.addEventListener('click', () => void send(false));
|
||||
direct.addEventListener('click', () => void send(true));
|
||||
input.focus();
|
||||
return overlay;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
// Надпись «СИЯНИЕ» вразрядку: Tenor Sans (OFL) в контурах — шрифт не скачивается.
|
||||
// Цвет — currentColor, поэтому надпись берёт цвет текста темы.
|
||||
const NS = 'http://www.w3.org/2000/svg';
|
||||
const WIDTH = 7336;
|
||||
const PATH = 'M721 -129Q619 -33 479 -33Q401 -33 341 -60Q281 -87 241 -132Q201 -177 180.5 -236Q160 -295 160 -359Q160 -427 181.5 -483.5Q203 -540 242 -581Q281 -622 334.5 -645Q388 -668 451 -668Q494 -668 529.5 -658Q565 -648 592.5 -632Q620 -616 637.5 -595.5Q655 -575 662 -554H736Q721 -588 697.5 -617Q674 -646 639 -667Q604 -688 557 -700Q510 -712 450 -712Q363 -712 291.5 -687Q220 -662 169 -615.5Q118 -569 90 -503.5Q62 -438 62 -357Q62 -287 84.5 -220.5Q107 -154 154 -102.5Q201 -51 274 -19.5Q347 12 448 12Q512 12 562.5 0Q613 -12 650.5 -29.5Q688 -47 713 -67Q738 -87 751 -102ZM1542 -82V-700H1451V0H1542L1957 -625V0H2048V-700H1957ZM3316 -700V0H3225V-309H3181Q3153 -309 3134.5 -304Q3116 -299 3101 -287Q3086 -275 3073 -256Q3060 -237 3042 -209L2963 -92Q2948 -69 2933.5 -50Q2919 -31 2902 -17.5Q2885 -4 2863.5 4Q2842 12 2812 12Q2790 12 2776 10Q2762 8 2748 0V-37Q2753 -36 2758 -35.5Q2763 -35 2768 -35Q2789 -35 2805 -41Q2821 -47 2835 -58.5Q2849 -70 2862 -86.5Q2875 -103 2889 -124Q2931 -185 2954 -221.5Q2977 -258 2990.5 -278Q3004 -298 3012.5 -307Q3021 -316 3033 -322L3043 -327V-331Q2995 -334 2960.5 -352Q2926 -370 2904 -397Q2882 -424 2872 -455.5Q2862 -487 2862 -517Q2862 -544 2872.5 -576Q2883 -608 2908.5 -635.5Q2934 -663 2978 -681.5Q3022 -700 3089 -700ZM3225 -656H3124Q3086 -656 3055.5 -645Q3025 -634 3003 -614.5Q2981 -595 2969.5 -568Q2958 -541 2958 -509Q2958 -482 2968.5 -454.5Q2979 -427 3000 -404.5Q3021 -382 3051.5 -368Q3082 -354 3122 -354H3225ZM4197 -348H4616V0H4707V-700H4616V-394H4197V-700H4106V0H4197ZM5588 -82V-700H5497V0H5588L6003 -625V0H6094V-700H6003ZM6884 -700V0H7336V-55H6975V-346H7285V-394H6975V-645H7336V-700Z';
|
||||
|
||||
export function createShineWordmark({ className = '' } = {}) {
|
||||
const svg = document.createElementNS(NS, 'svg');
|
||||
svg.setAttribute('viewBox', `52 -722 ${WIDTH - 42} 744`);
|
||||
svg.setAttribute('class', `shine-wordmark ${className}`.trim());
|
||||
svg.setAttribute('role', 'img');
|
||||
svg.setAttribute('aria-label', t('screens.shine_wordmark.text_001'));
|
||||
const path = document.createElementNS(NS, 'path');
|
||||
path.setAttribute('d', PATH);
|
||||
path.setAttribute('fill', 'currentColor');
|
||||
svg.append(path);
|
||||
return svg;
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { authService } from '../state.js';
|
||||
import { getSolanaCluster } from '../services/solana-rpc-gateway.js';
|
||||
import { formatStars } from '../services/shine-support-amount.js';
|
||||
|
||||
export function supportStatsValues(stats = {}) {
|
||||
const sent = BigInt(stats.supportSent ?? 0);
|
||||
const received = BigInt(stats.supportReceived ?? 0);
|
||||
const daoDirect = BigInt(stats.daoDirect ?? 0);
|
||||
return [sent, received, daoDirect];
|
||||
}
|
||||
|
||||
/** Adds an independent asynchronous block; failure/Free accounts do not get fictitious statistics. */
|
||||
export function attachSupportStats(parent, { login, isActive = () => true }) {
|
||||
const section = document.createElement('section');
|
||||
section.className = 'card stack profile-support-stats';
|
||||
section.style.cssText = 'margin-top:12px;gap:8px;';
|
||||
const title = document.createElement('strong');
|
||||
title.textContent = t('screens.support_phase2.statistics');
|
||||
const content = document.createElement('div');
|
||||
content.className = 'meta-muted';
|
||||
content.textContent = t('screens.support_phase2.loading');
|
||||
section.append(title, content);
|
||||
const history = document.createElement('details');
|
||||
history.className = 'profile-support-history';
|
||||
const historySummary = document.createElement('summary');
|
||||
historySummary.textContent = t('screens.support_phase2.history');
|
||||
const historyRows = document.createElement('div');
|
||||
historyRows.className = 'stack';
|
||||
historyRows.style.cssText = 'gap:8px;margin-top:10px;';
|
||||
history.append(historySummary, historyRows);
|
||||
section.append(history);
|
||||
parent.append(section);
|
||||
let historyOffset = 0;
|
||||
let loadingHistory = false;
|
||||
let historyLoaded = false;
|
||||
const historyLogin = String(login || '').trim().toLowerCase();
|
||||
const loadHistory = async () => {
|
||||
if (loadingHistory || !isActive() || !section.isConnected) return;
|
||||
loadingHistory = true;
|
||||
const note = document.createElement('div');
|
||||
note.className = 'meta-muted';
|
||||
note.textContent = t('screens.support_phase2.loading');
|
||||
historyRows.append(note);
|
||||
try {
|
||||
const result = await authService.getSupportHistory(login, 20, historyOffset);
|
||||
if (!isActive() || !section.isConnected) return;
|
||||
note.remove();
|
||||
if (!result.ready) {
|
||||
historyRows.textContent = t('screens.support_phase2.loading');
|
||||
return;
|
||||
}
|
||||
if (!historyOffset && !result.transfers?.length) {
|
||||
historyRows.textContent = t('screens.support_phase2.no_history');
|
||||
}
|
||||
const more = historyRows.querySelector('[data-stars-more]');
|
||||
more?.remove();
|
||||
for (const transfer of result.transfers || []) {
|
||||
const outgoing = transfer.senderLogin?.trim().toLowerCase() === historyLogin;
|
||||
const cents = transfer.kind === 'DAO' || outgoing
|
||||
? transfer.amountStarCents : transfer.recipientStarCents;
|
||||
const row = document.createElement('div');
|
||||
row.className = 'row';
|
||||
row.style.cssText = 'display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:6px;';
|
||||
const info = document.createElement('span');
|
||||
info.textContent = transfer.kind === 'DAO'
|
||||
? t('screens.support_phase2.history_dao')
|
||||
: `${outgoing ? '→' : '←'} ${outgoing ? transfer.recipientLogin : transfer.senderLogin}`;
|
||||
const value = document.createElement('strong');
|
||||
value.textContent = `${outgoing ? '−' : '+'}${formatStars(cents)}`;
|
||||
const detail = document.createElement('small');
|
||||
detail.className = 'meta-muted';
|
||||
const date = transfer.blockTime ? new Date(Number(transfer.blockTime) * 1000).toLocaleString() : '';
|
||||
const lamports = BigInt(transfer.amountLamports || '0');
|
||||
const sol = `${lamports / 1_000_000_000n}.${String(lamports % 1_000_000_000n).padStart(9, '0').replace(/0+$/, '') || '0'} SOL`;
|
||||
detail.textContent = `${date} · ${sol}`;
|
||||
const explorer = document.createElement('a');
|
||||
const sig = String(transfer.signature || '');
|
||||
if (/^[1-9A-HJ-NP-Za-km-z]{64,90}$/.test(sig)) {
|
||||
const network = getSolanaCluster();
|
||||
explorer.href = `https://explorer.solana.com/tx/${sig}${network && network !== 'mainnet-beta' ? `?cluster=${encodeURIComponent(network)}` : ''}`;
|
||||
explorer.target = '_blank'; explorer.rel = 'noopener noreferrer';
|
||||
explorer.textContent = t('screens.support_phase2.transaction');
|
||||
row.append(info, value, detail, explorer);
|
||||
} else row.append(info, value, detail);
|
||||
historyRows.append(row);
|
||||
}
|
||||
historyOffset += (result.transfers || []).length;
|
||||
if (result.hasMore) {
|
||||
const btn = document.createElement('button');
|
||||
btn.className = 'text-btn'; btn.type = 'button';
|
||||
btn.dataset.starsMore = '1';
|
||||
btn.textContent = t('screens.support_phase2.more');
|
||||
btn.addEventListener('click', () => void loadHistory());
|
||||
historyRows.append(btn);
|
||||
}
|
||||
historyLoaded = true;
|
||||
} catch {
|
||||
if (isActive() && section.isConnected) note.textContent = t('screens.support_phase2.history_unavailable');
|
||||
} finally { loadingHistory = false; }
|
||||
};
|
||||
history.addEventListener('toggle', () => {
|
||||
if (history.open && !historyLoaded) void loadHistory();
|
||||
});
|
||||
let pendingRefresh = null;
|
||||
const scheduleRetry = () => {
|
||||
if (pendingRefresh !== null) return;
|
||||
pendingRefresh = window.setTimeout(() => {
|
||||
pendingRefresh = null;
|
||||
if (isActive() && section.isConnected) void refresh();
|
||||
}, 10_000);
|
||||
};
|
||||
const refresh = async () => {
|
||||
try {
|
||||
const stats = await authService.getSupportStats(login);
|
||||
if (!isActive() || !section.isConnected) return;
|
||||
if (!stats.ready) {
|
||||
// Первичная индексация ещё идёт. Повторим запрос к кешу без RPC Solana.
|
||||
content.textContent = t('screens.support_phase2.loading');
|
||||
scheduleRetry();
|
||||
return;
|
||||
}
|
||||
if (!stats.available) {
|
||||
// Free-аккаунты не имеют Paid PDA, поэтому блок статистики не показываем.
|
||||
section.remove();
|
||||
return;
|
||||
}
|
||||
const values = supportStatsValues({
|
||||
supportSent: stats.supportSentStarCents,
|
||||
supportReceived: stats.supportReceivedStarCents,
|
||||
daoDirect: stats.daoDirectStarCents,
|
||||
});
|
||||
content.replaceChildren();
|
||||
content.className = 'stack';
|
||||
[t('screens.support_phase2.sent'), t('screens.support_phase2.received'), t('screens.support_phase2.shine')].forEach((label, idx) => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'row';
|
||||
row.style.cssText = 'display:flex;justify-content:space-between;gap:8px;';
|
||||
const name = document.createElement('span');
|
||||
const amount = document.createElement('strong');
|
||||
name.textContent = label;
|
||||
amount.textContent = formatStars(values[idx]);
|
||||
row.append(name, amount);
|
||||
content.append(row);
|
||||
});
|
||||
} catch {
|
||||
if (!isActive() || !section.isConnected) return;
|
||||
// A missing Paid PDA means Free, but network errors must not be displayed as zero.
|
||||
content.textContent = t('screens.support_phase2.unavailable');
|
||||
}
|
||||
};
|
||||
void refresh();
|
||||
return { element: section, refresh };
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { resolveToolbarActive } from '../router.js';
|
||||
import { state, authService } from '../state.js';
|
||||
import { openAuthRequiredModal } from '../services/auth-required-modal.js';
|
||||
import { SHINE_CONNECTIONS_LOGO_SRC } from './shine-logo.js';
|
||||
|
||||
const TOOLBAR_ICONS = {
|
||||
'messages-list': '<g transform="translate(12 12) scale(.88) translate(-11.5 -13)"><path d="M21 11.5a8.5 8.5 0 0 1-8.5 8.5H4l-2 2v-9.5A8.5 8.5 0 0 1 10.5 4H13a8 8 0 0 1 8 7.5Z"/><circle cx="8" cy="12" r="1.05" class="toolbar-svg-dot"/><circle cx="11.7" cy="12" r="1.05" class="toolbar-svg-dot"/><circle cx="15.4" cy="12" r="1.05" class="toolbar-svg-dot"/></g>',
|
||||
'channels-list': '<rect x="4" y="3" width="16" height="18" rx="3"/><path d="M8 8h8M8 12h8M8 16h5"/>',
|
||||
'notifications-view': '<path d="M6.2 16.8V11a5.8 5.8 0 0 1 11.6 0v5.8l1.7 1.7h-15Z"/><path d="M10.2 21a2 2 0 0 0 3.6 0"/>',
|
||||
'profile-view': '<circle cx="12" cy="6.8" r="3.6"/><path d="M4.4 21v-2.1a5.6 5.6 0 0 1 5.6-5.6h4a5.6 5.6 0 0 1 5.6 5.6V21Z"/>',
|
||||
};
|
||||
|
||||
const ITEMS = [
|
||||
{ pageId: 'messages-list', get label() { return t('screens.toolbar.text_001'); } },
|
||||
{ pageId: 'channels-list', get label() { return t('screens.toolbar.text_002'); } },
|
||||
{ pageId: 'network-view', get label() { return t('screens.toolbar.text_003'); }, mandala: true },
|
||||
{ pageId: 'notifications-view', get label() { return t('screens.toolbar.text_004'); } },
|
||||
{ pageId: 'profile-view', get label() { return t('screens.toolbar.text_005'); } },
|
||||
];
|
||||
|
||||
function iconHtml(item, extra = '') {
|
||||
const glyph = item.mandala
|
||||
? `<img class="toolbar-mandala" src="${SHINE_CONNECTIONS_LOGO_SRC}" alt="" aria-hidden="true" />`
|
||||
: `<svg class="toolbar-svg" viewBox="0 0 24 24" aria-hidden="true">${TOOLBAR_ICONS[item.pageId]}</svg>`;
|
||||
return `<span class="toolbar-icon${item.mandala ? ' toolbar-icon--mandala' : ''}">${glyph}${extra}</span>`;
|
||||
}
|
||||
|
||||
function normalizeCounters(payload = {}) {
|
||||
const notifications = payload?.notifications || {};
|
||||
const notificationTotal = Math.max(0, Number(payload?.notificationsUnreadCount ?? (
|
||||
Number(notifications.replies || 0) + Number(notifications.connections || 0) + Number(notifications.events || 0)
|
||||
)) || 0);
|
||||
return {
|
||||
dmUnreadCount: Math.max(0, Number(payload?.dmUnreadCount || 0) || 0),
|
||||
channelsUnreadCount: Math.max(0, Number(payload?.channelsUnreadCount || 0) || 0),
|
||||
notificationsUnreadCount: notificationTotal,
|
||||
notifications: {
|
||||
replies: Math.max(0, Number(notifications.replies ?? payload?.notificationRepliesUnreadCount ?? 0) || 0),
|
||||
connections: Math.max(0, Number(notifications.connections ?? payload?.notificationConnectionsUnreadCount ?? 0) || 0),
|
||||
events: Math.max(0, Number(notifications.events ?? payload?.notificationEventsUnreadCount ?? 0) || 0),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function setCounterState(payload = {}) {
|
||||
state.userCounters = normalizeCounters(payload);
|
||||
state.notificationUnreadTotal = state.userCounters.notificationsUnreadCount;
|
||||
}
|
||||
|
||||
function renderBadge(btn, count, ariaLabel, extraClass = '') {
|
||||
if (!btn) return;
|
||||
let badge = btn.querySelector('.toolbar-unread-badge');
|
||||
if (count <= 0) { badge?.remove(); return; }
|
||||
if (!badge) {
|
||||
badge = document.createElement('span');
|
||||
badge.className = `toolbar-unread-badge${extraClass ? ` ${extraClass}` : ''}`;
|
||||
(btn.querySelector('.toolbar-icon') || btn).append(badge);
|
||||
}
|
||||
badge.textContent = count > 99 ? '99+' : String(count);
|
||||
badge.setAttribute('aria-label', `${ariaLabel}: ${count}`);
|
||||
}
|
||||
|
||||
function applyCountersToMountedToolbars() {
|
||||
const c = normalizeCounters(state.userCounters);
|
||||
document.querySelectorAll('.toolbar').forEach((toolbar) => {
|
||||
renderBadge(toolbar.querySelector('[data-toolbar-page="messages-list"]'), c.dmUnreadCount, t('screens.toolbar.text_009'));
|
||||
renderBadge(toolbar.querySelector('[data-toolbar-page="channels-list"]'), c.channelsUnreadCount, t('screens.toolbar.text_010'));
|
||||
renderBadge(toolbar.querySelector('[data-toolbar-page="notifications-view"]'), c.notificationsUnreadCount, t('screens.toolbar.text_011'), 'notification-toolbar-badge');
|
||||
});
|
||||
}
|
||||
|
||||
let countersPushBound = false;
|
||||
function ensureCountersPushBound() {
|
||||
if (countersPushBound) return;
|
||||
countersPushBound = true;
|
||||
authService.onEvent('UserCountersChanged', (event) => {
|
||||
setCounterState(event?.payload || {});
|
||||
applyCountersToMountedToolbars();
|
||||
});
|
||||
}
|
||||
|
||||
async function refreshUserCounters() {
|
||||
if (!state.session.isAuthorized) return;
|
||||
try {
|
||||
setCounterState(await authService.getUserCounters());
|
||||
applyCountersToMountedToolbars();
|
||||
} catch {
|
||||
// Keep the last known counters; realtime push or the next refresh can recover.
|
||||
}
|
||||
}
|
||||
|
||||
function navigateWithGuestRules(pageId, navigate) {
|
||||
if (state.session.isAuthorized) {
|
||||
navigate(pageId);
|
||||
return;
|
||||
}
|
||||
if (pageId === 'messages-list') {
|
||||
openAuthRequiredModal({
|
||||
title: t('screens.toolbar.text_006'),
|
||||
text: t('screens.toolbar.text_015'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (pageId === 'profile-view') {
|
||||
openAuthRequiredModal({
|
||||
title: t('screens.toolbar.text_007'),
|
||||
text: t('screens.toolbar.text_016'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (pageId === 'notifications-view') {
|
||||
openAuthRequiredModal({
|
||||
title: t('screens.toolbar.text_008'),
|
||||
text: t('screens.toolbar.text_017'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
navigate(pageId);
|
||||
}
|
||||
|
||||
export function renderToolbar(currentPageId, navigate) {
|
||||
const root = document.createElement('nav');
|
||||
root.className = 'toolbar';
|
||||
const active = resolveToolbarActive(currentPageId);
|
||||
ensureCountersPushBound();
|
||||
const counters = normalizeCounters(state.userCounters);
|
||||
|
||||
ITEMS.forEach((item) => {
|
||||
const btn = document.createElement('button');
|
||||
const isProfile = item.pageId === 'profile-view';
|
||||
const isMessages = item.pageId === 'messages-list';
|
||||
const isNetwork = item.pageId === 'network-view';
|
||||
const isNotifications = item.pageId === 'notifications-view';
|
||||
btn.type = 'button';
|
||||
if (item.pageId === active) btn.setAttribute('aria-current', 'page');
|
||||
btn.dataset.toolbarPage = item.pageId;
|
||||
btn.className = `toolbar-btn${item.pageId === active ? ' active' : ''}${isProfile ? ' toolbar-btn-profile' : ''}${isMessages ? ' toolbar-btn-messages' : ''}${isNetwork ? ' toolbar-btn-network' : ''}${item.hero ? ' toolbar-btn-hero' : ''}`;
|
||||
if (isProfile) {
|
||||
btn.innerHTML = `
|
||||
${iconHtml(item, `<span id="toolbar-connection-indicator" class="toolbar-connection-indicator is-unknown">
|
||||
<span class="toolbar-connection-dot" aria-hidden="true"></span>
|
||||
</span>`)}
|
||||
<span class="sr-only">${item.label}</span>
|
||||
`;
|
||||
} else if (isNetwork) {
|
||||
btn.innerHTML = `${iconHtml(item)}<span class="sr-only">${item.label}</span>`;
|
||||
} else {
|
||||
btn.innerHTML = `${iconHtml(item)}<span class="sr-only">${item.label}</span>`;
|
||||
}
|
||||
btn.title = item.label;
|
||||
if (isMessages) renderBadge(btn, counters.dmUnreadCount, t('screens.toolbar.text_012'));
|
||||
if (item.pageId === 'channels-list') renderBadge(btn, counters.channelsUnreadCount, t('screens.toolbar.text_013'));
|
||||
if (isNotifications) renderBadge(btn, counters.notificationsUnreadCount, t('screens.toolbar.text_014'), 'notification-toolbar-badge');
|
||||
if (item.pageId === 'channels-list') {
|
||||
btn.addEventListener('click', () => navigate('channels-list'));
|
||||
} else if (isNetwork) {
|
||||
btn.addEventListener('click', () => {
|
||||
// Каждый вход через основную вкладку начинает новое исследование сети.
|
||||
// Переключение между V1–V4 внутри вкладки этот сброс не вызывает.
|
||||
if (state.session.isAuthorized) window.dispatchEvent(new Event('shine:network-tab-enter'));
|
||||
navigateWithGuestRules(item.pageId, navigate);
|
||||
});
|
||||
} else {
|
||||
btn.addEventListener('click', () => navigateWithGuestRules(item.pageId, navigate));
|
||||
}
|
||||
root.append(btn);
|
||||
});
|
||||
|
||||
if (state.session.isAuthorized) void refreshUserCounters();
|
||||
|
||||
return root;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { createDropdownMenu } from './dropdown-menu.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
|
||||
/** Заголовок-переключатель для списков; не создаёт собственный TopBar или меню. */
|
||||
export function createTopBarFilterTitle({ section, choices, value, onSelect, minWidth = 210 } = {}) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'topbar-filter-title';
|
||||
button.title = t('screens.topbar_filter_title.text_001', { value1: section });
|
||||
|
||||
const caption = document.createElement('span');
|
||||
caption.className = 'topbar-filter-title__caption';
|
||||
const chevron = document.createElement('span');
|
||||
chevron.className = 'topbar-filter-title__chevron';
|
||||
chevron.setAttribute('aria-hidden', 'true');
|
||||
chevron.innerHTML = iconHtml('chevron-down');
|
||||
button.append(caption, chevron);
|
||||
|
||||
let selected = value;
|
||||
const setValue = (nextValue) => {
|
||||
selected = nextValue;
|
||||
const label = choices.find(([key]) => key === selected)?.[1] || '';
|
||||
caption.textContent = `${section}: ${label}`;
|
||||
button.setAttribute('aria-label', t('screens.topbar_filter_title.text_002', { value1: section, value2: label }));
|
||||
};
|
||||
setValue(value);
|
||||
|
||||
const menu = createDropdownMenu({
|
||||
anchorEl: button,
|
||||
placement: 'bottom-start',
|
||||
minWidth,
|
||||
transparent: true,
|
||||
items: () => choices.map(([key, label]) => ({
|
||||
label,
|
||||
selected: key === selected,
|
||||
action: () => onSelect?.(key),
|
||||
})),
|
||||
});
|
||||
|
||||
return { element: button, setValue, close: () => menu.close(), destroy: () => menu.destroy() };
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
import { createDropdownMenu } from './dropdown-menu.js';
|
||||
|
||||
function appendNode(target, node) {
|
||||
if (!target || !(node instanceof Node)) return;
|
||||
target.append(node);
|
||||
}
|
||||
|
||||
function createActionButton(action = {}, cleanupFns) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = `icon-btn topbar__action${action.className ? ` ${action.className}` : ''}`;
|
||||
if (action.title) button.title = action.title;
|
||||
if (action.ariaLabel) button.setAttribute('aria-label', action.ariaLabel);
|
||||
if (action.id) button.dataset.action = action.id;
|
||||
|
||||
if (action.iconNode instanceof Node) {
|
||||
button.append(action.iconNode);
|
||||
} else if (action.icon) {
|
||||
button.innerHTML = iconHtml(action.icon);
|
||||
} else if (action.label === '⋮' || action.label === '⋯') {
|
||||
// Меню экрана везде рисуется одной иконкой «⋯»
|
||||
button.innerHTML = iconHtml('more');
|
||||
} else {
|
||||
button.textContent = String(action.label ?? '');
|
||||
}
|
||||
|
||||
if (action.menu) {
|
||||
const menu = createDropdownMenu({
|
||||
anchorEl: button,
|
||||
transparent: true,
|
||||
dimBackground: true,
|
||||
keepAnchorPressed: true,
|
||||
...(typeof action.menu === 'object' ? action.menu : {}),
|
||||
});
|
||||
cleanupFns.add(() => menu.destroy());
|
||||
} else if (typeof action.onClick === 'function') {
|
||||
button.addEventListener('click', action.onClick);
|
||||
}
|
||||
|
||||
return button;
|
||||
}
|
||||
|
||||
export function createTopBar({
|
||||
title = '',
|
||||
className = '',
|
||||
left = null,
|
||||
center = null,
|
||||
back = null,
|
||||
leftLabel = '',
|
||||
actions = [],
|
||||
} = {}) {
|
||||
const cleanupFns = new Set();
|
||||
const topbar = document.createElement('header');
|
||||
topbar.className = `topbar${className ? ` ${className}` : ''}`;
|
||||
|
||||
const leftSlot = document.createElement('div');
|
||||
leftSlot.className = 'topbar__left';
|
||||
|
||||
const backAction = back;
|
||||
if (backAction?.visible !== false && typeof backAction?.onClick === 'function') {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = `icon-btn topbar__back${backAction.className ? ` ${backAction.className}` : ''}`;
|
||||
button.innerHTML = iconHtml('back');
|
||||
button.setAttribute('aria-label', backAction.ariaLabel || t('screens.topbar.text_004'));
|
||||
button.title = backAction.title || t('screens.topbar.text_005');
|
||||
button.addEventListener('click', backAction.onClick);
|
||||
leftSlot.append(button);
|
||||
}
|
||||
|
||||
appendNode(leftSlot, left);
|
||||
|
||||
if (leftLabel) {
|
||||
const label = document.createElement('span');
|
||||
label.className = 'topbar__left-label';
|
||||
label.textContent = leftLabel;
|
||||
leftSlot.append(label);
|
||||
}
|
||||
|
||||
const centerSlot = document.createElement('div');
|
||||
centerSlot.className = 'topbar__center';
|
||||
const resolvedCenter = center;
|
||||
if (resolvedCenter instanceof Node) {
|
||||
centerSlot.append(resolvedCenter);
|
||||
} else {
|
||||
const heading = document.createElement('h1');
|
||||
heading.className = 'topbar__title';
|
||||
heading.textContent = String(title || '');
|
||||
centerSlot.append(heading);
|
||||
}
|
||||
|
||||
const rightSlot = document.createElement('div');
|
||||
rightSlot.className = 'topbar__right';
|
||||
const normalizedActions = actions;
|
||||
normalizedActions.forEach((action) => {
|
||||
rightSlot.append(createActionButton(action, cleanupFns));
|
||||
});
|
||||
|
||||
topbar.append(leftSlot, centerSlot, rightSlot);
|
||||
|
||||
topbar.addCleanup = (cleanup) => {
|
||||
if (typeof cleanup === 'function') cleanupFns.add(cleanup);
|
||||
return cleanup;
|
||||
};
|
||||
topbar.cleanup = () => {
|
||||
for (const cleanup of cleanupFns) {
|
||||
try {
|
||||
cleanup();
|
||||
} catch (error) {
|
||||
console.warn('[TopBar] cleanup failed', error);
|
||||
}
|
||||
}
|
||||
cleanupFns.clear();
|
||||
};
|
||||
|
||||
return topbar;
|
||||
}
|
||||
|
||||
/**
|
||||
* Шапка-строка поиска (поиск по переписке, по связям и т. п.): «назад» закрывает поиск,
|
||||
* крестик очищает поле, Enter – onSubmit, Escape – onClose.
|
||||
* trailing – узел справа внутри поля (например, счётчик «3 из 12»).
|
||||
*/
|
||||
export function createSearchTopBar({
|
||||
placeholder = t('remaining.navigation.search'),
|
||||
value = '',
|
||||
onInput = null,
|
||||
onSubmit = null,
|
||||
onClose = null,
|
||||
trailing = null,
|
||||
actions = [],
|
||||
className = '',
|
||||
} = {}) {
|
||||
const field = document.createElement('label');
|
||||
field.className = 'topbar-search';
|
||||
field.innerHTML = `
|
||||
<span class="topbar-search__icon" aria-hidden="true">${iconHtml('search')}</span>
|
||||
<input class="topbar-search__input" type="search" autocomplete="off" autocapitalize="off" spellcheck="false" enterkeyhint="search" />
|
||||
`;
|
||||
const input = field.querySelector('input');
|
||||
input.placeholder = placeholder;
|
||||
input.setAttribute('aria-label', placeholder);
|
||||
input.value = value;
|
||||
if (trailing instanceof Node) field.append(trailing);
|
||||
const clear = document.createElement('button');
|
||||
clear.type = 'button';
|
||||
clear.className = 'topbar-search__clear';
|
||||
clear.innerHTML = iconHtml('close');
|
||||
clear.setAttribute('aria-label', t('screens.topbar.text_006'));
|
||||
clear.title = t('screens.topbar.text_001');
|
||||
clear.hidden = !value;
|
||||
clear.addEventListener('click', (event) => {
|
||||
event.preventDefault();
|
||||
input.value = '';
|
||||
clear.hidden = true;
|
||||
input.focus();
|
||||
onInput?.('');
|
||||
});
|
||||
field.append(clear);
|
||||
input.addEventListener('input', () => {
|
||||
clear.hidden = !input.value;
|
||||
onInput?.(input.value);
|
||||
});
|
||||
input.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
onSubmit?.(input.value, event);
|
||||
} else if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
onClose?.();
|
||||
}
|
||||
});
|
||||
const topbar = createTopBar({
|
||||
center: field,
|
||||
className: `topbar--search${className ? ` ${className}` : ''}`,
|
||||
back: { onClick: () => onClose?.(), ariaLabel: t('screens.topbar.text_002'), title: t('screens.topbar.text_003') },
|
||||
actions,
|
||||
});
|
||||
topbar.searchInput = input;
|
||||
return topbar;
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
export const TWEMOJI_GROUP_ACTIVITY = {
|
||||
"id": "activity",
|
||||
get "label"() { return t('screens.twemoji_activity.text_002'); },
|
||||
"icon": "🎉",
|
||||
"items": [
|
||||
{
|
||||
"file": "Activity/1st Place Medal.webp",
|
||||
"emoji": "🥇"
|
||||
},
|
||||
{
|
||||
"file": "Activity/2nd Place Medal.webp",
|
||||
"emoji": "🥈"
|
||||
},
|
||||
{
|
||||
"file": "Activity/3rd Place Medal.webp",
|
||||
"emoji": "🥉"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Admission Tickets.webp",
|
||||
"emoji": "🎟️"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Artist Palette.webp",
|
||||
"emoji": "🎨"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Balloon.webp",
|
||||
"emoji": "🎈"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Basketball.webp",
|
||||
"emoji": "🏀"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Christmas Tree.webp",
|
||||
"emoji": "🎄"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Confetti Ball.webp",
|
||||
"emoji": "🎊"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Crystal Ball.webp",
|
||||
"emoji": "🔮"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Firecracker.webp",
|
||||
"emoji": "🧨"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Fireworks.webp",
|
||||
"emoji": "🎆"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Jack O Lantern.webp",
|
||||
"emoji": "🎃"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Magic Wand.webp",
|
||||
"emoji": "🪄"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Military Medal.webp",
|
||||
"emoji": "🎖️"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Mirror Ball.webp",
|
||||
"emoji": "🪩"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Party Popper.webp",
|
||||
"emoji": "🎉"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Performing Arts.webp",
|
||||
"emoji": "🎭"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Soccer Ball.webp",
|
||||
"emoji": "⚽"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Sparkler.webp",
|
||||
"emoji": "🎇"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Sparkles.webp",
|
||||
"emoji": "✨"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Sports Medal.webp",
|
||||
"emoji": "🏅"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Ticket.webp",
|
||||
"emoji": "🎫"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Trophy.webp",
|
||||
"emoji": "🏆"
|
||||
},
|
||||
{
|
||||
"file": "Activity/Video Game.webp",
|
||||
"emoji": "🎮"
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
@@ -0,0 +1,489 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
export const TWEMOJI_GROUP_ANIMALS_NATURE = {
|
||||
"id": "animals-and-nature",
|
||||
get "label"() { return t('screens.twemoji_animals_nature.text_002'); },
|
||||
"icon": "🌿",
|
||||
"items": [
|
||||
{
|
||||
"file": "Animals and Nature/Ant.webp",
|
||||
"emoji": "🐜"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Baby Chick.webp",
|
||||
"emoji": "🐤"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Bat.webp",
|
||||
"emoji": "🦇"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Bear.webp",
|
||||
"emoji": "🐻"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Beetle.webp",
|
||||
"emoji": "🪲"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Bird.webp",
|
||||
"emoji": "🐦"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Bison.webp",
|
||||
"emoji": "🦬"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Black Cat.webp",
|
||||
"emoji": "🐈⬛"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Blossom.webp",
|
||||
"emoji": "🌼"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Bouquet.webp",
|
||||
"emoji": "💐"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Bug.webp",
|
||||
"emoji": "🐛"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Butterfly.webp",
|
||||
"emoji": "🦋"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Cactus.webp",
|
||||
"emoji": "🌵"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Cat Face.webp",
|
||||
"emoji": "🐱"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Cat.webp",
|
||||
"emoji": "🐈"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Cherry Blossom.webp",
|
||||
"emoji": "🌸"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Chicken.webp",
|
||||
"emoji": "🐔"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Cloud With Lightning And Rain.webp",
|
||||
"emoji": "⛈️"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Cloud With Lightning.webp",
|
||||
"emoji": "🌩️"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Cloud With Rain.webp",
|
||||
"emoji": "🌧️"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Cloud With Snow.webp",
|
||||
"emoji": "🌨️"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Cloud.webp",
|
||||
"emoji": "☁️"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Cockroach.webp",
|
||||
"emoji": "🪳"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Cow.webp",
|
||||
"emoji": "🐄"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Cricket.webp",
|
||||
"emoji": "🦗"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Deciduous Tree.webp",
|
||||
"emoji": "🌳"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Deer.webp",
|
||||
"emoji": "🦌"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Dog Face.webp",
|
||||
"emoji": "🐶"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Dove.webp",
|
||||
"emoji": "🕊️"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Duck.webp",
|
||||
"emoji": "🦆"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Evergreen Tree.webp",
|
||||
"emoji": "🌲"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Fire.webp",
|
||||
"emoji": "🔥"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/First Quarter Moon Face.webp",
|
||||
"emoji": "🌛"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/First Quarter Moon.webp",
|
||||
"emoji": "🌓"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Fish.webp",
|
||||
"emoji": "🐟"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Flamingo.webp",
|
||||
"emoji": "🦩"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Four Leaf Clover.webp",
|
||||
"emoji": "🍀"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Fox.webp",
|
||||
"emoji": "🦊"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Frog.webp",
|
||||
"emoji": "🐸"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Front Facing Baby Chick.webp",
|
||||
"emoji": "🐥"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Full Moon Face.webp",
|
||||
"emoji": "🌝"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Full Moon.webp",
|
||||
"emoji": "🌕"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Giraffe.webp",
|
||||
"emoji": "🦒"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Glowing Star.webp",
|
||||
"emoji": "🌟"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Gorilla.webp",
|
||||
"emoji": "🦍"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Hamster.webp",
|
||||
"emoji": "🐹"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Hatching Chick.webp",
|
||||
"emoji": "🐣"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Hedgehog.webp",
|
||||
"emoji": "🦔"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Herb.webp",
|
||||
"emoji": "🌿"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Hibiscus.webp",
|
||||
"emoji": "🌺"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/High Voltage.webp",
|
||||
"emoji": "⚡"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Honeybee.webp",
|
||||
"emoji": "🐝"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Horse Face.webp",
|
||||
"emoji": "🐴"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Horse.webp",
|
||||
"emoji": "🐎"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Kangaroo.webp",
|
||||
"emoji": "🦘"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Koala.webp",
|
||||
"emoji": "🐨"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Lady Beetle.webp",
|
||||
"emoji": "🐞"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Last Quarter Moon Face.webp",
|
||||
"emoji": "🌜"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Last Quarter Moon.webp",
|
||||
"emoji": "🌗"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Leopard.webp",
|
||||
"emoji": "🐆"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Lion.webp",
|
||||
"emoji": "🦁"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Llama.webp",
|
||||
"emoji": "🦙"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Lobster.webp",
|
||||
"emoji": "🦞"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Microbe.webp",
|
||||
"emoji": "🦠"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Monkey Face.webp",
|
||||
"emoji": "🐵"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Mosquito.webp",
|
||||
"emoji": "🦟"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Mouse Face.webp",
|
||||
"emoji": "🐭"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/New Moon Face.webp",
|
||||
"emoji": "🌚"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/New Moon.webp",
|
||||
"emoji": "🌑"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Octopus.webp",
|
||||
"emoji": "🐙"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Owl.webp",
|
||||
"emoji": "🦉"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Ox.webp",
|
||||
"emoji": "🐂"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Palm Tree.webp",
|
||||
"emoji": "🌴"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Panda.webp",
|
||||
"emoji": "🐼"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Parrot.webp",
|
||||
"emoji": "🦜"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Paw Prints.webp",
|
||||
"emoji": "🐾"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Penguin.webp",
|
||||
"emoji": "🐧"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Pig Face.webp",
|
||||
"emoji": "🐷"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Pig Nose.webp",
|
||||
"emoji": "🐽"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Polar Bear.webp",
|
||||
"emoji": "🐻❄️"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Rabbit Face.webp",
|
||||
"emoji": "🐰"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Rabbit.webp",
|
||||
"emoji": "🐇"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Raccoon.webp",
|
||||
"emoji": "🦝"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Rainbow.webp",
|
||||
"emoji": "🌈"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Rose.webp",
|
||||
"emoji": "🌹"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Rosette.webp",
|
||||
"emoji": "🏵️"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Sauropod.webp",
|
||||
"emoji": "🦕"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Seal.webp",
|
||||
"emoji": "🦭"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Seedling.webp",
|
||||
"emoji": "🌱"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Shamrock.webp",
|
||||
"emoji": "☘️"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Shrimp.webp",
|
||||
"emoji": "🦐"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Snail.webp",
|
||||
"emoji": "🐌"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Snake.webp",
|
||||
"emoji": "🐍"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Snowflake.webp",
|
||||
"emoji": "❄️"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Snowman Without Snow.webp",
|
||||
"emoji": "⛄"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Snowman.webp",
|
||||
"emoji": "☃️"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Spider Web.webp",
|
||||
"emoji": "🕸️"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Spider.webp",
|
||||
"emoji": "🕷️"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Spouting Whale.webp",
|
||||
"emoji": "🐳"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Squid.webp",
|
||||
"emoji": "🦑"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Star.webp",
|
||||
"emoji": "⭐"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Sun Behind Cloud.webp",
|
||||
"emoji": "⛅"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Sun Behind Large Cloud.webp",
|
||||
"emoji": "🌥️"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Sun Behind Rain Cloud.webp",
|
||||
"emoji": "🌦️"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Sun Behind Small Cloud.webp",
|
||||
"emoji": "🌤️"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Sun With Face.webp",
|
||||
"emoji": "🌞"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Sun.webp",
|
||||
"emoji": "☀️"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Swan.webp",
|
||||
"emoji": "🦢"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/T Rex.webp",
|
||||
"emoji": "🦖"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Tiger Face.webp",
|
||||
"emoji": "🐯"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Tiger.webp",
|
||||
"emoji": "🐅"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Tropical Fish.webp",
|
||||
"emoji": "🐠"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Tulip.webp",
|
||||
"emoji": "🌷"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Turkey.webp",
|
||||
"emoji": "🦃"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Turtle.webp",
|
||||
"emoji": "🐢"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Unicorn.webp",
|
||||
"emoji": "🦄"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Waning Crescent Moon.webp",
|
||||
"emoji": "🌘"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Waxing Crescent Moon.webp",
|
||||
"emoji": "🌒"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Waxing Gibbous Moon.webp",
|
||||
"emoji": "🌔"
|
||||
},
|
||||
{
|
||||
"file": "Animals and Nature/Zebra.webp",
|
||||
"emoji": "🦓"
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { TWEMOJI_GROUP_ACTIVITY } from './twemoji-activity.js?v=202607151545';
|
||||
import { TWEMOJI_GROUP_ANIMALS_NATURE } from './twemoji-animals_nature.js?v=202607151545';
|
||||
import { TWEMOJI_GROUP_FLAGS } from './twemoji-flags.js?v=202607151545';
|
||||
import { TWEMOJI_GROUP_FOOD_DRINK } from './twemoji-food_drink.js?v=202607151545';
|
||||
import { TWEMOJI_GROUP_OBJECTS } from './twemoji-objects.js?v=202607151545';
|
||||
import { TWEMOJI_GROUP_PEOPLE } from './twemoji-people.js?v=202607151545';
|
||||
import { TWEMOJI_GROUP_SMILEYS } from './twemoji-smileys.js?v=202607151545';
|
||||
import { TWEMOJI_GROUP_SYMBOLS } from './twemoji-symbols.js?v=202607151545';
|
||||
import { TWEMOJI_GROUP_TRAVEL_PLACES } from './twemoji-travel_places.js?v=202607151545';
|
||||
|
||||
const TWEMOJI_SVG_BASE_URL = 'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/svg/';
|
||||
|
||||
function getTwemojiCodepoint(emoji) {
|
||||
return Array.from(String(emoji || ''))
|
||||
.map((char) => char.codePointAt(0))
|
||||
.filter((codepoint) => codepoint && codepoint !== 0xfe0f)
|
||||
.map((codepoint) => codepoint.toString(16))
|
||||
.join('-');
|
||||
}
|
||||
|
||||
function withPreviewUrls(group) {
|
||||
return {
|
||||
...group,
|
||||
items: group.items.map((item) => ({
|
||||
...item,
|
||||
name: item.name || String(item.emoji || ''),
|
||||
previewUrl: getTwemojiPreviewUrl(item.emoji),
|
||||
animatedUrl: getTwemojiAssetUrl(item.emoji),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export const TWEMOJI_GROUPS = [
|
||||
TWEMOJI_GROUP_SMILEYS,
|
||||
TWEMOJI_GROUP_PEOPLE,
|
||||
TWEMOJI_GROUP_ANIMALS_NATURE,
|
||||
TWEMOJI_GROUP_FOOD_DRINK,
|
||||
TWEMOJI_GROUP_TRAVEL_PLACES,
|
||||
TWEMOJI_GROUP_ACTIVITY,
|
||||
TWEMOJI_GROUP_OBJECTS,
|
||||
TWEMOJI_GROUP_SYMBOLS,
|
||||
TWEMOJI_GROUP_FLAGS,
|
||||
].map(withPreviewUrls);
|
||||
|
||||
export function getTwemojiAssetUrl(emoji) {
|
||||
return getTwemojiPreviewUrl(emoji);
|
||||
}
|
||||
|
||||
export function getTwemojiPreviewUrl(emoji) {
|
||||
const codepoint = getTwemojiCodepoint(emoji);
|
||||
return codepoint ? `${TWEMOJI_SVG_BASE_URL}${codepoint}.svg` : '';
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
export const TWEMOJI_GROUP_FLAGS = {
|
||||
"id": "flags",
|
||||
get "label"() { return t('screens.twemoji_flags.text_002'); },
|
||||
"icon": "🏳️",
|
||||
"items": [
|
||||
{
|
||||
"file": "Flags/Black Flag.webp",
|
||||
"emoji": "🏴"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Chequered Flag.webp",
|
||||
"emoji": "🏁"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Argentina.webp",
|
||||
"emoji": "🇦🇷"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Armenia.webp",
|
||||
"emoji": "🇦🇲"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Austria.webp",
|
||||
"emoji": "🇦🇹"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Bahamas.webp",
|
||||
"emoji": "🇧🇸"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Belarus.webp",
|
||||
"emoji": "🇧🇾"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Belgium.webp",
|
||||
"emoji": "🇧🇪"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Benin.webp",
|
||||
"emoji": "🇧🇯"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Brazil.webp",
|
||||
"emoji": "🇧🇷"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Bulgaria.webp",
|
||||
"emoji": "🇧🇬"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Burkina Faso.webp",
|
||||
"emoji": "🇧🇫"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Cameroon.webp",
|
||||
"emoji": "🇨🇲"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Chad.webp",
|
||||
"emoji": "🇹🇩"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag China.webp",
|
||||
"emoji": "🇨🇳"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Cote Divoire.webp",
|
||||
"emoji": "🇨🇮"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Croatia.webp",
|
||||
"emoji": "🇭🇷"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Czechia.webp",
|
||||
"emoji": "🇨🇿"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Djibouti.webp",
|
||||
"emoji": "🇩🇯"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Equatorial Guinea.webp",
|
||||
"emoji": "🇬🇶"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Estonia.webp",
|
||||
"emoji": "🇪🇪"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag France.webp",
|
||||
"emoji": "🇫🇷"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Gabon.webp",
|
||||
"emoji": "🇬🇦"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Germany.webp",
|
||||
"emoji": "🇩🇪"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Ghana.webp",
|
||||
"emoji": "🇬🇭"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Guinea Bissau.webp",
|
||||
"emoji": "🇬🇼"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Guinea.webp",
|
||||
"emoji": "🇬🇳"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Hungary.webp",
|
||||
"emoji": "🇭🇺"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag India.webp",
|
||||
"emoji": "🇮🇳"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Indonesia.webp",
|
||||
"emoji": "🇮🇩"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Ireland.webp",
|
||||
"emoji": "🇮🇪"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Italy.webp",
|
||||
"emoji": "🇮🇹"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Japan.webp",
|
||||
"emoji": "🇯🇵"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Jordan.webp",
|
||||
"emoji": "🇯🇴"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Lithuania.webp",
|
||||
"emoji": "🇱🇹"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Luxembourg.webp",
|
||||
"emoji": "🇱🇺"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Madagascar.webp",
|
||||
"emoji": "🇲🇬"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Mali.webp",
|
||||
"emoji": "🇲🇱"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Monaco.webp",
|
||||
"emoji": "🇲🇨"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Morocco.webp",
|
||||
"emoji": "🇲🇦"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Mozambique.webp",
|
||||
"emoji": "🇲🇿"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Myanmar Burma.webp",
|
||||
"emoji": "🇲🇲"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Netherlands.webp",
|
||||
"emoji": "🇳🇱"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Nigeria.webp",
|
||||
"emoji": "🇳🇬"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Palestinian Territories.webp",
|
||||
"emoji": "🇵🇸"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Peru.webp",
|
||||
"emoji": "🇵🇪"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Philippines.webp",
|
||||
"emoji": "🇵🇭"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Poland.webp",
|
||||
"emoji": "🇵🇱"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Romania.webp",
|
||||
"emoji": "🇷🇴"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Russia.webp",
|
||||
"emoji": "🇷🇺"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Sao Tome Principe.webp",
|
||||
"emoji": "🇸🇹"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Saudi Arabia.webp",
|
||||
"emoji": "🇸🇦"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Senegal.webp",
|
||||
"emoji": "🇸🇳"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Sierra Leone.webp",
|
||||
"emoji": "🇸🇱"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Singapore.webp",
|
||||
"emoji": "🇸🇬"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Sint Maarten.webp",
|
||||
"emoji": "🇸🇽"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Somalia.webp",
|
||||
"emoji": "🇸🇴"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag South Korea.webp",
|
||||
"emoji": "🇰🇷"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag South Sudan.webp",
|
||||
"emoji": "🇸🇸"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Spain.webp",
|
||||
"emoji": "🇪🇸"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Sudan.webp",
|
||||
"emoji": "🇸🇩"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Ukraine.webp",
|
||||
"emoji": "🇺🇦"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag United Arab Emirates.webp",
|
||||
"emoji": "🇦🇪"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag United Kingdom.webp",
|
||||
"emoji": "🇬🇧"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag United States.webp",
|
||||
"emoji": "🇺🇸"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Uzbekistan.webp",
|
||||
"emoji": "🇺🇿"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Vietnam.webp",
|
||||
"emoji": "🇻🇳"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Western Sahara.webp",
|
||||
"emoji": "🇪🇭"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Flag Yemen.webp",
|
||||
"emoji": "🇾🇪"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Pirate Flag.webp",
|
||||
"emoji": "🏴☠️"
|
||||
},
|
||||
{
|
||||
"file": "Flags/Triangular Flag.webp",
|
||||
"emoji": "🚩"
|
||||
},
|
||||
{
|
||||
"file": "Flags/White Flag.webp",
|
||||
"emoji": "🏳️"
|
||||
}
|
||||
]
|
||||
};
|
||||
@@ -0,0 +1,201 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
export const TWEMOJI_GROUP_FOOD_DRINK = {
|
||||
"id": "food-and-drink",
|
||||
get "label"() { return t('screens.twemoji_food_drink.text_002'); },
|
||||
"icon": "🍓",
|
||||
"items": [
|
||||
{
|
||||
"file": "Food and Drink/Baby Bottle.webp",
|
||||
"emoji": "🍼"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Banana.webp",
|
||||
"emoji": "🍌"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Bento Box.webp",
|
||||
"emoji": "🍱"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Beverage Box.webp",
|
||||
"emoji": "🧃"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Birthday Cake.webp",
|
||||
"emoji": "🎂"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Bottle With Popping Cork.webp",
|
||||
"emoji": "🍾"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Bubble Tea.webp",
|
||||
"emoji": "🧋"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Canned Food.webp",
|
||||
"emoji": "🥫"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Chocolate Bar.webp",
|
||||
"emoji": "🍫"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Clinking Glasses.webp",
|
||||
"emoji": "🥂"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Cocktail Glass.webp",
|
||||
"emoji": "🍸"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Cookie.webp",
|
||||
"emoji": "🍪"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Cooking.webp",
|
||||
"emoji": "🍳"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Cup With Straw.webp",
|
||||
"emoji": "🥤"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Cupcake.webp",
|
||||
"emoji": "🧁"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Custard.webp",
|
||||
"emoji": "🍮"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Dango.webp",
|
||||
"emoji": "🍡"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Doughnut.webp",
|
||||
"emoji": "🍩"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Fish Cake With Swirl.webp",
|
||||
"emoji": "🍥"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Fork And Knife With Plate.webp",
|
||||
"emoji": "🍽️"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/French Fries.webp",
|
||||
"emoji": "🍟"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Glass Of Milk.webp",
|
||||
"emoji": "🥛"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Hamburger.webp",
|
||||
"emoji": "🍔"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Hot Beverage.webp",
|
||||
"emoji": "☕"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Hot Dog.webp",
|
||||
"emoji": "🌭"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Lollipop.webp",
|
||||
"emoji": "🍭"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Mate.webp",
|
||||
"emoji": "🧉"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Meat On Bone.webp",
|
||||
"emoji": "🍖"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Oden.webp",
|
||||
"emoji": "🍢"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Pancakes.webp",
|
||||
"emoji": "🥞"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Pie.webp",
|
||||
"emoji": "🥧"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Pizza.webp",
|
||||
"emoji": "🍕"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Popcorn.webp",
|
||||
"emoji": "🍿"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Poultry Leg.webp",
|
||||
"emoji": "🍗"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Pouring Liquid.webp",
|
||||
"emoji": "🫗"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Pretzel.webp",
|
||||
"emoji": "🥨"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Rice Ball.webp",
|
||||
"emoji": "🍙"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Rice Cracker.webp",
|
||||
"emoji": "🍘"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Sandwich.webp",
|
||||
"emoji": "🥪"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Shortcake.webp",
|
||||
"emoji": "🍰"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Soft Ice Cream.webp",
|
||||
"emoji": "🍦"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Strawberry.webp",
|
||||
"emoji": "🍓"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Stuffed Flatbread.webp",
|
||||
"emoji": "🥙"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Sushi.webp",
|
||||
"emoji": "🍣"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Taco.webp",
|
||||
"emoji": "🌮"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Tropical Drink.webp",
|
||||
"emoji": "🍹"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Tumbler Glass.webp",
|
||||
"emoji": "🥃"
|
||||
},
|
||||
{
|
||||
"file": "Food and Drink/Wine Glass.webp",
|
||||
"emoji": "🍷"
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
export const TWEMOJI_GROUP_OBJECTS = {
|
||||
"id": "objects",
|
||||
get "label"() { return t('screens.twemoji_objects.text_002'); },
|
||||
"icon": "💡",
|
||||
"items": [
|
||||
{
|
||||
"file": "Objects/Abacus.webp",
|
||||
"emoji": "🧮"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Ballot Box With Ballot.webp",
|
||||
"emoji": "🗳️"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Bar Chart.webp",
|
||||
"emoji": "📊"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Bomb.webp",
|
||||
"emoji": "💣"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Books.webp",
|
||||
"emoji": "📚"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Briefcase.webp",
|
||||
"emoji": "💼"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Card Index Dividers.webp",
|
||||
"emoji": "🗂️"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Chart Decreasing.webp",
|
||||
"emoji": "📉"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Chart Increasing.webp",
|
||||
"emoji": "📈"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Clapper Board.webp",
|
||||
"emoji": "🎬"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Coffin.webp",
|
||||
"emoji": "⚰️"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Coin.webp",
|
||||
"emoji": "🪙"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Crown.webp",
|
||||
"emoji": "👑"
|
||||
},
|
||||
{
|
||||
"file": "Objects/File Folder.webp",
|
||||
"emoji": "📁"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Gem Stone.webp",
|
||||
"emoji": "💎"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Graduation Cap.webp",
|
||||
"emoji": "🎓"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Handbag.webp",
|
||||
"emoji": "👜"
|
||||
},
|
||||
{
|
||||
"file": "Objects/High Heeled Shoe.webp",
|
||||
"emoji": "👠"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Hourglass Done.webp",
|
||||
"emoji": "⌛"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Hourglass Not Done.webp",
|
||||
"emoji": "⏳"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Identification Card.webp",
|
||||
"emoji": "🪪"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Inbox Tray.webp",
|
||||
"emoji": "📥"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Incoming Envelope.webp",
|
||||
"emoji": "📨"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Key.webp",
|
||||
"emoji": "🔑"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Keyboard.webp",
|
||||
"emoji": "⌨️"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Laptop.webp",
|
||||
"emoji": "💻"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Light Bulb.webp",
|
||||
"emoji": "💡"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Locked With Key.webp",
|
||||
"emoji": "🔐"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Luggage.webp",
|
||||
"emoji": "🧳"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Magnifying Glass Tilted Left.webp",
|
||||
"emoji": "🔍"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Magnifying Glass Tilted Right.webp",
|
||||
"emoji": "🔎"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Megaphone.webp",
|
||||
"emoji": "📣"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Memo.webp",
|
||||
"emoji": "📝"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Microphone.webp",
|
||||
"emoji": "🎤"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Microscope.webp",
|
||||
"emoji": "🔬"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Military Helmet.webp",
|
||||
"emoji": "🪖"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Mobile Phone With Arrow.webp",
|
||||
"emoji": "📲"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Mobile Phone.webp",
|
||||
"emoji": "📱"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Money Bag.webp",
|
||||
"emoji": "💰"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Money With Wings.webp",
|
||||
"emoji": "💸"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Musical Note.webp",
|
||||
"emoji": "🎵"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Musical Notes.webp",
|
||||
"emoji": "🎶"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Newspaper.webp",
|
||||
"emoji": "📰"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Old Key.webp",
|
||||
"emoji": "🗝️"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Open Book.webp",
|
||||
"emoji": "📖"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Outbox Tray.webp",
|
||||
"emoji": "📤"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Pencil.webp",
|
||||
"emoji": "✏️"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Pill.webp",
|
||||
"emoji": "💊"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Printer.webp",
|
||||
"emoji": "🖨️"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Purse.webp",
|
||||
"emoji": "👛"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Reminder Ribbon.webp",
|
||||
"emoji": "🎗️"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Roll Of Paper.webp",
|
||||
"emoji": "🧻"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Shopping Bags.webp",
|
||||
"emoji": "🛍️"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Shopping Cart.webp",
|
||||
"emoji": "🛒"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Soap.webp",
|
||||
"emoji": "🧼"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Sponge.webp",
|
||||
"emoji": "🧽"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Stethoscope.webp",
|
||||
"emoji": "🩺"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Studio Microphone.webp",
|
||||
"emoji": "🎙️"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Syringe.webp",
|
||||
"emoji": "💉"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Tear Off Calendar.webp",
|
||||
"emoji": "📆"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Telephone Receiver.webp",
|
||||
"emoji": "📞"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Telephone.webp",
|
||||
"emoji": "☎️"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Telescope.webp",
|
||||
"emoji": "🔭"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Television.webp",
|
||||
"emoji": "📺"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Test Tube.webp",
|
||||
"emoji": "🧪"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Thermometer.webp",
|
||||
"emoji": "🌡️"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Toolbox.webp",
|
||||
"emoji": "🧰"
|
||||
},
|
||||
{
|
||||
"file": "Objects/Top Hat.webp",
|
||||
"emoji": "🎩"
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
export const TWEMOJI_GROUP_PEOPLE = {
|
||||
"id": "people",
|
||||
get "label"() { return t('screens.twemoji_people.text_002'); },
|
||||
"icon": "🧑",
|
||||
"items": [
|
||||
{
|
||||
"file": "People/Baby.webp",
|
||||
"emoji": "👶"
|
||||
},
|
||||
{
|
||||
"file": "People/Backhand Index Pointing Down.webp",
|
||||
"emoji": "👇"
|
||||
},
|
||||
{
|
||||
"file": "People/Backhand Index Pointing Left.webp",
|
||||
"emoji": "👈"
|
||||
},
|
||||
{
|
||||
"file": "People/Backhand Index Pointing Right.webp",
|
||||
"emoji": "👉"
|
||||
},
|
||||
{
|
||||
"file": "People/Backhand Index Pointing Up.webp",
|
||||
"emoji": "👆"
|
||||
},
|
||||
{
|
||||
"file": "People/Biting Lip.webp",
|
||||
"emoji": "🫦"
|
||||
},
|
||||
{
|
||||
"file": "People/Bone.webp",
|
||||
"emoji": "🦴"
|
||||
},
|
||||
{
|
||||
"file": "People/Bust In Silhouette.webp",
|
||||
"emoji": "👤"
|
||||
},
|
||||
{
|
||||
"file": "People/Busts In Silhouette.webp",
|
||||
"emoji": "👥"
|
||||
},
|
||||
{
|
||||
"file": "People/Call Me Hand.webp",
|
||||
"emoji": "🤙"
|
||||
},
|
||||
{
|
||||
"file": "People/Clapping Hands.webp",
|
||||
"emoji": "👏"
|
||||
},
|
||||
{
|
||||
"file": "People/Crossed Fingers.webp",
|
||||
"emoji": "🤞"
|
||||
},
|
||||
{
|
||||
"file": "People/Ear With Hearing Aid.webp",
|
||||
"emoji": "🦻"
|
||||
},
|
||||
{
|
||||
"file": "People/Ear.webp",
|
||||
"emoji": "👂"
|
||||
},
|
||||
{
|
||||
"file": "People/Eyes.webp",
|
||||
"emoji": "👀"
|
||||
},
|
||||
{
|
||||
"file": "People/Family Man Woman Girl Boy.webp",
|
||||
"emoji": "👨👩👧👦"
|
||||
},
|
||||
{
|
||||
"file": "People/Flexed Biceps.webp",
|
||||
"emoji": "💪"
|
||||
},
|
||||
{
|
||||
"file": "People/Folded Hands.webp",
|
||||
"emoji": "🙏"
|
||||
},
|
||||
{
|
||||
"file": "People/Foot.webp",
|
||||
"emoji": "🦶"
|
||||
},
|
||||
{
|
||||
"file": "People/Footprints.webp",
|
||||
"emoji": "👣"
|
||||
},
|
||||
{
|
||||
"file": "People/Hand With Fingers Splayed.webp",
|
||||
"emoji": "🖐️"
|
||||
},
|
||||
{
|
||||
"file": "People/Hand With Index Finger And Thumb Crossed.webp",
|
||||
"emoji": "🫰"
|
||||
},
|
||||
{
|
||||
"file": "People/Handshake.webp",
|
||||
"emoji": "🤝"
|
||||
},
|
||||
{
|
||||
"file": "People/Heart Hands.webp",
|
||||
"emoji": "🫶"
|
||||
},
|
||||
{
|
||||
"file": "People/Index Pointing At The Viewer.webp",
|
||||
"emoji": "🫵"
|
||||
},
|
||||
{
|
||||
"file": "People/Index Pointing Up.webp",
|
||||
"emoji": "☝️"
|
||||
},
|
||||
{
|
||||
"file": "People/Left Facing Fist.webp",
|
||||
"emoji": "🤛"
|
||||
},
|
||||
{
|
||||
"file": "People/Leftwards Hand.webp",
|
||||
"emoji": "🫲"
|
||||
},
|
||||
{
|
||||
"file": "People/Leg.webp",
|
||||
"emoji": "🦵"
|
||||
},
|
||||
{
|
||||
"file": "People/Love You Gesture.webp",
|
||||
"emoji": "🤟"
|
||||
},
|
||||
{
|
||||
"file": "People/Man Dancing.webp",
|
||||
"emoji": "🕺"
|
||||
},
|
||||
{
|
||||
"file": "People/Man Facepalming.webp",
|
||||
"emoji": "🤦♂️"
|
||||
},
|
||||
{
|
||||
"file": "People/Man Health Worker.webp",
|
||||
"emoji": "👨⚕️"
|
||||
},
|
||||
{
|
||||
"file": "People/Man Police Officer.webp",
|
||||
"emoji": "👮♂️"
|
||||
},
|
||||
{
|
||||
"file": "People/Man Shrugging.webp",
|
||||
"emoji": "🤷♂️"
|
||||
},
|
||||
{
|
||||
"file": "People/Man Teacher.webp",
|
||||
"emoji": "👨🏫"
|
||||
},
|
||||
{
|
||||
"file": "People/Man Technologist.webp",
|
||||
"emoji": "👨💻"
|
||||
},
|
||||
{
|
||||
"file": "People/Man Vampire.webp",
|
||||
"emoji": "🧛♂️"
|
||||
},
|
||||
{
|
||||
"file": "People/Man Zombie.webp",
|
||||
"emoji": "🧟♂️"
|
||||
},
|
||||
{
|
||||
"file": "People/Mechanical Arm.webp",
|
||||
"emoji": "🦾"
|
||||
},
|
||||
{
|
||||
"file": "People/Mechanical Leg.webp",
|
||||
"emoji": "🦿"
|
||||
},
|
||||
{
|
||||
"file": "People/Middle Finger.webp",
|
||||
"emoji": "🖕"
|
||||
},
|
||||
{
|
||||
"file": "People/Mouth.webp",
|
||||
"emoji": "👄"
|
||||
},
|
||||
{
|
||||
"file": "People/Mrs Claus.webp",
|
||||
"emoji": "🤶"
|
||||
},
|
||||
{
|
||||
"file": "People/Mx Claus.webp",
|
||||
"emoji": "🧑🎄"
|
||||
},
|
||||
{
|
||||
"file": "People/Nail Polish.webp",
|
||||
"emoji": "💅"
|
||||
},
|
||||
{
|
||||
"file": "People/Nose.webp",
|
||||
"emoji": "👃"
|
||||
},
|
||||
{
|
||||
"file": "People/Ok Hand.webp",
|
||||
"emoji": "👌"
|
||||
},
|
||||
{
|
||||
"file": "People/Old Woman.webp",
|
||||
"emoji": "👵"
|
||||
},
|
||||
{
|
||||
"file": "People/Oncoming Fist.webp",
|
||||
"emoji": "👊"
|
||||
},
|
||||
{
|
||||
"file": "People/Open Hands.webp",
|
||||
"emoji": "👐"
|
||||
},
|
||||
{
|
||||
"file": "People/Palm Down Hand.webp",
|
||||
"emoji": "🫳"
|
||||
},
|
||||
{
|
||||
"file": "People/Palm Up Hand.webp",
|
||||
"emoji": "🫴"
|
||||
},
|
||||
{
|
||||
"file": "People/Palms Up Together.webp",
|
||||
"emoji": "🤲"
|
||||
},
|
||||
{
|
||||
"file": "People/People Hugging.webp",
|
||||
"emoji": "🫂"
|
||||
},
|
||||
{
|
||||
"file": "People/Person Facepalming.webp",
|
||||
"emoji": "🤦"
|
||||
},
|
||||
{
|
||||
"file": "People/Person Shrugging.webp",
|
||||
"emoji": "🤷"
|
||||
},
|
||||
{
|
||||
"file": "People/Pinched Fingers.webp",
|
||||
"emoji": "🤌"
|
||||
},
|
||||
{
|
||||
"file": "People/Pinching Hand.webp",
|
||||
"emoji": "🤏"
|
||||
},
|
||||
{
|
||||
"file": "People/Pregnant Woman.webp",
|
||||
"emoji": "🤰"
|
||||
},
|
||||
{
|
||||
"file": "People/Raised Back Of Hand.webp",
|
||||
"emoji": "🤚"
|
||||
},
|
||||
{
|
||||
"file": "People/Raised Fist.webp",
|
||||
"emoji": "✊"
|
||||
},
|
||||
{
|
||||
"file": "People/Raised Hand.webp",
|
||||
"emoji": "✋"
|
||||
},
|
||||
{
|
||||
"file": "People/Raising Hands.webp",
|
||||
"emoji": "🙌"
|
||||
},
|
||||
{
|
||||
"file": "People/Right Facing Fist.webp",
|
||||
"emoji": "🤜"
|
||||
},
|
||||
{
|
||||
"file": "People/Rightwards Hand.webp",
|
||||
"emoji": "🫱"
|
||||
},
|
||||
{
|
||||
"file": "People/Santa Claus.webp",
|
||||
"emoji": "🎅"
|
||||
},
|
||||
{
|
||||
"file": "People/Sign Of The Horns.webp",
|
||||
"emoji": "🤘"
|
||||
},
|
||||
{
|
||||
"file": "People/Speaking Head.webp",
|
||||
"emoji": "🗣️"
|
||||
},
|
||||
{
|
||||
"file": "People/Technologist.webp",
|
||||
"emoji": "🧑💻"
|
||||
},
|
||||
{
|
||||
"file": "People/Thumbs Down.webp",
|
||||
"emoji": "👎"
|
||||
},
|
||||
{
|
||||
"file": "People/Thumbs Up.webp",
|
||||
"emoji": "👍"
|
||||
},
|
||||
{
|
||||
"file": "People/Tongue.webp",
|
||||
"emoji": "👅"
|
||||
},
|
||||
{
|
||||
"file": "People/Tooth.webp",
|
||||
"emoji": "🦷"
|
||||
},
|
||||
{
|
||||
"file": "People/Vampire.webp",
|
||||
"emoji": "🧛"
|
||||
},
|
||||
{
|
||||
"file": "People/Victory Hand.webp",
|
||||
"emoji": "✌️"
|
||||
},
|
||||
{
|
||||
"file": "People/Vulcan Salute.webp",
|
||||
"emoji": "🖖"
|
||||
},
|
||||
{
|
||||
"file": "People/Waving Hand.webp",
|
||||
"emoji": "👋"
|
||||
},
|
||||
{
|
||||
"file": "People/Woman Dancing.webp",
|
||||
"emoji": "💃"
|
||||
},
|
||||
{
|
||||
"file": "People/Woman Facepalming.webp",
|
||||
"emoji": "🤦♀️"
|
||||
},
|
||||
{
|
||||
"file": "People/Woman Health Worker.webp",
|
||||
"emoji": "👩⚕️"
|
||||
},
|
||||
{
|
||||
"file": "People/Woman Police Officer.webp",
|
||||
"emoji": "👮♀️"
|
||||
},
|
||||
{
|
||||
"file": "People/Woman Shrugging.webp",
|
||||
"emoji": "🤷♀️"
|
||||
},
|
||||
{
|
||||
"file": "People/Woman Technologist.webp",
|
||||
"emoji": "👩💻"
|
||||
},
|
||||
{
|
||||
"file": "People/Woman Vampire.webp",
|
||||
"emoji": "🧛♀️"
|
||||
},
|
||||
{
|
||||
"file": "People/Woman Zombie.webp",
|
||||
"emoji": "🧟♀️"
|
||||
},
|
||||
{
|
||||
"file": "People/Writing Hand.webp",
|
||||
"emoji": "✍️"
|
||||
},
|
||||
{
|
||||
"file": "People/Zombie.webp",
|
||||
"emoji": "🧟"
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
@@ -0,0 +1,504 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
export const TWEMOJI_GROUP_SMILEYS = {
|
||||
"id": "smileys",
|
||||
get "label"() { return t('screens.twemoji_smileys.text_001'); },
|
||||
"icon": "🙂",
|
||||
"items": [
|
||||
{
|
||||
"file": "Smileys/Alien Monster.webp",
|
||||
"emoji": "👾"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Alien.webp",
|
||||
"emoji": "👽"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Angry Face With Horns.webp",
|
||||
"emoji": "👿"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Angry Face.webp",
|
||||
"emoji": "😠"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Anguished Face.webp",
|
||||
"emoji": "😧"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Anxious Face With Sweat.webp",
|
||||
"emoji": "😰"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Astonished Face.webp",
|
||||
"emoji": "😲"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Beaming Face With Smiling Eyes.webp",
|
||||
"emoji": "😁"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Cat With Tears Of Joy.webp",
|
||||
"emoji": "😹"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Cat With Wry Smile.webp",
|
||||
"emoji": "😼"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Clown Face.webp",
|
||||
"emoji": "🤡"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Cold Face.webp",
|
||||
"emoji": "🥶"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Confounded Face.webp",
|
||||
"emoji": "😖"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Confused Face.webp",
|
||||
"emoji": "😕"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Cowboy Hat Face.webp",
|
||||
"emoji": "🤠"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Crying Cat.webp",
|
||||
"emoji": "😿"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Crying Face.webp",
|
||||
"emoji": "😢"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Disappointed Face.webp",
|
||||
"emoji": "😞"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Disguised Face.webp",
|
||||
"emoji": "🥸"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Dizzy Face.webp",
|
||||
"emoji": "😵"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Dotted Line Face.webp",
|
||||
"emoji": "🫥"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Downcast Face With Sweat.webp",
|
||||
"emoji": "😓"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Drooling Face.webp",
|
||||
"emoji": "🤤"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Exploding Head.webp",
|
||||
"emoji": "🤯"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Expressionless Face.webp",
|
||||
"emoji": "😑"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face Blowing A Kiss.webp",
|
||||
"emoji": "😘"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face Exhaling.webp",
|
||||
"emoji": "😮💨"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face Holding Back Tears.webp",
|
||||
"emoji": "🥹"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face In Clouds.webp",
|
||||
"emoji": "😶🌫️"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face Savoring Food.webp",
|
||||
"emoji": "😋"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face Screaming In Fear.webp",
|
||||
"emoji": "😱"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face Vomiting.webp",
|
||||
"emoji": "🤮"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face With Diagonal Mouth.webp",
|
||||
"emoji": "🫤"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face With Hand Over Mouth.webp",
|
||||
"emoji": "🤭"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face With Head Bandage.webp",
|
||||
"emoji": "🤕"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face With Medical Mask.webp",
|
||||
"emoji": "😷"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face With Monocle.webp",
|
||||
"emoji": "🧐"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face With Open Eyes And Hand Over Mouth.webp",
|
||||
"emoji": "🫢"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face With Open Mouth.webp",
|
||||
"emoji": "😮"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face With Peeking Eye.webp",
|
||||
"emoji": "🫣"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face With Raised Eyebrow.webp",
|
||||
"emoji": "🤨"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face With Rolling Eyes.webp",
|
||||
"emoji": "🙄"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face With Spiral Eyes.webp",
|
||||
"emoji": "😵💫"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face With Steam From Nose.webp",
|
||||
"emoji": "😤"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face With Symbols On Mouth.webp",
|
||||
"emoji": "🤬"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face With Tears Of Joy.webp",
|
||||
"emoji": "😂"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face With Thermometer.webp",
|
||||
"emoji": "🤒"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face With Tongue.webp",
|
||||
"emoji": "😛"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Face Without Mouth.webp",
|
||||
"emoji": "😶"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Fearful Face.webp",
|
||||
"emoji": "😨"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Flushed Face.webp",
|
||||
"emoji": "😳"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Frowning Face With Open Mouth.webp",
|
||||
"emoji": "😦"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Frowning Face.webp",
|
||||
"emoji": "☹️"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Ghost.webp",
|
||||
"emoji": "👻"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Goblin.webp",
|
||||
"emoji": "👺"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Grimacing Face.webp",
|
||||
"emoji": "😬"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Grinning Cat With Smiling Eyes.webp",
|
||||
"emoji": "😸"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Grinning Cat.webp",
|
||||
"emoji": "😺"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Grinning Face With Big Eyes.webp",
|
||||
"emoji": "😃"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Grinning Face With Smiling Eyes.webp",
|
||||
"emoji": "😄"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Grinning Face With Sweat.webp",
|
||||
"emoji": "😅"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Grinning Face.webp",
|
||||
"emoji": "😀"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Grinning Squinting Face.webp",
|
||||
"emoji": "😆"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Hear No Evil Monkey.webp",
|
||||
"emoji": "🙉"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Hot Face.webp",
|
||||
"emoji": "🥵"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Hugging Face.webp",
|
||||
"emoji": "🤗"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Hushed Face.webp",
|
||||
"emoji": "😯"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Kissing Cat.webp",
|
||||
"emoji": "😽"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Kissing Face With Closed Eyes.webp",
|
||||
"emoji": "😚"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Kissing Face.webp",
|
||||
"emoji": "😗"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Loudly Crying Face.webp",
|
||||
"emoji": "😭"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Lying Face.webp",
|
||||
"emoji": "🤥"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Melting Face.webp",
|
||||
"emoji": "🫠"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Money Mouth Face.webp",
|
||||
"emoji": "🤑"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Nauseated Face.webp",
|
||||
"emoji": "🤢"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Nerd Face.webp",
|
||||
"emoji": "🤓"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Neutral Face.webp",
|
||||
"emoji": "😐"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Ogre.webp",
|
||||
"emoji": "👹"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Partying Face.webp",
|
||||
"emoji": "🥳"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Pensive Face.webp",
|
||||
"emoji": "😔"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Persevering Face.webp",
|
||||
"emoji": "😣"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Pile Of Poo.webp",
|
||||
"emoji": "💩"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Pleading Face.webp",
|
||||
"emoji": "🥺"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Pouting Cat.webp",
|
||||
"emoji": "😾"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Pouting Face.webp",
|
||||
"emoji": "😡"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Relieved Face.webp",
|
||||
"emoji": "😌"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Robot.webp",
|
||||
"emoji": "🤖"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Rolling On The Floor Laughing.webp",
|
||||
"emoji": "🤣"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Sad But Relieved Face.webp",
|
||||
"emoji": "😥"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Saluting Face.webp",
|
||||
"emoji": "🫡"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/See No Evil Monkey.webp",
|
||||
"emoji": "🙈"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Shushing Face.webp",
|
||||
"emoji": "🤫"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Skull And Crossbones.webp",
|
||||
"emoji": "☠️"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Skull.webp",
|
||||
"emoji": "💀"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Sleeping Face.webp",
|
||||
"emoji": "😴"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Sleepy Face.webp",
|
||||
"emoji": "😪"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Slightly Frowning Face.webp",
|
||||
"emoji": "🙁"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Slightly Smiling Face.webp",
|
||||
"emoji": "🙂"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Smiling Cat With Heart Eyes.webp",
|
||||
"emoji": "😻"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Smiling Face With Halo.webp",
|
||||
"emoji": "😇"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Smiling Face With Hearts.webp",
|
||||
"emoji": "🥰"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Smiling Face With Horns.webp",
|
||||
"emoji": "😈"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Smiling Face With Smiling Eyes.webp",
|
||||
"emoji": "😊"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Smiling Face With Sunglasses.webp",
|
||||
"emoji": "😎"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Smiling Face With Tear.webp",
|
||||
"emoji": "🥲"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Smiling Face.webp",
|
||||
"emoji": "☺️"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Smirking Face.webp",
|
||||
"emoji": "😏"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Sneezing Face.webp",
|
||||
"emoji": "🤧"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Speak No Evil Monkey.webp",
|
||||
"emoji": "🙊"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Squinting Face With Tongue.webp",
|
||||
"emoji": "😝"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Star Struck.webp",
|
||||
"emoji": "🤩"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Thinking Face.webp",
|
||||
"emoji": "🤔"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Tired Face.webp",
|
||||
"emoji": "😫"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Unamused Face.webp",
|
||||
"emoji": "😒"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Upside Down Face.webp",
|
||||
"emoji": "🙃"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Weary Cat.webp",
|
||||
"emoji": "🙀"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Weary Face.webp",
|
||||
"emoji": "😩"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Winking Face With Tongue.webp",
|
||||
"emoji": "😜"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Winking Face.webp",
|
||||
"emoji": "😉"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Woozy Face.webp",
|
||||
"emoji": "🥴"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Worried Face.webp",
|
||||
"emoji": "😟"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Yawning Face.webp",
|
||||
"emoji": "🥱"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Zany Face.webp",
|
||||
"emoji": "🤪"
|
||||
},
|
||||
{
|
||||
"file": "Smileys/Zipper Mouth Face.webp",
|
||||
"emoji": "🤐"
|
||||
}
|
||||
]
|
||||
};
|
||||
@@ -0,0 +1,284 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
export const TWEMOJI_GROUP_SYMBOLS = {
|
||||
"id": "symbols",
|
||||
get "label"() { return t('screens.twemoji_symbols.text_002'); },
|
||||
"icon": "❤️",
|
||||
"items": [
|
||||
{
|
||||
"file": "Symbols/Anger Symbol.webp",
|
||||
"emoji": "💢"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Aquarius.webp",
|
||||
"emoji": "♒"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Aries.webp",
|
||||
"emoji": "♈"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Baby Symbol.webp",
|
||||
"emoji": "🚼"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Baggage Claim.webp",
|
||||
"emoji": "🛄"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Beating Heart.webp",
|
||||
"emoji": "💓"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Black Heart.webp",
|
||||
"emoji": "🖤"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Blue Heart.webp",
|
||||
"emoji": "💙"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Broken Heart.webp",
|
||||
"emoji": "💔"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Brown Heart.webp",
|
||||
"emoji": "🤎"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Cancer.webp",
|
||||
"emoji": "♋"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Capricorn.webp",
|
||||
"emoji": "♑"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Check Box With Check.webp",
|
||||
"emoji": "☑️"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Check Mark Button.webp",
|
||||
"emoji": "✅"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Check Mark.webp",
|
||||
"emoji": "✔️"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Collision.webp",
|
||||
"emoji": "💥"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Cool Button.webp",
|
||||
"emoji": "🆒"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Cross Mark.webp",
|
||||
"emoji": "❌"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Currency Exchange.webp",
|
||||
"emoji": "💱"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Customs.webp",
|
||||
"emoji": "🛃"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Dizzy.webp",
|
||||
"emoji": "💫"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Double Exclamation Mark.webp",
|
||||
"emoji": "‼️"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Exclamation Mark.webp",
|
||||
"emoji": "❗"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Exclamation Question Mark.webp",
|
||||
"emoji": "⁉️"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Free Button.webp",
|
||||
"emoji": "🆓"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Gemini.webp",
|
||||
"emoji": "♊"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Green Heart.webp",
|
||||
"emoji": "💚"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Growing Heart.webp",
|
||||
"emoji": "💗"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Heart Decoration.webp",
|
||||
"emoji": "💟"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Heart Exclamation.webp",
|
||||
"emoji": "❣️"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Heart On Fire.webp",
|
||||
"emoji": "❤️🔥"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Heart With Arrow.webp",
|
||||
"emoji": "💘"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Heart With Ribbon.webp",
|
||||
"emoji": "💝"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Hundred Points.webp",
|
||||
"emoji": "💯"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Kiss Mark.webp",
|
||||
"emoji": "💋"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Left Luggage.webp",
|
||||
"emoji": "🛅"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Leo.webp",
|
||||
"emoji": "♌"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Libra.webp",
|
||||
"emoji": "♎"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Love Letter.webp",
|
||||
"emoji": "💌"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Mending Heart.webp",
|
||||
"emoji": "❤️🩹"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Mens Room.webp",
|
||||
"emoji": "🚹"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/New Button.webp",
|
||||
"emoji": "🆕"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/No One Under Eighteen.webp",
|
||||
"emoji": "🔞"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Ok Button.webp",
|
||||
"emoji": "🆗"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Ophiuchus.webp",
|
||||
"emoji": "⛎"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Orange Heart.webp",
|
||||
"emoji": "🧡"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Passport Control.webp",
|
||||
"emoji": "🛂"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Pisces.webp",
|
||||
"emoji": "♓"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Purple Heart.webp",
|
||||
"emoji": "💜"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Question Mark.webp",
|
||||
"emoji": "❓"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Red Heart.webp",
|
||||
"emoji": "❤️"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Revolving Hearts.webp",
|
||||
"emoji": "💞"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Right Anger Bubble.webp",
|
||||
"emoji": "🗯️"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Sagittarius.webp",
|
||||
"emoji": "♐"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Scorpio.webp",
|
||||
"emoji": "♏"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Sparkling Heart.webp",
|
||||
"emoji": "💖"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Speech Balloon.webp",
|
||||
"emoji": "💬"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Taurus.webp",
|
||||
"emoji": "♉"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Thought Balloon.webp",
|
||||
"emoji": "💭"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Top Arrow.webp",
|
||||
"emoji": "🔝"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Two Hearts.webp",
|
||||
"emoji": "💕"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Up Button.webp",
|
||||
"emoji": "🆙"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Virgo.webp",
|
||||
"emoji": "♍"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/White Exclamation Mark.webp",
|
||||
"emoji": "❕"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/White Heart.webp",
|
||||
"emoji": "🤍"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/White Question Mark.webp",
|
||||
"emoji": "❔"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Womens Room.webp",
|
||||
"emoji": "🚺"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Yellow Heart.webp",
|
||||
"emoji": "💛"
|
||||
},
|
||||
{
|
||||
"file": "Symbols/Zzz.webp",
|
||||
"emoji": "💤"
|
||||
}
|
||||
]
|
||||
};
|
||||
@@ -0,0 +1,77 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
export const TWEMOJI_GROUP_TRAVEL_PLACES = {
|
||||
"id": "travel-and-places",
|
||||
get "label"() { return t('screens.twemoji_travel_places.text_002'); },
|
||||
"icon": "✈️",
|
||||
"items": [
|
||||
{
|
||||
"file": "Travel and Places/Airplane.webp",
|
||||
"emoji": "✈️"
|
||||
},
|
||||
{
|
||||
"file": "Travel and Places/Ambulance.webp",
|
||||
"emoji": "🚑"
|
||||
},
|
||||
{
|
||||
"file": "Travel and Places/Automobile.webp",
|
||||
"emoji": "🚗"
|
||||
},
|
||||
{
|
||||
"file": "Travel and Places/Beach With Umbrella.webp",
|
||||
"emoji": "🏖️"
|
||||
},
|
||||
{
|
||||
"file": "Travel and Places/Camping.webp",
|
||||
"emoji": "🏕️"
|
||||
},
|
||||
{
|
||||
"file": "Travel and Places/Classical Building.webp",
|
||||
"emoji": "🏛️"
|
||||
},
|
||||
{
|
||||
"file": "Travel and Places/Compass.webp",
|
||||
"emoji": "🧭"
|
||||
},
|
||||
{
|
||||
"file": "Travel and Places/Desert Island.webp",
|
||||
"emoji": "🏝️"
|
||||
},
|
||||
{
|
||||
"file": "Travel and Places/Hot Springs.webp",
|
||||
"emoji": "♨️"
|
||||
},
|
||||
{
|
||||
"file": "Travel and Places/House.webp",
|
||||
"emoji": "🏠"
|
||||
},
|
||||
{
|
||||
"file": "Travel and Places/Locomotive.webp",
|
||||
"emoji": "🚂"
|
||||
},
|
||||
{
|
||||
"file": "Travel and Places/Moai.webp",
|
||||
"emoji": "🗿"
|
||||
},
|
||||
{
|
||||
"file": "Travel and Places/Motor Boat.webp",
|
||||
"emoji": "🛥️"
|
||||
},
|
||||
{
|
||||
"file": "Travel and Places/Police Car.webp",
|
||||
"emoji": "🚓"
|
||||
},
|
||||
{
|
||||
"file": "Travel and Places/Rocket.webp",
|
||||
"emoji": "🚀"
|
||||
},
|
||||
{
|
||||
"file": "Travel and Places/Roller Coaster.webp",
|
||||
"emoji": "🎢"
|
||||
},
|
||||
{
|
||||
"file": "Travel and Places/Taxi.webp",
|
||||
"emoji": "🚕"
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
const paths = {
|
||||
heart: '<path d="M12 21S2.3 15.5 2.3 8.7C2.3 3.6 8.1 1.9 12 6.5c3.9-4.6 9.7-2.9 9.7 2.2C21.7 15.5 12 21 12 21Z"/>',
|
||||
message: '<path d="M5.2 2.35h13.6a2.7 2.7 0 0 1 2.7 2.7v9.7a2.7 2.7 0 0 1-2.7 2.7h-7.1L7.2 21v-3.55h-2a2.7 2.7 0 0 1-2.7-2.7v-9.7a2.7 2.7 0 0 1 2.7-2.7Z"/>',
|
||||
more: '<circle cx="4" cy="12" r="1.6" fill="currentColor" stroke="none"/><circle cx="12" cy="12" r="1.6" fill="currentColor" stroke="none"/><circle cx="20" cy="12" r="1.6" fill="currentColor" stroke="none"/>',
|
||||
moreVertical: '<circle cx="12" cy="4" r="1.6" fill="currentColor" stroke="none"/><circle cx="12" cy="12" r="1.6" fill="currentColor" stroke="none"/><circle cx="12" cy="20" r="1.6" fill="currentColor" stroke="none"/>',
|
||||
forward: '<path d="m14.4 3.1 7.2 7.1-7.2 6.6v-4.4C8.5 12.4 5 15.1 2.4 20c.4-7.6 4.4-11.7 12-12.4Z"/>',
|
||||
download: '<path d="M12 4v11M7 10.5l5 5 5-5M5 20h14"/>',
|
||||
reply: '<path d="M9 7 4 12l5 5"/><path d="M4 12h9a7 7 0 0 1 7 7"/>',
|
||||
copy: '<rect x="8" y="8" width="12" height="12" rx="2.5"/><path d="M16 8V6.5A2.5 2.5 0 0 0 13.5 4h-7A2.5 2.5 0 0 0 4 6.5v7A2.5 2.5 0 0 0 6.5 16H8"/>',
|
||||
info: '<circle cx="12" cy="12" r="9"/><path d="M12 11v5.5M12 7.6v.1"/>',
|
||||
trash: '<path d="M4 7h16M9.5 7V4.8h5V7M6.5 7l.9 12.2a1.9 1.9 0 0 0 1.9 1.8h5.4a1.9 1.9 0 0 0 1.9-1.8L17.5 7M10 11v6M14 11v6"/>',
|
||||
'bell-off': '<path d="M8.5 4.2A6 6 0 0 1 18 9c0 4.3 1.1 6.2 2 7.2M18 17H3c0-2 3-2 3-9M10 21h4M3 3l18 18"/>',
|
||||
phone: '<path d="M5 3.5h3.2l1.6 4.2-2.1 1.4a11 11 0 0 0 5.2 5.2l1.4-2.1 4.2 1.6V17a2.5 2.5 0 0 1-2.7 2.5A16 16 0 0 1 2.5 6.2 2.5 2.5 0 0 1 5 3.5Z"/>',
|
||||
video: '<rect x="2.5" y="6" width="13" height="12" rx="2.5"/><path d="m15.5 10.5 6-3.5v10l-6-3.5"/>',
|
||||
emoji: '<circle cx="12" cy="12" r="9"/><path d="M8.3 14.2a4.6 4.6 0 0 0 7.4 0"/><circle cx="9" cy="9.8" r=".9" fill="currentColor" stroke="none"/><circle cx="15" cy="9.8" r=".9" fill="currentColor" stroke="none"/>',
|
||||
send: '<path d="M12 19V5M5.5 11.5 12 5l6.5 6.5"/>',
|
||||
mic: '<rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21"/>',
|
||||
camera: '<path d="M4.5 7.5h2.8l1.7-2.5h6l1.7 2.5h2.8A1.5 1.5 0 0 1 21 9v9a1.5 1.5 0 0 1-1.5 1.5h-15A1.5 1.5 0 0 1 3 18V9a1.5 1.5 0 0 1 1.5-1.5Z"/><circle cx="12" cy="13" r="3.5"/>',
|
||||
image: '<rect x="3" y="4.5" width="18" height="15" rx="2.5"/><circle cx="8.5" cy="9.5" r="1.6"/><path d="m21 16-4.7-4.7-8.2 8.2"/>',
|
||||
list: '<path d="M9 6h11M9 12h11M9 18h11"/><circle cx="4.5" cy="6" r=".9" fill="currentColor" stroke="none"/><circle cx="4.5" cy="12" r=".9" fill="currentColor" stroke="none"/><circle cx="4.5" cy="18" r=".9" fill="currentColor" stroke="none"/>',
|
||||
doc: '<path d="M6.5 3h7.5L19 8v11.5a1.5 1.5 0 0 1-1.5 1.5h-11A1.5 1.5 0 0 1 5 19.5v-15A1.5 1.5 0 0 1 6.5 3Z"/><path d="M14 3v5h5M8.5 13h7M8.5 16.5h5"/>',
|
||||
close: '<path d="M6 6l12 12M18 6 6 18"/>',
|
||||
clock: '<circle cx="12" cy="12" r="8.5"/><path d="M12 7.5V12l3 2"/>',
|
||||
alert: '<circle cx="12" cy="12" r="9"/><path d="M12 7.5v5.5M12 16.4v.1"/>',
|
||||
'check-double': '<path d="m2.5 12.5 4 4L15 8"/><path d="m10.5 16 1 .5L21 8"/>',
|
||||
compose: '<path d="M13 4H6.5A2.5 2.5 0 0 0 4 6.5v11A2.5 2.5 0 0 0 6.5 20h11a2.5 2.5 0 0 0 2.5-2.5V11"/><path d="m18.5 3.8 1.7 1.7a1.3 1.3 0 0 1 0 1.8L12.4 15H9v-3.4l7.7-7.8a1.3 1.3 0 0 1 1.8 0Z"/>',
|
||||
channels: '<rect x="4" y="3" width="16" height="18" rx="3"/><path d="M8 8h8M8 12h8M8 16h5"/>',
|
||||
network: '<circle cx="12" cy="5" r="3"/><circle cx="5" cy="18" r="3"/><circle cx="19" cy="18" r="3"/><path d="m10 8-4 7m8-7 4 7M8 18h8"/>',
|
||||
bell: '<path d="M18 8a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9ZM10 21h4"/>',
|
||||
profile: '<circle cx="12" cy="7" r="4"/><path d="M4 21v-2a8 8 0 0 1 16 0v2"/>',
|
||||
share: '<path d="m14.4 3.1 7.2 7.1-7.2 6.6v-4.4C8.5 12.4 5 15.1 2.4 20c.4-7.6 4.4-11.7 12-12.4Z"/>',
|
||||
search: '<circle cx="10.5" cy="10.5" r="6.5"/><path d="m16 16 5 5"/>',
|
||||
link: '<path d="M10 14a4.5 4.5 0 0 0 6.4 0l3.2-3.2a4.5 4.5 0 0 0-6.4-6.4L12 5.6"/><path d="M14 10a4.5 4.5 0 0 0-6.4 0l-3.2 3.2a4.5 4.5 0 0 0 6.4 6.4l1.2-1.2"/>',
|
||||
gift: '<rect x="3" y="8" width="18" height="5" rx="1"/><path d="M5 13v7a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-7M12 8v13M12 8S10.5 3 8 3.5 7 8 12 8Zm0 0s1.5-5 4-4.5S17 8 12 8Z"/>',
|
||||
plus: '<path d="M12 5v14M5 12h14"/>',
|
||||
check: '<path d="m5 12.5 4.5 4.5L19 7.5"/>',
|
||||
open: '<path d="M5 12h14M13 6l6 6-6 6"/>',
|
||||
chevron: '<path d="m9 6 6 6-6 6"/>',
|
||||
'chevron-up': '<path d="m6 15 6-6 6 6"/>',
|
||||
'chevron-down': '<path d="m6 9 6 6 6-6"/>',
|
||||
calendar: '<rect x="3.5" y="5" width="17" height="15.5" rx="2.5"/><path d="M3.5 10h17M8 3v4M16 3v4"/>',
|
||||
pin: '<path d="M9 3.5h6M10 3.5v6.2L6.5 14h11L14 9.7V3.5M12 14v6.5"/>',
|
||||
back: '<path d="M19 12H5M11 5l-7 7 7 7"/>',
|
||||
down: '<path d="M12 5v14M5 12l7 7 7-7"/>',
|
||||
edit: '<path d="M4 20h4L19 9a2.8 2.8 0 0 0-4-4L4 16v4Z"/><path d="m13.5 6.5 4 4"/>',
|
||||
wallet: '<path d="M4 7.5A2.5 2.5 0 0 1 6.5 5H18v3"/><rect x="4" y="8" width="16" height="11" rx="2.5"/><circle cx="16" cy="13.5" r="1.2" fill="currentColor" stroke="none"/>',
|
||||
settings: '<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1Z"/>',
|
||||
'user-plus': '<circle cx="10" cy="8" r="3.5"/><path d="M3.5 20a6.5 6.5 0 0 1 13 0M19 8v6M16 11h6"/>',
|
||||
refresh: '<path d="M20 12a8 8 0 1 1-2.3-5.6"/><path d="M20 4v4.4h-4.4"/>',
|
||||
sparkle: '<path d="M11 4c.6 4.4 2.6 6.4 7 7-4.4.6-6.4 2.6-7 7-.6-4.4-2.6-6.4-7-7 4.4-.6 6.4-2.6 7-7Z"/><path d="M19 2.5v3M17.5 4h3"/>',
|
||||
rings: '<circle cx="12" cy="12" r="2"/><circle cx="12" cy="12" r="5.5"/><circle cx="12" cy="12" r="9"/>',
|
||||
place: '<path d="M12 21s-6.5-5.6-6.5-11a6.5 6.5 0 0 1 13 0c0 5.4-6.5 11-6.5 11Z"/><circle cx="12" cy="10" r="2.4"/>',
|
||||
groups: '<circle cx="9" cy="8" r="3"/><path d="M3.5 19a5.5 5.5 0 0 1 11 0"/><circle cx="17" cy="9.5" r="2.5"/><path d="M15.6 14.1A4.6 4.6 0 0 1 21 18.5"/>',
|
||||
eye: '<path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12Z"/><circle cx="12" cy="12" r="3"/>',
|
||||
eyeOff: '<path d="M10.2 5.7A9.6 9.6 0 0 1 12 5.5c6 0 9.5 6.5 9.5 6.5a16.4 16.4 0 0 1-2.6 3.4M6.4 7A16.2 16.2 0 0 0 2.5 12S6 18.5 12 18.5a9 9 0 0 0 4.9-1.4"/><path d="M9.9 9.9a3 3 0 0 0 4.2 4.2M3.5 3.5l17 17"/>',
|
||||
repost: '<path d="M17 2.5 20.5 6 17 9.5"/><path d="M3.5 11.5V9a3 3 0 0 1 3-3h14"/><path d="M7 21.5 3.5 18 7 14.5"/><path d="M20.5 12.5V15a3 3 0 0 1-3 3h-14"/>',
|
||||
expand: '<path d="M14 4h6v6M10 20H4v-6M20 4l-6.5 6.5M4 20l6.5-6.5"/>',
|
||||
clip: '<path d="m20.5 11.5-8.2 8.2a5 5 0 0 1-7.1-7.1l8.5-8.5a3.3 3.3 0 0 1 4.7 4.7l-8.5 8.5a1.7 1.7 0 0 1-2.4-2.4l7.8-7.8"/>',
|
||||
minus: '<path d="M5 12h14"/>',
|
||||
fit: '<path d="M4 9V5.5A1.5 1.5 0 0 1 5.5 4H9M15 4h3.5A1.5 1.5 0 0 1 20 5.5V9M20 15v3.5a1.5 1.5 0 0 1-1.5 1.5H15M9 20H5.5A1.5 1.5 0 0 1 4 18.5V15"/><circle cx="12" cy="12" r="2.5"/>',
|
||||
focus: '<circle cx="12" cy="12" r="7.5"/><circle cx="12" cy="12" r="2.2" fill="currentColor" stroke="none"/><path d="M12 2v2.5M12 19.5V22M2 12h2.5M19.5 12H22"/>',
|
||||
};
|
||||
|
||||
export function iconHtml(name, filled = false, className = '') {
|
||||
return `<svg${className ? ` class="${className}"` : ''} viewBox="0 0 24 24" fill="${filled ? 'currentColor' : 'none'}" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${paths[name] || paths.message}</svg>`;
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
|
||||
/**
|
||||
* Native password inputs are single-line only. A textarea allows long phrases to
|
||||
* wrap across up to three lines. Masking uses a non-interactive bullet mirror so
|
||||
* it also works in browsers without CSS text-security support.
|
||||
*/
|
||||
export function createExpandablePasswordTextarea() {
|
||||
const input = document.createElement('textarea');
|
||||
input.className = 'input auth-password-field__textarea';
|
||||
input.rows = 1;
|
||||
// 32 visible monospace characters per line on screens wide enough.
|
||||
// Soft wrap only: never add newline characters to the actual password.
|
||||
input.cols = 32;
|
||||
input.wrap = 'soft';
|
||||
input.autocapitalize = 'off';
|
||||
input.spellcheck = false;
|
||||
input.setAttribute('autocorrect', 'off');
|
||||
|
||||
const resize = () => {
|
||||
const computed = window.getComputedStyle(input);
|
||||
const lineHeight = Number.parseFloat(computed.lineHeight) || 24;
|
||||
const extras = (Number.parseFloat(computed.paddingTop) || 0)
|
||||
+ (Number.parseFloat(computed.paddingBottom) || 0)
|
||||
+ (Number.parseFloat(computed.borderTopWidth) || 0)
|
||||
+ (Number.parseFloat(computed.borderBottomWidth) || 0);
|
||||
input.style.height = `${lineHeight + extras}px`;
|
||||
input.style.height = `${Math.min(input.scrollHeight, 3 * lineHeight + extras)}px`;
|
||||
};
|
||||
input.addEventListener('input', resize);
|
||||
// Initial value may be restored from a registration draft before mounting.
|
||||
input.resizePasswordField = resize;
|
||||
input.clearPasswordField = () => {
|
||||
input.value = '';
|
||||
input.updatePasswordMask?.();
|
||||
resize();
|
||||
};
|
||||
return input;
|
||||
}
|
||||
|
||||
/** Passwords are deliberately visible initially on registration and sign-in. */
|
||||
export function createVisiblePasswordField(input) {
|
||||
const multiline = input.tagName === 'TEXTAREA';
|
||||
if (!multiline) input.type = 'text';
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = multiline ? 'auth-password-field auth-password-field--multiline' : 'auth-password-field';
|
||||
|
||||
let mask = null;
|
||||
let visible = true;
|
||||
if (multiline) {
|
||||
mask = document.createElement('div');
|
||||
mask.className = 'auth-password-field__mask';
|
||||
mask.setAttribute('aria-hidden', 'true');
|
||||
mask.hidden = true;
|
||||
const updateMask = () => {
|
||||
// Preserve explicit line breaks while not copying actual password text.
|
||||
mask.textContent = Array.from(input.value, char => char === '\n' ? '\n' : '•').join('');
|
||||
mask.scrollTop = input.scrollTop;
|
||||
mask.scrollLeft = input.scrollLeft;
|
||||
};
|
||||
input.addEventListener('input', updateMask);
|
||||
input.addEventListener('scroll', () => {
|
||||
mask.scrollTop = input.scrollTop;
|
||||
mask.scrollLeft = input.scrollLeft;
|
||||
});
|
||||
input.updatePasswordMask = updateMask;
|
||||
}
|
||||
|
||||
const toggle = document.createElement('button');
|
||||
toggle.type = 'button';
|
||||
toggle.className = 'auth-password-field__toggle';
|
||||
function updateToggle() {
|
||||
const isVisible = multiline ? visible : input.type !== 'password';
|
||||
toggle.innerHTML = iconHtml(isVisible ? 'eyeOff' : 'eye', false, 'key-toggle-icon');
|
||||
toggle.setAttribute('aria-label', isVisible ? t('screens.visible_password_field.text_001') : t('screens.visible_password_field.text_002'));
|
||||
toggle.setAttribute('title', isVisible ? t('screens.visible_password_field.text_003') : t('screens.visible_password_field.text_004'));
|
||||
toggle.setAttribute('aria-pressed', String(!isVisible));
|
||||
}
|
||||
toggle.addEventListener('click', () => {
|
||||
const start = input.selectionStart;
|
||||
const end = input.selectionEnd;
|
||||
if (multiline) {
|
||||
visible = !visible;
|
||||
wrap.classList.toggle('auth-password-field--masked', !visible);
|
||||
mask.hidden = visible;
|
||||
input.updatePasswordMask();
|
||||
input.resizePasswordField();
|
||||
} else {
|
||||
input.type = input.type === 'password' ? 'text' : 'password';
|
||||
}
|
||||
updateToggle();
|
||||
input.focus();
|
||||
try { if (start !== null && end !== null) input.setSelectionRange(start, end); } catch { /* unsupported input method */ }
|
||||
});
|
||||
updateToggle();
|
||||
wrap.append(input);
|
||||
if (mask) wrap.append(mask);
|
||||
wrap.append(toggle);
|
||||
return wrap;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Конфиг по умолчанию для конкретного деплоя UI.
|
||||
// Перед выкладкой на другой хост можно поменять этот файл без правки логики приложения.
|
||||
|
||||
export const defaultServerLogin = 'shineupme';
|
||||
export const defaultServerAddress = 'shineup.me';
|
||||
export const defaultServerHttp = `https://${defaultServerAddress}`;
|
||||
export const defaultServerWs = `wss://${defaultServerAddress}/ws`;
|
||||
export const defaultSolanaCluster = 'mainnet-beta';
|
||||
export const defaultSolanaEndpoint = `${defaultServerHttp}/solana-rpc`;
|
||||
|
||||
// Devnet ONLY: optional 6-decimal SPL test token representing USDT for UI/transfer tests.
|
||||
// Do not use this in Mainnet; official USDT mint is pinned by solana-usdt-service.js.
|
||||
export const devnetTestUsdtMint = '';
|
||||
@@ -0,0 +1,54 @@
|
||||
// Единое форматирование пользовательских дат, времени и чисел.
|
||||
// UI-язык общий для всех профилей; часы — в часовом поясе устройства.
|
||||
import { getLanguage } from './index.js';
|
||||
|
||||
const LANGUAGE_DEFAULTS = { ru: 'ru-RU', en: 'en-US' };
|
||||
|
||||
export function getIntlLocale() {
|
||||
const language = getLanguage();
|
||||
const defaults = LANGUAGE_DEFAULTS[language] || language;
|
||||
try {
|
||||
const list = globalThis.navigator?.languages;
|
||||
const candidates = Array.isArray(list) && list.length ? list : [globalThis.navigator?.language];
|
||||
for (const candidate of candidates) {
|
||||
const locale = String(candidate || '').trim().replace(/_/gu, '-');
|
||||
if (locale.toLowerCase().split('-')[0] !== language) continue;
|
||||
// Не принимаем некорректную локаль из browser API.
|
||||
try {
|
||||
const canonical = Intl.getCanonicalLocales(locale)[0];
|
||||
return canonical.includes('-') ? canonical : defaults;
|
||||
} catch { /* try next */ }
|
||||
}
|
||||
} catch { /* no navigator e.g. in tests */ }
|
||||
return defaults;
|
||||
}
|
||||
|
||||
// Для MVP даты и время отображаем в европейском порядке (день–месяц–год,
|
||||
// 24-часовые часы), в том числе при запасной английской локали en-US.
|
||||
// Числовые разделители берём из выбранной локали.
|
||||
export function getDateLocale() {
|
||||
const locale = getIntlLocale();
|
||||
return locale.toLowerCase().startsWith('en-us') ? 'en-GB' : locale;
|
||||
}
|
||||
|
||||
export function formatDate(value, options = { day: 'numeric', month: 'long', year: 'numeric' }) {
|
||||
return new Intl.DateTimeFormat(getDateLocale(), options).format(value instanceof Date ? value : new Date(value));
|
||||
}
|
||||
|
||||
export function formatTime(value, options = { hour: '2-digit', minute: '2-digit' }) {
|
||||
return new Intl.DateTimeFormat(getDateLocale(), { hourCycle: 'h23', ...options }).format(value instanceof Date ? value : new Date(value));
|
||||
}
|
||||
|
||||
export function formatDateTime(value, options = {
|
||||
day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit',
|
||||
}) {
|
||||
return new Intl.DateTimeFormat(getDateLocale(), { hourCycle: 'h23', ...options }).format(value instanceof Date ? value : new Date(value));
|
||||
}
|
||||
|
||||
export function formatNumber(value, options = {}) {
|
||||
return new Intl.NumberFormat(getIntlLocale(), options).format(value);
|
||||
}
|
||||
|
||||
export function formatRelative(value, unit, options = {}) {
|
||||
return new Intl.RelativeTimeFormat(getIntlLocale(), { numeric: 'auto', ...options }).format(value, unit);
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
// Один источник языка для всех профилей. Браузерные настройки имеют приоритет
|
||||
// над системным языком. Списки и словари живут в соседних JSON-файлах.
|
||||
const STORAGE_KEY = 'shine-ui-language-v1';
|
||||
const FALLBACK_LANGUAGE = 'en';
|
||||
const BOOT_LANGUAGES = [
|
||||
{ code: 'ru', name: 'Русский' },
|
||||
{ code: 'en', name: 'English' },
|
||||
];
|
||||
|
||||
let availableLanguages = BOOT_LANGUAGES;
|
||||
let defaultLanguage = FALLBACK_LANGUAGE;
|
||||
let activeLanguage = FALLBACK_LANGUAGE;
|
||||
let initialized = null;
|
||||
const dictionaries = new Map();
|
||||
const loadingDictionaries = new Map();
|
||||
const subscribers = new Set();
|
||||
|
||||
function normalizeCode(value) {
|
||||
const code = String(value || '').trim().toLowerCase().replace(/_/g, '-');
|
||||
return /^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/u.test(code) ? code : '';
|
||||
}
|
||||
|
||||
function matchLanguage(value, languages = availableLanguages) {
|
||||
const code = normalizeCode(value);
|
||||
if (!code) return '';
|
||||
const codes = new Set(languages.map((item) => item.code));
|
||||
if (codes.has(code)) return code;
|
||||
// Например: ru-RU → ru, en-US → en. Неподдерживаемый язык → далее по списку.
|
||||
const base = code.split('-')[0];
|
||||
return codes.has(base) ? base : '';
|
||||
}
|
||||
|
||||
function savedLanguage(languages) {
|
||||
try {
|
||||
return matchLanguage(globalThis.localStorage?.getItem(STORAGE_KEY), languages);
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
export function resolvePreferredLanguage({
|
||||
saved = '',
|
||||
browserLanguages = [],
|
||||
languages = availableLanguages,
|
||||
fallback = FALLBACK_LANGUAGE,
|
||||
} = {}) {
|
||||
const selected = matchLanguage(saved, languages);
|
||||
if (selected) return selected;
|
||||
for (const locale of browserLanguages) {
|
||||
const supported = matchLanguage(locale, languages);
|
||||
if (supported) return supported;
|
||||
}
|
||||
return matchLanguage(fallback, languages) || languages[0]?.code || FALLBACK_LANGUAGE;
|
||||
}
|
||||
|
||||
function browserLanguages() {
|
||||
try {
|
||||
const list = globalThis.navigator?.languages;
|
||||
return Array.isArray(list) && list.length
|
||||
? list
|
||||
: [globalThis.navigator?.language].filter(Boolean);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function preferredLanguage(languages) {
|
||||
return resolvePreferredLanguage({
|
||||
saved: savedLanguage(languages),
|
||||
browserLanguages: browserLanguages(),
|
||||
languages,
|
||||
fallback: defaultLanguage,
|
||||
});
|
||||
}
|
||||
|
||||
activeLanguage = preferredLanguage(availableLanguages);
|
||||
|
||||
function assetUrl(path) {
|
||||
const url = new URL(path, import.meta.url);
|
||||
const hash = String(globalThis.window?.__SHINE_BUILD_HASH__ || '').trim();
|
||||
if (hash) url.searchParams.set('v', hash);
|
||||
return url;
|
||||
}
|
||||
|
||||
async function readJson(path) {
|
||||
const response = await fetch(assetUrl(path), { cache: 'default' });
|
||||
if (!response.ok) throw new Error(`i18n: ${path}: HTTP ${response.status}`);
|
||||
return response.json();
|
||||
}
|
||||
|
||||
function validateManifest(raw) {
|
||||
if (!raw || !Array.isArray(raw.languages)) return null;
|
||||
const codes = new Set();
|
||||
const languages = raw.languages.flatMap((item) => {
|
||||
const code = normalizeCode(item?.code);
|
||||
if (!code || codes.has(code) || !String(item?.name || '').trim()) return [];
|
||||
codes.add(code);
|
||||
return [{ code, name: String(item.name).trim() }];
|
||||
});
|
||||
if (!languages.length) return null;
|
||||
return {
|
||||
languages,
|
||||
fallback: matchLanguage(raw.default, languages) || matchLanguage(FALLBACK_LANGUAGE, languages) || languages[0].code,
|
||||
};
|
||||
}
|
||||
|
||||
async function loadDictionary(code) {
|
||||
if (dictionaries.has(code)) return dictionaries.get(code);
|
||||
if (loadingDictionaries.has(code)) return loadingDictionaries.get(code);
|
||||
const promise = readJson(`./locales/${code}.json`)
|
||||
.then((data) => {
|
||||
if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('Invalid locale dictionary');
|
||||
dictionaries.set(code, data);
|
||||
return data;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.warn(`[i18n] Failed to load ${code}`, error);
|
||||
// Ошибка загрузки словаря не должна блокировать приложение; при следующем
|
||||
// переключении попытка может быть повторена.
|
||||
return {};
|
||||
})
|
||||
.finally(() => loadingDictionaries.delete(code));
|
||||
loadingDictionaries.set(code, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
function updateDocumentLanguage() {
|
||||
if (globalThis.document?.documentElement) document.documentElement.lang = activeLanguage;
|
||||
}
|
||||
|
||||
export function getLanguage() {
|
||||
return activeLanguage;
|
||||
}
|
||||
|
||||
export function getLanguages() {
|
||||
return availableLanguages.map((item) => ({ ...item }));
|
||||
}
|
||||
|
||||
export function getLanguageName(code = activeLanguage) {
|
||||
return availableLanguages.find((item) => item.code === code)?.name || code;
|
||||
}
|
||||
|
||||
export async function initI18n() {
|
||||
if (initialized) return initialized;
|
||||
initialized = (async () => {
|
||||
try {
|
||||
const manifest = validateManifest(await readJson('./languages.json'));
|
||||
if (manifest) {
|
||||
availableLanguages = manifest.languages;
|
||||
defaultLanguage = manifest.fallback;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[i18n] Using built-in language list', error);
|
||||
}
|
||||
activeLanguage = preferredLanguage(availableLanguages);
|
||||
updateDocumentLanguage();
|
||||
// Оба стартовых языка предзагружены: переключение ru ↔ en без ожидания сети.
|
||||
const preloaded = [defaultLanguage, activeLanguage, 'ru', 'en']
|
||||
.filter((code) => availableLanguages.some((item) => item.code === code));
|
||||
await Promise.all([...new Set(preloaded)].map(loadDictionary));
|
||||
return activeLanguage;
|
||||
})();
|
||||
return initialized;
|
||||
}
|
||||
|
||||
function lookup(dictionary, key) {
|
||||
return key.split('.').reduce((value, part) => (
|
||||
value && typeof value === 'object' && Object.prototype.hasOwnProperty.call(value, part)
|
||||
? value[part] : undefined
|
||||
), dictionary);
|
||||
}
|
||||
|
||||
// t('settings.save') или t('messages.unread', { count: 3 });
|
||||
// Если перевода нет, используется английский словарь, затем сам ключ.
|
||||
export function t(key, variables = {}) {
|
||||
const path = String(key || '');
|
||||
const translated = lookup(dictionaries.get(activeLanguage), path);
|
||||
const fallback = lookup(dictionaries.get(defaultLanguage), path);
|
||||
const russian = lookup(dictionaries.get('ru'), path);
|
||||
const text = typeof translated === 'string' ? translated
|
||||
: (typeof fallback === 'string' ? fallback : (typeof russian === 'string' ? russian : path));
|
||||
return text.replace(/\{([a-zA-Z0-9_]+)\}/gu, (whole, name) => (
|
||||
Object.prototype.hasOwnProperty.call(variables, name) ? String(variables[name]) : whole
|
||||
));
|
||||
}
|
||||
|
||||
export function th(key, variables = {}) {
|
||||
return t(key, variables).replace(/[&<>"']/gu, (character) => ({
|
||||
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
|
||||
})[character]);
|
||||
}
|
||||
|
||||
export function onLanguageChange(callback) {
|
||||
if (typeof callback !== 'function') return () => {};
|
||||
subscribers.add(callback);
|
||||
return () => subscribers.delete(callback);
|
||||
}
|
||||
|
||||
export async function setLanguage(value) {
|
||||
await initI18n();
|
||||
const code = matchLanguage(value, availableLanguages);
|
||||
if (!code) return false;
|
||||
await loadDictionary(code);
|
||||
const changed = code !== activeLanguage;
|
||||
activeLanguage = code;
|
||||
updateDocumentLanguage();
|
||||
try { globalThis.localStorage?.setItem(STORAGE_KEY, code); } catch {}
|
||||
if (changed) {
|
||||
subscribers.forEach((callback) => {
|
||||
try { callback(code); } catch (error) { console.error('[i18n] Language listener failed', error); }
|
||||
});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"default": "en",
|
||||
"languages": [
|
||||
{
|
||||
"code": "ru",
|
||||
"name": "Русский"
|
||||
},
|
||||
{
|
||||
"code": "en",
|
||||
"name": "English"
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,259 @@
|
||||
export const profile = {
|
||||
login: '@shine.alex',
|
||||
name: '',
|
||||
avatarInitials: 'АС',
|
||||
phone: '+7 (916) 221-45-88',
|
||||
address: 'Москва, Пресненская наб., 12',
|
||||
email: 'alex.shine@demo.local',
|
||||
socials: '@alexshine / t.me/alexshine',
|
||||
badges: ['Официальный аккаунт', 'Сияющий'],
|
||||
};
|
||||
|
||||
export const wallet = {
|
||||
balanceSOL: '182.4571',
|
||||
publicAddress: '9sVAXJ2CqP3BrtC6AFeQHhcuWjN1kUyhY7L8pkQJxMZe',
|
||||
updatedAt: 'сегодня, 14:42',
|
||||
};
|
||||
|
||||
export const clientSessions = [
|
||||
{
|
||||
sessionId: 'sess_7c5e5c4b',
|
||||
clientInfoFromClient: 'Android 15; Pixel 9',
|
||||
clientInfoFromRequest: 'UA=Java-http-client/17.0.18; remote=127.0.0.1',
|
||||
geo: 'RU/Moscow',
|
||||
lastAuthenticatedAtMs: 1774600010500,
|
||||
},
|
||||
{
|
||||
sessionId: 'sess_90ab11de',
|
||||
clientInfoFromClient: 'iOS 19; iPhone 17',
|
||||
clientInfoFromRequest: 'UA=ShineMobile/2.4; remote=10.0.2.12',
|
||||
geo: 'RU/Moscow',
|
||||
lastAuthenticatedAtMs: 1774553310000,
|
||||
},
|
||||
{
|
||||
sessionId: 'sess_3ea4f11c',
|
||||
clientInfoFromClient: 'Windows 11; Chrome 124',
|
||||
clientInfoFromRequest: 'UA=Mozilla/5.0; remote=192.168.1.21',
|
||||
geo: 'RU/Kazan',
|
||||
lastAuthenticatedAtMs: 1774499010000,
|
||||
},
|
||||
];
|
||||
|
||||
// Экран «Личные сообщения» — списочная форма «Связей». Храним СЕМАНТИКУ, не цвет.
|
||||
// Цвет/режим вычисляет js/pages/messages/dm-visual-resolver.js (resolveDmVisualState):
|
||||
// relationType: 'contact' | 'friend' | 'family' (family → золотой обод)
|
||||
// relationRole: 'parent'|'child'|'sibling'|'spouse'|null
|
||||
// isShining: true → небесный (celestial) обод/свечение (важнее relationType)
|
||||
// isConfirmed: true → статус доверия «Подтверждён» (золотой shield) — НЕ красит обод
|
||||
// hasActiveLink: true → статус «Связь» (изумруд) — приоритетнее «Подтверждён»
|
||||
// unreadCount: number; preview: string
|
||||
// toneOverride: 'default'|'family'|'shining' — ТОЛЬКО для тестового мока, в проде не использовать
|
||||
// (на проде поля придут из relationFlagsForTarget/shineConfirmed/shine — пока мок для оффлайн-демо)
|
||||
// ЛС — мок-плейсхолдер (на проде заменяется реальными relations/chats). Поля СЕМАНТИЧЕСКИЕ
|
||||
// (без хранения цвета) — визуал решает dm-visual-resolver.js. Аватары — через профиль (инициалы, пока нет фото).
|
||||
export const directMessages = [
|
||||
{ id: 'u1', name: 'Марина К.', initials: 'МК', preview: 'Вечером скину обновления по макетам.', lastMessage: 'Вечером скину обновления по макетам.', time: '15:08', relationType: 'contact', relationRole: null, isShining: false, isConfirmed: true, hasActiveLink: false, unreadCount: 0 },
|
||||
{ id: 'u2', login: 'ilya', name: 'Илья П.', initials: 'ИП', preview: 'Спасибо, уже проверяю!', lastMessage: 'Спасибо, уже проверяю!', time: '14:31', relationType: 'contact', relationRole: null, isShining: false, isConfirmed: false, hasActiveLink: true, unreadCount: 2, connectedVia: [{ login: 'pavel', name: 'Павел С.' }] },
|
||||
{ id: 'u3', login: 'elena', name: 'Елена Д.', initials: 'ЕД', preview: 'Тестовый стенд снова доступен.', lastMessage: 'Тестовый стенд снова доступен.', time: '13:02', relationType: 'contact', relationRole: null, isShining: true, isConfirmed: false, hasActiveLink: true, unreadCount: 5, connectedVia: [{ login: 'pavel', name: 'Павел С.' }, { login: 'marina', name: 'Марина К.' }] },
|
||||
{ id: 'u4', name: 'Никита О.', initials: 'НО', preview: 'Отлично, давай так и сделаем.', lastMessage: 'Отлично, давай так и сделаем.', time: 'вчера', relationType: 'contact', relationRole: null, isShining: false, isConfirmed: false, hasActiveLink: false, unreadCount: 0 },
|
||||
{ id: 'u6', login: 'pavel', name: 'Павел С.', initials: 'ПС', preview: 'Семейный архив обновил.', lastMessage: 'Семейный архив обновил.', time: 'вчера', relationType: 'family', relationRole: 'parent', isShining: false, isConfirmed: true, hasActiveLink: false, unreadCount: 0 },
|
||||
{ id: 'u7', login: 'anya', name: 'Аня В.', initials: 'АВ', preview: 'Семейный чат: жду в 19:00.', lastMessage: 'Семейный чат: жду в 19:00.', time: 'пн', relationType: 'family', relationRole: 'sibling', isShining: false, isConfirmed: true, hasActiveLink: true, unreadCount: 1, connectedVia: [{ login: 'marina', name: 'Марина К.' }] },
|
||||
];
|
||||
|
||||
export const contactDirectory = [
|
||||
{
|
||||
id: 'u5',
|
||||
name: 'Марк С.',
|
||||
initials: 'МС',
|
||||
about: 'Продуктовый аналитик, любит короткие созвоны и длинные отчёты.',
|
||||
},
|
||||
{
|
||||
id: 'u6',
|
||||
name: 'Мария Л.',
|
||||
initials: 'МЛ',
|
||||
about: 'UI-дизайнер, собирает референсы и следит за визуальным стилем.',
|
||||
},
|
||||
{
|
||||
id: 'u7',
|
||||
name: 'Марина Р.',
|
||||
initials: 'МР',
|
||||
about: 'Контент-менеджер, ведёт каналы и готовит анонсы.',
|
||||
},
|
||||
{
|
||||
id: 'u8',
|
||||
name: 'Максим В.',
|
||||
initials: 'МВ',
|
||||
about: 'Frontend-разработчик, отвечает за анимации и адаптивность.',
|
||||
},
|
||||
{
|
||||
id: 'u9',
|
||||
name: 'Мадина А.',
|
||||
initials: 'МА',
|
||||
about: 'Комьюнити-менеджер, быстро находит нужных людей.',
|
||||
},
|
||||
{
|
||||
id: 'u10',
|
||||
name: 'Ирина П.',
|
||||
initials: 'ИП',
|
||||
about: 'Редактор новостей, помогает с текстами и публикациями.',
|
||||
},
|
||||
{
|
||||
id: 'u11',
|
||||
name: 'Николай Д.',
|
||||
initials: 'НД',
|
||||
about: 'Технический писатель, структурирует знания по продукту.',
|
||||
},
|
||||
{
|
||||
id: 'u12',
|
||||
name: 'Егор Т.',
|
||||
initials: 'ЕТ',
|
||||
about: 'QA-инженер, любит проверять сложные сценарии вручную.',
|
||||
},
|
||||
];
|
||||
|
||||
export const chatMessages = {
|
||||
u1: [
|
||||
{ from: 'in', text: 'Привет! Видел новые карточки?' },
|
||||
{ from: 'out', text: 'Да, смотрятся сильно. Нужен финальный текст.' },
|
||||
{ from: 'in', text: 'Вечером скину обновления по макетам.' },
|
||||
],
|
||||
u2: [
|
||||
{ from: 'out', text: 'Скинул доступы в чат команды.' },
|
||||
{ from: 'in', text: 'Спасибо, уже проверяю!' },
|
||||
],
|
||||
u3: [
|
||||
{ from: 'in', text: 'Тестовый стенд снова доступен.' },
|
||||
{ from: 'out', text: 'Отлично, запускаю прогон сценариев.' },
|
||||
],
|
||||
u4: [
|
||||
{ from: 'in', text: 'Подтверждаю план на завтра.' },
|
||||
{ from: 'out', text: 'Отлично, давай так и сделаем.' },
|
||||
],
|
||||
};
|
||||
|
||||
export const channels = [
|
||||
{
|
||||
id: 'ch0',
|
||||
name: 'Личный канал',
|
||||
initials: 'ЛК',
|
||||
ownerLogin: '@shine.alex',
|
||||
ownerName: 'Вы',
|
||||
description: 'Ваш основной канал (нулевой).',
|
||||
lastMessage: 'Добро пожаловать в личный канал.',
|
||||
time: '16:05',
|
||||
messagesCount: 14,
|
||||
kind: 'own-personal',
|
||||
},
|
||||
{
|
||||
id: 'ch1',
|
||||
name: 'Команда продукта',
|
||||
initials: 'КП',
|
||||
ownerLogin: '@shine.alex',
|
||||
ownerName: 'Вы',
|
||||
description: 'Канал команды, который вы создали.',
|
||||
lastMessage: 'Обновили roadmap на апрель.',
|
||||
time: '15:42',
|
||||
messagesCount: 8,
|
||||
kind: 'own',
|
||||
},
|
||||
{
|
||||
id: 'ch2',
|
||||
name: 'Новости Bob',
|
||||
initials: 'NB',
|
||||
ownerLogin: '@bob',
|
||||
ownerName: 'Bob',
|
||||
description: 'Основной канал пользователя Bob.',
|
||||
lastMessage: 'Вышел новый дайджест разработчика.',
|
||||
time: '15:20',
|
||||
messagesCount: 5,
|
||||
kind: 'followed-user-channel',
|
||||
},
|
||||
{
|
||||
id: 'ch3',
|
||||
name: 'Стендап команды Bob',
|
||||
initials: 'SB',
|
||||
ownerLogin: '@bob',
|
||||
ownerName: 'Bob',
|
||||
description: 'Второй канал пользователя Bob.',
|
||||
lastMessage: 'Перенесли созвон на 19:30.',
|
||||
time: 'вчера',
|
||||
messagesCount: 11,
|
||||
kind: 'followed-user-channel',
|
||||
},
|
||||
{
|
||||
id: 'ch4',
|
||||
name: 'Анекдоты дня',
|
||||
initials: 'АД',
|
||||
ownerLogin: '@fun.club',
|
||||
ownerName: 'Fun Club',
|
||||
description: 'Публичный развлекательный канал по подписке.',
|
||||
lastMessage: 'Сегодня в выпуске 5 новых шуток.',
|
||||
time: 'вчера',
|
||||
messagesCount: 33,
|
||||
kind: 'subscribed',
|
||||
},
|
||||
];
|
||||
|
||||
export const channelPosts = {
|
||||
ch0: [
|
||||
{
|
||||
id: 'p0-1',
|
||||
title: 'Первый личный пост',
|
||||
body: 'Этот канал всегда ваш и стоит в списке первым.',
|
||||
},
|
||||
{
|
||||
id: 'p0-2',
|
||||
title: 'Планы',
|
||||
body: 'Сюда удобно сохранять личные заметки и объявления.',
|
||||
},
|
||||
],
|
||||
ch1: [
|
||||
{
|
||||
id: 'p1',
|
||||
title: 'Новый экран профиля',
|
||||
body: 'Добавлены бейджи статуса, переработан верхний блок и улучшены быстрые переходы.',
|
||||
},
|
||||
{
|
||||
id: 'p2',
|
||||
title: 'Навигация без перезагрузки',
|
||||
body: 'Переходы между экранами теперь стабильнее работают в SPA-режиме через hash-router.',
|
||||
},
|
||||
],
|
||||
ch2: [
|
||||
{
|
||||
id: 'p3',
|
||||
title: 'Анекдот утра',
|
||||
body: 'Разработчик говорит: "Я починил один баг". Баги в ответ: "Нас было трое".',
|
||||
},
|
||||
{
|
||||
id: 'p4',
|
||||
title: 'Анекдот про дедлайн',
|
||||
body: 'Дедлайн был настолько близко, что команда начала здороваться с ним по имени.',
|
||||
},
|
||||
],
|
||||
ch3: [
|
||||
{
|
||||
id: 'p5',
|
||||
title: 'Утренний дайджест',
|
||||
body: 'Собрали ключевые новости дня: обновления продуктов, движения рынка и заметные релизы.',
|
||||
},
|
||||
{
|
||||
id: 'p6',
|
||||
title: 'Что обсуждают сегодня',
|
||||
body: 'В фокусе дня: рост интереса к мобильным dApp-интерфейсам и новые анонсы сообществ.',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const notifications = {
|
||||
replies: [
|
||||
{ id: 'r1', title: 'Марина К. ответила на ваш комментарий', text: 'Согласна, такую структуру и оставим.', time: '12 минут назад' },
|
||||
{ id: 'r2', title: 'Илья П. ответил в обсуждении', text: 'Добавил примеры экранов для onboarding.', time: '48 минут назад' },
|
||||
],
|
||||
events: [
|
||||
{ id: 'e1', title: 'Елена Д. добавила вас в друзья', text: 'Теперь вы в связях первого уровня.', time: 'сегодня' },
|
||||
{ id: 'e2', title: 'Никита О. удалил из друзей', text: 'Связь перенесена в архив событий.', time: 'вчера' },
|
||||
{ id: 'e3', title: 'Марина К. поставила лайк', text: 'Оценен ваш пост о прототипе.', time: '2 дня назад' },
|
||||
],
|
||||
};
|
||||
|
||||
@@ -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
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user