CORE/CONTENT test5593 и адаптация UI
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
|
After Width: | Height: | Size: 48 KiB |
|
After Width: | Height: | Size: 124 KiB |
|
After Width: | Height: | Size: 54 KiB |
|
After Width: | Height: | Size: 61 KiB |
|
After Width: | Height: | Size: 52 KiB |
|
After Width: | Height: | Size: 80 KiB |
|
After Width: | Height: | Size: 27 KiB |
@@ -0,0 +1,4 @@
|
||||
<svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<circle cx="32" cy="23.5" r="10.5" stroke="#65B7FF" stroke-width="3.2"/>
|
||||
<path d="M14.5 49C17.1 39.2 23.9 34.5 32 34.5C40.1 34.5 46.9 39.2 49.5 49" stroke="#65B7FF" stroke-width="3.2" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 316 B |
@@ -0,0 +1,4 @@
|
||||
<svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M27.1 11.5h9.8l1.4 6.1c1.5.6 2.9 1.4 4.2 2.4l6-1.9 4.9 8.5-4.6 4.2c.1.8.2 1.6.2 2.4s-.1 1.6-.2 2.4l4.6 4.2-4.9 8.5-6-1.9c-1.3 1-2.7 1.8-4.2 2.4l-1.4 6.1h-9.8l-1.4-6.1c-1.5-.6-2.9-1.4-4.2-2.4l-6 1.9-4.9-8.5 4.6-4.2a16 16 0 0 1 0-4.8l-4.6-4.2 4.9-8.5 6 1.9c1.3-1 2.7-1.8 4.2-2.4l1.4-6.1Z" stroke="#65B7FF" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<circle cx="32" cy="33.2" r="8.2" stroke="#65B7FF" stroke-width="3.2"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 558 B |
@@ -0,0 +1,5 @@
|
||||
<svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M13 23.5C13 19.9 15.9 17 19.5 17H42C45.6 17 48.5 19.9 48.5 23.5V27H24C21.2 27 19 29.2 19 32C19 34.8 21.2 37 24 37H48.5V40.5C48.5 44.1 45.6 47 42 47H19.5C15.9 47 13 44.1 13 40.5V23.5Z" stroke="#65B7FF" stroke-width="3.2" stroke-linejoin="round"/>
|
||||
<path d="M19 32C19 29.2 21.2 27 24 27H51V37H24C21.2 37 19 34.8 19 32Z" stroke="#65B7FF" stroke-width="3.2" stroke-linejoin="round"/>
|
||||
<circle cx="42.5" cy="32" r="2.5" fill="#65B7FF"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 548 B |
@@ -0,0 +1,25 @@
|
||||
<svg width="64" height="64" viewBox="0 0 64 64" fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="14" y1="10" x2="52" y2="56" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#56C7FF"/>
|
||||
<stop offset="0.48" stop-color="#1687F8"/>
|
||||
<stop offset="1" stop-color="#075EE8"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="ring" x1="10" y1="8" x2="54" y2="58" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#A8EDFF"/>
|
||||
<stop offset="0.5" stop-color="#4BC7FF"/>
|
||||
<stop offset="1" stop-color="#2473FF"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
<circle cx="32" cy="32" r="29" fill="url(#bg)"/>
|
||||
<circle cx="32" cy="32" r="28" stroke="url(#ring)" stroke-width="2"/>
|
||||
<circle cx="32" cy="32" r="24.5" stroke="#BCEEFF" stroke-opacity="0.72" stroke-width="1.5"/>
|
||||
|
||||
<path d="M19.5 32.7L27.7 40.9L45 23.6"
|
||||
stroke="white"
|
||||
stroke-width="6"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 984 B |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none">
|
||||
<circle cx="32" cy="32" r="27" stroke="currentColor" stroke-width="4" opacity="0.72"/>
|
||||
<path d="M32 14l3.2 10.8L46 28l-10.8 3.2L32 42l-3.2-10.8L18 28l10.8-3.2L32 14z" stroke="currentColor" stroke-width="3" stroke-linejoin="round"/>
|
||||
<path d="M13 51L51 13" stroke="currentColor" stroke-width="5" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 405 B |
@@ -0,0 +1,314 @@
|
||||
// Запуск: SHINE_UI_TEST_DEPS=/путь/к/node_modules node --experimental-vm-modules shine-UI/channel-design-check.mjs
|
||||
// Зависимости проверки (не приложения): jsdom, postcss.
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { createRequire } from 'node:module';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
|
||||
const require = createRequire(path.join(process.env.SHINE_UI_TEST_DEPS || process.cwd() + '/node_modules', '_check.cjs'));
|
||||
const { JSDOM } = require('jsdom');
|
||||
const postcss = require('postcss');
|
||||
const ui = path.dirname(fileURLToPath(import.meta.url));
|
||||
const dom = new JSDOM('<button id="opener">Ответить</button><main id="app-screen"></main><div id="modal-root"></div>', { url: 'https://shine.test/#channel', pretendToBeVisual: true, runScripts: 'outside-only' });
|
||||
const context = dom.getInternalVMContext();
|
||||
const { window } = dom;
|
||||
const { document } = window;
|
||||
const state = { session: { login: 'alice', isAuthorized: true }, entrySettings: {} };
|
||||
let placed = 0;
|
||||
let authPrompts = 0;
|
||||
const mocks = {
|
||||
'arweave-attachment-manager.js': { markArweaveAttachmentPlaced: () => placed++, openArweaveAttachmentManager: async () => ({ name: 'photo.jpg', size: 1024, ar: 'test' }) },
|
||||
'attachment-format.js': { MAX_MESSAGE_ATTACHMENTS: 10, composeMessageWithAttachments: (text) => text },
|
||||
'state.js': { state },
|
||||
'ui-error-texts.js': { toUserMessage: (error) => error.message },
|
||||
'avatar-image.js': { renderUserAvatar: () => document.createElement('span') },
|
||||
'auth-required-modal.js': { openAuthRequiredModal: () => authPrompts++ },
|
||||
};
|
||||
async function moduleAt(relative, mockImports = false) {
|
||||
const module = new vm.SourceTextModule(fs.readFileSync(path.join(ui, relative), 'utf8'), { context });
|
||||
await module.link(async (specifier) => {
|
||||
const values = mockImports && mocks[path.basename(specifier)];
|
||||
assert.ok(values, `Неожиданный импорт ${specifier}`);
|
||||
return new vm.SyntheticModule(Object.keys(values), function () {
|
||||
for (const [key, value] of Object.entries(values)) this.setExport(key, value);
|
||||
}, { context });
|
||||
});
|
||||
await module.evaluate();
|
||||
return module.namespace;
|
||||
}
|
||||
const tick = () => new Promise((resolve) => setTimeout(resolve, 35));
|
||||
const query = (selector) => document.querySelector(selector);
|
||||
function input(value) {
|
||||
const field = query('textarea');
|
||||
field.value = value;
|
||||
field.dispatchEvent(new window.Event('input', { bubbles: true }));
|
||||
}
|
||||
function key(key, options = {}) {
|
||||
const event = new window.KeyboardEvent('keydown', { key, bubbles: true, cancelable: true, ...options });
|
||||
document.activeElement.dispatchEvent(event);
|
||||
return event;
|
||||
}
|
||||
|
||||
const { openChannelEditor } = await moduleAt('js/components/channel-editor.js', true);
|
||||
let sent = [];
|
||||
const options = { key: 'channel:one:message:1', onSubmit: async (value) => sent.push(value) };
|
||||
query('#opener').focus();
|
||||
let editor = openChannelEditor(options);
|
||||
await tick();
|
||||
assert.equal(document.activeElement.tagName, 'TEXTAREA');
|
||||
assert.equal(query('.channel-editor__submit').disabled, true);
|
||||
input('Первая строка\nВторая строка');
|
||||
assert.equal(key('Enter').defaultPrevented, false);
|
||||
assert.equal(sent.length, 0);
|
||||
editor.close();
|
||||
await tick();
|
||||
assert.equal(document.activeElement.id, 'opener');
|
||||
editor = openChannelEditor(options);
|
||||
await tick();
|
||||
assert.equal(query('textarea').value, 'Первая строка\nВторая строка');
|
||||
key('Enter', { ctrlKey: true, isComposing: true });
|
||||
assert.equal(sent.length, 0);
|
||||
key('Enter', { ctrlKey: true });
|
||||
await tick();
|
||||
assert.equal(sent.length, 1);
|
||||
assert.equal(query('.channel-editor-overlay'), null);
|
||||
editor = openChannelEditor(options);
|
||||
assert.equal(query('textarea').value, '');
|
||||
editor.close();
|
||||
await tick();
|
||||
|
||||
editor = openChannelEditor({ ...options, onSubmit: async () => { throw new Error('Нет соединения'); } });
|
||||
await tick();
|
||||
input('Не потерять');
|
||||
query('.channel-editor__submit').click();
|
||||
await tick();
|
||||
assert.equal(query('[role="alert"]').textContent, 'Нет соединения');
|
||||
assert.equal(query('textarea').value, 'Не потерять');
|
||||
assert.equal(query('.channel-editor__submit').disabled, false);
|
||||
query('.channel-editor__close').focus();
|
||||
key('Tab', { shiftKey: true });
|
||||
assert.equal(document.activeElement, query('.channel-editor__submit'));
|
||||
editor.close();
|
||||
await tick();
|
||||
state.session.login = 'bob';
|
||||
editor = openChannelEditor(options);
|
||||
assert.equal(query('textarea').value, '');
|
||||
editor.close();
|
||||
await tick();
|
||||
state.session.login = 'alice';
|
||||
editor = openChannelEditor(options);
|
||||
assert.equal(query('textarea').value, 'Не потерять');
|
||||
query('.channel-editor__clear').click();
|
||||
assert.equal(query('textarea').value, '');
|
||||
query('.channel-editor__attach').click();
|
||||
await tick();
|
||||
assert.equal(document.querySelectorAll('.channel-editor__attachment').length, 1);
|
||||
assert.equal(query('.channel-editor__submit').disabled, false);
|
||||
query('.channel-editor__submit').click();
|
||||
await tick();
|
||||
assert.equal(placed, 1);
|
||||
editor = openChannelEditor(options);
|
||||
await tick();
|
||||
window.history.back();
|
||||
await tick();
|
||||
assert.equal(query('.channel-editor-overlay'), null);
|
||||
editor.close();
|
||||
state.session.isAuthorized = false;
|
||||
assert.equal(openChannelEditor(options), null);
|
||||
assert.equal(authPrompts, 1);
|
||||
|
||||
const theme = await moduleAt('js/services/theme-service.js');
|
||||
assert.equal(theme.applyThemeMode('system').resolved, 'dark');
|
||||
theme.setThemeMode('light');
|
||||
assert.equal(document.documentElement.dataset.theme, 'light');
|
||||
theme.setThemeMode('dark');
|
||||
assert.equal(document.documentElement.dataset.theme, 'dark');
|
||||
const scroll = await moduleAt('js/services/channel-view-state.js');
|
||||
query('#app-screen').scrollTop = 123;
|
||||
scroll.rememberChannelPosition('alice:channel:one');
|
||||
query('#app-screen').scrollTop = 0;
|
||||
scroll.restoreChannelPosition(scroll.readChannelPosition('alice:channel:one'));
|
||||
assert.equal(query('#app-screen').scrollTop, 123);
|
||||
assert.equal(scroll.readChannelPosition('bob:channel:one'), undefined);
|
||||
|
||||
const { createDropdownMenu } = await moduleAt('js/components/dropdown-menu.js');
|
||||
const menu = createDropdownMenu({ anchorEl: query('#opener'), items: [{ label: 'Первый' }, { label: 'Второй' }] });
|
||||
menu.open();
|
||||
assert.equal(document.activeElement.textContent, 'Первый');
|
||||
key('ArrowDown');
|
||||
assert.equal(document.activeElement.textContent, 'Второй');
|
||||
key('Escape');
|
||||
assert.equal(document.activeElement.id, 'opener');
|
||||
menu.destroy();
|
||||
menu.destroy();
|
||||
assert.equal(query('.dropdown-portal'), null);
|
||||
console.log('PASS: редактор — клавиши, фокус, черновики, аккаунты, ошибка, вложение, отправка, Назад; темы, позиция чтения, меню.');
|
||||
|
||||
// DOM producer страниц исполняется с изолированным API: тест не пишет в блокчейн.
|
||||
let replyOptions;
|
||||
const reactionState = new Map();
|
||||
const iconModule = await moduleAt('js/components/ui-icon.js');
|
||||
const pageValues = {
|
||||
state, authService: {},
|
||||
channels: [],
|
||||
readChannelNotificationsState: () => ({}),
|
||||
createSkeletonCard: () => document.createElement('div'),
|
||||
createTopBar: ({ center }) => {
|
||||
const header = document.createElement('header');
|
||||
if (center) header.append(center);
|
||||
return header;
|
||||
},
|
||||
iconHtml: iconModule.iconHtml,
|
||||
parseMessageAttachments: (text) => ({ text: text || '', attachments: [] }),
|
||||
parseDmTechBlocks: (text) => ({ displayText: text, visibleText: text }),
|
||||
loadProfileSnapshot: async () => null,
|
||||
renderAvatar: () => document.createElement('span'),
|
||||
renderUserAvatar: () => document.createElement('span'),
|
||||
formatRelativeTime: () => 'сейчас',
|
||||
escapeHtml: (text) => String(text || ''),
|
||||
openChannelEditor: (options) => { replyOptions = options; },
|
||||
getMessageReactionState: (target) => reactionState.get(target.blockHash) || 'unliked',
|
||||
setMessageReactionState: (target, value) => reactionState.set(target.blockHash, value),
|
||||
makeShineMessageRoute: () => 'thread:test',
|
||||
attachMessageMenu: (card, head, items) => {
|
||||
const button = document.createElement('button');
|
||||
head.append(button);
|
||||
card.testMenu = items;
|
||||
const menu = createDropdownMenu({ anchorEl: button, items });
|
||||
card.cleanup = () => menu.destroy();
|
||||
},
|
||||
};
|
||||
async function pageProducer(file, exported) {
|
||||
const source = fs.readFileSync(path.join(ui, 'js/pages', file), 'utf8');
|
||||
const imports = new Map();
|
||||
for (const match of source.matchAll(/import\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g)) {
|
||||
imports.set(match[2], [...new Set([...(imports.get(match[2]) || []), ...match[1].split(',').map((name) => name.trim().split(/\s+as\s+/)[0]).filter(Boolean)])]);
|
||||
}
|
||||
const module = new vm.SourceTextModule(source + (exported === 'render' ? '' : `\nexport { ${exported} };`), { context });
|
||||
await module.link(async (specifier) => {
|
||||
const names = imports.get(specifier);
|
||||
assert.ok(names, specifier);
|
||||
return new vm.SyntheticModule(names, function () {
|
||||
names.forEach((name) => this.setExport(name, pageValues[name] || (() => {})));
|
||||
}, { context });
|
||||
});
|
||||
await module.evaluate();
|
||||
return module.namespace[exported];
|
||||
}
|
||||
state.session.isAuthorized = true;
|
||||
state.session.login = 'alice';
|
||||
const ref = { blockchainName: 'alice-1', blockNumber: 2, blockHash: 'a'.repeat(64) };
|
||||
let likes = 0;
|
||||
let navigations = 0;
|
||||
const handlers = { selector: { ownerBlockchainName: 'alice-1', channelRootBlockNumber: 1, channelRootBlockHash: 'b'.repeat(64) }, navigate: () => navigations++, onToggleLike: async () => likes++, onReply: async () => {}, onEdit: async () => {}, isActive: () => true };
|
||||
const renderPost = await pageProducer('channel-view.js', 'renderPostCard');
|
||||
const post = renderPost({ body: 'Публикация', authorLogin: 'alice', localNumber: 1, messageRef: ref, isOwnMessage: true, msgSubType: 10, likesCount: 7, repliesCount: 2 }, handlers);
|
||||
document.body.append(post);
|
||||
assert.equal(post.querySelector('.channel-message-body').textContent, 'Публикация');
|
||||
assert.equal(post.querySelectorAll('.channel-action-counter').length, 3);
|
||||
assert.ok(post.testMenu.some((item) => item.label === 'Редактировать'));
|
||||
assert.ok(post.testMenu.some((item) => item.label === 'Удалить'));
|
||||
post.querySelector('.channel-action-like').click();
|
||||
await tick();
|
||||
assert.equal(likes, 1);
|
||||
assert.equal(post.querySelector('.channel-action-like').disabled, false);
|
||||
post.querySelector('.channel-action-reply').click();
|
||||
assert.equal(replyOptions.context.author, 'alice');
|
||||
assert.equal(replyOptions.context.text, 'Публикация');
|
||||
assert.equal(navigations, 0);
|
||||
post.cleanup(); post.cleanup(); post.remove();
|
||||
const renderNode = await pageProducer('channel-thread-view.js', 'renderNodeCard');
|
||||
const node = renderNode({ authorBlockchainName: ref.blockchainName, messageRef: ref, authorLogin: 'bob', text: 'Ответ', msgSubType: 10, likesCount: 3 }, '', handlers, 2);
|
||||
document.body.append(node);
|
||||
assert.equal(node.querySelector('.channel-message-body').textContent, 'Ответ');
|
||||
assert.ok(!node.testMenu.some((item) => item.label === 'Удалить'));
|
||||
node.querySelector('.thread-reply-btn').click();
|
||||
assert.equal(replyOptions.context.author, 'bob');
|
||||
node.cleanup(); node.cleanup(); node.remove();
|
||||
console.log('PASS: карточки канала/ветки — текст, общий лайк без диалога, контекст ответа, меню по авторству, cleanup.');
|
||||
|
||||
pageValues.authService.onEvent = () => () => {};
|
||||
pageValues.toUserMessage = (error) => error.message;
|
||||
pageValues.rememberChannelPosition = scroll.rememberChannelPosition;
|
||||
pageValues.readChannelPosition = scroll.readChannelPosition;
|
||||
pageValues.restoreChannelPosition = scroll.restoreChannelPosition;
|
||||
state.channelsFeed = {};
|
||||
state.channelIndex = {};
|
||||
const chrome = { setTopbar() {}, setComposer() {} };
|
||||
for (const [file, method, params, payload] of [
|
||||
['channels-list.js', 'listSubscriptionsFeed', {}, { ownedChannels: [], followedUsersChannels: [], followedChannels: [] }],
|
||||
['channel-view.js', 'getChannelMessages', { ownerBlockchainName: 'alice-1', channelRootBlockNumber: 1, channelRootBlockHash: 'b'.repeat(64) }, { channel: { ownerLogin: 'alice', channelName: 'news' }, messages: [] }],
|
||||
['channel-thread-view.js', 'getMessageThread', { messageBlockchainName: 'alice-1', messageBlockNumber: 2, messageBlockHash: ref.blockHash }, { focus: null, descendants: [], ancestors: [] }],
|
||||
]) {
|
||||
let finish;
|
||||
pageValues.authService[method] = () => new Promise((resolve) => { finish = resolve; });
|
||||
const render = await pageProducer(file, 'render');
|
||||
const screen = render({ route: { params }, navigate() {}, chrome });
|
||||
query('#app-screen').append(screen);
|
||||
await tick();
|
||||
assert.ok(finish, `${file}: запрос начат`);
|
||||
screen.cleanup();
|
||||
screen.cleanup();
|
||||
const markup = screen.innerHTML;
|
||||
finish(payload);
|
||||
await tick();
|
||||
assert.equal(screen.innerHTML, markup, `${file}: async после dispose`);
|
||||
assert.equal(query('#app-screen').firstElementChild, screen, `${file}: root identity`);
|
||||
screen.remove();
|
||||
pageValues.authService[method] = async () => payload;
|
||||
const loaded = render({ route: { params }, navigate() {}, chrome });
|
||||
query('#app-screen').append(loaded);
|
||||
await tick();
|
||||
const expected = file === 'channels-list.js' ? '.channels-empty-state' : file === 'channel-view.js' ? '.channel-feed' : '.thread-block';
|
||||
assert.ok(loaded.querySelector(expected), `${file}: успешная загрузка ${loaded.textContent}`);
|
||||
if (loaded.refresh) await loaded.refresh();
|
||||
assert.equal(query('#app-screen').firstElementChild, loaded, `${file}: refresh сохраняет root`);
|
||||
loaded.cleanup(); loaded.remove();
|
||||
}
|
||||
console.log('PASS: список/канал/ветка — стабильный root, идемпотентный cleanup, поздний API-ответ после dispose.');
|
||||
|
||||
function walk(dir) {
|
||||
return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() ? walk(path.join(dir, entry.name)) : [path.join(dir, entry.name)]);
|
||||
}
|
||||
const scripts = walk(path.join(ui, 'js')).filter((file) => file.endsWith('.js'));
|
||||
for (const file of scripts) {
|
||||
const source = fs.readFileSync(file, 'utf8');
|
||||
for (const match of source.matchAll(/(?:from\s*|import\s*\()(['"])(\.[^'"]+)\1/g)) {
|
||||
assert.ok(fs.existsSync(path.resolve(path.dirname(file), match[2].split(/[?#]/)[0])), `${file}: ${match[2]}`);
|
||||
}
|
||||
}
|
||||
const repo = path.dirname(ui);
|
||||
const changed = execFileSync('git', ['ls-files', '--modified', '--others', '--exclude-standard'], { cwd: repo, encoding: 'utf8' }).trim().split('\n');
|
||||
let cssCount = 0;
|
||||
for (const relative of changed) {
|
||||
const file = path.join(repo, relative);
|
||||
if (relative.endsWith('.js')) execFileSync('node', ['--input-type=module', '--check'], { input: fs.readFileSync(file) });
|
||||
if (!relative.startsWith('shine-UI/styles/') || !relative.endsWith('.css')) continue;
|
||||
cssCount++;
|
||||
const source = fs.readFileSync(file, 'utf8');
|
||||
const tree = postcss.parse(source, { from: file });
|
||||
let baseline = ''; try { baseline = execFileSync('git', ['show', `HEAD:${relative}`], { cwd: repo, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }); } catch {}
|
||||
const baselineRules = new Map();
|
||||
postcss.parse(baseline).walkRules((rule) => baselineRules.set(rule.selector, (baselineRules.get(rule.selector) || 0) + 1));
|
||||
const rules = new Map();
|
||||
const duplicates = [];
|
||||
tree.walkRules((rule) => {
|
||||
const parents = []; for (let node = rule.parent; node; node = node.parent) if (node.type === 'atrule') parents.push(node.name + ':' + node.params);
|
||||
const key = parents.join('/') + ':' + rule.selector;
|
||||
const count = (rules.get(key) || 0) + 1;
|
||||
rules.set(key, count);
|
||||
if (count > Math.max(1, baselineRules.get(rule.selector) || 0)) duplicates.push(key);
|
||||
});
|
||||
assert.deepEqual(duplicates, [], `Новые повторы selectors: ${relative}`);
|
||||
assert.ok((source.match(/!important/g) || []).length <= (baseline.match(/!important/g) || []).length, `Вырос !important: ${relative}`);
|
||||
}
|
||||
const html = fs.readFileSync(path.join(ui, 'index.html'), 'utf8');
|
||||
const cssManifest = [...html.matchAll(/['"]\.\/(styles\/[^'"]+\.css)['"]/g)].map((match) => match[1]);
|
||||
assert.equal(new Set(cssManifest).size, cssManifest.length);
|
||||
for (const file of cssManifest) assert.ok(fs.existsSync(path.join(ui, file)), `CSS manifest: ${file}`);
|
||||
assert.ok(cssManifest.includes('styles/components/channel-editor.css'));
|
||||
console.log(`PASS: импорты ${scripts.length} JS; синтаксис изменённых JS; ${cssCount} CSS — parser, дубликаты selectors, !important; CSS manifest.`);
|
||||
dom.window.close();
|
||||
@@ -0,0 +1,31 @@
|
||||
import { TWEMOJI_GROUPS } from './js/components/twemoji-catalog.js?diagnostic=202607151545';
|
||||
|
||||
const items = TWEMOJI_GROUPS.flatMap((group) =>
|
||||
group.items.map((item) => ({ ...item, category: group.id })),
|
||||
);
|
||||
|
||||
function duplicateValues(key) {
|
||||
return Object.entries(
|
||||
items.reduce((groups, item) => {
|
||||
const value = item[key];
|
||||
(groups[value] ||= []).push(item.file);
|
||||
return groups;
|
||||
}, {}),
|
||||
)
|
||||
.filter(([, files]) => files.length > 1)
|
||||
.map(([value, files]) => ({ value, files }));
|
||||
}
|
||||
|
||||
const missing = items
|
||||
.filter((item) => !item.emoji || !item.file || !item.name || !item.category || !item.previewUrl || !item.animatedUrl)
|
||||
.map((item) => ({ file: item.file, missing: ['emoji', 'file', 'name', 'category', 'previewUrl', 'animatedUrl'].filter((field) => !item[field]) }));
|
||||
|
||||
console.log(JSON.stringify({
|
||||
categories: TWEMOJI_GROUPS.map((group) => ({ id: group.id, label: group.label, count: group.items.length })),
|
||||
total: items.length,
|
||||
uniqueUnicode: new Set(items.map((item) => item.emoji)).size,
|
||||
uniqueUrl: new Set(items.map((item) => item.file)).size,
|
||||
duplicateUnicode: duplicateValues('emoji'),
|
||||
duplicateUrl: duplicateValues('file'),
|
||||
missing,
|
||||
}, null, 2));
|
||||
@@ -0,0 +1,388 @@
|
||||
self.addEventListener('install', () => self.skipWaiting());
|
||||
self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim()));
|
||||
self.__shineStoppedCalls = self.__shineStoppedCalls || new Map();
|
||||
self.__shineDmPushQueues = self.__shineDmPushQueues || new Map();
|
||||
|
||||
self.addEventListener('message', (event) => {
|
||||
const data = event?.data || {};
|
||||
if (data.type === 'SKIP_WAITING') {
|
||||
self.skipWaiting();
|
||||
} else if (data.type === 'SHINE_DM_READ') {
|
||||
event.waitUntil(clearDirectMessageNotification(data.toLogin, data.fromLogin, data.latestSeenVersionMs));
|
||||
}
|
||||
});
|
||||
|
||||
async function broadcastToClients(payload) {
|
||||
const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
|
||||
clients.forEach((client) => {
|
||||
client.postMessage({
|
||||
type: 'SHINE_WEB_PUSH_EVENT',
|
||||
payload,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function broadcastCallActionToClients(action, payload) {
|
||||
const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
|
||||
clients.forEach((client) => {
|
||||
client.postMessage({
|
||||
type: 'SHINE_CALL_PUSH_ACTION',
|
||||
action,
|
||||
payload,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function rememberStoppedCall(callId, sentAtMs = 0) {
|
||||
if (!callId) return;
|
||||
const now = Date.now();
|
||||
const markAtMs = Number.isFinite(Number(sentAtMs)) ? Number(sentAtMs) : now;
|
||||
self.__shineStoppedCalls.set(callId, Math.max(now, markAtMs));
|
||||
const cutoff = now - 10 * 60 * 1000;
|
||||
for (const [id, ts] of self.__shineStoppedCalls.entries()) {
|
||||
if (Number(ts || 0) < cutoff) self.__shineStoppedCalls.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
function isCallStopped(callId, sentAtMs = 0) {
|
||||
if (!callId) return false;
|
||||
const stoppedAt = Number(self.__shineStoppedCalls.get(callId) || 0);
|
||||
if (!stoppedAt) return false;
|
||||
const incomingAt = Number.isFinite(Number(sentAtMs)) ? Number(sentAtMs) : 0;
|
||||
return incomingAt <= 0 || incomingAt <= stoppedAt;
|
||||
}
|
||||
|
||||
async function closeCallNotification(callId) {
|
||||
if (!callId) return;
|
||||
const list = await self.registration.getNotifications({ tag: callId });
|
||||
list.forEach((n) => {
|
||||
try { n.close(); } catch {}
|
||||
});
|
||||
}
|
||||
|
||||
function decodePushJson(rawText) {
|
||||
try {
|
||||
if (!rawText) return {};
|
||||
return JSON.parse(rawText);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function encodeCallPushPayloadForUrl(payload) {
|
||||
try {
|
||||
return encodeURIComponent(JSON.stringify(payload || {}));
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
// Чаты «без звука» (пишет приложение, см. js/services/dm-chat-prefs.js):
|
||||
// { владелец: { собеседник: срок в мс, 0 – навсегда } }; прежний формат – { владелец: [собеседники] }.
|
||||
async function isMutedDirectMessage(toLogin, fromLogin) {
|
||||
try {
|
||||
const owner = String(toLogin || '').trim().toLowerCase();
|
||||
const peer = String(fromLogin || '').trim().toLowerCase();
|
||||
if (!peer) return false;
|
||||
const cache = await caches.open('shine-dm-prefs');
|
||||
const response = await cache.match('/__shine/dm-muted.json');
|
||||
if (!response) return false;
|
||||
const muted = await response.json();
|
||||
// Сервер сейчас не кладёт в push получателя: тогда смотрим списки всех аккаунтов этого устройства.
|
||||
const lists = owner ? [muted?.[owner]] : Object.values(muted || {});
|
||||
const now = Date.now();
|
||||
return lists.some((list) => {
|
||||
if (Array.isArray(list)) return list.includes(peer);
|
||||
if (!list || typeof list !== 'object' || !Object.prototype.hasOwnProperty.call(list, peer)) return false;
|
||||
const until = Number(list[peer] || 0);
|
||||
return !until || until > now;
|
||||
});
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Идентификатор совпадает с UI, включая профиль получателя.
|
||||
function dmNotificationTag(toLogin, fromLogin) {
|
||||
return `shine-dm:${encodeURIComponent(String(toLogin || '').trim().toLowerCase())}:${encodeURIComponent(String(fromLogin || '').trim().toLowerCase())}`;
|
||||
}
|
||||
|
||||
function dmUnreadLabel(count) {
|
||||
const n = Math.max(1, Math.trunc(Number(count) || 1));
|
||||
const lastTwo = n % 100;
|
||||
const last = n % 10;
|
||||
if (!(lastTwo >= 11 && lastTwo <= 14) && last === 1) return `${n} непрочитанное сообщение`;
|
||||
if (!(lastTwo >= 11 && lastTwo <= 14) && last >= 2 && last <= 4) return `${n} непрочитанных сообщения`;
|
||||
return `${n} непрочитанных сообщений`;
|
||||
}
|
||||
|
||||
function queueDmAction(tag, task) {
|
||||
const preceding = self.__shineDmPushQueues.get(tag) || Promise.resolve();
|
||||
const next = preceding.catch(() => {}).then(task);
|
||||
self.__shineDmPushQueues.set(tag, next);
|
||||
void next.finally(() => {
|
||||
if (self.__shineDmPushQueues.get(tag) === next) self.__shineDmPushQueues.delete(tag);
|
||||
}).catch(() => {});
|
||||
return next;
|
||||
}
|
||||
|
||||
const DM_PUSH_CACHE = 'shine-dm-notification-state-v1';
|
||||
|
||||
async function getDmPushState(tag) {
|
||||
try {
|
||||
const cache = await caches.open(DM_PUSH_CACHE);
|
||||
const key = new URL(`./__shine/dm-push-state?tag=${encodeURIComponent(tag)}`, self.registration.scope).toString();
|
||||
const response = await cache.match(key);
|
||||
const state = response ? await response.json() : {};
|
||||
return { cache, key, state };
|
||||
} catch {
|
||||
// При запрете Cache Storage не теряем само уведомление.
|
||||
return { cache: null, key: null, state: {} };
|
||||
}
|
||||
}
|
||||
|
||||
async function saveDmPushState(cache, key, state) {
|
||||
if (!cache || !key) return;
|
||||
try {
|
||||
await cache.put(key, new Response(JSON.stringify(state), {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}));
|
||||
} catch {
|
||||
// Best effort: уведомление уже показано, отказ кэша не должен ломать push.
|
||||
}
|
||||
}
|
||||
|
||||
async function clearDirectMessageNotification(toLogin, fromLogin, latestSeenVersionMs = 0) {
|
||||
if (!toLogin || !fromLogin) return;
|
||||
const tag = dmNotificationTag(toLogin, fromLogin);
|
||||
await queueDmAction(tag, async () => {
|
||||
const { cache, key, state } = await getDmPushState(tag);
|
||||
state.lastReadVersionMs = Math.max(
|
||||
Number(state.lastReadVersionMs || 0), Number(state.versionMs || 0), Number(latestSeenVersionMs || 0),
|
||||
);
|
||||
state.unreadCount = 0;
|
||||
await saveDmPushState(cache, key, state);
|
||||
const shown = await self.registration.getNotifications({ tag });
|
||||
shown.forEach((notification) => notification.close());
|
||||
});
|
||||
}
|
||||
|
||||
async function showDirectMessageNotification(json) {
|
||||
const toLogin = String(json.toLogin || '').trim();
|
||||
const fromLogin = String(json.fromLogin || '').trim();
|
||||
if (!fromLogin) return;
|
||||
if (await isMutedDirectMessage(toLogin, fromLogin)) return;
|
||||
const tag = dmNotificationTag(toLogin, fromLogin);
|
||||
await queueDmAction(tag, async () => {
|
||||
const { cache, key, state } = await getDmPushState(tag);
|
||||
const messageKey = String(json.messageKey || '').trim();
|
||||
const version = Math.max(0, Number(json.notificationVersionMs || 0));
|
||||
// Уведомление могло быть создано клиентом по живому WS, а не этим Service Worker.
|
||||
const shown = await self.registration.getNotifications({ tag });
|
||||
const visible = shown.reduce((latest, row) => Number(row.data?.notificationVersionMs || 0) >= Number(latest?.data?.notificationVersionMs || 0)
|
||||
? row : latest, null);
|
||||
const visibleVersion = Number(visible?.data?.notificationVersionMs || 0);
|
||||
if (visibleVersion > Number(state.versionMs || 0)) {
|
||||
state.versionMs = visibleVersion;
|
||||
state.unreadCount = Number(visible?.data?.unreadCount || state.unreadCount || 0);
|
||||
}
|
||||
const previouslySeen = Array.isArray(state.seenMessageKeys) ? state.seenMessageKeys : [];
|
||||
if (messageKey && previouslySeen.includes(messageKey)) return;
|
||||
// Запоздавший push после прочтения не должен заново открывать уже закрытое уведомление.
|
||||
if (version && Number(state.lastReadVersionMs || 0) >= version) return;
|
||||
const remoteCount = Number(json.unreadCount);
|
||||
const validCount = Number.isInteger(remoteCount) && remoteCount >= 0;
|
||||
const latestVersion = Number(state.versionMs || 0);
|
||||
let count = validCount ? remoteCount : Math.max(1, Number(state.unreadCount || 0) + 1);
|
||||
if (version && latestVersion > version) count = Number(state.unreadCount || count);
|
||||
if (count <= 0) return;
|
||||
// Ранние пуши иногда доставляются позже новых: число на карточке не должно уменьшаться.
|
||||
if (!version && Number(state.unreadCount || 0) > count) count = Number(state.unreadCount);
|
||||
await self.registration.showNotification(`Сообщение от ${fromLogin}`, {
|
||||
body: dmUnreadLabel(count),
|
||||
tag,
|
||||
renotify: true, // каждое новое сообщение запрашивает повторный системный звук
|
||||
silent: false,
|
||||
data: {
|
||||
kind: 'new_message',
|
||||
fromLogin,
|
||||
toLogin,
|
||||
messageKey,
|
||||
unreadCount: count,
|
||||
notificationVersionMs: version,
|
||||
},
|
||||
});
|
||||
state.unreadCount = count;
|
||||
state.versionMs = Math.max(latestVersion, version);
|
||||
state.seenMessageKeys = messageKey
|
||||
? [...previouslySeen, messageKey].slice(-64)
|
||||
: previouslySeen;
|
||||
await saveDmPushState(cache, key, state);
|
||||
});
|
||||
}
|
||||
|
||||
self.addEventListener('push', (event) => {
|
||||
let body = '';
|
||||
let rawText = '';
|
||||
let kind = '';
|
||||
let fromLogin = '';
|
||||
let title = '';
|
||||
try {
|
||||
if (event.data) {
|
||||
const text = event.data.text();
|
||||
rawText = text || '';
|
||||
const json = decodePushJson(rawText);
|
||||
kind = String(json.kind || '');
|
||||
title = String(json.title || '');
|
||||
body = String(json.text || '');
|
||||
fromLogin = String(json.fromLogin || '');
|
||||
if (!kind && rawText) {
|
||||
body = rawText || '';
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
const json = decodePushJson(rawText);
|
||||
// DM обрабатывается отдельно от звонков: персональный tag, серверный unreadCount и защита от повтора.
|
||||
if (kind === 'new_message') {
|
||||
event.waitUntil(Promise.all([
|
||||
showDirectMessageNotification(json),
|
||||
broadcastToClients({ ...json, receivedAt: Date.now() }),
|
||||
]));
|
||||
return;
|
||||
}
|
||||
const callId = String(json.callId || '').trim();
|
||||
const fromSessionId = String(json.fromSessionId || '').trim();
|
||||
const targetSessionId = String(json.targetSessionId || '').trim();
|
||||
const toLogin = String(json.toLogin || '').trim();
|
||||
const reason = String(json.reason || '').trim();
|
||||
const sentAtMs = Number(json.sentAtMs || 0);
|
||||
const expiresAtMs = Number(json.expiresAtMs || 0);
|
||||
const nowMs = Date.now();
|
||||
|
||||
if (kind === 'stop_call' && callId) {
|
||||
rememberStoppedCall(callId, sentAtMs || nowMs);
|
||||
}
|
||||
|
||||
const isExpiredIncomingCall = kind === 'incoming_call'
|
||||
&& Number.isFinite(expiresAtMs)
|
||||
&& expiresAtMs > 0
|
||||
&& nowMs > expiresAtMs;
|
||||
const isIncomingCallAlreadyStopped = kind === 'incoming_call' && callId && isCallStopped(callId, sentAtMs || nowMs);
|
||||
|
||||
const shouldNotify = (
|
||||
kind === 'test_push'
|
||||
|| (kind === 'incoming_call' && !isExpiredIncomingCall && !isIncomingCallAlreadyStopped)
|
||||
|| (!kind && body)
|
||||
);
|
||||
const notificationTitle = kind === 'test_push'
|
||||
? (title || 'SHiNE: тестовый push')
|
||||
: (kind === 'incoming_call'
|
||||
? 'SHiNE: входящий звонок'
|
||||
: 'SHiNE: входящее сообщение');
|
||||
|
||||
const notifyPromise = shouldNotify
|
||||
? self.registration.showNotification(notificationTitle, {
|
||||
body: body || (fromLogin ? `Новое сообщение от ${fromLogin}` : 'Новое сообщение'),
|
||||
tag: callId || (kind === 'test_push' ? 'shine-test-push' : 'shine-direct-message'),
|
||||
renotify: true,
|
||||
requireInteraction: kind === 'incoming_call',
|
||||
data: {
|
||||
kind,
|
||||
callId,
|
||||
fromLogin,
|
||||
fromSessionId,
|
||||
targetSessionId,
|
||||
toLogin,
|
||||
sentAtMs,
|
||||
expiresAtMs,
|
||||
reason,
|
||||
},
|
||||
actions: kind === 'incoming_call'
|
||||
? [
|
||||
{ action: 'accept', title: 'Ответить' },
|
||||
{ action: 'decline', title: 'Сбросить' },
|
||||
]
|
||||
: [],
|
||||
})
|
||||
: Promise.resolve();
|
||||
|
||||
const closeOnStopPromise = kind === 'stop_call' && callId
|
||||
? closeCallNotification(callId)
|
||||
: Promise.resolve();
|
||||
|
||||
event.waitUntil(Promise.all([
|
||||
notifyPromise,
|
||||
closeOnStopPromise,
|
||||
broadcastToClients({
|
||||
kind,
|
||||
body,
|
||||
fromLogin,
|
||||
fromSessionId,
|
||||
targetSessionId,
|
||||
toLogin,
|
||||
callId,
|
||||
sentAtMs,
|
||||
expiresAtMs,
|
||||
reason,
|
||||
stale: isExpiredIncomingCall || isIncomingCallAlreadyStopped,
|
||||
rawText,
|
||||
receivedAt: nowMs,
|
||||
}),
|
||||
]));
|
||||
});
|
||||
|
||||
self.addEventListener('notificationclick', (event) => {
|
||||
event.notification?.close();
|
||||
const action = String(event?.action || '').trim().toLowerCase();
|
||||
const data = event?.notification?.data || {};
|
||||
const payload = {
|
||||
kind: String(data.kind || '').trim(),
|
||||
callId: String(data.callId || '').trim(),
|
||||
fromLogin: String(data.fromLogin || '').trim(),
|
||||
fromSessionId: String(data.fromSessionId || '').trim(),
|
||||
targetSessionId: String(data.targetSessionId || '').trim(),
|
||||
toLogin: String(data.toLogin || '').trim(),
|
||||
sentAtMs: Number(data.sentAtMs || 0),
|
||||
expiresAtMs: Number(data.expiresAtMs || 0),
|
||||
reason: String(data.reason || '').trim(),
|
||||
};
|
||||
|
||||
event.waitUntil((async () => {
|
||||
if ((action === 'accept' || action === 'decline') && payload.callId) {
|
||||
await broadcastCallActionToClients(action, payload);
|
||||
}
|
||||
|
||||
const allClients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
|
||||
const existing = allClients[0] || null;
|
||||
|
||||
const openUrlBase = './index.html';
|
||||
const encodedPayload = encodeCallPushPayloadForUrl(payload);
|
||||
const openUrl = (action === 'accept' || action === 'decline')
|
||||
? `${openUrlBase}?callPushAction=${encodeURIComponent(action)}&callPushPayload=${encodedPayload}`
|
||||
: `${openUrlBase}?pushOpenPayload=${encodedPayload}`;
|
||||
|
||||
if (existing) {
|
||||
try {
|
||||
if (action === 'accept' || action === 'decline') {
|
||||
existing.postMessage({
|
||||
type: 'SHINE_CALL_PUSH_ACTION',
|
||||
action,
|
||||
payload,
|
||||
});
|
||||
} else {
|
||||
existing.postMessage({
|
||||
type: 'SHINE_NOTIFICATION_CLICK',
|
||||
payload,
|
||||
});
|
||||
}
|
||||
} catch {}
|
||||
await existing.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
await self.clients.openWindow(openUrl);
|
||||
})());
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64" shape-rendering="crispEdges" role="img" aria-label="QR demo 64x64">
|
||||
<rect width="64" height="64" fill="#ffffff"/>
|
||||
<rect x="0" y="0" width="16" height="16" fill="#000000"/>
|
||||
<rect x="2" y="2" width="12" height="12" fill="#ffffff"/>
|
||||
<rect x="4" y="4" width="8" height="8" fill="#000000"/>
|
||||
<rect x="48" y="0" width="16" height="16" fill="#000000"/>
|
||||
<rect x="50" y="2" width="12" height="12" fill="#ffffff"/>
|
||||
<rect x="52" y="4" width="8" height="8" fill="#000000"/>
|
||||
<rect x="0" y="48" width="16" height="16" fill="#000000"/>
|
||||
<rect x="2" y="50" width="12" height="12" fill="#ffffff"/>
|
||||
<rect x="4" y="52" width="8" height="8" fill="#000000"/>
|
||||
|
||||
<rect x="20" y="4" width="2" height="2" fill="#000000"/>
|
||||
<rect x="24" y="4" width="2" height="2" fill="#000000"/>
|
||||
<rect x="28" y="4" width="2" height="2" fill="#000000"/>
|
||||
<rect x="34" y="4" width="2" height="2" fill="#000000"/>
|
||||
<rect x="38" y="4" width="2" height="2" fill="#000000"/>
|
||||
<rect x="42" y="4" width="2" height="2" fill="#000000"/>
|
||||
|
||||
<rect x="18" y="10" width="2" height="2" fill="#000000"/>
|
||||
<rect x="22" y="10" width="2" height="2" fill="#000000"/>
|
||||
<rect x="26" y="10" width="2" height="2" fill="#000000"/>
|
||||
<rect x="30" y="10" width="2" height="2" fill="#000000"/>
|
||||
<rect x="34" y="10" width="2" height="2" fill="#000000"/>
|
||||
<rect x="40" y="10" width="2" height="2" fill="#000000"/>
|
||||
<rect x="44" y="10" width="2" height="2" fill="#000000"/>
|
||||
|
||||
<rect x="18" y="18" width="2" height="2" fill="#000000"/>
|
||||
<rect x="22" y="18" width="2" height="2" fill="#000000"/>
|
||||
<rect x="30" y="18" width="2" height="2" fill="#000000"/>
|
||||
<rect x="34" y="18" width="2" height="2" fill="#000000"/>
|
||||
<rect x="38" y="18" width="2" height="2" fill="#000000"/>
|
||||
<rect x="44" y="18" width="2" height="2" fill="#000000"/>
|
||||
|
||||
<rect x="20" y="24" width="2" height="2" fill="#000000"/>
|
||||
<rect x="24" y="24" width="2" height="2" fill="#000000"/>
|
||||
<rect x="28" y="24" width="2" height="2" fill="#000000"/>
|
||||
<rect x="32" y="24" width="2" height="2" fill="#000000"/>
|
||||
<rect x="40" y="24" width="2" height="2" fill="#000000"/>
|
||||
<rect x="44" y="24" width="2" height="2" fill="#000000"/>
|
||||
|
||||
<rect x="18" y="30" width="2" height="2" fill="#000000"/>
|
||||
<rect x="22" y="30" width="2" height="2" fill="#000000"/>
|
||||
<rect x="26" y="30" width="2" height="2" fill="#000000"/>
|
||||
<rect x="34" y="30" width="2" height="2" fill="#000000"/>
|
||||
<rect x="38" y="30" width="2" height="2" fill="#000000"/>
|
||||
<rect x="44" y="30" width="2" height="2" fill="#000000"/>
|
||||
|
||||
<rect x="18" y="36" width="2" height="2" fill="#000000"/>
|
||||
<rect x="22" y="36" width="2" height="2" fill="#000000"/>
|
||||
<rect x="30" y="36" width="2" height="2" fill="#000000"/>
|
||||
<rect x="34" y="36" width="2" height="2" fill="#000000"/>
|
||||
<rect x="40" y="36" width="2" height="2" fill="#000000"/>
|
||||
<rect x="44" y="36" width="2" height="2" fill="#000000"/>
|
||||
|
||||
<rect x="20" y="42" width="2" height="2" fill="#000000"/>
|
||||
<rect x="24" y="42" width="2" height="2" fill="#000000"/>
|
||||
<rect x="28" y="42" width="2" height="2" fill="#000000"/>
|
||||
<rect x="32" y="42" width="2" height="2" fill="#000000"/>
|
||||
<rect x="36" y="42" width="2" height="2" fill="#000000"/>
|
||||
<rect x="42" y="42" width="2" height="2" fill="#000000"/>
|
||||
|
||||
<rect x="50" y="20" width="2" height="2" fill="#000000"/>
|
||||
<rect x="54" y="20" width="2" height="2" fill="#000000"/>
|
||||
<rect x="58" y="20" width="2" height="2" fill="#000000"/>
|
||||
<rect x="50" y="24" width="2" height="2" fill="#000000"/>
|
||||
<rect x="56" y="24" width="2" height="2" fill="#000000"/>
|
||||
<rect x="60" y="24" width="2" height="2" fill="#000000"/>
|
||||
<rect x="50" y="28" width="2" height="2" fill="#000000"/>
|
||||
<rect x="54" y="28" width="2" height="2" fill="#000000"/>
|
||||
<rect x="58" y="28" width="2" height="2" fill="#000000"/>
|
||||
|
||||
<rect x="20" y="50" width="2" height="2" fill="#000000"/>
|
||||
<rect x="24" y="50" width="2" height="2" fill="#000000"/>
|
||||
<rect x="30" y="50" width="2" height="2" fill="#000000"/>
|
||||
<rect x="36" y="50" width="2" height="2" fill="#000000"/>
|
||||
<rect x="42" y="50" width="2" height="2" fill="#000000"/>
|
||||
<rect x="20" y="54" width="2" height="2" fill="#000000"/>
|
||||
<rect x="28" y="54" width="2" height="2" fill="#000000"/>
|
||||
<rect x="34" y="54" width="2" height="2" fill="#000000"/>
|
||||
<rect x="40" y="54" width="2" height="2" fill="#000000"/>
|
||||
<rect x="44" y="54" width="2" height="2" fill="#000000"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.4 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 191 KiB |
|
After Width: | Height: | Size: 201 KiB |
|
After Width: | Height: | Size: 1.7 MiB |
|
After Width: | Height: | Size: 48 KiB |
|
After Width: | Height: | Size: 227 KiB |
|
After Width: | Height: | Size: 694 KiB |
@@ -0,0 +1,561 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover, interactive-widget=resizes-visual"
|
||||
/>
|
||||
<meta name="theme-color" content="#121419" />
|
||||
<base href="/" />
|
||||
<link rel="manifest" href="./manifest.webmanifest" />
|
||||
<link rel="icon" type="image/jpeg" href="./img/logo.jpg" />
|
||||
<link rel="apple-touch-icon" href="./img/logo.jpg" />
|
||||
<title>СИЯНИЕ</title>
|
||||
<script>
|
||||
(function applySavedThemeBeforePaint() {
|
||||
let mode = 'system';
|
||||
try {
|
||||
const saved = localStorage.getItem('shine-ui-theme-mode-v1');
|
||||
if (saved === 'light' || saved === 'dark' || saved === 'system') mode = saved;
|
||||
} catch {}
|
||||
const resolved = mode === 'system'
|
||||
? (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark')
|
||||
: mode;
|
||||
document.documentElement.dataset.themeMode = mode;
|
||||
document.documentElement.dataset.theme = resolved;
|
||||
document.documentElement.style.colorScheme = resolved;
|
||||
// Своя палитра (см. js/services/theme-service.js) применяется до отрисовки, без вспышки.
|
||||
try {
|
||||
const applied = JSON.parse(localStorage.getItem('shine-ui-palette-applied-v1') || 'null');
|
||||
const colors = applied && applied[resolved];
|
||||
if (colors) {
|
||||
Object.keys(colors).forEach(function (role) {
|
||||
if (/^#[0-9a-f]{6}$/i.test(colors[role])) document.documentElement.style.setProperty('--' + role, colors[role]);
|
||||
});
|
||||
if (colors.accent) document.documentElement.style.setProperty('--focus-ring', colors.accent);
|
||||
}
|
||||
} catch {}
|
||||
}());
|
||||
</script>
|
||||
<script>
|
||||
window.__SHINE_BUILD_HASH__ = '20261119-graph-v4c';
|
||||
window.__SHINE_CLIENT_VERSION__ = '1.20.9';
|
||||
</script>
|
||||
<script>
|
||||
(function attachStylesWithBuildHash() {
|
||||
const v = encodeURIComponent(window.__SHINE_BUILD_HASH__ || 'dev');
|
||||
const cssFiles = ['./styles/main.css', './styles/layout.css', './styles/app-shell.css', './styles/buttons-white.css', './styles/components/topbar.css', './styles/components/dropdown-menu.css', './styles/components/primitives.css', './styles/components/feedback.css', './styles/components/tabs.css', './styles/components/chips.css', './styles/components/nav-list.css', './styles/components/palette-editor.css', './styles/components/avatar.css', './styles/components/modal.css', './styles/components/person-note.css', './styles/components/person-row.css', './styles/components/compose.css', './styles/components/attachments.css', './styles/components/media-viewer.css', './styles/components/channel-editor.css', './styles/components/emoji-picker.css', './styles/components/call-ui.css', './styles/components/scroll-to-bottom.css', './styles/components/overflow-dots.css', './styles/components/toolbar.css', './styles/features/preauth.css', './styles/features/messages.css', './styles/features/chat.css', './styles/features/channels-common.css', './styles/features/channels-list.css', './styles/features/channel.css', './styles/features/channel-thread.css', './styles/features/notifications.css', './styles/features/network.css', './styles/features/profile.css', './styles/features/profile-page.css', './styles/features/settings.css', './styles/features/devices.css', './styles/features/developer-tools.css', './styles/features/wallet-transfer.css', './styles/features/wallet-swap.css', './styles/network-graph.css', './styles/network-legacy.css'];
|
||||
// Стили, добавленные скриптом, браузер не ждёт перед первой отрисовкой: без этого
|
||||
// на долю секунды виден экран без CSS (логотип 640×640), а потом он «прыгает» на место.
|
||||
const root = document.documentElement;
|
||||
let pending = cssFiles.length;
|
||||
const reveal = () => root.classList.add('shine-styles-ready');
|
||||
const settle = () => { pending -= 1; if (pending <= 0) reveal(); };
|
||||
cssFiles.forEach((file) => {
|
||||
const link = document.createElement('link');
|
||||
link.rel = 'stylesheet';
|
||||
link.href = `${file}?v=${v}`;
|
||||
link.onload = settle;
|
||||
link.onerror = settle;
|
||||
document.head.appendChild(link);
|
||||
});
|
||||
setTimeout(reveal, 4000);
|
||||
}());
|
||||
</script>
|
||||
<style>
|
||||
html { background: var(--background, #121419); }
|
||||
html[data-theme='light'] { background: var(--background, #f3f2f7); }
|
||||
html:not(.shine-styles-ready) body { visibility: hidden; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<!-- Заставка повторяет верх экрана входа (те же классы и раскладка): смена на него незаметна. -->
|
||||
<div id="initial-splash" class="initial-splash">
|
||||
<div class="initial-splash__frame">
|
||||
<section class="auth-screen auth-screen--welcome">
|
||||
<div class="auth-logo-wrap">
|
||||
<img class="auth-logo" src="./img/shine-logo-transparent-final.png" alt="Логотип Сияние" />
|
||||
</div>
|
||||
<div class="stack auth-brand-block">
|
||||
<h1 class="auth-brand"><svg class="shine-wordmark" viewBox="52 -722 7294 744" role="img" aria-label="Сияние"><path fill="currentColor" d="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"/></svg></h1>
|
||||
<p class="meta-muted auth-site-name" id="initial-splash-host"></p>
|
||||
</div>
|
||||
<div class="auth-actions shine-actions initial-splash__actions" aria-hidden="true">
|
||||
<span class="shine-btn"></span>
|
||||
<span class="secondary-btn shine-btn--register"></span>
|
||||
<span class="text-btn start-language-link"></span>
|
||||
<span class="text-btn start-settings-link"></span>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<script>
|
||||
document.getElementById('initial-splash-host').textContent = window.location.host || 'shineup.me';
|
||||
</script>
|
||||
</div>
|
||||
<div class="app-shell">
|
||||
<div id="topbar-slot" class="topbar-slot" hidden></div>
|
||||
<main id="app-screen" class="screen-content"></main>
|
||||
<div id="composer-slot" class="composer-slot" hidden></div>
|
||||
<div id="toolbar-slot" class="toolbar-slot" hidden></div>
|
||||
<div class="app-shell-fade app-shell-fade--top" aria-hidden="true"></div>
|
||||
<div class="app-shell-fade app-shell-fade--bottom" aria-hidden="true"></div>
|
||||
</div>
|
||||
<div id="modal-root"></div>
|
||||
<script>
|
||||
// Public VAPID key for Web Push (Base64URL)
|
||||
window.__SHINE_WEBPUSH_VAPID_PUBLIC_KEY__ = 'BOdoWZndZRaNe9kyUFsJ5-xEfFABXNKennAKg15Z7ycAwUIQ7yDV_sIWWYJCwJriN4g9oU-CyJPrn1U6lfxuDbI';
|
||||
</script>
|
||||
<script>
|
||||
(function attachBootErrorOverlay() {
|
||||
const stateKey = '__SHINE_BOOT_ERROR_STATE__';
|
||||
const menuId = 'boot-error-action-sheet';
|
||||
const escapeText = (value) => String(value == null ? '' : value)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
const safeString = (value, maxLen = 1000) => {
|
||||
const text = String(value == null ? '' : value).trim();
|
||||
if (text.length <= maxLen) return text;
|
||||
return `${text.slice(0, Math.max(0, maxLen - 3))}...`;
|
||||
};
|
||||
const setState = (next) => {
|
||||
try {
|
||||
window[stateKey] = next;
|
||||
} catch {}
|
||||
};
|
||||
const getState = () => {
|
||||
try {
|
||||
return window[stateKey] || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const getKnownClientError = () => {
|
||||
try {
|
||||
return typeof window.__SHINE_GET_LAST_CLIENT_ERROR__ === 'function'
|
||||
? window.__SHINE_GET_LAST_CLIENT_ERROR__()
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const showFeedback = (message, kind = 'success') => {
|
||||
try {
|
||||
if (typeof window.__SHINE_SHOW_TOAST__ === 'function') {
|
||||
window.__SHINE_SHOW_TOAST__(message, kind);
|
||||
} else {
|
||||
console.info(message);
|
||||
}
|
||||
} catch {}
|
||||
};
|
||||
const buildReport = () => {
|
||||
const state = getState() || {};
|
||||
const known = getKnownClientError();
|
||||
const viewport = {
|
||||
width: Math.round(window.innerWidth || 0),
|
||||
height: Math.round(window.innerHeight || 0),
|
||||
dpr: Number(window.devicePixelRatio || 1),
|
||||
visualWidth: Math.round(window.visualViewport?.width || 0),
|
||||
visualHeight: Math.round(window.visualViewport?.height || 0),
|
||||
visualScale: Number(window.visualViewport?.scale || 1),
|
||||
};
|
||||
const screenInfo = window.screen ? {
|
||||
width: Math.round(window.screen.width || 0),
|
||||
height: Math.round(window.screen.height || 0),
|
||||
availWidth: Math.round(window.screen.availWidth || 0),
|
||||
availHeight: Math.round(window.screen.availHeight || 0),
|
||||
pixelDepth: Number(window.screen.pixelDepth || 0),
|
||||
} : null;
|
||||
return {
|
||||
kind: safeString(state.kind || 'boot_error', 64),
|
||||
title: safeString(state.title || 'BOOT ERROR', 128),
|
||||
message: safeString(state.message || '', 500),
|
||||
stack: safeString(state.stack || '', 8000),
|
||||
sourceUrl: safeString(state.sourceUrl || '', 240),
|
||||
lineNumber: Number.isFinite(state.lineNumber) ? state.lineNumber : null,
|
||||
columnNumber: Number.isFinite(state.columnNumber) ? state.columnNumber : null,
|
||||
reasonType: safeString(state.reasonType || '', 64),
|
||||
route: safeString(window.location.hash || window.location.pathname || '', 200),
|
||||
href: safeString(window.location.href || '', 240),
|
||||
pageTitle: safeString(document.title || '', 200),
|
||||
pageVisibility: safeString(document.visibilityState || '', 32),
|
||||
userAgent: safeString(navigator.userAgent || '', 240),
|
||||
locale: safeString(navigator.language || '', 32),
|
||||
clientTs: Number.isFinite(state.clientTs) ? state.clientTs : Date.now(),
|
||||
viewport,
|
||||
screenInfo,
|
||||
lastKnownClientError: known || null,
|
||||
contextJson: safeString(JSON.stringify({
|
||||
bootState: state,
|
||||
currentRoute: window.location.hash || window.location.pathname || '',
|
||||
hasClientErrorSender: typeof window.__SHINE_SEND_CLIENT_ERROR__ === 'function',
|
||||
}), 2000),
|
||||
};
|
||||
};
|
||||
const buildSendPayload = (report) => {
|
||||
const payload = {
|
||||
kind: safeString(report?.kind || 'boot_error', 64),
|
||||
message: safeString(report?.message || report?.title || 'Неизвестная ошибка', 500),
|
||||
stack: safeString(report?.stack || '', 8000),
|
||||
sourceUrl: safeString(report?.sourceUrl || '', 240),
|
||||
lineNumber: Number.isFinite(report?.lineNumber) ? report.lineNumber : null,
|
||||
columnNumber: Number.isFinite(report?.columnNumber) ? report.columnNumber : null,
|
||||
route: safeString(report?.route || '', 200),
|
||||
href: safeString(report?.href || '', 240),
|
||||
userAgent: safeString(report?.userAgent || '', 240),
|
||||
clientTs: Number.isFinite(report?.clientTs) ? report.clientTs : Date.now(),
|
||||
requestOp: '',
|
||||
requestIdRef: '',
|
||||
contextJson: safeString(JSON.stringify({
|
||||
...report,
|
||||
contextJson: undefined,
|
||||
}), 2000),
|
||||
};
|
||||
return payload;
|
||||
};
|
||||
const shareErrorText = async (report) => {
|
||||
const text = formatReportText(report);
|
||||
if (!text) throw new Error('Текст ошибки пуст');
|
||||
if (!navigator.share) {
|
||||
throw new Error('Отправка через системное меню недоступна в этом браузере');
|
||||
}
|
||||
try {
|
||||
await navigator.share({
|
||||
title: report?.title || 'Описание ошибки',
|
||||
text,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error?.name === 'AbortError') return false;
|
||||
throw error;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
const formatReportText = (report) => {
|
||||
const lines = [
|
||||
`Ошибка: ${report.title || report.kind || 'unknown'}`,
|
||||
`Описание: ${report.message || '–'}`,
|
||||
`Окно: ${report.pageTitle || '–'}`,
|
||||
`Маршрут: ${report.route || '–'}`,
|
||||
`URL: ${report.href || '–'}`,
|
||||
`Видимость: ${report.pageVisibility || '–'}`,
|
||||
`Время: ${new Date(Number(report.clientTs || Date.now())).toISOString()}`,
|
||||
`UA: ${report.userAgent || '–'}`,
|
||||
`Экран: ${report.viewport ? `${report.viewport.width}x${report.viewport.height} @${report.viewport.dpr || 1}x` : '–'}`,
|
||||
`Монитор: ${report.screenInfo ? `${report.screenInfo.width}x${report.screenInfo.height}` : '–'}`,
|
||||
`Источник: ${report.sourceUrl || '–'}`,
|
||||
`Строка: ${Number.isFinite(report.lineNumber) ? report.lineNumber : '–'}`,
|
||||
`Колонка: ${Number.isFinite(report.columnNumber) ? report.columnNumber : '–'}`,
|
||||
`Тип причины: ${report.reasonType || '–'}`,
|
||||
];
|
||||
if (report.stack) {
|
||||
lines.push('Stack:', report.stack);
|
||||
}
|
||||
if (report.lastKnownClientError) {
|
||||
lines.push('Последняя известная ошибка:', JSON.stringify(report.lastKnownClientError, null, 2));
|
||||
}
|
||||
if (report.contextJson) {
|
||||
lines.push('Контекст:', report.contextJson);
|
||||
}
|
||||
return lines.join('\n');
|
||||
};
|
||||
const copyText = async (text) => {
|
||||
const value = String(text || '');
|
||||
if (!value) return false;
|
||||
if (navigator.clipboard?.writeText) {
|
||||
await navigator.clipboard.writeText(value);
|
||||
return true;
|
||||
}
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = value;
|
||||
ta.setAttribute('readonly', 'readonly');
|
||||
ta.style.position = 'fixed';
|
||||
ta.style.opacity = '0';
|
||||
ta.style.pointerEvents = 'none';
|
||||
document.body.append(ta);
|
||||
ta.focus();
|
||||
ta.select();
|
||||
const ok = document.execCommand('copy');
|
||||
ta.remove();
|
||||
return !!ok;
|
||||
};
|
||||
const removeMenu = () => {
|
||||
try {
|
||||
document.getElementById(menuId)?.remove();
|
||||
} catch {}
|
||||
};
|
||||
const dismissError = () => {
|
||||
removeMenu();
|
||||
try {
|
||||
document.getElementById('boot-error-overlay')?.remove();
|
||||
setState(null);
|
||||
} catch {}
|
||||
};
|
||||
const openMenu = () => {
|
||||
try {
|
||||
removeMenu();
|
||||
document.dispatchEvent(new CustomEvent('shine:dropdown-open', { detail: { owner: 'boot-error' } }));
|
||||
const report = buildReport();
|
||||
const root = document.getElementById('modal-root') || document.body;
|
||||
const shell = document.createElement('div');
|
||||
shell.id = menuId;
|
||||
shell.className = 'modal-shell boot-error-menu-shell';
|
||||
// Меню диагностики должно быть над аварийным экраном.
|
||||
shell.style.zIndex = '1000000';
|
||||
shell.innerHTML = `
|
||||
<div class="modal-backdrop" data-action="close"></div>
|
||||
<div class="modal-dialog boot-error-menu-dialog" role="dialog" aria-modal="true" aria-labelledby="boot-error-menu-title" tabindex="-1">
|
||||
<div class="modal-card stack boot-error-menu-card">
|
||||
<strong class="modal-title" id="boot-error-menu-title">Описание ошибки</strong>
|
||||
<p class="meta-muted boot-error-menu-message">${escapeText(report.message || report.title || 'Ошибка')}</p>
|
||||
<button type="button" class="secondary-btn" data-action="copy">Скопировать текст ошибки</button>
|
||||
<button type="button" class="secondary-btn" data-action="share">Отправить текст ошибки</button>
|
||||
<button type="button" class="secondary-btn" data-action="send"${typeof window.__SHINE_SEND_CLIENT_ERROR_TO_SERVER__ === 'function' ? '' : ' disabled'}>Отправить в лог на сервере</button>
|
||||
<button type="button" class="secondary-btn" data-action="dismiss">Закрыть</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
root.append(shell);
|
||||
|
||||
const dialog = shell.querySelector('.modal-dialog');
|
||||
const close = () => {
|
||||
window.removeEventListener('keydown', onKeyDown);
|
||||
shell.remove();
|
||||
};
|
||||
const onKeyDown = (event) => {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
close();
|
||||
}
|
||||
};
|
||||
|
||||
shell.addEventListener('click', (event) => {
|
||||
if (event.target === shell || event.target?.dataset?.action === 'close') {
|
||||
close();
|
||||
}
|
||||
});
|
||||
|
||||
shell.querySelector('[data-action="copy"]')?.addEventListener('click', async () => {
|
||||
try {
|
||||
await copyText(formatReportText(report));
|
||||
showFeedback('Описание ошибки скопировано');
|
||||
} catch {
|
||||
showFeedback('Не удалось скопировать описание ошибки', 'error');
|
||||
}
|
||||
close();
|
||||
});
|
||||
|
||||
shell.querySelector('[data-action="share"]')?.addEventListener('click', async () => {
|
||||
try {
|
||||
const shared = await shareErrorText(report);
|
||||
if (shared === false) return close();
|
||||
showFeedback('Текст ошибки открыт для отправки');
|
||||
} catch (error) {
|
||||
showFeedback(error?.message || 'Не удалось открыть системное меню отправки', 'error');
|
||||
}
|
||||
close();
|
||||
});
|
||||
|
||||
shell.querySelector('[data-action="send"]')?.addEventListener('click', async () => {
|
||||
try {
|
||||
const sender = window.__SHINE_SEND_CLIENT_ERROR_TO_SERVER__;
|
||||
if (typeof sender !== 'function') {
|
||||
throw new Error('Отправка в лог на сервере недоступна');
|
||||
}
|
||||
const ok = await sender(buildSendPayload(report));
|
||||
if (!ok) {
|
||||
throw new Error('Не удалось отправить ошибку в лог на сервере');
|
||||
}
|
||||
setState({ ...(getState() || {}), sentToServer: true });
|
||||
updateBootOverlay();
|
||||
showFeedback('Ошибка отправлена в лог на сервере');
|
||||
} catch (error) {
|
||||
showFeedback(error?.message || 'Не удалось отправить ошибку в лог на сервере', 'error');
|
||||
}
|
||||
close();
|
||||
});
|
||||
|
||||
shell.querySelector('[data-action="dismiss"]')?.addEventListener('click', () => {
|
||||
close();
|
||||
try {
|
||||
document.getElementById('boot-error-overlay')?.remove();
|
||||
setState(null);
|
||||
} catch {}
|
||||
});
|
||||
const onPeerDropdownOpen = (event) => {
|
||||
if (event?.detail?.owner === 'boot-error') return;
|
||||
close();
|
||||
};
|
||||
document.addEventListener('shine:dropdown-open', onPeerDropdownOpen, { once: true });
|
||||
dialog?.focus?.();
|
||||
window.addEventListener('keydown', onKeyDown);
|
||||
} catch (error) {
|
||||
console.warn('boot error menu failed', error);
|
||||
}
|
||||
};
|
||||
// Краткая безопасная причина для скриншота. Исходный stack и произвольный
|
||||
// текст исключения доступны в меню диагностики, но не на публичном экране.
|
||||
const explainBootFailure = (state) => {
|
||||
const message = String(state.message || '');
|
||||
const reason = String(state.reasonType || '');
|
||||
if (/failed to (fetch|load|import)|module script|importing a module|networkerror|loading chunk/i.test(message)) {
|
||||
return 'Не удалось загрузить модуль приложения.';
|
||||
}
|
||||
if (/syntaxerror|unexpected token|unexpected identifier|unexpected end of input/i.test(`${reason} ${message}`)) {
|
||||
return 'Ошибка синтаксиса JavaScript.';
|
||||
}
|
||||
if (/referenceerror|is not defined/i.test(`${reason} ${message}`)) {
|
||||
return 'Отсутствует необходимая функция или переменная.';
|
||||
}
|
||||
if (/typeerror|cannot read properties|is not a function/i.test(`${reason} ${message}`)) {
|
||||
return 'Ошибка выполнения JavaScript (TypeError).';
|
||||
}
|
||||
if (state.kind === 'unhandled_rejection') {
|
||||
return 'Не удалось завершить операцию при запуске.';
|
||||
}
|
||||
return 'Техническая ошибка при запуске приложения.';
|
||||
};
|
||||
const bootSourceHint = (state) => {
|
||||
let filename = '';
|
||||
try {
|
||||
const path = new URL(String(state.sourceUrl || ''), window.location.origin).pathname;
|
||||
const candidate = path.split('/').pop() || '';
|
||||
if (/^[a-zA-Z0-9_.-]{1,80}$/.test(candidate)) filename = candidate;
|
||||
} catch {}
|
||||
const line = Number.isSafeInteger(state.lineNumber) && state.lineNumber > 0
|
||||
? state.lineNumber : null;
|
||||
return filename ? `Источник: ${filename}${line ? `:${line}` : ''}` : '';
|
||||
};
|
||||
const updateBootOverlay = () => {
|
||||
const el = document.getElementById('boot-error-overlay');
|
||||
const state = getState();
|
||||
if (!el || !state) return;
|
||||
const cause = el.querySelector('[data-boot-error="cause"]');
|
||||
const source = el.querySelector('[data-boot-error="source"]');
|
||||
const status = el.querySelector('[data-boot-error="status"]');
|
||||
if (cause) cause.textContent = `Причина: ${explainBootFailure(state)}`;
|
||||
if (source) {
|
||||
source.textContent = bootSourceHint(state);
|
||||
source.hidden = !source.textContent;
|
||||
}
|
||||
if (status) status.textContent = state.sentToServer === true
|
||||
? 'Отчёт об ошибке принят сервером.'
|
||||
: 'Отправка отчёта не подтверждена. Пришлите скриншот этого окна.';
|
||||
};
|
||||
const show = (title, text, extra = {}) => {
|
||||
try {
|
||||
const reportState = {
|
||||
kind: safeString(extra.kind || title || 'boot_error', 64),
|
||||
title: safeString(title || 'BOOT ERROR', 128),
|
||||
message: safeString(extra.message || text || '', 500),
|
||||
stack: safeString(extra.stack || '', 8000),
|
||||
sourceUrl: safeString(extra.sourceUrl || extra.filename || '', 240),
|
||||
lineNumber: Number.isFinite(extra.lineNumber) ? extra.lineNumber : (Number.isFinite(extra.lineno) ? extra.lineno : null),
|
||||
columnNumber: Number.isFinite(extra.columnNumber) ? extra.columnNumber : (Number.isFinite(extra.colno) ? extra.colno : null),
|
||||
reasonType: safeString(extra.reasonType || '', 64),
|
||||
clientTs: Number.isFinite(extra.clientTs) ? extra.clientTs : Date.now(),
|
||||
sentToServer: false,
|
||||
};
|
||||
setState(reportState);
|
||||
|
||||
let el = document.getElementById('boot-error-overlay');
|
||||
if (!el) {
|
||||
const light = document.documentElement.dataset.theme === 'light';
|
||||
const surface = light ? '#ffffff' : '#1c1f27';
|
||||
const text = light ? '#20222c' : '#f1f1f5';
|
||||
const secondary = light ? '#666977' : '#a8abb8';
|
||||
const border = light ? '#dedee5' : '#303440';
|
||||
const accent = light ? '#4d447c' : '#b8aef5';
|
||||
const accentText = light ? '#ffffff' : '#211c34';
|
||||
el = document.createElement('div');
|
||||
el.id = 'boot-error-overlay';
|
||||
el.setAttribute('role', 'alert');
|
||||
el.setAttribute('aria-label', 'Ошибка запуска приложения');
|
||||
// Стили встроены специально: аварийный экран виден даже без CSS.
|
||||
el.style.cssText = 'position:fixed;inset:0;z-index:999999;box-sizing:border-box;display:flex;align-items:center;justify-content:center;padding:20px;background:rgba(0,0,0,.48);visibility:visible;font-family:system-ui,-apple-system,sans-serif;';
|
||||
const card = document.createElement('section');
|
||||
card.style.cssText = `box-sizing:border-box;width:min(100%,440px);max-height:calc(100dvh - 40px);overflow:auto;padding:22px;border:1px solid var(--border-subtle,${border});border-radius:14px;background:var(--surface,${surface});color:var(--text-primary,${text});box-shadow:0 14px 42px rgba(0,0,0,.20);`;
|
||||
const heading = document.createElement('strong');
|
||||
heading.textContent = 'Не удалось запустить SHiNE';
|
||||
heading.style.cssText = 'display:block;font-size:18px;line-height:1.4;font-weight:600;margin-bottom:10px;';
|
||||
const intro = document.createElement('p');
|
||||
intro.textContent = 'При загрузке возникла ошибка. Попробуйте обновить страницу.';
|
||||
intro.style.cssText = 'margin:0 0 12px;font-size:14px;line-height:1.5;';
|
||||
const cause = document.createElement('p');
|
||||
cause.dataset.bootError = 'cause';
|
||||
cause.style.cssText = `margin:0 0 4px;font-size:13px;line-height:1.5;color:var(--text-secondary,${secondary});overflow-wrap:anywhere;`;
|
||||
const source = document.createElement('p');
|
||||
source.dataset.bootError = 'source';
|
||||
source.style.cssText = `margin:0 0 12px;font-size:12px;line-height:1.5;color:var(--text-secondary,${secondary});overflow-wrap:anywhere;`;
|
||||
const status = document.createElement('p');
|
||||
status.dataset.bootError = 'status';
|
||||
status.style.cssText = `margin:0 0 18px;font-size:12px;line-height:1.5;color:var(--text-secondary,${secondary});`;
|
||||
const actions = document.createElement('div');
|
||||
actions.style.cssText = 'display:flex;flex-wrap:wrap;gap:10px;';
|
||||
const button = (label, primary) => {
|
||||
const result = document.createElement('button');
|
||||
result.type = 'button';
|
||||
result.textContent = label;
|
||||
result.style.cssText = `flex:1 1 130px;min-height:42px;padding:10px;border:1px solid var(--border-control,${border});border-radius:10px;font:inherit;font-size:14px;font-weight:600;cursor:pointer;background:${primary ? `var(--accent,${accent})` : `var(--surface,${surface})`};color:${primary ? `var(--on-accent,${accentText})` : `var(--text-primary,${text})`};`;
|
||||
return result;
|
||||
};
|
||||
const retry = button('Обновить страницу', true);
|
||||
retry.addEventListener('click', () => window.location.reload());
|
||||
const details = button('Подробности', false);
|
||||
details.addEventListener('click', openMenu);
|
||||
actions.append(retry, details);
|
||||
card.append(heading, intro, cause, source, status, actions);
|
||||
el.appendChild(card);
|
||||
document.body.appendChild(el);
|
||||
}
|
||||
updateBootOverlay();
|
||||
} catch (error) {
|
||||
console.warn('boot error overlay failed', error);
|
||||
}
|
||||
};
|
||||
window.addEventListener('error', (e) => {
|
||||
// После запуска приложения ошибки обрабатывает единый client-error-reporter.
|
||||
if (window.__SHINE_APP_ERROR_HANDLERS_READY__ === true) return;
|
||||
// Предупреждение браузера о переносе замеров ResizeObserver на следующий кадр – не ошибка
|
||||
if (/^ResizeObserver loop/.test(String(e?.message || ''))) return;
|
||||
show('window.error', `${e?.message || ''}\n${e?.filename || ''}:${e?.lineno || ''}:${e?.colno || ''}`, {
|
||||
kind: 'window_error',
|
||||
message: e?.message || '',
|
||||
stack: e?.error?.stack || '',
|
||||
sourceUrl: e?.filename || '',
|
||||
lineNumber: e?.lineno,
|
||||
columnNumber: e?.colno,
|
||||
reasonType: e?.error?.constructor?.name || e?.constructor?.name || 'ErrorEvent',
|
||||
});
|
||||
});
|
||||
window.addEventListener('unhandledrejection', (e) => {
|
||||
if (window.__SHINE_APP_ERROR_HANDLERS_READY__ === true) return;
|
||||
const reason = e?.reason;
|
||||
show('unhandledrejection', reason?.stack || reason?.message || String(reason || 'unknown'), {
|
||||
kind: 'unhandled_rejection',
|
||||
message: reason?.message || String(reason || 'Unhandled promise rejection'),
|
||||
stack: reason?.stack || '',
|
||||
reasonType: reason?.constructor?.name || typeof reason,
|
||||
});
|
||||
});
|
||||
}());
|
||||
</script>
|
||||
<script>
|
||||
(async function attachAppWithBuildHash() {
|
||||
const isLocalPreview = ['localhost', '127.0.0.1', '::1'].includes(String(window.location.hostname || '').toLowerCase());
|
||||
if (isLocalPreview && 'serviceWorker' in navigator) {
|
||||
try {
|
||||
const registrations = await navigator.serviceWorker.getRegistrations();
|
||||
await Promise.all(registrations.map((registration) => registration.unregister()));
|
||||
} catch {}
|
||||
}
|
||||
const v = encodeURIComponent(window.__SHINE_BUILD_HASH__ || 'dev');
|
||||
const script = document.createElement('script');
|
||||
script.type = 'module';
|
||||
script.src = isLocalPreview ? `./js/app.js?v=${v}&local=${Date.now()}` : `./js/app.js?v=${v}`;
|
||||
document.body.appendChild(script);
|
||||
}());
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||