SHA256
Compare commits
44
Commits
993930eb82
...
ui-polish
| Author | SHA256 | Date | |
|---|---|---|---|
|
|
bca788c5e6 | ||
|
|
68eec2b28b | ||
|
|
694aaf1f0e | ||
|
|
5caa4ce0ae | ||
|
|
af5b26c934 | ||
|
|
6997bc7600 | ||
|
|
9eedbf60a8 | ||
|
|
6294646922 | ||
|
|
42797b1a43 | ||
|
|
8c3751aba0 | ||
|
|
f40353725e | ||
|
|
3f0d71f788 | ||
|
|
f2ba7ce630 | ||
|
|
edc3d50136 | ||
|
|
a7a600035a | ||
|
|
3f05806563 | ||
|
|
2fb19ee66d | ||
|
|
d91ca5fbb3 | ||
|
|
7173f33d5f | ||
|
|
b3f9e1fe21 | ||
|
|
401ba918ad | ||
|
|
82d5a768f8 | ||
|
|
835109c81a | ||
|
|
d5f2c12fe7 | ||
|
|
11f169b080 | ||
|
|
96d23b16fc | ||
|
|
26db18e250 | ||
|
|
8fee7e1a9b | ||
|
|
e7cf98889b | ||
|
|
3fdff2a92b | ||
|
|
4d5a485933 | ||
|
|
b9cbbb857b | ||
|
|
56de0f2c74 | ||
|
|
68fe0532ce | ||
|
|
3edde418a2 | ||
|
|
923f281bf6 | ||
|
|
9ea276ba77 | ||
|
|
cfb0f9b734 | ||
|
|
b5ce7b0fa0 | ||
|
|
58de6a025d | ||
|
|
e6937cb49c | ||
|
|
7ac9e5a806 | ||
|
|
89630878af | ||
|
|
8b2012fad3 |
+1
-1
@@ -1,2 +1,2 @@
|
||||
client.version=1.19.0
|
||||
client.version=1.19.32
|
||||
server.version=1.15.0
|
||||
|
||||
@@ -228,6 +228,24 @@ DeleteMessage принимает type=5/6. DeleteConversation принимает
|
||||
|
||||
Это правило не меняет wire/API-формат DM и не меняет байтовый формат tombstone.
|
||||
|
||||
## UI чата: поиск, переход к дате, «Медиа и файлы», «без звука», закрепление (12.10.2026)
|
||||
|
||||
Всё ниже работает на клиенте и не меняет ни формат DM, ни серверный API.
|
||||
|
||||
- Поиск по переписке и календарь «перейти к дате» работают по расшифрованным сообщениям на устройстве. Если история загружена не целиком, клиент сам долистывает её обычным `GetDirectMessages` (страницы по 50) до начала. Экран «Медиа и файлы» (`/chat/<login>/media`) делает то же самое и показывает фото и видео (`<S:file...>` до 20 МБ) сеткой, а остальные файлы списком. Голосовые в этот экран не попадают.
|
||||
- При разборе страницы истории ключ `clientKey` достаётся из локального хранилища ключей один раз на страницу, а не для каждого сообщения. Сама расшифровка (X25519 + HKDF + AES-GCM) не меняется.
|
||||
- «Без звука» и «закреплён» – настройки этого устройства. Они хранятся в `localStorage` отдельно для каждого `ownerLogin`, на сервер не передаются и с другими устройствами не синхронизируются. Для чата «без звука» входящее сообщение доставляется и считается непрочитанным как обычно, но клиент не проигрывает сигнал и не показывает системное уведомление. Список таких чатов дублируется в Cache Storage, чтобы service worker не показывал push `new_message` от этого собеседника. Если в push нет `toLogin`, проверяются списки всех профилей устройства.
|
||||
- Закреплённые чаты показываются в списке выше остальных, независимо от фильтра по типу связи. Последний закреплённый показывается первым.
|
||||
|
||||
## UI: список чатов и «без звука» на время (13.10.2026)
|
||||
|
||||
Тоже только клиент: формат DM и серверный API не меняются.
|
||||
|
||||
- Список чатов: сначала переписки – по времени последнего сообщения, закреплённые выше всех. Связи без переписки идут ниже отдельной группой «Начать переписку»: во «Всех» – только близкие и друзья (первые пять и «Показать всех»), в фильтре по типу связи – все люди этого типа, в поиске по чатам – все совпадения. Так сотни контактов не вытесняют сами переписки.
|
||||
- «Без звука» выбирается на 1 час, 8 часов, сутки, неделю или навсегда. Срок хранится рядом со списком (`mutedUntil`: собеседник → время в мс); когда он выходит, звук включается сам – и в открытом приложении (значки в списке и шапке чата обновляются), и в service worker, который сверяет срок при каждом push.
|
||||
- Формат для service worker в Cache Storage: `{ ownerLogin: { peerLogin: untilMs } }`, где `0` – навсегда. Прежний формат `{ ownerLogin: [peerLogin] }` worker тоже понимает.
|
||||
- Ошибка отправки: временное сообщение («часики») убирается из ленты, текст возвращается в поле ввода, а тост называет причину и предлагает «Повторить» (отправить тот же текст ещё раз). Для вложений, уже загруженных на сервер, «Повторить» отправляет только DM с ключами, без новой загрузки файлов. Пузыри «Ошибка отправки: …» от имени пользователя в ленту больше не добавляются; при неудачной пересылке временное сообщение в целевом чате тоже убирается.
|
||||
|
||||
|
||||
## 15. Файлы в личных сообщениях
|
||||
|
||||
|
||||
@@ -14,6 +14,12 @@ class SpaHandler(SimpleHTTPRequestHandler):
|
||||
rel = Path(translated).relative_to(Path.cwd())
|
||||
return str(ROOT / rel)
|
||||
|
||||
def end_headers(self):
|
||||
# Локальная разработка: модули без версии в адресе (./router.js) иначе берутся из эвристического
|
||||
# кэша браузера – новый app.js встречается со старым router.js и приложение не стартует.
|
||||
self.send_header("Cache-Control", "no-cache")
|
||||
super().end_headers()
|
||||
|
||||
def do_GET(self):
|
||||
file_path = Path(self.translate_path(self.path.split("?", 1)[0]))
|
||||
if file_path.exists() and file_path.is_file():
|
||||
|
||||
@@ -74,6 +74,31 @@ function encodeCallPushPayloadForUrl(payload) {
|
||||
}
|
||||
}
|
||||
|
||||
// Чаты «без звука» (пишет приложение, см. 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;
|
||||
}
|
||||
}
|
||||
|
||||
self.addEventListener('push', (event) => {
|
||||
let body = '';
|
||||
let rawText = '';
|
||||
@@ -130,7 +155,7 @@ self.addEventListener('push', (event) => {
|
||||
: 'SHiNE: входящее сообщение');
|
||||
|
||||
const notifyPromise = shouldNotify
|
||||
? self.registration.showNotification(notificationTitle, {
|
||||
? (kind === 'new_message' ? isMutedDirectMessage(toLogin, fromLogin) : Promise.resolve(false)).then((muted) => (muted ? undefined : self.registration.showNotification(notificationTitle, {
|
||||
body: body || (fromLogin ? `Новое сообщение от ${fromLogin}` : 'Новое сообщение'),
|
||||
tag: callId || (kind === 'test_push' ? 'shine-test-push' : 'shine-direct-message'),
|
||||
renotify: true,
|
||||
@@ -152,7 +177,7 @@ self.addEventListener('push', (event) => {
|
||||
{ action: 'decline', title: 'Сбросить' },
|
||||
]
|
||||
: [],
|
||||
})
|
||||
})))
|
||||
: Promise.resolve();
|
||||
|
||||
const closeOnStopPromise = kind === 'stop_call' && callId
|
||||
|
||||
+37
-10
@@ -39,32 +39,59 @@
|
||||
}());
|
||||
</script>
|
||||
<script>
|
||||
window.__SHINE_BUILD_HASH__ = '20261011-search-v1';
|
||||
window.__SHINE_BUILD_HASH__ = '20261015230000';
|
||||
window.__SHINE_CLIENT_VERSION__ = '1.2.10';
|
||||
</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/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/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/network-graph.css'];
|
||||
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/network-graph.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" aria-label="Сияние">
|
||||
<div class="initial-splash__logo-wrap">
|
||||
<img
|
||||
class="initial-splash__logo"
|
||||
src="./img/shine-logo-transparent-final.png"
|
||||
alt="Логотип Сияние"
|
||||
/>
|
||||
<!-- Заставка повторяет верх экрана входа (те же классы и раскладка): смена на него незаметна. -->
|
||||
<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>
|
||||
<div class="initial-splash__brand">Сияние</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>
|
||||
|
||||
+73
-11
@@ -3,6 +3,7 @@ import {
|
||||
getRoute,
|
||||
PRE_AUTH_PAGES,
|
||||
syncTrackedRouteHistory,
|
||||
consumeHistoryLayerPop,
|
||||
} from './router.js';
|
||||
import { renderToolbar } from './components/toolbar.js';
|
||||
import {
|
||||
@@ -16,6 +17,7 @@ import { initPwaInstallPromptHandling } from './services/pwa-install-service.js'
|
||||
import { initPwaPush } from './services/pwa-push-service.js';
|
||||
import { initCallUiOverlay } from './services/call-ui-service.js';
|
||||
import { showToast } from './services/channels-ux.js';
|
||||
import { toUserMessage } from './services/ui-error-texts.js';
|
||||
import { KeyRotationClient } from './services/key-rotation-service.js';
|
||||
import {
|
||||
handleCallPushAction,
|
||||
@@ -69,7 +71,7 @@ import * as loginOtherDeviceView from './pages/login-other-device-view.js?v=2026
|
||||
import * as loginPasswordView from './pages/login-password-view.js?v=202606201650';
|
||||
import * as publicSupportQueueView from './pages/public-support-queue-view.js';
|
||||
|
||||
import * as profileView from './pages/profile-view.js?v=202609260900';
|
||||
import * as profileView from './pages/profile-view.js?v=202610130400';
|
||||
import * as profileEditView from './pages/profile-edit-view.js';
|
||||
import * as profilesView from './pages/profiles-view.js';
|
||||
import * as walletView from './pages/wallet-view.js?v=202609260900';
|
||||
@@ -95,13 +97,20 @@ import * as deviceCameraView from './pages/device-camera-view.js';
|
||||
import * as showKeysView from './pages/show-keys-view.js';
|
||||
import * as clientSessionView from './pages/device-session-view.js?v=202606131435';
|
||||
import * as languageView from './pages/language-view.js';
|
||||
import * as appearanceView from './pages/appearance-view.js';
|
||||
import * as notificationSettingsView from './pages/notification-settings-view.js';
|
||||
import * as appLogView from './pages/app-log-view.js';
|
||||
import * as pwaDiagnosticsView from './pages/pwa-diagnostics-view.js';
|
||||
import * as solanaUsersInitView from './pages/solana-users-init-view.js';
|
||||
import * as solanaRpcCheckView from './pages/solana-rpc-check-view.js';
|
||||
import * as messagesList from './pages/messages-list.js?v=202609260900';
|
||||
import * as messagesList from './pages/messages-list.js?v=202610130400';
|
||||
import * as contactSearchView from './pages/contact-search-view.js';
|
||||
import * as chatView from './pages/chat-view.js?v=202609260900';
|
||||
import * as chatView from './pages/chat-view.js?v=202610130200';
|
||||
import * as chatMediaView from './pages/chat-media-view.js';
|
||||
import { isDmChatMuted } from './services/dm-chat-prefs.js';
|
||||
import { getDevicePref } from './services/device-prefs.js';
|
||||
import { isDeveloperToolsEnabled } from './services/feature-settings.js';
|
||||
import { confirmDialog } from './components/confirm-dialog.js';
|
||||
import * as userProfileView from './pages/user-profile-view.js';
|
||||
import * as userProfileListView from './pages/user-profile-list-view.js';
|
||||
import * as userRelationManageView from './pages/user-relation-manage-view.js';
|
||||
@@ -113,8 +122,8 @@ import * as channelDonateView from './pages/channel-donate-view.js';
|
||||
import * as channelThreadView from './pages/channel-thread-view.js';
|
||||
import * as addChannelView from './pages/add-channel-view.js';
|
||||
import * as addPersonalPublicChatView from './pages/add-personal-public-chat-view.js';
|
||||
import * as networkView from './pages/network-view.js?v=202609260900';
|
||||
import * as notificationsView from './pages/notifications-view.js?v=202609260900';
|
||||
import * as networkView from './pages/network-view.js?v=202610130200';
|
||||
import * as notificationsView from './pages/notifications-view.js?v=202610130400';
|
||||
|
||||
const CONVERSATION_CLEAR_NOTICE_TEXT = 'История переписки очищена с этого места';
|
||||
const DM_UNSUPPORTED_FORMAT_TEXT = 'Формат сообщения не поддерживается';
|
||||
@@ -167,6 +176,8 @@ const routes = {
|
||||
'show-keys-view': showKeysView,
|
||||
'device-session-view': clientSessionView,
|
||||
'language-view': languageView,
|
||||
'appearance-view': appearanceView,
|
||||
'notification-settings-view': notificationSettingsView,
|
||||
'app-log-view': appLogView,
|
||||
'pwa-diagnostics-view': pwaDiagnosticsView,
|
||||
'solana-users-init-view': solanaUsersInitView,
|
||||
@@ -174,6 +185,7 @@ const routes = {
|
||||
'messages-list': messagesList,
|
||||
'contact-search-view': contactSearchView,
|
||||
'chat-view': chatView,
|
||||
'chat-media-view': chatMediaView,
|
||||
user: userProfileView,
|
||||
'user-profile-list-view': userProfileListView,
|
||||
'user-relation-manage-view': userRelationManageView,
|
||||
@@ -206,6 +218,35 @@ const UI_BUILD_HASH_PATTERN = /window\.__SHINE_BUILD_HASH__\s*=\s*'([^']+)'/;
|
||||
let currentCleanup = null;
|
||||
let pingIntervalId = null;
|
||||
let reconnectIntervalId = null;
|
||||
let channelsPrefetchTimerId = null;
|
||||
let channelsPrefetchEpoch = 0;
|
||||
const CHANNELS_PREFETCH_INTERVAL_MS = 60_000;
|
||||
|
||||
// Раз в минуту, пока вкладка на экране, подтягиваем каналы в память, чтобы они открывались сразу.
|
||||
function startChannelsPrefetch() {
|
||||
stopChannelsPrefetch();
|
||||
const epoch = ++channelsPrefetchEpoch;
|
||||
let running = false;
|
||||
const tick = async () => {
|
||||
if (running || document.visibilityState !== 'visible' || !wsIsOpen()) return;
|
||||
running = true;
|
||||
try {
|
||||
await channelsList.refreshChannelsInBackground({ isCurrent: () => epoch === channelsPrefetchEpoch });
|
||||
} catch {
|
||||
// Сеть недоступна – попробуем на следующем круге.
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
};
|
||||
channelsPrefetchTimerId = window.setInterval(() => void tick(), CHANNELS_PREFETCH_INTERVAL_MS);
|
||||
window.setTimeout(() => { if (epoch === channelsPrefetchEpoch) void tick(); }, 3_000);
|
||||
}
|
||||
|
||||
function stopChannelsPrefetch() {
|
||||
channelsPrefetchEpoch += 1;
|
||||
if (channelsPrefetchTimerId) window.clearInterval(channelsPrefetchTimerId);
|
||||
channelsPrefetchTimerId = null;
|
||||
}
|
||||
let sessionRuntimeStarted = false;
|
||||
let connectionState = '';
|
||||
let connectionStatusText = '';
|
||||
@@ -280,6 +321,8 @@ const GUEST_ALLOWED_PAGES = new Set([
|
||||
|
||||
setClientErrorTransport((payload) => authService.reportClientUiError(payload));
|
||||
setClientErrorSentNotifier((payload) => {
|
||||
// Технические подробности – только с включёнными инструментами разработчика.
|
||||
if (!isDeveloperToolsEnabled()) return;
|
||||
const login = String(state.session.login || 'guest').trim();
|
||||
const isoTs = new Date(Number(payload?.clientTs || Date.now())).toISOString();
|
||||
showToast(`Ошибка отправлена на сервер · ${login} · ${isoTs}`);
|
||||
@@ -618,6 +661,8 @@ async function unlockHiddenDmAudio() {
|
||||
|
||||
async function playDmSignal({ extended = false } = {}) {
|
||||
try {
|
||||
// «Звук в открытом приложении» выключен в настройках уведомлений.
|
||||
if (getDevicePref('dmSound', true) === false) return false;
|
||||
if (!hiddenDmAudioUnlocked || !hiddenDmAudioContext) return false;
|
||||
if (hiddenDmAudioContext.state === 'suspended') {
|
||||
await hiddenDmAudioContext.resume();
|
||||
@@ -903,7 +948,7 @@ async function ensurePushTargetProfile(payload = {}, { action = '' } = {}) {
|
||||
const currentLogin = String(state.session.login || '').trim();
|
||||
if (!targetLogin || targetLogin.toLowerCase() === currentLogin.toLowerCase()) return true;
|
||||
if (!savedProfileExists(targetLogin)) {
|
||||
showToast(`Уведомление пришло профилю ${targetLogin}, который не сохранён на этом устройстве.`);
|
||||
showToast(`Уведомление пришло профилю ${targetLogin}, который не сохранён на этом устройстве.`, { kind: 'info' });
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -911,7 +956,8 @@ async function ensurePushTargetProfile(payload = {}, { action = '' } = {}) {
|
||||
const question = kind === 'incoming_call'
|
||||
? `Входящий звонок для профиля «${targetLogin}». Переключиться на этот профиль?`
|
||||
: `Это сообщение пришло профилю «${targetLogin}». Переключиться, чтобы открыть его?`;
|
||||
if (!window.confirm(question)) return false;
|
||||
const confirmed = await confirmDialog({ title: 'Переключить профиль?', text: question, confirmLabel: 'Переключить' });
|
||||
if (!confirmed) return false;
|
||||
|
||||
try {
|
||||
await switchToSavedProfile(targetLogin);
|
||||
@@ -923,7 +969,7 @@ async function ensurePushTargetProfile(payload = {}, { action = '' } = {}) {
|
||||
}
|
||||
return false;
|
||||
} catch (error) {
|
||||
showToast(`Не удалось переключить профиль: ${error?.message || 'unknown'}`);
|
||||
showToast(toUserMessage(error, 'Не удалось переключить профиль.'), { kind: 'error' });
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1253,7 +1299,17 @@ async function ensureSessionAfterWsReconnect() {
|
||||
return wsSessionRestoreInFlight;
|
||||
}
|
||||
|
||||
// Без инструментов разработчика – спокойное сообщение вместо окна со стеком вызовов,
|
||||
// не чаще раза в полминуты (ошибка уже записана в журнал и отправлена на сервер).
|
||||
let lastCrashNoticeAt = 0;
|
||||
function showGlobalErrorAlert(title, details = {}) {
|
||||
if (!isDeveloperToolsEnabled()) {
|
||||
const now = Date.now();
|
||||
if (now - lastCrashNoticeAt < 30000) return;
|
||||
lastCrashNoticeAt = now;
|
||||
showToast('Что-то пошло не так. Сведения об ошибке уже отправлены разработчикам – попробуйте ещё раз.', { kind: 'error' });
|
||||
return;
|
||||
}
|
||||
const lines = [title];
|
||||
if (details.message) lines.push(`Сообщение: ${details.message}`);
|
||||
if (details.pageId) lines.push(`Экран: ${details.pageId}`);
|
||||
@@ -1458,7 +1514,7 @@ function renderApp() {
|
||||
try {
|
||||
const chrome = createChromeController(showAppChrome, page.pageMeta?.shellMode);
|
||||
currentChromeCleanup = () => chrome.dispose();
|
||||
// В переписке нижняя панель прячется (pageMeta.hideToolbar), чтобы не отнимать место у сообщений.
|
||||
// Нижняя панель видна везде, кроме экранов с pageMeta.hideToolbar (например, смена ключей).
|
||||
if (showAppChrome && !page.pageMeta?.hideToolbar) {
|
||||
mountSlot(toolbarEl, '--toolbar-height', renderToolbar(page.pageMeta.id, navigate));
|
||||
toolbarHeightObserver?.sync?.();
|
||||
@@ -1546,6 +1602,7 @@ async function ensureSessionRuntimeStarted() {
|
||||
}
|
||||
|
||||
startConnectionMonitor();
|
||||
startChannelsPrefetch();
|
||||
|
||||
if (reconnectIntervalId) {
|
||||
window.clearInterval(reconnectIntervalId);
|
||||
@@ -1597,6 +1654,7 @@ async function init() {
|
||||
|
||||
setSessionResetHandler(() => {
|
||||
sessionRuntimeStarted = false;
|
||||
stopChannelsPrefetch();
|
||||
startConnectionMonitor();
|
||||
clearKeepAliveEntries();
|
||||
if (reconnectIntervalId) {
|
||||
@@ -1786,7 +1844,8 @@ async function init() {
|
||||
if (added && isIncomingForCurrent) {
|
||||
shouldRefreshToolbarUnread = true;
|
||||
}
|
||||
if (added && isIncomingForCurrent && !payload.backlog) {
|
||||
// Чат «без звука»: сообщение и счётчик непрочитанных приходят как обычно, но без сигнала и уведомления.
|
||||
if (added && isIncomingForCurrent && !payload.backlog && !isDmChatMuted(chatId)) {
|
||||
const parsedText = parseDmTechBlocks(text);
|
||||
const displayText = String(parsedText.displayText || '');
|
||||
const suppressHiddenNotification = parsedText.callSummary?.status === 'completed';
|
||||
@@ -1996,7 +2055,10 @@ async function init() {
|
||||
}
|
||||
})();
|
||||
|
||||
window.addEventListener('popstate', renderApp);
|
||||
window.addEventListener('popstate', (event) => {
|
||||
if (event.isTrusted && consumeHistoryLayerPop()) return;
|
||||
renderApp();
|
||||
});
|
||||
document.addEventListener('pointerdown', () => {
|
||||
void unlockHiddenDmAudio();
|
||||
}, { passive: true });
|
||||
|
||||
@@ -591,7 +591,7 @@ export function openArweaveAttachmentManager({
|
||||
</div>
|
||||
${turboMode
|
||||
? `
|
||||
<p class="ar-attachment-note"><strong>Turbo</strong> — более удобный способ загрузки файлов в Arweave через сторонний сервис. Обычно дешевле прямой загрузки. Файлы до 100 КБ загружаются бесплатно.</p>
|
||||
<p class="ar-attachment-note"><strong>Turbo</strong> – более удобный способ загрузки файлов в Arweave через сторонний сервис. Обычно дешевле прямой загрузки. Файлы до 100 КБ загружаются бесплатно.</p>
|
||||
`
|
||||
: `
|
||||
<div class="form-field">
|
||||
|
||||
@@ -76,7 +76,7 @@ export function openChannelAttachmentManager({
|
||||
</div>
|
||||
|
||||
<div class="public-attachment-manager__arweave" data-panel="arweave" hidden>
|
||||
<p class="meta-muted">Выберите Turbo — более удобный способ загрузки в Arweave через сторонний сервис — или прямую загрузку в сеть Arweave.</p>
|
||||
<p class="meta-muted">Выберите Turbo – более удобный способ загрузки в Arweave через сторонний сервис – или прямую загрузку в сеть Arweave.</p>
|
||||
<div class="public-attachment-manager__arweave-loading meta-muted">Открываем настройки Arweave…</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -6,6 +6,8 @@ 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 { resolvePublicFileUrl } from '../services/public-file-service.js';
|
||||
import { openHistoryLayer } from '../router.js';
|
||||
|
||||
const drafts = new Map();
|
||||
|
||||
@@ -14,6 +16,24 @@ function draftKey(key) {
|
||||
return `${login}:${String(key || 'editor')}`;
|
||||
}
|
||||
|
||||
// Превью вложения в редакторе: картинки и видео – миниатюрой (как в Threads), остальное – строкой с именем.
|
||||
const previewUrls = new Map();
|
||||
function attachmentKind(item) {
|
||||
const name = String(item?.name || '').toLowerCase();
|
||||
if (/\.(jpe?g|png|gif|webp|avif|heic|bmp)$/.test(name)) return 'image';
|
||||
if (/\.(mp4|webm|mov|m4v|ogv)$/.test(name)) return 'video';
|
||||
return 'file';
|
||||
}
|
||||
function attachmentPreviewUrl(item, login) {
|
||||
const key = item?.ar ? `ar:${item.ar}` : `sha:${item?.sha256 || ''}`;
|
||||
if (!previewUrls.has(key)) {
|
||||
previewUrls.set(key, item?.ar
|
||||
? Promise.resolve(`${String(state.entrySettings.arweaveServer || 'https://arweave.net').replace(/\/$/, '')}/${item.ar}`)
|
||||
: resolvePublicFileUrl({ sha256: item?.sha256, authorLogin: login, solanaEndpoint: state.entrySettings.solanaServer, fallbackServerLogin: state.entrySettings.shineServerLogin }).catch(() => ''));
|
||||
}
|
||||
return previewUrls.get(key);
|
||||
}
|
||||
|
||||
function attachmentLabel(item) {
|
||||
const name = String(item?.name || 'Файл');
|
||||
const size = Number(item?.size || 0);
|
||||
@@ -36,6 +56,7 @@ export function openChannelEditor({
|
||||
allowEmptyText = false,
|
||||
allowAttachments = true,
|
||||
rawText = false,
|
||||
openAttachOnStart = false,
|
||||
onSubmit,
|
||||
isActive = () => true,
|
||||
} = {}) {
|
||||
@@ -87,12 +108,45 @@ export function openChannelEditor({
|
||||
const draftMark = document.createElement('span');
|
||||
draftMark.className = 'channel-editor__draft';
|
||||
draftMark.textContent = 'Черновик';
|
||||
header.append(closeButton, heading, draftMark);
|
||||
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';
|
||||
|
||||
if (context && (context.author || context.text || context.attachmentLabel)) {
|
||||
// Цепочка как в 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', 'На что вы отвечаете');
|
||||
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 || 'Запись без текста');
|
||||
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');
|
||||
@@ -115,6 +169,7 @@ export function openChannelEditor({
|
||||
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.className = 'channel-editor__input';
|
||||
textarea.rows = 1;
|
||||
textarea.maxLength = 2000;
|
||||
textarea.placeholder = placeholder;
|
||||
textarea.setAttribute('aria-label', placeholder);
|
||||
@@ -131,7 +186,7 @@ export function openChannelEditor({
|
||||
const clearButton = document.createElement('button');
|
||||
clearButton.type = 'button';
|
||||
clearButton.className = 'text-btn channel-editor__clear';
|
||||
clearButton.textContent = 'Очистить черновик';
|
||||
clearButton.textContent = 'Очистить';
|
||||
|
||||
const author = document.createElement('div');
|
||||
author.className = 'channel-editor__author';
|
||||
@@ -147,17 +202,24 @@ export function openChannelEditor({
|
||||
authorText.append(where);
|
||||
}
|
||||
author.append(authorText);
|
||||
if (chain.length) author.classList.add('is-chained');
|
||||
body.append(author);
|
||||
body.append(textarea, attachmentsBox, error, clearButton);
|
||||
|
||||
const footer = document.createElement('footer');
|
||||
footer.className = 'channel-editor__footer';
|
||||
const attachButton = document.createElement('button');
|
||||
attachButton.type = 'button';
|
||||
attachButton.className = 'secondary-btn channel-editor__attach';
|
||||
attachButton.innerHTML = `${iconHtml('clip')}<span class="sr-only">Прикрепить</span>`;
|
||||
attachButton.title = 'Прикрепить файл';
|
||||
attachButton.className = 'icon-btn channel-editor__attach';
|
||||
attachButton.innerHTML = `${iconHtml('image')}<span class="sr-only">Прикрепить фото, видео или файл</span>`;
|
||||
attachButton.title = 'Фото, видео или файл';
|
||||
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');
|
||||
@@ -184,15 +246,42 @@ export function openChannelEditor({
|
||||
|
||||
const sync = () => {
|
||||
textarea.style.height = 'auto';
|
||||
textarea.style.height = `${Math.max(160, textarea.scrollHeight)}px`;
|
||||
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 kind = attachmentKind(item);
|
||||
if (kind !== 'file') {
|
||||
const thumb = document.createElement('div');
|
||||
thumb.className = `channel-editor__thumb channel-editor__thumb--${kind}`;
|
||||
thumb.title = attachmentLabel(item);
|
||||
const media = document.createElement(kind === 'image' ? 'img' : 'video');
|
||||
if (kind === 'image') media.alt = String(item?.name || 'Изображение');
|
||||
else { media.muted = true; media.preload = 'metadata'; media.playsInline = true; }
|
||||
void attachmentPreviewUrl(item, login).then((url) => { if (url && media.isConnected !== false) media.src = url; });
|
||||
const remove = document.createElement('button');
|
||||
remove.type = 'button';
|
||||
remove.className = 'channel-editor__thumb-remove';
|
||||
remove.setAttribute('aria-label', `Убрать вложение ${item?.name || ''}`);
|
||||
remove.innerHTML = iconHtml('close');
|
||||
remove.disabled = inFlight;
|
||||
remove.addEventListener('click', () => {
|
||||
attachments.splice(index, 1);
|
||||
saveDraft();
|
||||
sync();
|
||||
});
|
||||
thumb.append(media, remove);
|
||||
attachmentsBox.append(thumb);
|
||||
return;
|
||||
}
|
||||
const card = document.createElement('div');
|
||||
card.className = 'channel-editor__attachment';
|
||||
const label = document.createElement('span');
|
||||
@@ -213,19 +302,13 @@ export function openChannelEditor({
|
||||
});
|
||||
};
|
||||
|
||||
const openedUrl = location.href;
|
||||
const historyId = `${Date.now()}:${Math.random()}`;
|
||||
history.pushState({ ...history.state, channelEditor: historyId }, '', openedUrl);
|
||||
// «Назад» закрывает редактор, а не уводит со страницы; слой в истории ведёт роутер.
|
||||
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 onBack = (event) => {
|
||||
if (closed) return;
|
||||
event.stopImmediatePropagation();
|
||||
close({ fromHistory: true });
|
||||
};
|
||||
const observer = new MutationObserver(() => {
|
||||
if (!overlay.isConnected) close({ restoreFocus: false });
|
||||
});
|
||||
@@ -239,14 +322,8 @@ export function openChannelEditor({
|
||||
viewport?.removeEventListener('resize', updateViewport);
|
||||
viewport?.removeEventListener('scroll', updateViewport);
|
||||
window.removeEventListener('resize', updateViewport);
|
||||
window.removeEventListener('popstate', onBack, true);
|
||||
overlay.remove();
|
||||
if (!fromHistory && location.href === openedUrl && history.state?.channelEditor === historyId) {
|
||||
window.addEventListener('popstate', (event) => {
|
||||
if (location.href === openedUrl) event.stopImmediatePropagation();
|
||||
}, { capture: true, once: true });
|
||||
history.back();
|
||||
}
|
||||
if (!fromHistory) historyLayer.close();
|
||||
if (restoreFocus && opener?.isConnected) opener.focus({ preventScroll: true });
|
||||
};
|
||||
overlay.cleanup = () => close({ restoreFocus: false });
|
||||
@@ -362,7 +439,6 @@ export function openChannelEditor({
|
||||
});
|
||||
submitButton.addEventListener('click', () => void submit());
|
||||
document.addEventListener('keydown', onDocumentKeydown);
|
||||
window.addEventListener('popstate', onBack, true);
|
||||
viewport?.addEventListener('resize', updateViewport);
|
||||
viewport?.addEventListener('scroll', updateViewport);
|
||||
window.addEventListener('resize', updateViewport);
|
||||
@@ -375,7 +451,9 @@ export function openChannelEditor({
|
||||
const expand = overlay.querySelector('.channel-editor__context-toggle');
|
||||
if (quote && expand && quote.clientHeight > 0) expand.hidden = quote.scrollHeight <= quote.clientHeight;
|
||||
sync();
|
||||
textarea.focus();
|
||||
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,102 @@
|
||||
// Вложения личных сообщений: превью картинок и видео после расшифровки и карточка файла со «Скачать».
|
||||
// Общие для ленты чата и экрана «Медиа и файлы».
|
||||
import { decryptDmFileToBlob, downloadAndDecryptDmFile } 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') 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) {
|
||||
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 createDmFileAttachmentCard(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 = 'Скачать';
|
||||
downloadBtn.setAttribute('aria-label', `Скачать ${attachment.name || 'файл'}`);
|
||||
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: 'Скачивание' }));
|
||||
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 ? 'Файл сохранён' : 'Файл скачан', { timeoutMs: 1600 });
|
||||
}
|
||||
} catch (error) {
|
||||
showToast(actionErrorText('Не удалось скачать файл', error), { kind: 'error' });
|
||||
} finally {
|
||||
downloadBtn.disabled = false;
|
||||
showDownloadIcon();
|
||||
}
|
||||
});
|
||||
|
||||
fileCard.append(fileIcon, fileCopy, downloadBtn);
|
||||
return fileCard;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// Пункт меню чата «Без звука» со сроком – общий для шапки чата и меню строки в списке чатов.
|
||||
// Срок выбирается во вложенном списке того же меню; включённый звук возвращается одним нажатием.
|
||||
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 = [
|
||||
['На 1 час', HOUR],
|
||||
['На 8 часов', 8 * HOUR],
|
||||
['На сутки', 24 * HOUR],
|
||||
['На неделю', 7 * 24 * HOUR],
|
||||
['Навсегда', 0],
|
||||
];
|
||||
|
||||
export function createDmMuteMenuItem(chatId, { iconClass = '', onChange = null } = {}) {
|
||||
const until = getDmChatMutedUntil(chatId);
|
||||
if (until !== null) {
|
||||
return {
|
||||
label: 'Включить звук',
|
||||
hint: until ? `Без звука ${formatDmMuteUntil(until)}` : '',
|
||||
iconHtml: iconHtml('bell', false, iconClass),
|
||||
action: () => {
|
||||
setDmChatMuted(chatId, false);
|
||||
showToast('Уведомления включены', { timeoutMs: 1400 });
|
||||
onChange?.(false);
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
label: 'Без звука',
|
||||
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 ? `Уведомления выключены ${formatDmMuteUntil(untilMs)}` : 'Уведомления от этого чата выключены', { timeoutMs: 1800 });
|
||||
onChange?.(true);
|
||||
},
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
|
||||
let activeDropdown = null;
|
||||
|
||||
function normalizeItems(items) {
|
||||
@@ -73,8 +75,29 @@ export function createDropdownMenu({
|
||||
menuEl.style.top = `${Math.round(top)}px`;
|
||||
};
|
||||
|
||||
const appendItems = () => {
|
||||
normalizeItems(items).forEach((item) => {
|
||||
// Пункт с 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', `Назад: ${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';
|
||||
@@ -105,11 +128,33 @@ export function createDropdownMenu({
|
||||
|
||||
const label = document.createElement('span');
|
||||
label.textContent = String(item.label || '');
|
||||
button.append(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?.();
|
||||
});
|
||||
@@ -117,6 +162,16 @@ export function createDropdownMenu({
|
||||
});
|
||||
};
|
||||
|
||||
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();
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
// Общие состояния экрана: загрузка, «пусто» и ошибка – один вид на всё приложение.
|
||||
// Индикатор загрузки появляется с задержкой (CSS): если данные пришли быстро, его не видно
|
||||
// вовсе, и экран не мелькает.
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
|
||||
export function createSpinner({ size = 'md', label = 'Загрузка' } = {}) {
|
||||
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 = 'Загрузка', 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 = 'Не удалось загрузить',
|
||||
text = 'Проверьте соединение и попробуйте ещё раз.',
|
||||
onRetry = null,
|
||||
className = '',
|
||||
} = {}) {
|
||||
return createStateMessage({
|
||||
kind: 'error', icon: 'alert', title, text, actionLabel: onRetry ? 'Повторить' : '', onAction: onRetry, className,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// Шторка «Заметка о человеке»: текст и цветная метка, видны только владельцу аккаунта.
|
||||
// Открывается с карты связей и из профиля человека; хранение – 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: `Заметка: ${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 = 'Видна только вам. Пока хранится на этом устройстве.';
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.className = 'input person-note__text';
|
||||
textarea.rows = 5;
|
||||
textarea.maxLength = PERSON_NOTE_MAX_TEXT;
|
||||
textarea.placeholder = 'Кто это, откуда знакомы, о чём договорились…';
|
||||
textarea.value = current?.text || '';
|
||||
textarea.setAttribute('aria-label', 'Текст заметки');
|
||||
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 = 'Метка на карте связей';
|
||||
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: 'Без метки' }, ...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 = 'Удалить';
|
||||
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 = 'Сохранить';
|
||||
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 = 'Изменить заметку';
|
||||
el.addEventListener('click', onClick);
|
||||
}
|
||||
el.className = `person-note-preview${className ? ` ${className}` : ''}`;
|
||||
if (note.mark) el.dataset.mark = note.mark;
|
||||
el.textContent = note.text.trim() || 'Метка без текста';
|
||||
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;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
// 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 || '')
|
||||
@@ -12,25 +13,19 @@ export function escapeProfileHtml(text) {
|
||||
|
||||
const esc = escapeProfileHtml;
|
||||
|
||||
function statusCardHtml({ kind, title, received, given }) {
|
||||
const receivedCount = Number(received || 0);
|
||||
const givenCount = Number(given || 0);
|
||||
// Карточка статуса у аватара: кто подтвердил этот аккаунт и кого подтвердил он сам.
|
||||
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';
|
||||
const receivedTitle = isOfficial ? 'Кто подтвердил этот официальный аккаунт' : 'Кто подтвердил, что этот аккаунт сияющий';
|
||||
const givenTitle = isOfficial ? 'Какие официальные аккаунты подтвердил этот пользователь' : 'Кого этот пользователь подтвердил как сияющего';
|
||||
|
||||
return `
|
||||
<section class="pf-status-card pf-status-card--${esc(kind)}" aria-label="${esc(title)}">
|
||||
<div class="pf-status-card-title">${esc(title)}</div>
|
||||
<button type="button" class="pf-status-card-count" data-profile-list="${receivedKind}"
|
||||
aria-label="${esc(receivedTitle)}: ${receivedCount}" title="${esc(receivedTitle)}">
|
||||
<strong>${receivedCount}</strong><span>подтвердили</span>
|
||||
<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)}: подтвердили ${Number(received || 0)}">
|
||||
<strong>${Number(received || 0)}</strong><span>подтвердили</span>
|
||||
</button>
|
||||
<button type="button" class="pf-status-card-count" data-profile-list="${givenKind}"
|
||||
aria-label="${esc(givenTitle)}: ${givenCount}" title="${esc(givenTitle)}">
|
||||
<strong>${givenCount}</strong><span>подтвердил</span>
|
||||
<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>`;
|
||||
}
|
||||
@@ -71,6 +66,7 @@ export function profileCardHtml({ card, login = '', tilesHtml = '', tilesWrapCla
|
||||
const official = card?.accountRole === 'primary';
|
||||
const shining = card?.shineStatus === 'shining';
|
||||
const cardLogin = card?.login || login;
|
||||
const city = displayCity(card?.city);
|
||||
const fullName = [card?.firstName, card?.lastName].map((v) => String(v || '').trim()).filter(Boolean).join(' ');
|
||||
const displayName = fullName || cardLogin || 'Профиль';
|
||||
const about = String(card?.about || '').trim();
|
||||
@@ -91,32 +87,30 @@ export function profileCardHtml({ card, login = '', tilesHtml = '', tilesWrapCla
|
||||
const friends = Number(stats.friendsCount || 0);
|
||||
const closeFriends = Number(stats.closeFriendsCount || 0);
|
||||
|
||||
const officialCard = official
|
||||
? statusCardHtml({
|
||||
kind: 'primary',
|
||||
title: 'Официальный',
|
||||
received: stats.primaryReceivedCount,
|
||||
given: stats.primaryGivenCount,
|
||||
})
|
||||
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' ? 'подтвердила' : card?.gender === 'male' ? 'подтвердил' : 'подтвердил(а)';
|
||||
const officialSide = (isSelf || official || primaryReceived || primaryGiven)
|
||||
? statusSideHtml({ kind: 'primary', title: 'Официальный', active: official, received: primaryReceived, given: primaryGiven, verb })
|
||||
: '';
|
||||
const shiningCard = shining
|
||||
? statusCardHtml({
|
||||
kind: 'shine',
|
||||
title: 'Сияющий',
|
||||
received: stats.shineReceivedCount,
|
||||
given: stats.shineGivenCount,
|
||||
})
|
||||
const shineSide = (isSelf || shining || shineReceived || shineGiven)
|
||||
? statusSideHtml({ kind: 'shine', title: 'Сияющий', active: shining, received: shineReceived, given: shineGiven, verb })
|
||||
: '';
|
||||
|
||||
return `
|
||||
<div class="pf-hero" aria-label="Профиль ${esc(cardLogin)}">
|
||||
<div class="pf-identity">
|
||||
<div class="pf-status-card-slot pf-status-card-slot--left">${officialCard}</div>
|
||||
<div class="pf-avatar user-profile-avatar-slot"></div>
|
||||
<div class="pf-status-card-slot pf-status-card-slot--right">${shiningCard}</div>
|
||||
<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">
|
||||
|
||||
@@ -42,7 +42,7 @@ export function openShareSheet({ title = 'Поделиться', kicker = '', te
|
||||
} catch {
|
||||
field.focus();
|
||||
field.select();
|
||||
showToast('Выделил ссылку – скопируйте её вручную', { kind: 'error' });
|
||||
showToast('Ссылка выделена – скопируйте её вручную', { kind: 'info' });
|
||||
}
|
||||
});
|
||||
wrap.append(preview, label, copy);
|
||||
|
||||
@@ -116,3 +116,67 @@ export function createTopBar({
|
||||
|
||||
return topbar;
|
||||
}
|
||||
|
||||
/**
|
||||
* Шапка-строка поиска (поиск по переписке, по связям и т. п.): «назад» закрывает поиск,
|
||||
* крестик очищает поле, Enter – onSubmit, Escape – onClose.
|
||||
* trailing – узел справа внутри поля (например, счётчик «3 из 12»).
|
||||
*/
|
||||
export function createSearchTopBar({
|
||||
placeholder = 'Поиск',
|
||||
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', 'Очистить');
|
||||
clear.title = 'Очистить';
|
||||
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: 'Закрыть поиск', title: 'Закрыть поиск' },
|
||||
actions,
|
||||
});
|
||||
topbar.searchInput = input;
|
||||
return topbar;
|
||||
}
|
||||
|
||||
@@ -15,7 +15,8 @@ const paths = {
|
||||
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"/>',
|
||||
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.7L7 20.5"/>',
|
||||
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"/>',
|
||||
@@ -35,6 +36,10 @@ const paths = {
|
||||
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"/>',
|
||||
@@ -42,9 +47,18 @@ const paths = {
|
||||
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 = '') {
|
||||
|
||||
@@ -5,6 +5,7 @@ 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', title: 'Сервер доступа' };
|
||||
const MAX_ACCESS_SERVERS = 1;
|
||||
@@ -97,7 +98,7 @@ function createConfirmModal() {
|
||||
}) {
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="access-servers-confirm-modal">
|
||||
<div class="modal-card stack" style="max-width:min(94vw,34rem);">
|
||||
<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>
|
||||
@@ -166,7 +167,7 @@ function createPasswordModal() {
|
||||
open({ title, text, note = '' }) {
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="access-servers-password-modal">
|
||||
<div class="modal-card stack" style="max-width:min(94vw,36rem);">
|
||||
<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>
|
||||
@@ -407,7 +408,7 @@ export function render({navigate, chrome}) {
|
||||
currentAccessServers = [];
|
||||
renderServerList();
|
||||
refreshAddButton();
|
||||
listStatus.textContent = error?.message || 'Не удалось прочитать сервер доступа.';
|
||||
listStatus.textContent = actionErrorText('Не удалось прочитать сервер доступа', error);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -462,7 +463,7 @@ export function render({navigate, chrome}) {
|
||||
if (!disposed) {
|
||||
suggestEl.hidden = true;
|
||||
suggestEl.innerHTML = '';
|
||||
addStatus.textContent = error?.message || 'Не удалось получить список серверов.';
|
||||
addStatus.textContent = actionErrorText('Не удалось получить список серверов', error);
|
||||
}
|
||||
} finally {
|
||||
suggestionsLoading = false;
|
||||
@@ -558,7 +559,7 @@ export function render({navigate, chrome}) {
|
||||
if (isInsufficientFundsForRentError(error)) {
|
||||
showTopupRequiredStatus(target, signingMaterial?.payerAddress);
|
||||
} else {
|
||||
target.textContent = error?.message || 'Не удалось обновить сервер доступа.';
|
||||
target.textContent = actionErrorText('Не удалось обновить сервер доступа', error);
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
@@ -620,7 +621,7 @@ export function render({navigate, chrome}) {
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
addStatus.textContent = error?.message || 'Не удалось проверить выбранный сервер.';
|
||||
addStatus.textContent = actionErrorText('Не удалось проверить выбранный сервер', error);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
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 {
|
||||
@@ -46,7 +47,7 @@ function renderAvatarPreview(slot, avatar, title) {
|
||||
avatar,
|
||||
authorLogin: state.session.login,
|
||||
size: 'xl',
|
||||
className: 'channel-profile-avatar',
|
||||
className: 'channel-profile-avatar avatar-plain',
|
||||
title: label,
|
||||
alt: 'Аватар канала',
|
||||
});
|
||||
@@ -292,9 +293,9 @@ export function render({navigate, chrome}) {
|
||||
}
|
||||
});
|
||||
|
||||
avatarRemoveBtn.addEventListener('click', () => {
|
||||
avatarRemoveBtn.addEventListener('click', async () => {
|
||||
if (!selectedAvatar?.sha256) return;
|
||||
const confirmed = window.confirm('Убрать аватар и сделать канал без аватара?');
|
||||
const confirmed = await confirmDialog({ title: 'Убрать аватар канала?', text: 'Канал будет без картинки – её можно добавить позже.', confirmLabel: 'Убрать' });
|
||||
if (!confirmed) return;
|
||||
selectedAvatar = null;
|
||||
avatarAvailabilityLabel = '';
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
// «Оформление»: тема (Авто / Светлая / Тёмная) и палитра – образцами, применяются сразу.
|
||||
// Тонкая ручная настройка цветов – прежний редактор палитры.
|
||||
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', title: 'Оформление' };
|
||||
|
||||
const THEME_MODES = [
|
||||
['system', 'Авто'],
|
||||
['light', 'Светлая'],
|
||||
['dark', 'Тёмная'],
|
||||
];
|
||||
|
||||
export function render({ navigate, chrome } = {}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack appearance-screen';
|
||||
let closeEditor = null; // openPaletteEditor возвращает функцию закрытия
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'Оформление',
|
||||
back: { onClick: () => navigate('settings-view') },
|
||||
}));
|
||||
|
||||
// --- тема ---
|
||||
const themeTitle = document.createElement('p');
|
||||
themeTitle.className = 'nav-list__title';
|
||||
themeTitle.textContent = 'Тема';
|
||||
const themeTabs = document.createElement('div');
|
||||
themeTabs.className = 'tabs tabs--three appearance-theme';
|
||||
themeTabs.setAttribute('role', 'radiogroup');
|
||||
themeTabs.setAttribute('aria-label', 'Тема оформления');
|
||||
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 = 'Цвета';
|
||||
const grid = document.createElement('div');
|
||||
grid.className = 'palette-grid';
|
||||
grid.setAttribute('role', 'radiogroup');
|
||||
grid.setAttribute('aria-label', 'Палитра');
|
||||
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 = '<span class="nav-row__label">Настроить цвета вручную</span><span class="nav-row__hint"></span>';
|
||||
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'
|
||||
? `Как в системе устройства: сейчас ${resolved === 'light' ? 'светлая' : 'тёмная'}.`
|
||||
: 'Не зависит от настроек устройства.';
|
||||
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
|
||||
? `Свои правки поверх «${PALETTE_PRESETS[settings.preset]?.label || settings.preset}»`
|
||||
: 'Каждый цвет отдельно, для светлой и тёмной темы';
|
||||
}
|
||||
|
||||
sync();
|
||||
screen.append(themeTitle, themeTabs, themeHint, paletteTitle, grid, more);
|
||||
screen.cleanup = () => {
|
||||
const close = closeEditor;
|
||||
closeEditor = null;
|
||||
close?.();
|
||||
};
|
||||
return screen;
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
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';
|
||||
|
||||
@@ -130,8 +131,8 @@ export function render({navigate, chrome}) {
|
||||
{ label: 'Добавить файл', action: () => uploadFile() },
|
||||
{
|
||||
label: 'Очистить историю',
|
||||
action: () => {
|
||||
const confirmed = window.confirm('Очистить журнал загруженных файлов этой сессии?');
|
||||
action: async () => {
|
||||
const confirmed = await confirmDialog({ title: 'Очистить журнал?', text: 'Список загруженных в этой сессии файлов будет очищен. Сами файлы останутся в Arweave.', confirmLabel: 'Очистить', danger: true });
|
||||
if (!confirmed) return;
|
||||
clearArweaveAttachmentHistory(state.session.login);
|
||||
renderHistory();
|
||||
|
||||
@@ -125,7 +125,7 @@ function openChannelProfileEditor({ channel, selector, onSaved }) {
|
||||
avatar: selectedAvatar?.sha256 ? { ar: String(selectedAvatar.ar || ''), sha256Hex: selectedAvatar.sha256 } : null,
|
||||
authorLogin: String(channel?.ownerLogin || state.session.login || '').trim(),
|
||||
size: 'xl',
|
||||
className: 'channel-about-avatar channel-profile-avatar',
|
||||
className: 'channel-about-avatar channel-profile-avatar avatar-plain',
|
||||
title: title || 'Канал',
|
||||
alt: 'Аватар канала',
|
||||
}));
|
||||
@@ -157,7 +157,7 @@ function openChannelProfileEditor({ channel, selector, onSaved }) {
|
||||
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 = 'Название — до 50 символов, описание — до 250.';
|
||||
if (errorEl) errorEl.textContent = 'Название – до 50 символов, описание – до 250.';
|
||||
return;
|
||||
}
|
||||
save.disabled = true;
|
||||
@@ -640,7 +640,7 @@ export function render({ navigate, route, chrome }) {
|
||||
avatar: String(channel?.avaAr || channel?.avaSha256 || '').trim() ? { ar: String(channel.avaAr || '').trim(), sha256Hex: String(channel?.avaSha256 || '').trim() } : null,
|
||||
authorLogin: ownerLogin,
|
||||
size: 'xl',
|
||||
className: 'channel-about-avatar channel-profile-avatar',
|
||||
className: 'channel-about-avatar channel-profile-avatar avatar-plain',
|
||||
title: cleanName,
|
||||
alt: 'Аватар канала',
|
||||
});
|
||||
@@ -648,7 +648,7 @@ export function render({ navigate, route, chrome }) {
|
||||
content.querySelector('#channel-about-owner-avatar')?.append(renderAvatar({
|
||||
initials: ownerName.slice(0, 1).toUpperCase() || '?',
|
||||
size: 'md',
|
||||
className: 'channel-about-owner-avatar-img',
|
||||
className: 'channel-about-owner-avatar-img avatar-plain',
|
||||
alt: '',
|
||||
}));
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+349
-215
@@ -1,8 +1,10 @@
|
||||
import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.js';
|
||||
import { getPreviousTrackedPath } from '../router.js';
|
||||
import { createOverflowDots } from '../components/overflow-dots.js';
|
||||
import { rememberChannelPosition, readChannelPosition, requestReplyEditorOnOpen, restoreChannelPosition } from '../services/channel-view-state.js';
|
||||
import { getPreviousTrackedPath, navigateUp, parseRouteFromPath, toPrettyPath } from '../router.js';
|
||||
import { prefetchThreadPage, threadTotalReplies } from './channel-thread-view.js';
|
||||
import { attachMessageMenu } from '../components/message-menu.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import {
|
||||
@@ -15,12 +17,17 @@ import {
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import {
|
||||
animatePress,
|
||||
createSkeletonCard,
|
||||
createLoadErrorCard,
|
||||
createSkeletonRows,
|
||||
SKELETON_DELAY_MS,
|
||||
dayKey,
|
||||
formatDayLabel,
|
||||
formatPostStamp,
|
||||
formatRelativeTime,
|
||||
formatShortAge,
|
||||
longPressFeel,
|
||||
notifyRepostSoon,
|
||||
REPOSTS_ENABLED,
|
||||
shareOrCopyLink,
|
||||
showToast,
|
||||
softHaptic,
|
||||
@@ -47,9 +54,11 @@ import {
|
||||
makeShineChannelDonateRoute,
|
||||
} from '../services/shine-routes.js';
|
||||
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
||||
import { dropPageData, readPageData, writePageData } from '../services/page-data-cache.js';
|
||||
import { sortedChannelPublications } from '../services/channel-message-ordinals.js';
|
||||
import { scrollNodeIntoContainer } from '../services/scroll-utils.js';
|
||||
|
||||
export const pageMeta = { id: 'channel-view', title: 'Канал', hideToolbar: true, shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
|
||||
export const pageMeta = { id: 'channel-view', title: 'Канал', shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
|
||||
const CHANNEL_TYPE_STORIES = 0;
|
||||
const CHANNEL_TYPE_PERSONAL = 100;
|
||||
const MSG_SUBTYPE_TEXT_RATING = 30;
|
||||
@@ -635,7 +644,7 @@ function createChannelAvatarElement(channel, size = 96) {
|
||||
avatar: (txId || sha256) ? { ar: txId, sha256Hex: sha256 } : null,
|
||||
authorLogin: String(channel?.ownerLogin || '').trim(),
|
||||
size: 'xl',
|
||||
className: 'channel-profile-avatar',
|
||||
className: 'channel-profile-avatar avatar-plain',
|
||||
title,
|
||||
alt: 'Аватар канала',
|
||||
});
|
||||
@@ -1026,7 +1035,7 @@ function flashAndScrollToMessage(messageRef) {
|
||||
const target = cards.find((card) => card.dataset.messageKey === key);
|
||||
if (!target) return false;
|
||||
target.classList.remove('is-focus-flash');
|
||||
target.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
scrollNodeIntoContainer(target, { behavior: 'smooth' });
|
||||
window.setTimeout(() => {
|
||||
if (target.isConnected) target.classList.add('is-focus-flash');
|
||||
}, 60);
|
||||
@@ -1567,27 +1576,12 @@ async function loadFromApi(route, channelId) {
|
||||
}
|
||||
|
||||
function renderLoadError(screen, navigate, message, onRetry) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack channels-status';
|
||||
card.innerHTML = `
|
||||
<strong>Не удалось загрузить канал</strong>
|
||||
<p class="meta-muted">${message || 'Проверьте подключение к серверу и повторите попытку.'}</p>
|
||||
`;
|
||||
|
||||
const retry = document.createElement('button');
|
||||
retry.type = 'button';
|
||||
retry.className = 'primary-btn';
|
||||
retry.textContent = 'Повторить';
|
||||
retry.addEventListener('click', onRetry);
|
||||
|
||||
const back = document.createElement('button');
|
||||
back.type = 'button';
|
||||
back.className = 'secondary-btn';
|
||||
back.textContent = 'Назад к каналам';
|
||||
back.addEventListener('click', () => navigate('channels-list'));
|
||||
|
||||
card.append(retry, back);
|
||||
screen.append(card);
|
||||
screen.append(createLoadErrorCard({
|
||||
title: 'Не удалось загрузить канал',
|
||||
message: message || 'Проверьте подключение и повторите попытку.',
|
||||
onRetry,
|
||||
secondary: { label: 'Назад к каналам', onClick: () => navigate('channels-list') },
|
||||
}));
|
||||
}
|
||||
|
||||
function renderDemoFallback(screen, navigate, error) {
|
||||
@@ -1609,9 +1603,7 @@ function renderDemoFallback(screen, navigate, error) {
|
||||
|
||||
function scrollChannelToBottom(screen, smooth = true) {
|
||||
const feed = screen.querySelector('.channel-feed');
|
||||
if (feed) {
|
||||
feed.scrollIntoView({ behavior: smooth ? 'smooth' : 'auto', block: 'end' });
|
||||
}
|
||||
if (feed) scrollNodeIntoContainer(feed, { block: 'end', behavior: smooth ? 'smooth' : 'auto' });
|
||||
const appScreen = document.getElementById('app-screen');
|
||||
if (appScreen) {
|
||||
appScreen.scrollTo({ top: appScreen.scrollHeight, behavior: smooth ? 'smooth' : 'auto' });
|
||||
@@ -1638,7 +1630,7 @@ function applyPendingScroll(screen, routeKey, forceBottom = false) {
|
||||
|
||||
const element = screen.querySelector(`[data-message-key="${target}"]`);
|
||||
if (element) {
|
||||
element.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
scrollNodeIntoContainer(element, { behavior: 'smooth' });
|
||||
pendingScrollByRoute.delete(routeKey);
|
||||
}
|
||||
};
|
||||
@@ -1718,7 +1710,7 @@ function openMessageLikesListModal({ navigate, messageRef, initialTab = 'shining
|
||||
<button type="button" class="ui-button" data-like-tab="official">Официальные <span data-like-tab-count="official"></span></button>
|
||||
<button type="button" class="ui-button" data-like-tab="all">Все <span data-like-tab-count="all"></span></button>
|
||||
</div>
|
||||
<div class="channel-likes-modal__status">Загрузка...</div>
|
||||
<div class="channel-likes-modal__status"><div class="loading-state" style="--loading-delay:250ms"><span class="spinner" role="status" aria-label="Загрузка"></span></div></div>
|
||||
<div class="channel-likes-user-list"></div>
|
||||
</section>
|
||||
`;
|
||||
@@ -1855,7 +1847,7 @@ function openMessageLikePopup({ anchor, post, navigate, onToggleLike }) {
|
||||
close();
|
||||
} catch (error) {
|
||||
button.disabled = false;
|
||||
showToast(toUserMessage(error, 'Не удалось изменить лайк.'));
|
||||
showToast(toUserMessage(error, 'Не удалось изменить лайк.'), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1871,6 +1863,7 @@ function renderPostCard(post, {
|
||||
onRepost,
|
||||
onShare,
|
||||
onEdit,
|
||||
channel = null,
|
||||
isActive = () => true,
|
||||
}) {
|
||||
const versionsTotal = Number(post?.versionsTotal || 1);
|
||||
@@ -1964,9 +1957,19 @@ function renderPostCard(post, {
|
||||
&& !isDiarySelector(selector)
|
||||
&& !!post.messageRef?.blockchainName
|
||||
&& String(post.messageRef.blockchainName).trim().toLowerCase() === String(selector.ownerBlockchainName || '').trim().toLowerCase();
|
||||
// Запись владельца – как пост в Threads: аватар и название канала слева сверху, текст и действия под названием.
|
||||
const threadsLayout = isOwnerPost && Boolean(channel);
|
||||
if (isOwnerPost) {
|
||||
card.classList.add('channel-message-card--owner');
|
||||
authorTile.hidden = true;
|
||||
authorTile.hidden = !threadsLayout;
|
||||
}
|
||||
if (threadsLayout) {
|
||||
card.classList.add('channel-message-card--threads');
|
||||
const channelAvatar = createChannelAvatarElement(channel, 36);
|
||||
channelAvatar.classList.add('channel-message-avatar');
|
||||
avatar.replaceWith(channelAvatar);
|
||||
loginEl.textContent = String(channel.displayTitle || channel.displayName || channel.name || post.authorLogin).trim();
|
||||
if (post.timestampMs) timestamp.textContent = formatShortAge(post.timestampMs);
|
||||
}
|
||||
|
||||
const isDeletedMessage = String(post.body || '').trim().toLowerCase() === 'удалено';
|
||||
@@ -2069,12 +2072,22 @@ function renderPostCard(post, {
|
||||
try {
|
||||
await onToggleLike(post.messageRef, isLiked ? 'unlike' : 'like');
|
||||
} catch (error) {
|
||||
showToast(toUserMessage(error, 'Не удалось изменить лайк.'));
|
||||
showToast(toUserMessage(error, 'Не удалось изменить лайк.'), { kind: 'error' });
|
||||
} finally {
|
||||
if (likeButton.isConnected) likeButton.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
// Сервер считает только прямые ответы; полное число по всем уровням берём из обсуждения (кэш или подгрузка).
|
||||
if (Number(post.repliesCount || 0) > 0) {
|
||||
const threadRoute = buildThreadRoute(post, selector);
|
||||
if (threadRoute) {
|
||||
const threadPath = new URL(`/${toPrettyPath(threadRoute)}`, window.location.origin).pathname;
|
||||
card.dataset.threadPath = threadPath;
|
||||
const known = readPageData('thread', threadPath)?.data;
|
||||
if (known) post.repliesCount = threadTotalReplies(known);
|
||||
}
|
||||
}
|
||||
const discussionButton = document.createElement('button');
|
||||
discussionButton.type = 'button';
|
||||
discussionButton.className = 'ui-button channel-action-item channel-action-discussion';
|
||||
@@ -2086,15 +2099,33 @@ function renderPostCard(post, {
|
||||
if (post.recentRepliers.length) {
|
||||
const faces = document.createElement('span');
|
||||
faces.className = 'channel-action-faces';
|
||||
post.recentRepliers.forEach((login) => faces.append(renderUserAvatar({ login, size: 'xs', className: 'channel-action-face' })));
|
||||
post.recentRepliers.forEach((login) => faces.append(renderUserAvatar({ login, size: 'xs', className: 'channel-action-face avatar-plain' })));
|
||||
discussionButton.append(faces);
|
||||
}
|
||||
setActionTitle(discussionButton, `Открыть обсуждение, ответов: ${post.repliesCount || 0}`);
|
||||
// По ТЗ: «Обсуждение» открывает запись с обсуждением и сразу редактор ответа (гостю – только обсуждение).
|
||||
const openDiscussion = ({ withEditor = false } = {}) => {
|
||||
const route = buildThreadRoute(post, selector);
|
||||
if (!route) return;
|
||||
if (withEditor && state.session.isAuthorized) requestReplyEditorOnOpen(route);
|
||||
navigate(route);
|
||||
};
|
||||
discussionButton.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
const route = buildThreadRoute(post, selector);
|
||||
if (route) navigate(route);
|
||||
openDiscussion({ withEditor: true });
|
||||
});
|
||||
// Нажатие на саму запись открывает её вместе с обсуждением.
|
||||
card.addEventListener('click', (event) => {
|
||||
if (event.target.closest('button, a, input, textarea, .message-attachment-carousel')) return;
|
||||
if (String(window.getSelection?.() || '').trim()) return;
|
||||
openDiscussion();
|
||||
});
|
||||
card.classList.add('is-openable');
|
||||
// Обсуждение начинаем грузить уже при касании – к моменту клика оно обычно готово.
|
||||
card.addEventListener('pointerdown', () => {
|
||||
const route = buildThreadRoute(post, selector);
|
||||
if (route) prefetchThreadPage(`/${toPrettyPath(route)}`);
|
||||
}, { passive: true });
|
||||
|
||||
const replyButton = document.createElement('button');
|
||||
replyButton.type = 'button';
|
||||
@@ -2108,6 +2139,7 @@ function renderPostCard(post, {
|
||||
replyButton.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
animatePress(event.currentTarget);
|
||||
if (state.session.isAuthorized) { openDiscussion({ withEditor: true }); return; }
|
||||
openReplyModal({
|
||||
onSubmit: async (text) => onReply(post.messageRef, text),
|
||||
isActive,
|
||||
@@ -2137,8 +2169,24 @@ function renderPostCard(post, {
|
||||
await onShare(route);
|
||||
});
|
||||
|
||||
// Порядок как в макете V4: лайк → поделиться → обсуждение; дата и «⋯» — справа
|
||||
actions.append(likeButton, shareButton, discussionButton);
|
||||
// Порядок как в макете V4: лайк → поделиться → обсуждение; дата и «⋯» — справа.
|
||||
// В раскладке Threads: лайк → обсуждение → поделиться, дата и «⋯» в шапке.
|
||||
const repostButton = document.createElement('button');
|
||||
repostButton.type = 'button';
|
||||
repostButton.className = 'ui-button channel-action-item channel-action-repost';
|
||||
repostButton.innerHTML = `
|
||||
<span class="channel-action-icon" aria-hidden="true">${iconHtml('repost')}</span>
|
||||
<span class="channel-action-label">Репост</span>
|
||||
`;
|
||||
setActionTitle(repostButton, 'Репост');
|
||||
repostButton.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
if (!REPOSTS_ENABLED) { notifyRepostSoon(); return; }
|
||||
void onRepost?.(post.messageRef);
|
||||
});
|
||||
// Четыре кнопки как в Threads: лайк, ответы, репост, поделиться.
|
||||
if (threadsLayout) actions.append(likeButton, discussionButton, repostButton, shareButton);
|
||||
else actions.append(likeButton, shareButton, discussionButton);
|
||||
if (selector?.publicOrdinalUrlsAllowed && post.messageRef?.blockNumber != null) {
|
||||
const streamRoute = makeShineChannelStreamRoute({
|
||||
ownerBlockchainName: selector?.ownerBlockchainName,
|
||||
@@ -2148,6 +2196,11 @@ function renderPostCard(post, {
|
||||
if (streamRoute) menuItems.unshift({ label: 'Ссылка на сообщение в ленте', iconHtml: iconHtml('share'), action: () => onShare(streamRoute) });
|
||||
}
|
||||
menuItems.unshift({ label: 'Ответить', iconHtml: iconHtml('reply'), action: () => replyButton.click() });
|
||||
// Те же действия, что у ответов в обсуждении.
|
||||
menuItems.splice(1, 0, { label: 'Скопировать текст', iconHtml: iconHtml('copy'), action: async () => {
|
||||
try { await copyTextToClipboard(parsedBody.text); showToast('Текст скопирован'); }
|
||||
catch { showToast('Не удалось скопировать', { kind: 'error' }); }
|
||||
} });
|
||||
if (post.msgSubType === MSG_SUBTYPE_TEXT_REPOST && post.targetRef?.blockchainName && Number.isFinite(post.targetRef?.blockNumber) && post.targetRef?.blockHash) {
|
||||
const originalBtn = document.createElement('button');
|
||||
originalBtn.type = 'button';
|
||||
@@ -2221,12 +2274,12 @@ function renderPostCard(post, {
|
||||
danger: true,
|
||||
})) return;
|
||||
try { await onEdit(post.messageRef, '', { isDelete: true }); }
|
||||
catch (error) { if (isActive()) showToast(toUserMessage(error, 'Не удалось удалить сообщение.')); }
|
||||
catch (error) { if (isActive()) showToast(toUserMessage(error, 'Не удалось удалить сообщение.'), { kind: 'error' }); }
|
||||
} });
|
||||
}
|
||||
if (versionsTotal > 1) menuItems.push({ label: 'История изменений', action: () => openMessageHistoryModal({ versions: post.versions }) });
|
||||
attachMessageMenu(card, headRow, menuItems);
|
||||
if (isOwnerPost) {
|
||||
if (isOwnerPost && !threadsLayout) {
|
||||
if (post.timestampMs) timestamp.textContent = formatPostStamp(post.timestampMs);
|
||||
const meta = document.createElement('div');
|
||||
meta.className = 'channel-message-meta';
|
||||
@@ -2334,6 +2387,7 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
|
||||
onRepost: handlers.onRepost,
|
||||
onShare: handlers.onShare,
|
||||
onEdit: handlers.onEdit,
|
||||
channel: channelData.channel,
|
||||
isActive: handlers.isActive,
|
||||
});
|
||||
const key = messageRefKey(item.post.messageRef);
|
||||
@@ -2450,11 +2504,60 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
|
||||
};
|
||||
}
|
||||
|
||||
// Полные счётчики ответов для видимых записей: обсуждения подгружаются по одному (они же потом открываются сразу).
|
||||
function watchReplyTotals(screen) {
|
||||
if (!('IntersectionObserver' in window)) return () => {};
|
||||
let stopped = false;
|
||||
const queue = [];
|
||||
let running = false;
|
||||
const setCount = (card, total) => {
|
||||
card.querySelectorAll('.channel-action-discussion .channel-action-counter, .channel-action-reply .channel-action-counter')
|
||||
.forEach((counter) => { counter.textContent = total ? String(total) : ''; });
|
||||
};
|
||||
const pump = async () => {
|
||||
if (running) return;
|
||||
running = true;
|
||||
while (!stopped && queue.length) {
|
||||
const card = queue.shift();
|
||||
try {
|
||||
const data = await prefetchThreadPage(card.dataset.threadPath);
|
||||
if (!stopped && data && card.isConnected) setCount(card, threadTotalReplies(data));
|
||||
} catch {
|
||||
// Не удалось – остаётся серверный счётчик прямых ответов.
|
||||
}
|
||||
}
|
||||
running = false;
|
||||
};
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
entries.forEach((entry) => {
|
||||
if (!entry.isIntersecting) return;
|
||||
observer.unobserve(entry.target);
|
||||
queue.push(entry.target);
|
||||
});
|
||||
void pump();
|
||||
}, { rootMargin: '200px 0px' });
|
||||
screen.querySelectorAll('.channel-message-card[data-thread-path]').forEach((card) => observer.observe(card));
|
||||
return () => {
|
||||
stopped = true;
|
||||
observer.disconnect();
|
||||
};
|
||||
}
|
||||
|
||||
// Фоновая подгрузка канала в кэш, чтобы он открывался сразу (вызывается из обхода ленты каналов).
|
||||
export async function prefetchChannelPage(path) {
|
||||
const pathname = new URL(path, window.location.origin).pathname;
|
||||
const route = parseRouteFromPath(pathname);
|
||||
if (route.pageId !== 'channel-view') return false;
|
||||
const data = await loadFromApi(route, route.params.channelId || '');
|
||||
writePageData('channel', pathname, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Место под заглушку занимаем сразу, а сами строки рисуем, только если загрузка затянулась.
|
||||
function renderSkeleton(screen) {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'stack';
|
||||
wrap.append(createSkeletonCard(), createSkeletonCard(), createSkeletonCard());
|
||||
screen.append(wrap);
|
||||
window.setTimeout(() => { if (wrap.isConnected) wrap.append(createSkeletonRows('post', 3)); }, SKELETON_DELAY_MS);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
@@ -2500,16 +2603,16 @@ export function render({ navigate, route, chrome }) {
|
||||
const channelHeaderButton = document.createElement('button');
|
||||
channelHeaderButton.type = 'button';
|
||||
channelHeaderButton.className = 'topbar-identity channel-header-route-btn';
|
||||
channelHeaderButton.innerHTML = '<span class="topbar-identity__text"><span class="topbar-identity__title">Канал</span><span class="topbar-identity__sub">Загрузка…</span></span>';
|
||||
channelHeaderButton.innerHTML = '<span class="topbar-identity__text"><span class="topbar-identity__title">Канал</span><span class="topbar-identity__sub"> </span></span>';
|
||||
channelHeaderButton.disabled = true;
|
||||
|
||||
const header = createTopBar({
|
||||
center: channelHeaderButton,
|
||||
back: state.session.isAuthorized ? { onClick: () => navigate('channels-list') } : null,
|
||||
back: state.session.isAuthorized ? { onClick: () => navigateUp((route) => route?.pageId === 'channels-list', 'channels-list') } : null,
|
||||
className: 'channel-view-topbar topbar--identity',
|
||||
actions: [
|
||||
{
|
||||
icon: 'moreVertical',
|
||||
iconNode: createOverflowDots(),
|
||||
title: 'Действия канала',
|
||||
ariaLabel: 'Открыть меню канала',
|
||||
className: 'channel-header-more-btn',
|
||||
@@ -2535,7 +2638,7 @@ export function render({ navigate, route, chrome }) {
|
||||
iconHtml: iconHtml('list'),
|
||||
action: () => {
|
||||
if (activeOpenEntrypointHistory) activeOpenEntrypointHistory();
|
||||
else showToast('В этом канале пока нет оглавления');
|
||||
else showToast('В этом канале пока нет оглавления', { kind: 'info' });
|
||||
},
|
||||
});
|
||||
if (!apiData?.isOwnChannel) {
|
||||
@@ -2909,6 +3012,168 @@ export function render({ navigate, route, chrome }) {
|
||||
}
|
||||
};
|
||||
|
||||
// Рисует канал по готовым данным: и из кэша при возврате, и после загрузки с сервера.
|
||||
const paint = (apiData, restorePosition) => {
|
||||
activeSelector = apiData?.selector || null;
|
||||
const titleLabel = apiData?.channel?.displayTitle || apiData?.channel?.name || 'channel';
|
||||
const entrypointPosts = getEntrypointPosts(apiData?.posts);
|
||||
const openEntrypointHistory = () => {
|
||||
openEntrypointHistoryModal({
|
||||
channelTitle: titleLabel,
|
||||
posts: apiData?.posts,
|
||||
onSelect: (post) => {
|
||||
if (!flashAndScrollToMessage(post?.messageRef)) {
|
||||
showToast('Не удалось найти запись оглавления в ленте', { kind: 'error' });
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
activeOpenEntrypointHistory = openEntrypointHistory;
|
||||
if (channelHeaderButton) {
|
||||
// Под названием показываем владельца и короткое название, одинаково для ленты и /s/<номер>.
|
||||
const slug = String(apiData?.channel?.name || '').trim();
|
||||
const owner = String(apiData?.channel?.ownerName || extractLoginFromBlockchainName(apiData?.selector?.ownerBlockchainName) || '').trim();
|
||||
channelHeaderButton.replaceChildren();
|
||||
const text = document.createElement('span');
|
||||
text.className = 'topbar-identity__text';
|
||||
const titleNode = document.createElement('span');
|
||||
titleNode.className = 'topbar-identity__title';
|
||||
titleNode.textContent = titleLabel;
|
||||
const subNode = document.createElement('span');
|
||||
subNode.className = 'topbar-identity__sub';
|
||||
subNode.textContent = apiData?.isDiary ? 'Только вам' : `${owner ? `@${owner}` : ''}${owner && slug ? ' / ' : ''}${slug}`;
|
||||
text.append(titleNode, subNode);
|
||||
channelHeaderButton.append(createChannelAvatarElement(apiData?.channel, 40), text);
|
||||
channelHeaderButton.setAttribute('aria-label', `${titleLabel}. О канале`);
|
||||
channelHeaderButton.disabled = false;
|
||||
channelHeaderButton.onclick = (event) => {
|
||||
animatePress(event.currentTarget);
|
||||
const aboutRoute = makeShineChannelAboutRoute({
|
||||
ownerBlockchainName: apiData?.channel?.ownerBlockchainName || apiData?.selector?.ownerBlockchainName || '',
|
||||
channelRootBlockNumber: apiData?.selector?.channelRootBlockNumber ?? apiData?.channel?.channelRoot?.blockNumber ?? '',
|
||||
channelRootBlockHash: apiData?.selector?.channelRootBlockHash ?? apiData?.channel?.channelRoot?.blockHash ?? '',
|
||||
});
|
||||
if (aboutRoute) navigate(aboutRoute);
|
||||
};
|
||||
}
|
||||
activeChannelData = apiData;
|
||||
|
||||
if (channelMoreButton) {
|
||||
channelMoreButton.disabled = false;
|
||||
}
|
||||
if (channelEntrypointButton) {
|
||||
const canShowEntrypointButton = !apiData?.isDiary && entrypointPosts.length > 0;
|
||||
channelEntrypointButton.hidden = !canShowEntrypointButton;
|
||||
channelEntrypointButton.disabled = !canShowEntrypointButton;
|
||||
channelEntrypointButton.onclick = () => {
|
||||
const latestEntrypoint = entrypointPosts[0];
|
||||
if (!latestEntrypoint?.messageRef || !flashAndScrollToMessage(latestEntrypoint.messageRef)) {
|
||||
showToast('Не удалось найти актуальное оглавление', { kind: 'error' });
|
||||
}
|
||||
};
|
||||
}
|
||||
clearContent();
|
||||
const stopSeenTracking = renderBody(screen, navigate, routeKey, apiData, {
|
||||
chrome,
|
||||
restorePosition,
|
||||
scrollToMessageOrdinal,
|
||||
showStatus,
|
||||
isActive: () => !disposed,
|
||||
onAddMessage: activeAddMessage = async () => {
|
||||
if (apiData?.channel?.deleted) {
|
||||
const confirmed = await confirmDialog({
|
||||
title: 'Восстановить канал?',
|
||||
text: 'Новое сообщение восстановит канал: он перестанет считаться удалённым и снова появится в обычном списке ваших каналов.',
|
||||
confirmLabel: 'Восстановить и написать',
|
||||
});
|
||||
if (!confirmed || disposed) return;
|
||||
}
|
||||
openAddMessageModal({
|
||||
channelName: apiData?.channel?.name || '',
|
||||
channelTitle: apiData?.channel?.displayTitle || '',
|
||||
navigate,
|
||||
isActive: () => !disposed,
|
||||
onSubmit: async ({ text: bodyText, msgSubType }) => {
|
||||
try {
|
||||
await onAddPost(bodyText, msgSubType);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось добавить сообщение.'));
|
||||
}
|
||||
},
|
||||
});
|
||||
},
|
||||
onToggleLike: async (messageRef, action) => {
|
||||
try {
|
||||
await onToggleLike(messageRef, action);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
showStatus(toUserMessage(error, action === 'unlike' ? 'Не удалось убрать лайк.' : 'Не удалось поставить лайк.'));
|
||||
}
|
||||
},
|
||||
onReply: async (messageRef, text) => {
|
||||
try {
|
||||
await onReply(messageRef, text);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось отправить ответ.'));
|
||||
}
|
||||
},
|
||||
onRating: async (messageRef, text) => {
|
||||
try {
|
||||
await onRating(messageRef, text);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось отправить оценку.'));
|
||||
}
|
||||
},
|
||||
onStatusAction: async (post) => {
|
||||
try {
|
||||
await onStatusAction(post);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
showStatus(toUserMessage(error, 'Не удалось записать действие.'));
|
||||
}
|
||||
},
|
||||
onOpenEntrypointMenu: () => {
|
||||
openEntrypointMenuModal({
|
||||
onShowHistory: openEntrypointHistory,
|
||||
});
|
||||
},
|
||||
onRepost: async (messageRef) => {
|
||||
try {
|
||||
await onRepost(messageRef);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
showStatus(toUserMessage(error, 'Не удалось сделать репост.'));
|
||||
}
|
||||
},
|
||||
onAddPost: async (bodyText) => {
|
||||
try {
|
||||
await onAddPost(bodyText);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось добавить сообщение.'));
|
||||
}
|
||||
},
|
||||
onShare: onShare,
|
||||
onEdit: async (messageRef, text) => {
|
||||
try {
|
||||
await onEditPost(messageRef, text);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось изменить сообщение.'));
|
||||
}
|
||||
},
|
||||
onSubscribeChannel: (event) => subscribeToChannel(apiData, event),
|
||||
});
|
||||
const stopReplyTotals = watchReplyTotals(screen);
|
||||
cleanupSeenTracking = () => {
|
||||
if (typeof stopSeenTracking === 'function') stopSeenTracking();
|
||||
stopReplyTotals();
|
||||
};
|
||||
};
|
||||
|
||||
refresh = async () => {
|
||||
if (disposed) return;
|
||||
const seq = ++refreshSeq;
|
||||
@@ -2921,183 +3186,52 @@ export function render({ navigate, route, chrome }) {
|
||||
? getChannelScrollRoot()?.scrollTop
|
||||
: (returnedFromChannelPage ? readChannelPosition(positionKey) : undefined);
|
||||
if (!hadContent) clearContent();
|
||||
activeChannelData = null;
|
||||
activeOpenEntrypointHistory = null;
|
||||
activeSelector = null;
|
||||
showStatus('');
|
||||
channelHeaderButton.innerHTML = '<span class="channel-header-title">Канал</span><span class="channel-header-owner">Загрузка…</span>';
|
||||
channelHeaderButton.disabled = true;
|
||||
channelHeaderButton.onclick = null;
|
||||
if (channelMoreButton) channelMoreButton.disabled = true;
|
||||
if (channelEntrypointButton) {
|
||||
channelEntrypointButton.disabled = true;
|
||||
channelEntrypointButton.hidden = true;
|
||||
channelEntrypointButton.onclick = null;
|
||||
const cacheKey = window.location.pathname;
|
||||
// При возврате на канал сразу показываем прошлую загрузку, без заглушки и пустого кадра.
|
||||
const cached = hadContent ? null : readPageData('channel', cacheKey);
|
||||
let shown = hadContent;
|
||||
if (cached) {
|
||||
// Роутер вставляет экран в страницу сразу после render: ждём этого (до первого кадра), иначе прокрутку не к чему применить.
|
||||
await Promise.resolve();
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
try {
|
||||
paint(cached.data, restorePosition);
|
||||
shown = true;
|
||||
} catch (error) {
|
||||
dropPageData('channel', cacheKey);
|
||||
clearContent();
|
||||
}
|
||||
}
|
||||
|
||||
const skeleton = hadContent ? null : renderSkeleton(screen);
|
||||
if (!shown) {
|
||||
activeChannelData = null;
|
||||
activeOpenEntrypointHistory = null;
|
||||
activeSelector = null;
|
||||
channelHeaderButton.innerHTML = '<span class="channel-header-title">Канал</span><span class="channel-header-owner"> </span>';
|
||||
channelHeaderButton.disabled = true;
|
||||
channelHeaderButton.onclick = null;
|
||||
if (channelMoreButton) channelMoreButton.disabled = true;
|
||||
if (channelEntrypointButton) {
|
||||
channelEntrypointButton.disabled = true;
|
||||
channelEntrypointButton.hidden = true;
|
||||
channelEntrypointButton.onclick = null;
|
||||
}
|
||||
}
|
||||
const skeleton = shown ? null : renderSkeleton(screen);
|
||||
|
||||
try {
|
||||
const apiData = await loadFromApi(route, channelId);
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
activeSelector = apiData?.selector || null;
|
||||
const titleLabel = apiData?.channel?.displayTitle || apiData?.channel?.name || 'channel';
|
||||
const entrypointPosts = getEntrypointPosts(apiData?.posts);
|
||||
const openEntrypointHistory = () => {
|
||||
openEntrypointHistoryModal({
|
||||
channelTitle: titleLabel,
|
||||
posts: apiData?.posts,
|
||||
onSelect: (post) => {
|
||||
if (!flashAndScrollToMessage(post?.messageRef)) {
|
||||
showToast('Не удалось найти запись оглавления в ленте');
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
activeOpenEntrypointHistory = openEntrypointHistory;
|
||||
if (channelHeaderButton) {
|
||||
// Под названием показываем владельца и короткое название, одинаково для ленты и /s/<номер>.
|
||||
const slug = String(apiData?.channel?.name || '').trim();
|
||||
const owner = String(apiData?.channel?.ownerName || extractLoginFromBlockchainName(apiData?.selector?.ownerBlockchainName) || '').trim();
|
||||
channelHeaderButton.replaceChildren();
|
||||
const text = document.createElement('span');
|
||||
text.className = 'topbar-identity__text';
|
||||
const titleNode = document.createElement('span');
|
||||
titleNode.className = 'topbar-identity__title';
|
||||
titleNode.textContent = titleLabel;
|
||||
const subNode = document.createElement('span');
|
||||
subNode.className = 'topbar-identity__sub';
|
||||
subNode.textContent = apiData?.isDiary ? 'Только вам' : `${owner ? `@${owner}` : ''}${owner && slug ? ' / ' : ''}${slug}`;
|
||||
text.append(titleNode, subNode);
|
||||
channelHeaderButton.append(createChannelAvatarElement(apiData?.channel, 40), text);
|
||||
channelHeaderButton.setAttribute('aria-label', `${titleLabel}. О канале`);
|
||||
channelHeaderButton.disabled = false;
|
||||
channelHeaderButton.onclick = (event) => {
|
||||
animatePress(event.currentTarget);
|
||||
const aboutRoute = makeShineChannelAboutRoute({
|
||||
ownerBlockchainName: apiData?.channel?.ownerBlockchainName || apiData?.selector?.ownerBlockchainName || '',
|
||||
channelRootBlockNumber: apiData?.selector?.channelRootBlockNumber ?? apiData?.channel?.channelRoot?.blockNumber ?? '',
|
||||
channelRootBlockHash: apiData?.selector?.channelRootBlockHash ?? apiData?.channel?.channelRoot?.blockHash ?? '',
|
||||
});
|
||||
if (aboutRoute) navigate(aboutRoute);
|
||||
};
|
||||
}
|
||||
activeChannelData = apiData;
|
||||
|
||||
if (channelMoreButton) {
|
||||
channelMoreButton.disabled = false;
|
||||
}
|
||||
if (channelEntrypointButton) {
|
||||
const canShowEntrypointButton = !apiData?.isDiary && entrypointPosts.length > 0;
|
||||
channelEntrypointButton.hidden = !canShowEntrypointButton;
|
||||
channelEntrypointButton.disabled = !canShowEntrypointButton;
|
||||
channelEntrypointButton.onclick = () => {
|
||||
const latestEntrypoint = entrypointPosts[0];
|
||||
if (!latestEntrypoint?.messageRef || !flashAndScrollToMessage(latestEntrypoint.messageRef)) {
|
||||
showToast('Не удалось найти актуальное оглавление');
|
||||
}
|
||||
};
|
||||
}
|
||||
const signature = writePageData('channel', cacheKey, apiData);
|
||||
// Сервер вернул то же, что уже на экране, – ничего не трогаем, чтобы не дёргать ленту.
|
||||
if (cached && cached.signature === signature) return;
|
||||
skeleton?.remove();
|
||||
clearContent();
|
||||
cleanupSeenTracking = renderBody(screen, navigate, routeKey, apiData, {
|
||||
chrome,
|
||||
restorePosition,
|
||||
scrollToMessageOrdinal,
|
||||
showStatus,
|
||||
isActive: () => !disposed,
|
||||
onAddMessage: activeAddMessage = async () => {
|
||||
if (apiData?.channel?.deleted) {
|
||||
const confirmed = await confirmDialog({
|
||||
title: 'Восстановить канал?',
|
||||
text: 'Новое сообщение восстановит канал: он перестанет считаться удалённым и снова появится в обычном списке ваших каналов.',
|
||||
confirmLabel: 'Восстановить и написать',
|
||||
});
|
||||
if (!confirmed || disposed) return;
|
||||
}
|
||||
openAddMessageModal({
|
||||
channelName: apiData?.channel?.name || '',
|
||||
channelTitle: apiData?.channel?.displayTitle || '',
|
||||
navigate,
|
||||
isActive: () => !disposed,
|
||||
onSubmit: async ({ text: bodyText, msgSubType }) => {
|
||||
try {
|
||||
await onAddPost(bodyText, msgSubType);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось добавить сообщение.'));
|
||||
}
|
||||
},
|
||||
});
|
||||
},
|
||||
onToggleLike: async (messageRef, action) => {
|
||||
try {
|
||||
await onToggleLike(messageRef, action);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
showStatus(toUserMessage(error, action === 'unlike' ? 'Не удалось убрать лайк.' : 'Не удалось поставить лайк.'));
|
||||
}
|
||||
},
|
||||
onReply: async (messageRef, text) => {
|
||||
try {
|
||||
await onReply(messageRef, text);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось отправить ответ.'));
|
||||
}
|
||||
},
|
||||
onRating: async (messageRef, text) => {
|
||||
try {
|
||||
await onRating(messageRef, text);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось отправить оценку.'));
|
||||
}
|
||||
},
|
||||
onStatusAction: async (post) => {
|
||||
try {
|
||||
await onStatusAction(post);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
showStatus(toUserMessage(error, 'Не удалось записать действие.'));
|
||||
}
|
||||
},
|
||||
onOpenEntrypointMenu: () => {
|
||||
openEntrypointMenuModal({
|
||||
onShowHistory: openEntrypointHistory,
|
||||
});
|
||||
},
|
||||
onRepost: async (messageRef) => {
|
||||
try {
|
||||
await onRepost(messageRef);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
showStatus(toUserMessage(error, 'Не удалось сделать репост.'));
|
||||
}
|
||||
},
|
||||
onAddPost: async (bodyText) => {
|
||||
try {
|
||||
await onAddPost(bodyText);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось добавить сообщение.'));
|
||||
}
|
||||
},
|
||||
onShare: onShare,
|
||||
onEdit: async (messageRef, text) => {
|
||||
try {
|
||||
await onEditPost(messageRef, text);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось изменить сообщение.'));
|
||||
}
|
||||
},
|
||||
onSubscribeChannel: (event) => subscribeToChannel(apiData, event),
|
||||
});
|
||||
paint(apiData, shown ? getChannelScrollRoot()?.scrollTop : restorePosition);
|
||||
} catch (error) {
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
skeleton?.remove();
|
||||
if (hadContent) { showStatus(toUserMessage(error, 'Не удалось обновить канал.')); return; }
|
||||
if (shown) { showStatus(toUserMessage(error, 'Не удалось обновить канал.')); return; }
|
||||
channelHeaderButton.innerHTML = '<span class="channel-header-title">Канал</span>';
|
||||
if (isChannelsDemoMode()) {
|
||||
renderDemoFallback(screen, navigate, error);
|
||||
return;
|
||||
|
||||
@@ -5,7 +5,9 @@ import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { parseMessageAttachments } from '../services/attachment-format.js';
|
||||
import {
|
||||
animatePress,
|
||||
createSkeletonCard,
|
||||
createLoadErrorCard,
|
||||
createSkeletonRows,
|
||||
SKELETON_DELAY_MS,
|
||||
formatListTime,
|
||||
readChannelNotificationsState,
|
||||
showToast,
|
||||
@@ -20,6 +22,9 @@ import { createDropdownMenu } from '../components/dropdown-menu.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
||||
import { rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.js';
|
||||
import { pageDataAge } from '../services/page-data-cache.js';
|
||||
import { toPrettyPath } from '../router.js';
|
||||
import { prefetchChannelPage } from './channel-view.js';
|
||||
|
||||
export const pageMeta = { id: 'channels-list', title: 'Каналы', shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
|
||||
|
||||
@@ -710,6 +715,35 @@ function mapApiFeed(feed, notificationsState, diaryPayload = null) {
|
||||
return { ownChannels, followedUserChannels, subscribedChannels, index };
|
||||
}
|
||||
|
||||
const PREFETCH_CHANNELS = 6;
|
||||
const PREFETCH_FRESH_MS = 50_000;
|
||||
|
||||
// Фоновое обновление ленты каналов и самых активных каналов: экран «Каналы» и сами каналы
|
||||
// открываются сразу из памяти. Запросы идут по одному, чтобы не нагружать сервер.
|
||||
export async function refreshChannelsInBackground({ isCurrent = () => true } = {}) {
|
||||
if (!state.session.isAuthorized || state.session.isLocalDemo) return;
|
||||
const login = state.session.login;
|
||||
const feed = await authService.listSubscriptionsFeed(login, 200);
|
||||
if (!isCurrent() || state.session.login !== login) return;
|
||||
const groups = mapApiFeed(feed, {}, null);
|
||||
setChannelsFeed(feed, groups.index);
|
||||
const routes = toListModel(groups)
|
||||
.filter((row) => row.route)
|
||||
.sort((a, b) => Number(b.lastMessageAt || 0) - Number(a.lastMessageAt || 0))
|
||||
.slice(0, PREFETCH_CHANNELS)
|
||||
.map((row) => `/${toPrettyPath(row.route)}`);
|
||||
for (const route of routes) {
|
||||
if (!isCurrent() || state.session.login !== login) return;
|
||||
const pathname = new URL(route, window.location.origin).pathname;
|
||||
if (pathname === window.location.pathname || pageDataAge('channel', pathname) < PREFETCH_FRESH_MS) continue;
|
||||
try {
|
||||
await prefetchChannelPage(pathname);
|
||||
} catch {
|
||||
// Фоновая подгрузка не должна мешать: канал загрузится обычным путём при открытии.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function toListModel(groups) {
|
||||
return [
|
||||
...(groups.ownChannels || []),
|
||||
@@ -725,7 +759,7 @@ function renderEmptyState(listState, navigate) {
|
||||
heading.textContent = listState.query ? 'Ничего не найдено' : listState.viewMode === CHANNELS_VIEW_DELETED ? 'Удалённых каналов нет' : listState.viewMode === CHANNELS_VIEW_FOLLOWING ? 'Пока нет подписок' : listState.viewMode === CHANNELS_VIEW_OWNED ? 'Здесь будут ваши каналы' : 'Откройте свой первый канал';
|
||||
const text = document.createElement('p');
|
||||
text.className = 'meta-muted';
|
||||
text.textContent = listState.viewMode === CHANNELS_VIEW_DELETED ? 'Здесь появятся только ваши каналы, помеченные как удалённые.' : state.session.isAuthorized ? 'Найдите канал по названию, адресу или автору — либо создайте свой.' : 'Войдите, чтобы видеть свои каналы и подписки.';
|
||||
text.textContent = listState.viewMode === CHANNELS_VIEW_DELETED ? 'Здесь появятся только ваши каналы, помеченные как удалённые.' : state.session.isAuthorized ? 'Найдите канал по названию, адресу или автору – либо создайте свой.' : 'Войдите, чтобы видеть свои каналы и подписки.';
|
||||
const action = document.createElement('button');
|
||||
action.type = 'button';
|
||||
action.className = 'primary-btn';
|
||||
@@ -737,34 +771,15 @@ function renderEmptyState(listState, navigate) {
|
||||
}
|
||||
|
||||
function renderSkeletonList(container, count = 4) {
|
||||
container.innerHTML = '';
|
||||
const list = document.createElement('div');
|
||||
list.className = 'stack';
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
list.append(createSkeletonCard());
|
||||
}
|
||||
container.append(list);
|
||||
container.replaceChildren(createSkeletonRows('list', count));
|
||||
}
|
||||
|
||||
function renderErrorState(container, error, onRetry) {
|
||||
const errCard = document.createElement('div');
|
||||
errCard.className = 'card stack channels-status';
|
||||
|
||||
const title = document.createElement('strong');
|
||||
title.textContent = 'Не удалось загрузить каналы';
|
||||
|
||||
const details = document.createElement('p');
|
||||
details.className = 'meta-muted';
|
||||
details.textContent = toUserMessage(error, 'Проверьте подключение к серверу и повторите попытку.');
|
||||
|
||||
const retry = document.createElement('button');
|
||||
retry.className = 'primary-btn';
|
||||
retry.type = 'button';
|
||||
retry.textContent = 'Повторить';
|
||||
retry.addEventListener('click', onRetry);
|
||||
|
||||
errCard.append(title, details, retry);
|
||||
container.append(errCard);
|
||||
container.append(createLoadErrorCard({
|
||||
title: 'Не удалось загрузить каналы',
|
||||
message: toUserMessage(error, 'Проверьте подключение и повторите попытку.'),
|
||||
onRetry,
|
||||
}));
|
||||
}
|
||||
|
||||
function renderDemoFallback(container, navigate, error, onRetry, { localOnly = false } = {}) {
|
||||
@@ -888,7 +903,7 @@ function renderListContent({ screen, container, listState, navigate, refreshFeed
|
||||
}
|
||||
|
||||
const list = document.createElement('div');
|
||||
list.className = 'stack channels-groups channels-list-body-fade';
|
||||
list.className = 'stack channels-groups';
|
||||
|
||||
const rerenderList = () => renderListContent({ screen, container, listState, navigate, refreshFeed });
|
||||
|
||||
@@ -934,7 +949,24 @@ function renderListContent({ screen, container, listState, navigate, refreshFeed
|
||||
async function loadFeedAndRender({ screen, listState, contentEl, navigate, silent = false }) {
|
||||
if (listState.disposed) return;
|
||||
const seq = ++listState.loadSeq;
|
||||
if (!silent) renderSkeletonList(contentEl, 5);
|
||||
// Уже загруженный список показываем сразу и тихо обновляем; заглушка – только при долгой первой загрузке.
|
||||
if (!silent && state.session.isAuthorized && state.channelsFeed && listState.viewMode !== CHANNELS_VIEW_DELETED) {
|
||||
listState.channels = toListModel(mapApiFeed(state.channelsFeed, listState.notificationsState, null));
|
||||
renderListContent({
|
||||
screen,
|
||||
container: contentEl,
|
||||
listState,
|
||||
navigate,
|
||||
refreshFeed: async () => loadFeedAndRender({ screen, listState, contentEl, navigate }),
|
||||
});
|
||||
silent = true;
|
||||
}
|
||||
if (!silent) {
|
||||
window.setTimeout(() => {
|
||||
if (!listState.disposed && seq === listState.loadSeq && !contentEl.hasChildNodes()) renderSkeletonList(contentEl, 5);
|
||||
}, SKELETON_DELAY_MS);
|
||||
contentEl.replaceChildren();
|
||||
}
|
||||
|
||||
if (!state.session.isAuthorized) {
|
||||
setChannelsFeed(null, {});
|
||||
@@ -1045,7 +1077,7 @@ export function render({ navigate, route, chrome }) {
|
||||
className: 'topbar--root',
|
||||
actions: [
|
||||
{
|
||||
icon: 'moreVertical',
|
||||
iconNode: createOverflowDots(),
|
||||
title: 'Меню каналов',
|
||||
ariaLabel: 'Открыть меню каналов',
|
||||
className: 'channels-menu-btn',
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
// «Медиа и файлы» личной переписки: сетка фото и видео и список документов по месяцам.
|
||||
// История догружается с сервера целиком; превью расшифровываются, только когда плитка видна.
|
||||
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 } from '../state.js';
|
||||
import { navigateUp } from '../router.js';
|
||||
|
||||
export const pageMeta = { id: 'chat-media-view', title: 'Медиа и файлы' };
|
||||
|
||||
const monthTitle = new Intl.DateTimeFormat('ru-RU', { month: 'long', year: 'numeric' });
|
||||
|
||||
// Все вложения переписки, от новых к старым.
|
||||
function collectAttachments(chatId) {
|
||||
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 attachment of list) {
|
||||
if (attachment?.kind === 'voice') continue;
|
||||
const entry = { attachment, timeMs: resolveMessageTimeMs(msg), 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 raw = entry.timeMs ? monthTitle.format(new Date(entry.timeMs)) : 'Без даты';
|
||||
const label = raw.charAt(0).toUpperCase() + raw.slice(1);
|
||||
const last = groups[groups.length - 1];
|
||||
if (last?.label === label) last.items.push(entry);
|
||||
else groups.push({ 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: 'Медиа и файлы',
|
||||
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 = `Переписка с ${peerName}`;
|
||||
|
||||
const tabs = document.createElement('div');
|
||||
tabs.className = 'tabs tabs--auto tabs--dense chat-media-tabs';
|
||||
tabs.setAttribute('role', 'radiogroup');
|
||||
tabs.setAttribute('aria-label', 'Что показать');
|
||||
const tabButtons = new Map();
|
||||
for (const [value, label] of [['media', 'Медиа'], ['files', 'Файлы']]) {
|
||||
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' ? 'Видео' : 'Фото'} ${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);
|
||||
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
|
||||
? 'Не удалось загрузить всю историю – показано то, что уже есть на устройстве.'
|
||||
: '<span class="dm-history-loader__spinner" aria-hidden="true"></span><span>Загружаю историю переписки…</span>';
|
||||
thumbObserver?.disconnect();
|
||||
body.replaceChildren();
|
||||
|
||||
const entries = activeTab === 'media' ? media : files;
|
||||
if (!entries.length) {
|
||||
if (!loading) renderEmpty(activeTab === 'media' ? 'В этой переписке пока нет фото и видео.' : 'В этой переписке пока нет файлов.');
|
||||
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' ? 'Вы' : 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;
|
||||
}
|
||||
+628
-254
File diff suppressed because it is too large
Load Diff
@@ -1,192 +1,184 @@
|
||||
// «Новый чат»: выбрать, кому написать. Пока поле пустое – свои близкие и друзья; при вводе –
|
||||
// сначала свои (мгновенно, на устройстве), затем вся сеть (по имени и логину). Нажатие
|
||||
// открывает переписку, профиль – кнопкой справа.
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { authService } from '../state.js';
|
||||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { loadProfileSnapshot } from '../services/user-profile-params.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', title: 'Поиск контактов' };
|
||||
const searchAvatarSnapshotCache = new Map();
|
||||
const searchAvatarPendingByLogin = new Map();
|
||||
export const pageMeta = { id: 'contact-search-view', title: 'Новый чат' };
|
||||
|
||||
async function loadSearchAvatarSnapshot(login) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
if (!cleanLogin) return null;
|
||||
const key = cleanLogin.toLowerCase();
|
||||
if (searchAvatarSnapshotCache.has(key)) return searchAvatarSnapshotCache.get(key);
|
||||
if (searchAvatarPendingByLogin.has(key)) return searchAvatarPendingByLogin.get(key);
|
||||
const pending = loadProfileSnapshot(cleanLogin)
|
||||
.then((snapshot) => {
|
||||
searchAvatarSnapshotCache.set(key, snapshot || null);
|
||||
searchAvatarPendingByLogin.delete(key);
|
||||
return snapshot || null;
|
||||
})
|
||||
.catch(() => {
|
||||
searchAvatarSnapshotCache.set(key, null);
|
||||
searchAvatarPendingByLogin.delete(key);
|
||||
return null;
|
||||
});
|
||||
searchAvatarPendingByLogin.set(key, pending);
|
||||
return pending;
|
||||
const RELATION_TEXT = { close_friend: 'близкий друг', friend: 'друг', contact: 'контакт' };
|
||||
const RELATION_ORDER = { close_friend: 0, friend: 1, contact: 2 };
|
||||
|
||||
function searchText(value) {
|
||||
return String(value || '').toLowerCase().replaceAll('ё', 'е').trim();
|
||||
}
|
||||
|
||||
function createSearchAvatar(login) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const title = cleanLogin ? `Профиль ${cleanLogin}` : '';
|
||||
const avatarEl = renderUserAvatar({
|
||||
login: cleanLogin || 'unknown',
|
||||
size: 'md',
|
||||
className: 'avatar',
|
||||
title,
|
||||
});
|
||||
if (!cleanLogin) return avatarEl;
|
||||
void loadSearchAvatarSnapshot(cleanLogin).then((snapshot) => {
|
||||
if (!avatarEl.isConnected) return;
|
||||
const upgraded = renderUserAvatar({
|
||||
login: cleanLogin,
|
||||
avatar: snapshot?.avatar?.source
|
||||
? {
|
||||
ar: String(snapshot.avatar.txId || snapshot.avatar.ar || '').trim(),
|
||||
sha256Hex: String(snapshot?.avatar?.sha256Hex || '').trim().toLowerCase(),
|
||||
}
|
||||
: null,
|
||||
size: 'md',
|
||||
className: 'avatar',
|
||||
title,
|
||||
});
|
||||
avatarEl.replaceWith(upgraded);
|
||||
});
|
||||
return avatarEl;
|
||||
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}) {
|
||||
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 = 'text';
|
||||
input.name = 'contact';
|
||||
input.placeholder = 'Логин или его начало';
|
||||
input.setAttribute('aria-label', 'Логин для поиска');
|
||||
input.type = 'search';
|
||||
input.placeholder = 'Имя или логин';
|
||||
input.setAttribute('aria-label', 'Кому написать');
|
||||
input.enterKeyHint = 'search';
|
||||
input.autocomplete = 'off';
|
||||
input.maxLength = 80;
|
||||
field.append(input);
|
||||
|
||||
const resultsCard = document.createElement('section');
|
||||
resultsCard.className = 'stack contact-search-results';
|
||||
resultsCard.hidden = true;
|
||||
const results = document.createElement('div');
|
||||
results.className = 'contact-search-results';
|
||||
|
||||
const status = document.createElement('p');
|
||||
status.className = 'contact-search-results-title';
|
||||
const openChat = (login) => navigate(`chat/${encodeURIComponent(normalizeDmChatId(login))}`);
|
||||
|
||||
const resultsList = document.createElement('div');
|
||||
resultsList.className = 'stack dm-list';
|
||||
|
||||
const renderResults = (matches, query) => {
|
||||
resultsList.innerHTML = '';
|
||||
|
||||
if (!query.trim()) {
|
||||
status.textContent = '';
|
||||
resultsCard.hidden = true;
|
||||
return;
|
||||
}
|
||||
|
||||
resultsCard.hidden = false;
|
||||
|
||||
if (!matches.length) {
|
||||
status.textContent = 'Найдено пользователей: 0';
|
||||
return;
|
||||
}
|
||||
|
||||
status.textContent = `Найдено пользователей: ${matches.length}`;
|
||||
|
||||
matches.forEach((login) => {
|
||||
const row = document.createElement('article');
|
||||
row.className = 'list-item dm-dialog-card';
|
||||
const avatarEl = createSearchAvatar(login);
|
||||
row.innerHTML = `
|
||||
<div class="contact-search-result-main">
|
||||
<strong class="dm-row-title">${login}</strong>
|
||||
</div>
|
||||
<span class="dm-chevron" aria-hidden="true">›</span>
|
||||
`;
|
||||
row.prepend(avatarEl);
|
||||
row.addEventListener('click', () => {
|
||||
navigate(makeProfileRoute(login));
|
||||
});
|
||||
resultsList.append(row);
|
||||
function personRow(person, sub) {
|
||||
return createPersonRow({
|
||||
login: person.login,
|
||||
name: displayName(person),
|
||||
firstName: person.firstName,
|
||||
lastName: person.lastName,
|
||||
avatar: person.avatar || (person.avatarAr ? { ar: person.avatarAr } : null),
|
||||
ring: person.relationFlag === 'close_friend' ? 'close' : '',
|
||||
sub,
|
||||
onClick: () => openChat(person.login),
|
||||
actions: [{ icon: 'profile', label: 'Профиль', onClick: () => navigate(makeProfileRoute(person.login)) }],
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
const runSearch = async () => {
|
||||
const query = input.value.trim();
|
||||
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 ? `Ваши связи · ${ownShown.length}` : 'Близкие и друзья'));
|
||||
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('Во всей сети'));
|
||||
if (remote.loading) frag.append(createLoadingState({ label: 'Ищу', delayMs: 150 }));
|
||||
else if (remote.error) {
|
||||
const note = document.createElement('p');
|
||||
note.className = 'empty-note';
|
||||
note.textContent = toUserMessage(remote.error, 'Поиск по сети сейчас недоступен.');
|
||||
frag.append(note);
|
||||
} else {
|
||||
others.forEach((user) => {
|
||||
const person = { login: String(user.login || ''), displayName: user.displayName, avatarAr: user.avatarAr };
|
||||
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: 'Никого не нашлось', text: 'Проверьте имя или логин.' }));
|
||||
}
|
||||
} else if (!ownShown.length) {
|
||||
frag.append(createStateMessage({
|
||||
icon: 'message',
|
||||
title: query ? 'Никого не нашлось' : 'Кому написать?',
|
||||
text: 'Начните вводить имя или логин – поищем среди ваших связей и во всей сети.',
|
||||
}));
|
||||
}
|
||||
results.append(frag);
|
||||
}
|
||||
|
||||
async function runRemote() {
|
||||
const query = searchText(input.value).replace(/^@/, '');
|
||||
const seq = ++searchSeq;
|
||||
if (!query) {
|
||||
renderResults([], '');
|
||||
if (query.length < 2) {
|
||||
remote = { query: '', items: [], loading: false, error: null };
|
||||
renderResults();
|
||||
return;
|
||||
}
|
||||
|
||||
remote = { query, items: [], loading: true, error: null };
|
||||
renderResults();
|
||||
try {
|
||||
const logins = await authService.searchUsers(query);
|
||||
if (seq !== searchSeq) return;
|
||||
renderResults((logins || []).slice(0, 5), query);
|
||||
} catch (e) {
|
||||
if (seq !== searchSeq) return;
|
||||
status.textContent = `Ошибка поиска: ${e.message || 'unknown'}`;
|
||||
resultsCard.hidden = false;
|
||||
resultsList.innerHTML = '';
|
||||
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 };
|
||||
}
|
||||
};
|
||||
|
||||
const scheduleSearch = () => {
|
||||
if (searchTimer) window.clearTimeout(searchTimer);
|
||||
searchTimer = window.setTimeout(() => {
|
||||
searchTimer = 0;
|
||||
void runSearch();
|
||||
}, 500);
|
||||
};
|
||||
|
||||
const searchButton = document.createElement('button');
|
||||
searchButton.className = 'search-field__action';
|
||||
searchButton.type = 'button';
|
||||
searchButton.textContent = 'Найти';
|
||||
searchButton.addEventListener('click', async () => {
|
||||
if (searchTimer) {
|
||||
window.clearTimeout(searchTimer);
|
||||
searchTimer = 0;
|
||||
}
|
||||
await runSearch();
|
||||
});
|
||||
renderResults();
|
||||
}
|
||||
|
||||
input.addEventListener('input', () => {
|
||||
scheduleSearch();
|
||||
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();
|
||||
searchButton.click();
|
||||
results.querySelector('.person-row__main')?.click();
|
||||
});
|
||||
|
||||
const formCard = document.createElement('label');
|
||||
formCard.className = 'search-field contact-search-field';
|
||||
formCard.innerHTML = `<span class="search-field__icon" aria-hidden="true">${iconHtml('search')}</span>`;
|
||||
formCard.append(input, searchButton);
|
||||
|
||||
resultsCard.append(status, resultsList);
|
||||
// Свои связи – из того же ответа, что и список чатов.
|
||||
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: 'Найти человека',
|
||||
back: { label: '←', onClick: () => navigate('messages-list') },
|
||||
}));
|
||||
screen.append(
|
||||
formCard,
|
||||
resultsCard,
|
||||
);
|
||||
title: 'Новый чат',
|
||||
back: { onClick: () => navigate('messages-list') },
|
||||
}));
|
||||
screen.append(field, results);
|
||||
results.append(createLoadingState({ label: 'Загружаю связи' }));
|
||||
void loadMine();
|
||||
window.requestAnimationFrame(() => { if (!disposed) input.focus(); });
|
||||
|
||||
screen.cleanup = () => {
|
||||
disposed = true;
|
||||
searchSeq += 1;
|
||||
if (searchTimer) window.clearTimeout(searchTimer);
|
||||
};
|
||||
|
||||
|
||||
@@ -618,7 +618,7 @@ export function render({navigate, chrome}) {
|
||||
await reloadRequests({ silent: true });
|
||||
cleanupEvent = authService.onEvent('IncomingTrustedDeviceLoginRequest', () => {
|
||||
if (disposed) return;
|
||||
showToast('Пришла новая заявка на вход через доверенное устройство');
|
||||
showToast('Пришла новая заявка на вход через доверенное устройство', { kind: 'info' });
|
||||
void reloadRequests({ silent: true });
|
||||
});
|
||||
} catch (error) {
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
makeKeyTransferText,
|
||||
renderQrSvg,
|
||||
} from '../services/qr-key-transfer-service.js';
|
||||
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'device-qr-view', title: 'Показать QR-код' };
|
||||
|
||||
@@ -56,7 +57,7 @@ export function render({navigate, chrome}) {
|
||||
qrEl.textContent = '';
|
||||
loginEl.textContent = 'Логин: нет данных';
|
||||
keysEl.textContent = 'Ключи: нет данных';
|
||||
statusEl.textContent = error?.message || 'Не удалось подготовить QR-код.';
|
||||
statusEl.textContent = actionErrorText('Не удалось подготовить QR-код', error);
|
||||
statusEl.style.display = '';
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import {
|
||||
authService,
|
||||
isSessionInvalidError,
|
||||
@@ -72,9 +75,9 @@ export function render({navigate, route, chrome}) {
|
||||
|
||||
actionBtn.addEventListener('click', async () => {
|
||||
const isCurrentSession = session.sessionId === state.session.sessionId;
|
||||
const confirmed = window.confirm(
|
||||
isCurrentSession ? 'Хотите завершить текущую сессию?' : 'Хотите завершить этот сеанс?',
|
||||
);
|
||||
const confirmed = await confirmDialog(isCurrentSession
|
||||
? { title: 'Выйти на этом устройстве?', text: 'Чтобы снова пользоваться приложением здесь, придётся войти заново.', confirmLabel: 'Выйти', danger: true }
|
||||
: { title: 'Завершить сеанс?', text: 'Это устройство выйдет из аккаунта.', confirmLabel: 'Завершить', danger: true });
|
||||
if (!confirmed) return;
|
||||
|
||||
try {
|
||||
@@ -90,7 +93,7 @@ export function render({navigate, route, chrome}) {
|
||||
} catch (error) {
|
||||
if (!isSessionInvalidError(error)) {
|
||||
setAuthError(error.message);
|
||||
window.alert(error.message);
|
||||
showToast(toUserMessage(error, 'Не удалось завершить сеанс.'), { kind: 'error' });
|
||||
return;
|
||||
}
|
||||
if (isCurrentSession) {
|
||||
@@ -112,7 +115,7 @@ export function render({navigate, route, chrome}) {
|
||||
return;
|
||||
}
|
||||
setAuthError(error.message);
|
||||
window.alert(error.message);
|
||||
showToast(toUserMessage(error, 'Действие не выполнено. Попробуйте ещё раз.'), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||
import {
|
||||
authService,
|
||||
isSessionInvalidError,
|
||||
refreshSessions,
|
||||
setAuthError,
|
||||
setAuthInfo,
|
||||
state,
|
||||
terminateCurrentSession,
|
||||
@@ -151,7 +152,13 @@ export function render({navigate, chrome}) {
|
||||
closeAll.type = 'button';
|
||||
closeAll.textContent = 'Закрыть все остальные сеансы';
|
||||
closeAll.addEventListener('click', async () => {
|
||||
if (!window.confirm('Все остальные активные сеансы будут закрыты. Продолжить?')) return;
|
||||
const confirmed = await confirmDialog({
|
||||
title: 'Закрыть остальные сеансы?',
|
||||
text: 'Все другие устройства выйдут из аккаунта. Это устройство останется.',
|
||||
confirmLabel: 'Закрыть',
|
||||
danger: true,
|
||||
});
|
||||
if (!confirmed) return;
|
||||
closeAll.disabled = true;
|
||||
try {
|
||||
const result = await authService.closeOtherSessions();
|
||||
@@ -164,8 +171,7 @@ export function render({navigate, chrome}) {
|
||||
await terminateCurrentSession({ infoMessage: 'Сессия на этом устройстве уже завершена. Выполните вход заново.' });
|
||||
return;
|
||||
}
|
||||
setAuthError(error.message);
|
||||
showToast(error.message, { kind: 'error' });
|
||||
showToast(actionErrorText('Не удалось закрыть сеансы', error), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
const othersList = document.createElement('div');
|
||||
@@ -188,8 +194,7 @@ export function render({navigate, chrome}) {
|
||||
});
|
||||
return;
|
||||
}
|
||||
setAuthError(error.message);
|
||||
showToast(error.message, { kind: 'error' });
|
||||
showToast(actionErrorText('Не удалось обновить список сеансов', error), { kind: 'error' });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import {
|
||||
authorizeLocalDemoSession,
|
||||
isLocalDemoAvailable,
|
||||
@@ -180,7 +182,7 @@ export function render({ navigate }) {
|
||||
await saveEntrySettings(draft);
|
||||
navigate('start-view');
|
||||
} catch (error) {
|
||||
window.alert(error?.message || 'Не удалось сохранить настройки входа.');
|
||||
showToast(toUserMessage(error, 'Не удалось сохранить настройки входа.'), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -176,7 +176,7 @@ export function render({navigate,chrome}){
|
||||
await refresh();
|
||||
};
|
||||
go.addEventListener('click',()=>void run().catch(e=>{err.textContent=e?.message||String(e);go.disabled=false;}));
|
||||
const nodes=[statusCard(s),note('Локальные входящие и исходящие копии будут приведены к новому client key. Клиент сначала пробует старый ключ, а для сообщений, уже пришедших после смены PDA, — новый. На сервер собеседника повторная отправка не выполняется.'),progress];if(oldP)nodes.push(oldP.wrap);if(newP)nodes.push(newP.wrap);nodes.push(go,err);setRoot(...nodes);
|
||||
const nodes=[statusCard(s),note('Локальные входящие и исходящие копии будут приведены к новому client key. Клиент сначала пробует старый ключ, а для сообщений, уже пришедших после смены PDA, – новый. На сервер собеседника повторная отправка не выполняется.'),progress];if(oldP)nodes.push(oldP.wrap);if(newP)nodes.push(newP.wrap);nodes.push(go,err);setRoot(...nodes);
|
||||
if(cachedOldBundle&&cachedNewBundle)void run().catch(e=>{err.textContent=e?.message||String(e);go.disabled=false;});
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
describeTransferKeys,
|
||||
parseKeyTransferText,
|
||||
} from '../services/qr-key-transfer-service.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { actionErrorText, toUserMessage } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'login-camera-view', title: 'Войти по QR-коду', showAppChrome: false };
|
||||
|
||||
@@ -184,7 +184,7 @@ export function render({ navigate }) {
|
||||
await video.play?.();
|
||||
scanLoop();
|
||||
} catch (error) {
|
||||
cameraError.textContent = error?.message || 'Не удалось открыть камеру. Проверьте разрешения браузера.';
|
||||
cameraError.textContent = actionErrorText('Не удалось открыть камеру. Проверьте разрешения браузера', error);
|
||||
cameraError.style.display = '';
|
||||
setStatus(status, cameraError.textContent, 'error');
|
||||
}
|
||||
|
||||
@@ -3,15 +3,29 @@ import {
|
||||
getChatMessages,
|
||||
isSessionInvalidError,
|
||||
normalizeDmChatId,
|
||||
rememberDmPeer,
|
||||
setContacts,
|
||||
state,
|
||||
terminateCurrentSession,
|
||||
} from '../state.js';
|
||||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createSearchTopBar, createTopBar } from '../components/topbar.js';
|
||||
import { createDropdownMenu } from '../components/dropdown-menu.js';
|
||||
import { createDmMuteMenuItem } from '../components/dm-mute-menu.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import {
|
||||
DM_CHAT_PREFS_EVENT,
|
||||
getPinnedDmChats,
|
||||
isDmChatMuted,
|
||||
setDmChatPinned,
|
||||
} from '../services/dm-chat-prefs.js';
|
||||
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||||
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
||||
import { formatListTime } from '../services/channels-ux.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { matchesPeopleQuery } from '../services/people-search.js';
|
||||
import { createErrorState, createLoadingState, createStateMessage } from '../components/feedback.js';
|
||||
import { openHistoryLayer } from '../router.js';
|
||||
|
||||
export const pageMeta = { id: 'messages-list', title: 'Личные сообщения' };
|
||||
const PREVIEW_MAX_LEN = 200;
|
||||
@@ -48,7 +62,9 @@ async function loadDmAvatarSnapshot(login) {
|
||||
return pending;
|
||||
}
|
||||
|
||||
function createDmAvatar(login, { className = '', avatar = null, firstName = '', lastName = '' } = {}) {
|
||||
// whenVisible(fn) – отложить запрос профиля до появления строки на экране: в списке на сотни
|
||||
// контактов иначе уходят сотни запросов сразу.
|
||||
function createDmAvatar(login, { className = '', avatar = null, firstName = '', lastName = '', whenVisible = null } = {}) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const title = cleanLogin ? `Профиль ${cleanLogin}` : '';
|
||||
const avatarEl = renderUserAvatar({
|
||||
@@ -61,10 +77,13 @@ function createDmAvatar(login, { className = '', avatar = null, firstName = '',
|
||||
className,
|
||||
});
|
||||
if (!cleanLogin || avatar?.ar || avatar?.sha256Hex) return avatarEl;
|
||||
void loadDmAvatarSnapshot(cleanLogin).then((snapshot) => {
|
||||
if (!avatarEl.isConnected) return;
|
||||
const upgrade = () => loadDmAvatarSnapshot(cleanLogin).then((snapshot) => {
|
||||
// Фото нет – оставляем инициалы имени как есть (раньше подменялись на букву логина).
|
||||
if (!avatarEl.isConnected || !snapshot?.avatar?.source) return;
|
||||
const upgraded = renderUserAvatar({
|
||||
login: cleanLogin,
|
||||
firstName: String(firstName || '').trim(),
|
||||
lastName: String(lastName || '').trim(),
|
||||
avatar: snapshot?.avatar?.source
|
||||
? {
|
||||
ar: String(snapshot.avatar.txId || snapshot.avatar.ar || '').trim(),
|
||||
@@ -78,6 +97,8 @@ function createDmAvatar(login, { className = '', avatar = null, firstName = '',
|
||||
upgraded.classList.add('avatar');
|
||||
avatarEl.replaceWith(upgraded);
|
||||
});
|
||||
if (typeof whenVisible === 'function') whenVisible(avatarEl, upgrade);
|
||||
else void upgrade();
|
||||
return avatarEl;
|
||||
}
|
||||
|
||||
@@ -112,12 +133,13 @@ function clipPreviewText(text, maxLen = PREVIEW_MAX_LEN) {
|
||||
}
|
||||
|
||||
const DM_PREVIEW_ENCRYPTED = 'Зашифрованное сообщение';
|
||||
const DM_PREVIEW_EMPTY = 'Нет сообщений';
|
||||
|
||||
async function resolveDialogPreview(dialog) {
|
||||
const localText = clipPreviewText(String(dialog?.lastMessageText || '').trim());
|
||||
if (localText) return localText;
|
||||
const blobB64 = String(dialog?.lastMessageBlobB64 || '').trim();
|
||||
if (!blobB64) return 'Диалог пока пуст.';
|
||||
if (!blobB64) return DM_PREVIEW_EMPTY;
|
||||
|
||||
const cacheKey = [
|
||||
blobB64,
|
||||
@@ -181,6 +203,10 @@ function latestLocalDialogMessage(peerLogin) {
|
||||
return { text, timeMs: resolveLocalMessageTimeMs(latest) };
|
||||
}
|
||||
|
||||
// Последний загруженный список чатов (в памяти вкладки): при возврате на «Чаты» он рисуется
|
||||
// сразу, без пустого кадра, и тихо обновляется с сервера.
|
||||
let lastChatList = null; // { login, items }
|
||||
|
||||
function formatChatRowTime(ts) {
|
||||
return formatListTime(ts);
|
||||
}
|
||||
@@ -198,6 +224,7 @@ export function render({ navigate, chrome }) {
|
||||
const login = String(state.session.login || '').trim();
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack dm-screen dm-list-screen';
|
||||
let disposed = false;
|
||||
let currentChatFilter = 'all';
|
||||
const CHAT_FILTERS = [
|
||||
['all', 'Все'],
|
||||
@@ -237,23 +264,122 @@ export function render({ navigate, chrome }) {
|
||||
event.preventDefault();
|
||||
});
|
||||
|
||||
// Шапка: поиск по своим чатам и контактам (мгновенно, на устройстве) и «Новый чат».
|
||||
let chatQuery = '';
|
||||
let chatSearch = null;
|
||||
const head = createTopBar({
|
||||
title: 'Чаты',
|
||||
className: 'topbar--root',
|
||||
actions: [
|
||||
{
|
||||
icon: 'search',
|
||||
title: 'Найти человека',
|
||||
ariaLabel: 'Найти человека',
|
||||
title: 'Поиск по чатам',
|
||||
ariaLabel: 'Поиск по чатам',
|
||||
className: 'messages-search-btn',
|
||||
onClick: () => openChatsSearch(),
|
||||
},
|
||||
{
|
||||
icon: 'compose',
|
||||
title: 'Новый чат',
|
||||
ariaLabel: 'Новый чат',
|
||||
className: 'messages-compose-btn',
|
||||
onClick: () => navigate('contact-search-view'),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
function openChatsSearch() {
|
||||
if (chatSearch) return;
|
||||
const bar = createSearchTopBar({
|
||||
placeholder: 'Имя или логин',
|
||||
onInput: (value) => {
|
||||
chatQuery = String(value || '').toLowerCase().replaceAll('ё', 'е').trim();
|
||||
renderList();
|
||||
},
|
||||
onSubmit: () => list.querySelector('.dm-dialog-card')?.click(),
|
||||
onClose: () => closeChatsSearch(),
|
||||
});
|
||||
chatSearch = { bar, layer: openHistoryLayer(() => closeChatsSearch({ fromHistory: true })) };
|
||||
chrome?.setTopbar(bar);
|
||||
bar.searchInput?.focus();
|
||||
filterRow.hidden = true;
|
||||
}
|
||||
|
||||
function closeChatsSearch({ fromHistory = false } = {}) {
|
||||
if (!chatSearch) return;
|
||||
const { layer } = chatSearch;
|
||||
chatSearch = null;
|
||||
chatQuery = '';
|
||||
if (!fromHistory) layer?.close();
|
||||
filterRow.hidden = false;
|
||||
if (!disposed) {
|
||||
chrome?.setTopbar(head);
|
||||
renderList();
|
||||
}
|
||||
}
|
||||
|
||||
const list = document.createElement('div');
|
||||
list.className = 'stack dm-list';
|
||||
|
||||
// Меню чата по долгому нажатию (или правой кнопкой): закрепить и выключить звук.
|
||||
// Одно меню на весь список; якорь ставится у строки, на которой его открыли.
|
||||
const rowMenuAnchor = document.createElement('span');
|
||||
rowMenuAnchor.className = 'dm-row-menu-anchor';
|
||||
rowMenuAnchor.setAttribute('aria-hidden', 'true');
|
||||
let rowMenuItem = null;
|
||||
let rowMenuOpenedAt = 0;
|
||||
const rowMenu = createDropdownMenu({
|
||||
anchorEl: rowMenuAnchor,
|
||||
minWidth: 200,
|
||||
transparent: true,
|
||||
items: () => {
|
||||
if (!rowMenuItem) return [];
|
||||
const id = normalizeDmChatId(rowMenuItem.peerLogin);
|
||||
return [
|
||||
{
|
||||
label: rowMenuItem.pinned ? 'Открепить' : 'Закрепить',
|
||||
iconHtml: iconHtml('pin'),
|
||||
action: () => setDmChatPinned(id, !rowMenuItem.pinned),
|
||||
},
|
||||
createDmMuteMenuItem(id),
|
||||
];
|
||||
},
|
||||
});
|
||||
const openRowMenu = (row, item) => {
|
||||
if (Date.now() - rowMenuOpenedAt < 700) return;
|
||||
rowMenuItem = item;
|
||||
rowMenuOpenedAt = Date.now();
|
||||
const rect = row.getBoundingClientRect();
|
||||
const listRect = screen.getBoundingClientRect();
|
||||
rowMenuAnchor.style.top = `${rect.top - listRect.top + rect.height / 2}px`;
|
||||
rowMenuAnchor.style.left = `${rect.right - listRect.left - 24}px`;
|
||||
rowMenu.open();
|
||||
try { navigator.vibrate?.(12); } catch { /* вибрация не обязательна */ }
|
||||
};
|
||||
function bindRowMenu(row, item) {
|
||||
let pressTimer = 0;
|
||||
let startX = 0;
|
||||
let startY = 0;
|
||||
const cancel = () => { window.clearTimeout(pressTimer); pressTimer = 0; };
|
||||
row.addEventListener('pointerdown', (event) => {
|
||||
if (event.pointerType === 'mouse') return;
|
||||
startX = event.clientX;
|
||||
startY = event.clientY;
|
||||
cancel();
|
||||
pressTimer = window.setTimeout(() => openRowMenu(row, item), 500);
|
||||
});
|
||||
row.addEventListener('pointermove', (event) => {
|
||||
if (pressTimer && Math.hypot(event.clientX - startX, event.clientY - startY) > 8) cancel();
|
||||
});
|
||||
row.addEventListener('pointerup', cancel);
|
||||
row.addEventListener('pointercancel', cancel);
|
||||
row.addEventListener('contextmenu', (event) => {
|
||||
event.preventDefault();
|
||||
cancel();
|
||||
openRowMenu(row, item);
|
||||
});
|
||||
}
|
||||
|
||||
function renderRow(item) {
|
||||
const row = document.createElement('article');
|
||||
row.className = 'list-item dm-dialog-card';
|
||||
@@ -263,6 +389,7 @@ function renderRow(item) {
|
||||
avatar: item.avatar,
|
||||
firstName: item.firstName,
|
||||
lastName: item.lastName,
|
||||
whenVisible,
|
||||
});
|
||||
avatarEl.classList.add('avatar');
|
||||
const avatarWrap = document.createElement('div');
|
||||
@@ -273,6 +400,7 @@ function renderRow(item) {
|
||||
<div class="dm-row-main">
|
||||
<div class="dm-row-titleline dm-row-titlewrap">
|
||||
<strong class="dm-row-title"></strong>
|
||||
${item.muted ? `<span class="dm-row-muted" title="Без звука">${iconHtml('bell-off')}</span>` : ''}
|
||||
${relationBadge ? `<span class="dm-contact-note dm-contact-note--${relationFlag}">${relationBadge}</span>` : ''}
|
||||
</div>
|
||||
<p class="dm-row-last-message"></p>
|
||||
@@ -281,7 +409,11 @@ function renderRow(item) {
|
||||
<div class="dm-row-meta-line">
|
||||
${item.lastMessageTimeMs ? '<span class="dm-row-time"></span>' : '<span class="dm-row-time dm-row-time--empty"></span>'}
|
||||
</div>
|
||||
${item.unreadCount ? `<span class="dm-unread-badge">${item.unreadCount > 99 ? '99+' : item.unreadCount}</span>` : '<span class="dm-row-meta-spacer" aria-hidden="true"></span>'}
|
||||
${item.unreadCount
|
||||
? `<span class="dm-unread-badge${item.muted ? ' dm-unread-badge--muted' : ''}">${item.unreadCount > 99 ? '99+' : item.unreadCount}</span>`
|
||||
: (item.pinned
|
||||
? `<span class="dm-row-pin" title="Закреплён">${iconHtml('pin')}</span>`
|
||||
: '<span class="dm-row-meta-spacer" aria-hidden="true"></span>')}
|
||||
</div>
|
||||
`;
|
||||
const titleEl = row.querySelector('.dm-row-title');
|
||||
@@ -291,18 +423,146 @@ function renderRow(item) {
|
||||
const fullName = [String(item.firstName || '').trim(), String(item.lastName || '').trim()].filter(Boolean).join(' ');
|
||||
titleEl.textContent = fullName || String(item.peerLogin || '');
|
||||
}
|
||||
if (previewEl) previewEl.textContent = 'Загрузка…';
|
||||
if (timeEl) timeEl.textContent = formatChatRowTime(item.lastMessageTimeMs);
|
||||
row.prepend(avatarWrap);
|
||||
void resolveDialogPreview(item).then((text) => {
|
||||
if (!previewEl?.isConnected) return;
|
||||
previewEl.textContent = String(text || '').trim() || 'Диалог пока пуст.';
|
||||
// Текст превью ставится сразу, если известен; иначе строка пустая до расшифровки –
|
||||
// без мелькающего «Загрузка…».
|
||||
const showPreview = (text) => {
|
||||
if (!previewEl) return;
|
||||
previewEl.textContent = String(text || '').trim() || DM_PREVIEW_EMPTY;
|
||||
previewEl.classList.toggle('is-encrypted', text === DM_PREVIEW_ENCRYPTED);
|
||||
previewEl.classList.toggle('is-empty', previewEl.textContent === DM_PREVIEW_EMPTY);
|
||||
};
|
||||
const knownText = clipPreviewText(String(item.lastMessageText || '').trim());
|
||||
if (knownText || !item.lastMessageBlobB64) showPreview(knownText);
|
||||
else {
|
||||
if (previewEl) previewEl.textContent = '\u00a0';
|
||||
void resolveDialogPreview(item).then((text) => {
|
||||
if (previewEl?.isConnected) showPreview(text);
|
||||
});
|
||||
}
|
||||
if (item.pinned) row.classList.add('is-pinned');
|
||||
row.addEventListener('click', (event) => {
|
||||
// Долгое нажатие уже открыло меню чата – отпускание пальца не должно открывать сам чат.
|
||||
if (Date.now() - rowMenuOpenedAt < 700) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
navigate(`chat/${encodeURIComponent(normalizeDmChatId(item.peerLogin))}`);
|
||||
});
|
||||
row.addEventListener('click', () => navigate(`chat/${encodeURIComponent(normalizeDmChatId(item.peerLogin))}`));
|
||||
bindRowMenu(row, item);
|
||||
return row;
|
||||
}
|
||||
|
||||
// Профили для аватаров – только у строк, которые видны (или вот-вот будут видны).
|
||||
const visibleWaiters = new Map();
|
||||
const avatarObserver = typeof IntersectionObserver === 'function'
|
||||
? new IntersectionObserver((entries) => {
|
||||
entries.forEach((entry) => {
|
||||
if (!entry.isIntersecting) return;
|
||||
const fn = visibleWaiters.get(entry.target);
|
||||
visibleWaiters.delete(entry.target);
|
||||
avatarObserver.unobserve(entry.target);
|
||||
fn?.();
|
||||
});
|
||||
}, { rootMargin: '200px 0px' })
|
||||
: null;
|
||||
function whenVisible(el, fn) {
|
||||
if (!avatarObserver) { fn(); return; }
|
||||
visibleWaiters.set(el, fn);
|
||||
avatarObserver.observe(el);
|
||||
}
|
||||
|
||||
// Последний ответ сервера, уже разобранный: фильтр перерисовывает без запроса.
|
||||
let lastItems = lastChatList?.login === login ? lastChatList.items : null;
|
||||
let startExpanded = false;
|
||||
const START_PREVIEW = 5;
|
||||
|
||||
function hasConversation(item) {
|
||||
return Boolean(item.hasDialog || item.lastMessageTimeMs > 0 || item.unreadCount > 0 || item.pinned);
|
||||
}
|
||||
|
||||
function matchesChatQuery(item) {
|
||||
return matchesPeopleQuery(`${item.firstName || ''} ${item.lastName || ''} ${item.peerLogin || ''}`, chatQuery);
|
||||
}
|
||||
|
||||
function renderList() {
|
||||
if (!lastItems) return;
|
||||
const pinnedOrder = getPinnedDmChats();
|
||||
// В поиске – по всем чатам и контактам сразу, без фильтра по типу связи.
|
||||
const filtered = chatQuery
|
||||
? lastItems.filter(matchesChatQuery)
|
||||
: lastItems.filter((item) => currentChatFilter === 'all' || normalizeRelationFlag(item.relationFlag) === currentChatFilter);
|
||||
// Переписки – по свежести, закреплённые выше всех (последний закреплённый – первым).
|
||||
const chats = filtered.filter(hasConversation).sort((a, b) => {
|
||||
const pinA = a.pinned ? pinnedOrder.indexOf(normalizeDmChatId(a.peerLogin)) : -1;
|
||||
const pinB = b.pinned ? pinnedOrder.indexOf(normalizeDmChatId(b.peerLogin)) : -1;
|
||||
if (pinA >= 0 || pinB >= 0) {
|
||||
if (pinA < 0) return 1;
|
||||
if (pinB < 0) return -1;
|
||||
return pinA - pinB;
|
||||
}
|
||||
return compareChatRows(a, b);
|
||||
});
|
||||
// Без переписки: во «Всех» – только близкие и друзья (контактов могут быть сотни),
|
||||
// в фильтре по типу связи – все этого типа.
|
||||
const byName = (a, b) => (relationOrder(a.relationFlag) - relationOrder(b.relationFlag))
|
||||
|| String(a.firstName || a.peerLogin).localeCompare(String(b.firstName || b.peerLogin), 'ru');
|
||||
const silent = filtered
|
||||
.filter((item) => !hasConversation(item) && normalizeRelationFlag(item.relationFlag) !== 'none')
|
||||
.filter((item) => chatQuery || currentChatFilter !== 'all' || ['close_friend', 'friend'].includes(normalizeRelationFlag(item.relationFlag)))
|
||||
.sort(byName);
|
||||
|
||||
list.replaceChildren();
|
||||
if (!chats.length && !silent.length) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'empty-note';
|
||||
if (chatQuery) {
|
||||
empty.textContent = 'Среди ваших чатов и контактов никого не нашлось.';
|
||||
const wide = document.createElement('button');
|
||||
wide.type = 'button';
|
||||
wide.className = 'secondary-btn dm-search-wide';
|
||||
wide.textContent = 'Искать во всей сети';
|
||||
wide.addEventListener('click', () => navigate('contact-search-view'));
|
||||
list.append(empty, wide);
|
||||
return;
|
||||
}
|
||||
if (currentChatFilter === 'all') {
|
||||
list.append(createStateMessage({
|
||||
icon: 'message',
|
||||
title: 'Пока нет переписок',
|
||||
text: 'Напишите кому-нибудь из друзей или найдите человека по имени.',
|
||||
actionLabel: 'Новый чат',
|
||||
onAction: () => navigate('contact-search-view'),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
empty.textContent = 'Здесь пока никого.';
|
||||
list.append(empty);
|
||||
return;
|
||||
}
|
||||
const frag = document.createDocumentFragment();
|
||||
chats.forEach((item) => frag.append(renderRow(item)));
|
||||
if (silent.length) {
|
||||
const divider = document.createElement('div');
|
||||
divider.className = 'dm-divider';
|
||||
divider.textContent = chats.length ? `Начать переписку · ${silent.length}` : `Без переписки · ${silent.length}`;
|
||||
frag.append(divider);
|
||||
const collapsed = !chatQuery && !startExpanded && silent.length > START_PREVIEW + 1 && chats.length > 0;
|
||||
(collapsed ? silent.slice(0, START_PREVIEW) : silent).forEach((item) => frag.append(renderRow(item)));
|
||||
if (collapsed) {
|
||||
const more = document.createElement('button');
|
||||
more.type = 'button';
|
||||
more.className = 'list-more';
|
||||
more.innerHTML = `${iconHtml('chevron-down')}<span>Показать всех · ${silent.length}</span>`;
|
||||
more.addEventListener('click', () => { startExpanded = true; renderList(); });
|
||||
frag.append(more);
|
||||
}
|
||||
}
|
||||
list.append(frag);
|
||||
}
|
||||
|
||||
let loadSeq = 0;
|
||||
async function loadList() {
|
||||
if (state.session.isLocalDemo) {
|
||||
const empty = document.createElement('div');
|
||||
@@ -311,16 +571,19 @@ function renderRow(item) {
|
||||
list.replaceChildren(empty);
|
||||
return;
|
||||
}
|
||||
const seq = ++loadSeq;
|
||||
// Первый показ – спиннер, но только если ждать заметно (без мелькания).
|
||||
if (!lastItems && !list.childElementCount) list.replaceChildren(createLoadingState({ label: 'Загружаю чаты' }));
|
||||
|
||||
try {
|
||||
const payload = await authService.listContacts();
|
||||
if (disposed || seq !== loadSeq) return;
|
||||
const dialogs = Array.isArray(payload?.dialogs) ? payload.dialogs : [];
|
||||
const contacts = dialogs
|
||||
.filter((dialog) => normalizeRelationFlag(dialog?.relationFlag) !== 'none')
|
||||
.map((dialog) => String(dialog?.peerLogin || '').trim())
|
||||
.filter(Boolean);
|
||||
setContacts(contacts);
|
||||
list.innerHTML = '';
|
||||
|
||||
const byPeer = new Map();
|
||||
dialogs.forEach((dialog) => {
|
||||
@@ -361,33 +624,34 @@ function renderRow(item) {
|
||||
byPeer.set(key, newest);
|
||||
});
|
||||
|
||||
const rows = Array.from(byPeer.values())
|
||||
// Технический tombstone очистки истории сам по себе не создаёт видимый диалог.
|
||||
// Пустые друзья/контакты остаются, а пользователь без связи исчезает после очистки.
|
||||
.filter((item) => normalizeRelationFlag(item.relationFlag) !== 'none' || Boolean(item.hasDialog))
|
||||
.filter((item) => currentChatFilter === 'all' || normalizeRelationFlag(item.relationFlag) === currentChatFilter)
|
||||
.sort((a, b) => {
|
||||
const orderA = relationOrder(a.relationFlag);
|
||||
const orderB = relationOrder(b.relationFlag);
|
||||
if (orderA !== orderB) return orderA - orderB;
|
||||
return compareChatRows(a, b);
|
||||
});
|
||||
byPeer.forEach((item) => rememberDmPeer({
|
||||
login: item.peerLogin,
|
||||
relationType: item.relationFlag,
|
||||
firstName: item.firstName,
|
||||
lastName: item.lastName,
|
||||
avatar: item.avatar,
|
||||
shineStatus: item.shineStatus,
|
||||
}));
|
||||
|
||||
if (!rows.length) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'empty-note';
|
||||
empty.textContent = 'Пока нет переписок. Найдите человека через поиск вверху.';
|
||||
list.append(empty);
|
||||
return;
|
||||
}
|
||||
|
||||
rows.forEach((item) => {
|
||||
list.append(renderRow(item));
|
||||
const pinnedOrder = getPinnedDmChats();
|
||||
byPeer.forEach((item) => {
|
||||
const id = normalizeDmChatId(item.peerLogin);
|
||||
item.pinned = pinnedOrder.includes(id);
|
||||
item.muted = isDmChatMuted(id);
|
||||
});
|
||||
// Технический tombstone очистки истории сам по себе не создаёт видимый диалог:
|
||||
// пользователь без связи исчезает после очистки.
|
||||
const nextItems = Array.from(byPeer.values())
|
||||
.filter((item) => normalizeRelationFlag(item.relationFlag) !== 'none' || Boolean(item.hasDialog));
|
||||
// Ничего не изменилось – не перерисовываем (иначе мигают аватары и превью).
|
||||
const unchanged = lastItems && JSON.stringify(nextItems) === JSON.stringify(lastItems) && list.childElementCount;
|
||||
lastItems = nextItems;
|
||||
lastChatList = { login, items: nextItems };
|
||||
if (!unchanged) renderList();
|
||||
} catch (error) {
|
||||
if (disposed || seq !== loadSeq) return;
|
||||
if (isSessionInvalidError(error)) {
|
||||
list.innerHTML = '';
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack';
|
||||
|
||||
@@ -413,22 +677,45 @@ function renderRow(item) {
|
||||
list.append(card);
|
||||
return;
|
||||
}
|
||||
|
||||
list.innerHTML = '';
|
||||
const fail = document.createElement('div');
|
||||
fail.className = 'card meta-muted';
|
||||
fail.textContent = `Не удалось загрузить сообщения: ${error.message || 'unknown'}`;
|
||||
list.append(fail);
|
||||
// Уже показанный список не стираем из-за неудачного обновления.
|
||||
if (lastItems) return;
|
||||
list.replaceChildren(createErrorState({
|
||||
title: 'Не удалось загрузить чаты',
|
||||
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
||||
onRetry: () => { list.replaceChildren(); void loadList(); },
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
reloadForFilter = () => { void loadList(); };
|
||||
// Фильтр перерисовывает уже загруженный список мгновенно и тихо обновляет его с сервера.
|
||||
reloadForFilter = () => {
|
||||
startExpanded = false;
|
||||
renderList();
|
||||
void loadList();
|
||||
};
|
||||
|
||||
chrome?.setTopbar(head);
|
||||
screen.append(filterRow, list);
|
||||
screen.append(filterRow, list, rowMenuAnchor);
|
||||
if (lastItems) renderList();
|
||||
loadList();
|
||||
|
||||
screen.cleanup = () => {};
|
||||
// Закрепили или выключили звук (здесь же или в чате) – список перестраивается из кэша сервера.
|
||||
const handlePrefsUpdated = () => { void loadList(); };
|
||||
window.addEventListener(DM_CHAT_PREFS_EVENT, handlePrefsUpdated);
|
||||
|
||||
screen.cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
window.removeEventListener(DM_CHAT_PREFS_EVENT, handlePrefsUpdated);
|
||||
avatarObserver?.disconnect();
|
||||
visibleWaiters.clear();
|
||||
rowMenu.destroy();
|
||||
if (chatSearch) {
|
||||
const { layer } = chatSearch;
|
||||
chatSearch = null;
|
||||
layer?.close();
|
||||
}
|
||||
};
|
||||
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { authService } from '../state.js';
|
||||
import { KeyRotationClient } from '../services/key-rotation-service.js';
|
||||
import { inspectBlockchainDataItem } from '../services/blockchain-entry-inspector.js';
|
||||
import { makeProfileRoute, makeShineChannelRoute, makeShineMessageRoute } from '../services/shine-routes.js';
|
||||
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'my-blockchain-view', title: 'Мой блокчейн' };
|
||||
|
||||
@@ -609,7 +610,7 @@ export function render({ navigate, chrome }, { historyOnly = false } = {}) {
|
||||
if (disposed || seq !== loadSeq) return;
|
||||
const err = document.createElement('div');
|
||||
err.className = 'card';
|
||||
err.textContent = `Не удалось загрузить блокчейн: ${error?.message || error}`;
|
||||
err.textContent = actionErrorText('Не удалось загрузить блокчейн', error);
|
||||
list.append(err);
|
||||
} finally {
|
||||
if (seq === loadSeq) {
|
||||
|
||||
+2286
-1122
File diff suppressed because it is too large
Load Diff
@@ -1,16 +1,17 @@
|
||||
// Адаптер реальных данных → нейтральная модель движка force-графа.
|
||||
//
|
||||
// Источник — результат buildGraphModel() из network-view.js (он уже нормализует ответ
|
||||
// authService.getUserConnectionsGraph в роли/направления/метки). Здесь только конвертация
|
||||
// в форму, которую понимает движок ({ focusId, nodes[] }). Сервер не трогаем — это чтение.
|
||||
// Ответ сервера (после buildGraphModel в network-view.js) → люди и нити для карты связей.
|
||||
// Сервер не трогаем – только чтение.
|
||||
|
||||
function normLogin(value) {
|
||||
return String(value || '').trim();
|
||||
}
|
||||
|
||||
function normKey(value) {
|
||||
return normLogin(value).toLowerCase();
|
||||
}
|
||||
|
||||
const FAMILY_ROLES = ['parent', 'child', 'spouse', 'sibling'];
|
||||
|
||||
function relationTypeFromRelation(relation) {
|
||||
export function relationTypeFromRelation(relation) {
|
||||
const explicit = String(relation?.mark?.relationType || '').trim().toLowerCase();
|
||||
if (explicit === 'close_friend' || explicit === 'friend' || explicit === 'contact') return explicit;
|
||||
const role = relation?.role;
|
||||
@@ -19,60 +20,43 @@ function relationTypeFromRelation(relation) {
|
||||
return 'contact';
|
||||
}
|
||||
|
||||
// Сила связи (0..1) → радиус орбиты в движке. Реальный API пока не отдаёт численную силу,
|
||||
// поэтому выводим её эвристически из роли и направления связи:
|
||||
// - родственники держим ближе всего, контакты — дальше всего;
|
||||
// - взаимные дружеские связи ближе односторонних.
|
||||
function deriveStrength(relation) {
|
||||
if (relation.isRelative) return 0.9;
|
||||
if (relation?.mark?.relationType === 'close_friend') return 0.9;
|
||||
if (relation.role === 'contact') return 0.4;
|
||||
if (relation.forward && relation.backward) return 0.8;
|
||||
return 0.55;
|
||||
function personFromMark(login, mark) {
|
||||
return {
|
||||
id: normKey(login),
|
||||
login,
|
||||
name: mark?.displayName || login,
|
||||
firstName: mark?.firstName || '',
|
||||
lastName: mark?.lastName || '',
|
||||
avatar: mark?.avatar || null,
|
||||
shining: Boolean(mark?.shine),
|
||||
official: Boolean(mark?.official),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{centerLogin:string, centerMark:object|null, relations:Array}} graphModel
|
||||
* @returns {{focusId:string, nodes:Array}}
|
||||
* @returns {{ center: object, peers: Array<{ person: object, relationType: string, mutual: boolean, direction: string }> }}
|
||||
*/
|
||||
export function engineModelFromGraphModel(graphModel) {
|
||||
const focusLogin = normLogin(graphModel?.centerLogin);
|
||||
const centerMark = graphModel?.centerMark || null;
|
||||
|
||||
const focusNode = {
|
||||
id: focusLogin,
|
||||
login: focusLogin,
|
||||
name: centerMark?.displayName || centerMark?.login || focusLogin,
|
||||
avatar: centerMark?.avatar || null,
|
||||
relationType: 'self',
|
||||
strength: 1,
|
||||
shining: Boolean(centerMark?.shine),
|
||||
official: Boolean(centerMark?.official),
|
||||
tier: 1,
|
||||
};
|
||||
|
||||
const relations = Array.isArray(graphModel?.relations) ? graphModel.relations : [];
|
||||
const seen = new Set();
|
||||
const nodes = relations
|
||||
.map((r) => {
|
||||
const login = normLogin(r?.login);
|
||||
const key = login.toLowerCase();
|
||||
// исключаем сам фокус (не должно быть линии на собственный ник) и дубли
|
||||
if (!login || key === focusLogin.toLowerCase() || seen.has(key)) return null;
|
||||
seen.add(key);
|
||||
return {
|
||||
id: login,
|
||||
login,
|
||||
name: r?.mark?.displayName || login,
|
||||
avatar: r?.mark?.avatar || null,
|
||||
relationType: relationTypeFromRelation(r),
|
||||
strength: deriveStrength(r || {}),
|
||||
shining: Boolean(r?.mark?.shine),
|
||||
official: Boolean(r?.mark?.official),
|
||||
tier: 1,
|
||||
};
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
return { focusId: focusLogin, nodes: [focusNode, ...nodes] };
|
||||
export function peopleFromGraphModel(graphModel) {
|
||||
const centerLogin = normLogin(graphModel?.centerLogin);
|
||||
const center = personFromMark(centerLogin, graphModel?.centerMark || null);
|
||||
const seen = new Set([center.id]);
|
||||
const peers = [];
|
||||
for (const relation of Array.isArray(graphModel?.relations) ? graphModel.relations : []) {
|
||||
const login = normLogin(relation?.login);
|
||||
const key = normKey(login);
|
||||
if (!login || seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
const forward = Boolean(relation?.forward);
|
||||
const backward = Boolean(relation?.backward);
|
||||
peers.push({
|
||||
person: personFromMark(login, relation?.mark || null),
|
||||
relationType: relationTypeFromRelation(relation),
|
||||
// Пунктир на карте – связь только с одной стороны.
|
||||
mutual: forward && backward,
|
||||
// Со стороны центра: взаимно, только центр (out) или только этот человек (in – «ждёт ответа»).
|
||||
direction: forward && backward ? 'mutual' : (forward ? 'out' : 'in'),
|
||||
});
|
||||
}
|
||||
return { center, peers };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,659 @@
|
||||
// Группы людей на карте связей: «Компании» (кто с кем знаком), «Интересы» (кто на что подписан)
|
||||
// и «Города» (кто где живёт).
|
||||
//
|
||||
// Компании ищутся по знакомствам между людьми первого круга – из их собственных графов связей.
|
||||
// Метод Лувена (максимум модулярности) собирает вместе тех, кто плотно знаком между собой:
|
||||
// школа кунг-фу знакома внутри себя, коллеги – внутри себя, а между ними редкие мостики.
|
||||
// Всё считается на устройстве за миллисекунды и детерминированно: те же данные – та же картина.
|
||||
//
|
||||
// Названия: своё (дал владелец карты) → по каналу, который читает большинство компании и
|
||||
// заметно реже остальные → по самому связанному человеку («Илья С. и др.»).
|
||||
//
|
||||
// Раскладка «островами»: внутри компании люди стоят сотами (ровный шаг, подписи не
|
||||
// налезают), в середине – самые связанные, знакомые – рядом. Острова упаковываются вокруг
|
||||
// человека в центре: крупные ближе, связанные между собой – по соседству.
|
||||
|
||||
export const REST_GROUP = 'rest';
|
||||
export const ISLAND_COLORS = 8; // цветов подложек; сами цвета – в движке карты (зависят от темы)
|
||||
|
||||
// Вес знакомства по виду связи: близкие сближают сильнее контактов.
|
||||
const TIE_WEIGHT = { close_friend: 3, family: 3, friend: 2, contact: 1 };
|
||||
const RELATION_RANK = { close_friend: 0, family: 1, friend: 2, contact: 3 };
|
||||
|
||||
export function tieWeight(type, mutual = true) {
|
||||
return (TIE_WEIGHT[type] || 1) * (mutual ? 1 : 0.6);
|
||||
}
|
||||
|
||||
function byName(a, b) {
|
||||
return String(a.name || a.id).localeCompare(String(b.name || b.id), 'ru');
|
||||
}
|
||||
|
||||
// Короткое имя для подписей: «Илья С.»; без фамилии – как есть.
|
||||
export function shortPersonName(person) {
|
||||
const first = String(person?.firstName || '').trim();
|
||||
const last = String(person?.lastName || '').trim();
|
||||
const text = first && last ? `${first} ${last[0]}.` : String(person?.name || person?.login || person?.id || '');
|
||||
return text.length > 18 ? `${text.slice(0, 17)}…` : text;
|
||||
}
|
||||
|
||||
function jaccard(a, b) {
|
||||
if (!a.size || !b.size) return 0;
|
||||
let common = 0;
|
||||
const [small, big] = a.size <= b.size ? [a, b] : [b, a];
|
||||
small.forEach((id) => { if (big.has(id)) common += 1; });
|
||||
return common / (a.size + b.size - common);
|
||||
}
|
||||
|
||||
// --- Сообщества -----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Метод Лувена: узлы переходят в соседнее сообщество, пока это повышает модулярность,
|
||||
* затем сообщества сворачиваются в узлы, и всё повторяется уровнем выше.
|
||||
* @param {string[]} ids
|
||||
* @param {Map<string, Map<string, number>>} weights – веса знакомств (можно несимметрично)
|
||||
* @returns {string[][]} сообщества (одиночки – тоже сообщества)
|
||||
*/
|
||||
export function detectCommunities(ids, weights, { resolution = 1 } = {}) {
|
||||
const order = [...new Set(ids)].sort();
|
||||
if (!order.length) return [];
|
||||
const index = new Map(order.map((id, i) => [id, i]));
|
||||
// Неориентированный граф: у пары – наибольший из весов в обе стороны.
|
||||
const pairs = new Map();
|
||||
weights.forEach((near, a) => {
|
||||
const i = index.get(a);
|
||||
if (i === undefined) return;
|
||||
near.forEach((w, b) => {
|
||||
const j = index.get(b);
|
||||
if (j === undefined || j === i || !(w > 0)) return;
|
||||
const key = i < j ? i * order.length + j : j * order.length + i;
|
||||
pairs.set(key, Math.max(pairs.get(key) || 0, w));
|
||||
});
|
||||
});
|
||||
let adj = order.map(() => new Map());
|
||||
let loops = new Float64Array(order.length);
|
||||
let total = 0;
|
||||
pairs.forEach((w, key) => {
|
||||
const i = Math.floor(key / order.length);
|
||||
const j = key % order.length;
|
||||
adj[i].set(j, w);
|
||||
adj[j].set(i, w);
|
||||
total += w;
|
||||
});
|
||||
if (total <= 0) return order.map((id) => [id]);
|
||||
|
||||
let membership = order.map((_, i) => i); // исходный человек → узел текущего уровня
|
||||
for (let level = 0; level < 16; level += 1) {
|
||||
const n = adj.length;
|
||||
const degree = new Float64Array(n);
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
let k = 2 * loops[i];
|
||||
adj[i].forEach((w) => { k += w; });
|
||||
degree[i] = k;
|
||||
}
|
||||
const m2 = 2 * total;
|
||||
const comm = Int32Array.from({ length: n }, (_, i) => i);
|
||||
const tot = Float64Array.from(degree);
|
||||
let improved = false;
|
||||
for (let pass = 0; pass < 40; pass += 1) {
|
||||
let moved = 0;
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
const own = comm[i];
|
||||
const links = new Map();
|
||||
adj[i].forEach((w, j) => { links.set(comm[j], (links.get(comm[j]) || 0) + w); });
|
||||
tot[own] -= degree[i];
|
||||
let best = own;
|
||||
let bestGain = (links.get(own) || 0) - (resolution * tot[own] * degree[i]) / m2;
|
||||
links.forEach((w, c) => {
|
||||
if (c === own) return;
|
||||
const gain = w - (resolution * tot[c] * degree[i]) / m2;
|
||||
if (gain > bestGain + 1e-12) { best = c; bestGain = gain; }
|
||||
else if (best !== own && Math.abs(gain - bestGain) <= 1e-12 && c < best) best = c;
|
||||
});
|
||||
tot[best] += degree[i];
|
||||
if (best !== own) { comm[i] = best; moved += 1; }
|
||||
}
|
||||
if (!moved) break;
|
||||
improved = true;
|
||||
}
|
||||
if (!improved) break;
|
||||
const renum = new Map();
|
||||
for (let i = 0; i < n; i += 1) if (!renum.has(comm[i])) renum.set(comm[i], renum.size);
|
||||
if (renum.size === n) break;
|
||||
const nextAdj = Array.from({ length: renum.size }, () => new Map());
|
||||
const nextLoops = new Float64Array(renum.size);
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
const ci = renum.get(comm[i]);
|
||||
nextLoops[ci] += loops[i];
|
||||
adj[i].forEach((w, j) => {
|
||||
const cj = renum.get(comm[j]);
|
||||
if (ci === cj) {
|
||||
if (i < j) nextLoops[ci] += w;
|
||||
} else {
|
||||
nextAdj[ci].set(cj, (nextAdj[ci].get(cj) || 0) + w);
|
||||
}
|
||||
});
|
||||
}
|
||||
membership = membership.map((node) => renum.get(comm[node]));
|
||||
adj = nextAdj;
|
||||
loops = nextLoops;
|
||||
}
|
||||
const groups = new Map();
|
||||
membership.forEach((c, i) => {
|
||||
if (!groups.has(c)) groups.set(c, []);
|
||||
groups.get(c).push(order[i]);
|
||||
});
|
||||
return [...groups.values()];
|
||||
}
|
||||
|
||||
// Самый связанный внутри группы: по нему компания узнаётся («Илья С. и др.»).
|
||||
// При равенстве – тот, кто ближе вам, затем по имени.
|
||||
function hubOf(members, weights, byId) {
|
||||
const inside = new Set(members);
|
||||
const rows = members.map((id) => {
|
||||
let score = 0;
|
||||
weights.get(id)?.forEach((w, other) => { if (inside.has(other)) score += w; });
|
||||
const person = byId.get(id) || { id };
|
||||
return { id, score, rank: RELATION_RANK[person.relationType] ?? 9, person };
|
||||
});
|
||||
rows.sort((a, b) => b.score - a.score || a.rank - b.rank || byName(a.person, b.person));
|
||||
return rows[0]?.id || '';
|
||||
}
|
||||
|
||||
// «Илья С. и др.»: число людей подпись покажет отдельно («· 26»), как у названных компаний.
|
||||
function autoLabel(members, hubId, byId) {
|
||||
const hub = shortPersonName(byId.get(hubId) || { id: hubId });
|
||||
return members.length > 1 ? `${hub} и др.` : hub;
|
||||
}
|
||||
|
||||
/**
|
||||
* Названия по подпискам: канал, который читает заметная часть группы и заметно чаще,
|
||||
* чем все остальные. Каждый канал – одной группе (с самым сильным перевесом).
|
||||
* @returns {Map<string, string>} id группы → ключ канала
|
||||
*/
|
||||
function channelNames(groups, subs, everyone) {
|
||||
const out = new Map();
|
||||
if (!subs?.of?.size) return out;
|
||||
const total = new Map();
|
||||
let known = 0;
|
||||
for (const id of everyone) {
|
||||
const list = subs.of.get(id);
|
||||
if (!list) continue;
|
||||
known += 1;
|
||||
list.forEach((key) => total.set(key, (total.get(key) || 0) + 1));
|
||||
}
|
||||
if (!known) return out;
|
||||
const candidates = [];
|
||||
for (const group of groups) {
|
||||
const n = group.members.length;
|
||||
if (n < 3) continue;
|
||||
const counts = new Map();
|
||||
group.members.forEach((id) => subs.of.get(id)?.forEach((key) => counts.set(key, (counts.get(key) || 0) + 1)));
|
||||
counts.forEach((count, key) => {
|
||||
const share = count / n;
|
||||
const lift = share / ((total.get(key) || count) / known);
|
||||
if (count >= 3 && share >= 0.34 && lift >= 1.3) candidates.push({ group: group.id, key, score: count * lift });
|
||||
});
|
||||
}
|
||||
candidates.sort((a, b) => b.score - a.score || (a.key < b.key ? -1 : 1));
|
||||
const usedChannels = new Set();
|
||||
for (const row of candidates) {
|
||||
if (out.has(row.group) || usedChannels.has(row.key)) continue;
|
||||
out.set(row.group, row.key);
|
||||
usedChannels.add(row.key);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Цвета островов: свои (сохранённые) остаются; остальным – свободный цвет, а когда свободных
|
||||
// нет – тот, что у наименее связанных с этой группой (на карте связанные стоят рядом,
|
||||
// и одинаковые цвета соседей сливались бы).
|
||||
function assignColors(groups, savedColors, weights = null) {
|
||||
const used = new Map(); // цвет → группы
|
||||
const take = (group, color) => {
|
||||
group.color = color;
|
||||
if (!used.has(color)) used.set(color, []);
|
||||
used.get(color).push(group);
|
||||
};
|
||||
groups.forEach((group) => {
|
||||
const color = savedColors.get(group.id);
|
||||
if (group.kind !== 'rest' && Number.isInteger(color) && color >= 0 && color < ISLAND_COLORS && !used.has(color)) take(group, color);
|
||||
});
|
||||
const affinity = (g1, g2) => {
|
||||
if (!weights) return 0;
|
||||
const inside = new Set(g2.members);
|
||||
let sum = 0;
|
||||
g1.members.forEach((id) => weights.get(id)?.forEach((w, other) => { if (inside.has(other)) sum += w; }));
|
||||
return sum;
|
||||
};
|
||||
groups.forEach((group) => {
|
||||
if (group.kind === 'rest' || Number.isInteger(group.color)) return;
|
||||
// Свой цвет у группы – от её id (у компании это её самый связанный человек): перенос
|
||||
// одного человека или новые знакомые не перекрашивают всю карту.
|
||||
const own = hashColor(group.id);
|
||||
let pick = -1;
|
||||
for (let k = 0; k < ISLAND_COLORS; k += 1) {
|
||||
const c = (own + k) % ISLAND_COLORS;
|
||||
if (!used.has(c)) { pick = c; break; }
|
||||
}
|
||||
if (pick < 0) {
|
||||
let best = Infinity;
|
||||
for (let c = 0; c < ISLAND_COLORS; c += 1) {
|
||||
const clash = used.get(c).reduce((sum, other) => sum + 1 + affinity(group, other), 0);
|
||||
if (clash < best) { best = clash; pick = c; }
|
||||
}
|
||||
}
|
||||
take(group, pick);
|
||||
});
|
||||
}
|
||||
|
||||
function hashColor(text) {
|
||||
let h = 2166136261;
|
||||
for (let i = 0; i < text.length; i += 1) {
|
||||
h ^= text.charCodeAt(i);
|
||||
h = Math.imul(h, 16777619);
|
||||
}
|
||||
return (h >>> 0) % ISLAND_COLORS;
|
||||
}
|
||||
|
||||
function sortGroups(groups) {
|
||||
return groups.sort((a, b) => (a.kind === 'rest') - (b.kind === 'rest')
|
||||
|| b.members.length - a.members.length
|
||||
|| String(a.label).localeCompare(String(b.label), 'ru'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Компании первого круга.
|
||||
* @param {Object} o
|
||||
* @param {Array<{id:string, name:string, firstName?:string, lastName?:string, relationType:string}>} o.people
|
||||
* @param {Map<string, Map<string, number>>} o.weights – веса знакомств
|
||||
* @param {{ groups: Array<{id:string, name:string, members:string[], color?:number}>, assign: Map<string,string> }} o.saved
|
||||
* @param {{ of: Map<string,string[]>, info: Map<string,{name:string}> } | null} [o.subs] – подписки для названий
|
||||
* @returns {{ groups: Array<object>, byPerson: Map<string,string>, snapshots: Array<{id:string, members:string[]}> }}
|
||||
*/
|
||||
export function buildCompanies({ people, weights, saved, subs = null }) {
|
||||
const byId = new Map(people.map((person) => [person.id, person]));
|
||||
const ids = people.map((person) => person.id);
|
||||
const assign = new Map([...(saved?.assign || new Map())].filter(([id]) => byId.has(id)));
|
||||
const savedGroups = (saved?.groups || []).filter((group) => group && group.id);
|
||||
const savedById = new Map(savedGroups.map((group) => [group.id, group]));
|
||||
|
||||
const communities = detectCommunities(ids, weights)
|
||||
.map((members) => members.filter((id) => !assign.has(id)))
|
||||
.filter((members) => members.length);
|
||||
|
||||
// Сохранённые компании узнаются по составу: наибольшее совпадение, не меньше трети.
|
||||
const scores = [];
|
||||
communities.forEach((members, ci) => {
|
||||
const set = new Set(members);
|
||||
savedGroups.forEach((group) => {
|
||||
const score = jaccard(set, new Set((group.members || []).filter((id) => byId.has(id) && !assign.has(id))));
|
||||
if (score >= 0.3) scores.push({ ci, id: group.id, score });
|
||||
});
|
||||
});
|
||||
scores.sort((a, b) => b.score - a.score || a.ci - b.ci || (a.id < b.id ? -1 : 1));
|
||||
const matchedCommunity = new Map();
|
||||
const matchedSaved = new Set();
|
||||
for (const row of scores) {
|
||||
if (matchedCommunity.has(row.ci) || matchedSaved.has(row.id)) continue;
|
||||
matchedCommunity.set(row.ci, row.id);
|
||||
matchedSaved.add(row.id);
|
||||
}
|
||||
|
||||
const groups = new Map();
|
||||
const rest = [];
|
||||
communities.forEach((members, ci) => {
|
||||
const savedId = matchedCommunity.get(ci);
|
||||
if (savedId) {
|
||||
groups.set(savedId, { id: savedId, kind: 'company', members: [...members], saved: true });
|
||||
} else if (members.length >= 3) {
|
||||
const hub = hubOf(members, weights, byId);
|
||||
const id = `a:${hub}`;
|
||||
groups.set(id, { id, kind: 'company', members: [...members], saved: false });
|
||||
} else {
|
||||
rest.push(...members);
|
||||
}
|
||||
});
|
||||
// Перенесённые вручную – в свою компанию (даже если её состав сейчас не узнан).
|
||||
assign.forEach((groupId, personId) => {
|
||||
if (groupId === REST_GROUP) { rest.push(personId); return; }
|
||||
let group = groups.get(groupId);
|
||||
if (!group && savedById.has(groupId)) {
|
||||
group = { id: groupId, kind: 'company', members: [], saved: true };
|
||||
groups.set(groupId, group);
|
||||
}
|
||||
if (group) group.members.push(personId);
|
||||
else rest.push(personId);
|
||||
});
|
||||
|
||||
const list = [...groups.values()].filter((group) => group.members.length);
|
||||
const named = channelNames(list.filter((group) => !savedById.get(group.id)?.name), subs, ids);
|
||||
for (const group of list) {
|
||||
group.members.sort((a, b) => byName(byId.get(a) || { id: a }, byId.get(b) || { id: b }));
|
||||
group.hubId = hubOf(group.members, weights, byId);
|
||||
const own = savedById.get(group.id);
|
||||
group.name = String(own?.name || '').trim();
|
||||
group.channel = named.get(group.id) || '';
|
||||
group.autoLabel = group.channel ? (subs.info.get(group.channel)?.name || '') : '';
|
||||
if (!group.autoLabel) group.autoLabel = autoLabel(group.members, group.hubId, byId);
|
||||
group.label = group.name || group.autoLabel;
|
||||
// Коротко – для подписи на мелкой карте: без «и др.».
|
||||
group.shortLabel = group.name || (group.channel ? group.autoLabel : shortPersonName(byId.get(group.hubId) || { id: group.hubId }));
|
||||
}
|
||||
if (rest.length) {
|
||||
rest.sort((a, b) => byName(byId.get(a) || { id: a }, byId.get(b) || { id: b }));
|
||||
list.push({ id: REST_GROUP, kind: 'rest', members: rest, name: '', autoLabel: 'Без компании', label: 'Без компании', shortLabel: 'Без компании', hubId: '' });
|
||||
}
|
||||
sortGroups(list);
|
||||
assignColors(list, new Map(savedGroups.map((group) => [group.id, group.color])), weights);
|
||||
|
||||
// Состав узнанных компаний обновляется, чтобы их узнавать и дальше, когда люди прибавятся.
|
||||
const snapshots = [];
|
||||
list.forEach((group) => {
|
||||
const own = savedById.get(group.id);
|
||||
if (!own) return;
|
||||
const now = group.members.filter((id) => !assign.has(id));
|
||||
if (jaccard(new Set(now), new Set(own.members || [])) < 0.85 || own.color !== group.color) {
|
||||
snapshots.push({ id: group.id, members: now, color: group.color });
|
||||
}
|
||||
});
|
||||
|
||||
const byPerson = new Map();
|
||||
list.forEach((group) => group.members.forEach((id) => byPerson.set(id, group.id)));
|
||||
return { groups: list, byPerson, snapshots };
|
||||
}
|
||||
|
||||
/**
|
||||
* Интересы: люди собираются у каналов, на которые подписаны. Каждый – у одного канала, самого
|
||||
* «своего»: из читаемых им каналов – того, что реже всего встречается среди этих людей (общие
|
||||
* «Новости района» читают все, а «Ушу» – только свои). Канал, у которого так набирается
|
||||
* меньше minSize человек, группой не считается – его читатели переходят к следующему.
|
||||
* @param {Object} o
|
||||
* @param {Array<{id:string, name:string}>} o.people
|
||||
* @param {{ of: Map<string,string[]>, info: Map<string,{name:string}> }} o.subs
|
||||
*/
|
||||
export function buildInterestGroups({ people, subs }) {
|
||||
const byId = new Map(people.map((person) => [person.id, person]));
|
||||
const followers = new Map();
|
||||
people.forEach((person) => subs?.of?.get(person.id)?.forEach((key) => {
|
||||
if (!followers.has(key)) followers.set(key, []);
|
||||
followers.get(key).push(person.id);
|
||||
}));
|
||||
const minSize = people.length > 30 ? 3 : 2;
|
||||
const eligible = new Set([...followers.entries()].filter(([, ids]) => ids.length >= minSize).map(([key]) => key));
|
||||
let assignment = new Map();
|
||||
for (let round = 0; round < 12; round += 1) {
|
||||
assignment = new Map();
|
||||
for (const person of people) {
|
||||
let best = '';
|
||||
for (const key of subs?.of?.get(person.id) || []) {
|
||||
if (!eligible.has(key)) continue;
|
||||
const n = followers.get(key).length;
|
||||
if (!best || n < followers.get(best).length || (n === followers.get(best).length && key < best)) best = key;
|
||||
}
|
||||
if (best) assignment.set(person.id, best);
|
||||
}
|
||||
const sizes = new Map();
|
||||
assignment.forEach((key) => sizes.set(key, (sizes.get(key) || 0) + 1));
|
||||
let dropped = false;
|
||||
eligible.forEach((key) => {
|
||||
if ((sizes.get(key) || 0) < minSize) { eligible.delete(key); dropped = true; }
|
||||
});
|
||||
if (!dropped) break;
|
||||
}
|
||||
const byChannel = new Map();
|
||||
assignment.forEach((key, id) => {
|
||||
if (!byChannel.has(key)) byChannel.set(key, []);
|
||||
byChannel.get(key).push(id);
|
||||
});
|
||||
const list = [...byChannel.entries()].map(([key, members]) => {
|
||||
const name = String(subs.info.get(key)?.name || key);
|
||||
return { id: `c:${key}`, kind: 'interest', channel: key, members, name: '', autoLabel: name, label: name, shortLabel: name, hubId: '' };
|
||||
});
|
||||
const remaining = new Set(people.map((person) => person.id).filter((id) => !assignment.has(id)));
|
||||
for (const group of list) {
|
||||
group.members.sort((a, b) => byName(byId.get(a) || { id: a }, byId.get(b) || { id: b }));
|
||||
// Что ещё читают в этой группе – для карточки группы.
|
||||
const counts = new Map();
|
||||
group.members.forEach((id) => subs.of.get(id)?.forEach((key) => {
|
||||
if (key !== group.channel) counts.set(key, (counts.get(key) || 0) + 1);
|
||||
}));
|
||||
group.alsoRead = [...counts.entries()]
|
||||
.filter(([, count]) => count >= 2)
|
||||
.sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
|
||||
.slice(0, 3)
|
||||
.map(([key, count]) => ({ key, count, name: String(subs.info.get(key)?.name || key) }));
|
||||
}
|
||||
if (remaining.size) {
|
||||
const members = [...remaining].sort((a, b) => byName(byId.get(a) || { id: a }, byId.get(b) || { id: b }));
|
||||
list.push({ id: REST_GROUP, kind: 'rest', members, name: '', autoLabel: 'Без общих подписок', label: 'Без общих подписок', shortLabel: 'Без подписок', hubId: '' });
|
||||
}
|
||||
sortGroups(list);
|
||||
assignColors(list, new Map());
|
||||
const byPerson = new Map();
|
||||
list.forEach((group) => group.members.forEach((id) => byPerson.set(id, group.id)));
|
||||
return { groups: list, byPerson, snapshots: [] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Города: кто где живёт (по полю «Город» в профиле). Разные написания одного города – одна
|
||||
* группа (cities.js). Когда городов много, города с одним человеком собираются в «Другие города».
|
||||
* @param {Object} o
|
||||
* @param {Array<{id:string, name:string}>} o.people
|
||||
* @param {{ of: Map<string,string> }} o.cities
|
||||
* @param {(value:string) => string} o.cityKey
|
||||
* @param {(key:string, spellings:string[]) => string} o.cityLabel
|
||||
*/
|
||||
export function buildCityGroups({ people, cities, cityKey, cityLabel }) {
|
||||
const byId = new Map(people.map((person) => [person.id, person]));
|
||||
const byCity = new Map();
|
||||
const unknown = [];
|
||||
for (const person of people) {
|
||||
const raw = cities?.of?.get(person.id) || '';
|
||||
const key = raw ? cityKey(raw) : '';
|
||||
if (!key) { unknown.push(person.id); continue; }
|
||||
if (!byCity.has(key)) byCity.set(key, { members: [], spellings: [] });
|
||||
byCity.get(key).members.push(person.id);
|
||||
byCity.get(key).spellings.push(raw);
|
||||
}
|
||||
let list = [...byCity.entries()].map(([key, row]) => {
|
||||
const name = cityLabel(key, row.spellings);
|
||||
return { id: `city:${key}`, kind: 'city', city: key, members: row.members, name: '', autoLabel: name, label: name, shortLabel: name, hubId: '' };
|
||||
});
|
||||
const singles = list.filter((group) => group.members.length === 1);
|
||||
if (list.length > 14 && singles.length > 1) {
|
||||
list = list.filter((group) => group.members.length > 1);
|
||||
const members = singles.flatMap((group) => group.members);
|
||||
list.push({ id: 'city:*', kind: 'city', city: '', members, name: '', autoLabel: 'Другие города', label: 'Другие города', shortLabel: 'Другие города', hubId: '' });
|
||||
}
|
||||
for (const group of list) group.members.sort((a, b) => byName(byId.get(a) || { id: a }, byId.get(b) || { id: b }));
|
||||
if (unknown.length) {
|
||||
unknown.sort((a, b) => byName(byId.get(a) || { id: a }, byId.get(b) || { id: b }));
|
||||
list.push({ id: REST_GROUP, kind: 'rest', members: unknown, name: '', autoLabel: 'Город не указан', label: 'Город не указан', shortLabel: 'Не указан', hubId: '' });
|
||||
}
|
||||
sortGroups(list);
|
||||
assignColors(list, new Map());
|
||||
const byPerson = new Map();
|
||||
list.forEach((group) => group.members.forEach((id) => byPerson.set(id, group.id)));
|
||||
return { groups: list, byPerson, snapshots: [] };
|
||||
}
|
||||
|
||||
// --- Раскладка островами --------------------------------------------------------------------
|
||||
|
||||
export const ISLAND_STEP = 74; // шаг сот: точка и подпись под ней не налезают на соседей
|
||||
export const ISLAND_PAD = 30; // от края точек до края острова (для упаковки)
|
||||
const ISLAND_GAP = 62; // между островами: над каждым – его подпись
|
||||
const NODE_RADIUS = 22; // точка первого круга (как в движке карты)
|
||||
|
||||
// Места на шестиугольной сетке, ближайшие к середине: остров получается круглым при любом
|
||||
// числе людей (а не шестиугольником с недостроенным краем). При равном расстоянии – по углу.
|
||||
function hexSlots(count) {
|
||||
const size = ISLAND_STEP / Math.sqrt(3);
|
||||
const rings = Math.ceil(Math.sqrt(count / 3)) + 2;
|
||||
const all = [];
|
||||
for (let q = -rings; q <= rings; q += 1) {
|
||||
for (let r = Math.max(-rings, -q - rings); r <= Math.min(rings, -q + rings); r += 1) {
|
||||
const x = size * Math.sqrt(3) * (q + r / 2);
|
||||
const y = size * 1.5 * r;
|
||||
all.push({ x, y, d: Math.round(Math.hypot(x, y) * 100), a: Math.atan2(y, x) });
|
||||
}
|
||||
}
|
||||
all.sort((p, s) => p.d - s.d || p.a - s.a);
|
||||
return all.slice(0, count).map(({ x, y }) => ({ x, y }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Люди острова по сотам: самые связанные – в середине, знакомые – рядом. Начальная
|
||||
* расстановка по спирали, затем жадные обмены местами, пока они сокращают сумму длин
|
||||
* знакомств (с весом) и держат связанных ближе к середине.
|
||||
*/
|
||||
function islandSlots(members, weights, rankOf) {
|
||||
const n = members.length;
|
||||
const slots = hexSlots(n);
|
||||
const index = new Map(members.map((id, i) => [id, i]));
|
||||
const links = members.map(() => []);
|
||||
const strength = new Float64Array(n);
|
||||
members.forEach((a, i) => {
|
||||
weights.get(a)?.forEach((w, b) => {
|
||||
const j = index.get(b);
|
||||
if (j === undefined || j === i) return;
|
||||
links[i].push([j, w]);
|
||||
strength[i] += w;
|
||||
});
|
||||
});
|
||||
// Начало: по связанности, при равенстве – ближе к вам, затем по имени (порядок members).
|
||||
const order = members.map((_, i) => i).sort((a, b) => strength[b] - strength[a] || rankOf(members[a]) - rankOf(members[b]) || a - b);
|
||||
const at = new Int32Array(n); // человек → номер места
|
||||
order.forEach((person, k) => { at[person] = k; });
|
||||
const radius = slots.map((p) => Math.hypot(p.x, p.y));
|
||||
const centerPull = 0.35;
|
||||
const dist = (s, t) => Math.hypot(slots[s].x - slots[t].x, slots[s].y - slots[t].y);
|
||||
const costAt = (i, s, skip) => {
|
||||
let c = centerPull * strength[i] * radius[s] + 4 * rankOf(members[i]) * radius[s] / ISLAND_STEP;
|
||||
for (const [j, w] of links[i]) if (j !== skip) c += w * dist(s, at[j]);
|
||||
return c;
|
||||
};
|
||||
if (n > 2 && n <= 260) {
|
||||
for (let pass = 0; pass < 8; pass += 1) {
|
||||
let swapped = 0;
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
for (let j = i + 1; j < n; j += 1) {
|
||||
const si = at[i];
|
||||
const sj = at[j];
|
||||
const before = costAt(i, si, j) + costAt(j, sj, i);
|
||||
const after = costAt(i, sj, j) + costAt(j, si, i);
|
||||
if (after < before - 1e-6) {
|
||||
at[i] = sj;
|
||||
at[j] = si;
|
||||
swapped += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!swapped) break;
|
||||
}
|
||||
}
|
||||
const out = new Map();
|
||||
members.forEach((id, i) => out.set(id, { x: slots[at[i]].x, y: slots[at[i]].y }));
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Острова вокруг центра. Каждый следующий – туда, где он ближе всего к центру (с учётом
|
||||
* растяжения под экран), но рядом с теми островами, с кем у него больше знакомств.
|
||||
* Положение по каждому направлению считается точно: для каждого уже стоящего острова
|
||||
* запретный отрезок расстояний – корни квадратного уравнения.
|
||||
*/
|
||||
function packIslands(islands, affinity, focusRadius, stretch) {
|
||||
const placed = [];
|
||||
const centers = new Map();
|
||||
const ANGLES = 96;
|
||||
for (const island of islands) {
|
||||
let best = null;
|
||||
for (let k = 0; k < ANGLES; k += 1) {
|
||||
const theta = -Math.PI / 2 + (k * Math.PI * 2) / ANGLES;
|
||||
const ux = Math.cos(theta) * stretch.x;
|
||||
const uy = Math.sin(theta) * stretch.y;
|
||||
const uu = ux * ux + uy * uy;
|
||||
const intervals = [];
|
||||
const keep = focusRadius + island.r + ISLAND_GAP;
|
||||
intervals.push([-Infinity, keep / Math.sqrt(uu)]);
|
||||
for (const other of placed) {
|
||||
const reach = island.r + other.r + ISLAND_GAP;
|
||||
const b = -2 * (ux * other.x + uy * other.y);
|
||||
const c = other.x * other.x + other.y * other.y - reach * reach;
|
||||
const disc = b * b - 4 * uu * c;
|
||||
if (disc <= 0) continue;
|
||||
const sq = Math.sqrt(disc);
|
||||
intervals.push([(-b - sq) / (2 * uu), (-b + sq) / (2 * uu)]);
|
||||
}
|
||||
intervals.sort((p, q) => p[0] - q[0]);
|
||||
let d = 0;
|
||||
for (let guard = 0; guard < intervals.length + 2; guard += 1) {
|
||||
let moved = false;
|
||||
for (const [d1, d2] of intervals) {
|
||||
if (d1 < d + 1e-6 && d < d2 - 1e-6) { d = d2; moved = true; }
|
||||
}
|
||||
if (!moved) break;
|
||||
}
|
||||
const x = ux * d;
|
||||
const y = uy * d;
|
||||
let pull = 0;
|
||||
let pullW = 0;
|
||||
affinity.get(island.id)?.forEach((w, otherId) => {
|
||||
const c = centers.get(otherId);
|
||||
if (!c) return;
|
||||
pull += w * Math.hypot(x - c.x, y - c.y);
|
||||
pullW += w;
|
||||
});
|
||||
const cost = d + (pullW ? (0.55 * pull) / pullW : 0) + k * 1e-6;
|
||||
if (!best || cost < best.cost) best = { x, y, cost };
|
||||
}
|
||||
const spot = { id: island.id, x: best.x, y: best.y, r: island.r };
|
||||
placed.push(spot);
|
||||
centers.set(island.id, spot);
|
||||
}
|
||||
return centers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Координаты людей первого круга островами.
|
||||
* @param {Object} o
|
||||
* @param {Array<{id:string, kind:string, members:string[]}>} o.groups – по порядку (крупные первыми)
|
||||
* @param {Map<string, Map<string, number>>} o.weights
|
||||
* @param {(id:string) => number} o.rankOf – близость к центру (0 – близкий … 3 – контакт)
|
||||
* @param {number} o.focusRadius – сколько места оставить вокруг человека в центре
|
||||
* @param {{x:number, y:number}} o.stretch
|
||||
* @returns {{ positions: Map<string,{x:number,y:number}>, islands: Map<string,{x:number,y:number,r:number}> }}
|
||||
*/
|
||||
export function layoutIslands({ groups, weights, rankOf, focusRadius = 70, stretch = { x: 1, y: 1 } }) {
|
||||
const local = new Map();
|
||||
const islands = [];
|
||||
for (const group of groups) {
|
||||
if (!group.members.length) continue;
|
||||
const slots = islandSlots(group.members, weights, rankOf);
|
||||
let r = 0;
|
||||
slots.forEach((p) => { r = Math.max(r, Math.hypot(p.x, p.y)); });
|
||||
local.set(group.id, slots);
|
||||
islands.push({ id: group.id, r: r + NODE_RADIUS + ISLAND_PAD });
|
||||
}
|
||||
// Сколько знакомств между островами – соседями становятся самые связанные.
|
||||
const groupOf = new Map();
|
||||
groups.forEach((group) => group.members.forEach((id) => groupOf.set(id, group.id)));
|
||||
const affinity = new Map();
|
||||
weights.forEach((near, a) => {
|
||||
const ga = groupOf.get(a);
|
||||
if (!ga) return;
|
||||
near.forEach((w, b) => {
|
||||
const gb = groupOf.get(b);
|
||||
if (!gb || gb === ga) return;
|
||||
if (!affinity.has(ga)) affinity.set(ga, new Map());
|
||||
affinity.get(ga).set(gb, (affinity.get(ga).get(gb) || 0) + w);
|
||||
});
|
||||
});
|
||||
const centers = packIslands(islands, affinity, focusRadius, stretch);
|
||||
const positions = new Map();
|
||||
local.forEach((slots, groupId) => {
|
||||
const c = centers.get(groupId);
|
||||
slots.forEach((p, id) => positions.set(id, { x: c.x + p.x, y: c.y + p.y }));
|
||||
});
|
||||
return { positions, islands: centers };
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
// Компании карты связей на этом устройстве: свои названия и кого куда перенесли вручную.
|
||||
// Отдельно для аккаунта и для каждой карты (человека в центре). Сами компании каждый раз
|
||||
// находятся заново по знакомствам (communities.js); здесь – только то, что владелец решил сам:
|
||||
// названная компания узнаётся по составу, перенесённый человек остаётся там, куда его поставили.
|
||||
import { state } from '../../state.js';
|
||||
import { REST_GROUP } from './communities.js';
|
||||
|
||||
const PREFIX = 'shine-network-companies-v1:';
|
||||
const MAX_MAPS = 20;
|
||||
const MAX_NAME = 40;
|
||||
|
||||
function ownerLogin() {
|
||||
return String(state.session?.login || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function readAll() {
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return {};
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(PREFIX + owner) || '{}');
|
||||
return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function writeAll(all) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return;
|
||||
const keys = Object.keys(all);
|
||||
if (keys.length > MAX_MAPS) {
|
||||
keys.sort((a, b) => (all[a]?.updatedAt || 0) - (all[b]?.updatedAt || 0))
|
||||
.slice(0, keys.length - MAX_MAPS)
|
||||
.forEach((key) => { delete all[key]; });
|
||||
}
|
||||
try {
|
||||
localStorage.setItem(PREFIX + owner, JSON.stringify(all));
|
||||
} catch {
|
||||
// Нет места или приватный режим – названия проживут до закрытия экрана.
|
||||
}
|
||||
}
|
||||
|
||||
function emptyEntry() {
|
||||
return { groups: {}, assign: {}, updatedAt: 0 };
|
||||
}
|
||||
|
||||
function entryOf(all, centerKey) {
|
||||
const entry = all[centerKey];
|
||||
if (!entry || typeof entry !== 'object') return emptyEntry();
|
||||
return {
|
||||
groups: entry.groups && typeof entry.groups === 'object' ? entry.groups : {},
|
||||
assign: entry.assign && typeof entry.assign === 'object' ? entry.assign : {},
|
||||
updatedAt: Number(entry.updatedAt) || 0,
|
||||
};
|
||||
}
|
||||
|
||||
function save(centerKey, entry) {
|
||||
if (!centerKey) return;
|
||||
const all = readAll();
|
||||
// Компания без названия и без перенесённых в неё людей больше ничего не значит.
|
||||
const used = new Set(Object.values(entry.assign));
|
||||
Object.keys(entry.groups).forEach((id) => {
|
||||
if (!String(entry.groups[id]?.name || '').trim() && !used.has(id)) delete entry.groups[id];
|
||||
});
|
||||
if (!Object.keys(entry.groups).length && !Object.keys(entry.assign).length) delete all[centerKey];
|
||||
else all[centerKey] = { ...entry, updatedAt: Date.now() };
|
||||
writeAll(all);
|
||||
}
|
||||
|
||||
function newId() {
|
||||
return `u${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
||||
}
|
||||
|
||||
/** Что владелец решил сам: { groups: [{ id, name, members, color }], assign: Map(человек → компания) }. */
|
||||
export function getCompanySettings(centerKey) {
|
||||
const entry = entryOf(readAll(), centerKey);
|
||||
return {
|
||||
groups: Object.entries(entry.groups).map(([id, group]) => ({
|
||||
id,
|
||||
name: String(group?.name || '').slice(0, MAX_NAME),
|
||||
members: Array.isArray(group?.members) ? group.members.map(String) : [],
|
||||
color: Number.isInteger(group?.color) ? group.color : undefined,
|
||||
})),
|
||||
assign: new Map(Object.entries(entry.assign).map(([id, group]) => [id, String(group)])),
|
||||
};
|
||||
}
|
||||
|
||||
/** Снимок для «Отменить»: вернуть всё как было – restoreCompanySettings. */
|
||||
export function snapshotCompanySettings(centerKey) {
|
||||
return JSON.parse(JSON.stringify(entryOf(readAll(), centerKey)));
|
||||
}
|
||||
|
||||
export function restoreCompanySettings(centerKey, snapshot) {
|
||||
if (!snapshot) return;
|
||||
save(centerKey, entryOf({ [centerKey]: snapshot }, centerKey));
|
||||
}
|
||||
|
||||
// Компания, найденная автоматически, становится «своей» (с постоянным id), как только ей
|
||||
// дали название или перенесли в неё человека: дальше её узнают по составу.
|
||||
function ensureSaved(entry, group) {
|
||||
if (entry.groups[group.id]) return group.id;
|
||||
const id = newId();
|
||||
entry.groups[id] = {
|
||||
name: '',
|
||||
members: group.members.filter((personId) => !entry.assign[personId]),
|
||||
color: Number.isInteger(group.color) && group.color >= 0 ? group.color : undefined,
|
||||
};
|
||||
return id;
|
||||
}
|
||||
|
||||
/** Название компании (пустое – вернуть автоматическое). Возвращает id компании. */
|
||||
export function setCompanyName(centerKey, group, name) {
|
||||
const entry = entryOf(readAll(), centerKey);
|
||||
const id = ensureSaved(entry, group);
|
||||
entry.groups[id].name = String(name || '').trim().slice(0, MAX_NAME);
|
||||
save(centerKey, entry);
|
||||
return id;
|
||||
}
|
||||
|
||||
/** Перенести человека в компанию (group – из buildCompanies или { id: REST_GROUP }). */
|
||||
export function assignToCompany(centerKey, personId, group) {
|
||||
const entry = entryOf(readAll(), centerKey);
|
||||
if (group.id === REST_GROUP) {
|
||||
entry.assign[personId] = REST_GROUP;
|
||||
} else {
|
||||
const id = ensureSaved(entry, group);
|
||||
entry.assign[personId] = id;
|
||||
}
|
||||
save(centerKey, entry);
|
||||
}
|
||||
|
||||
/** Новая компания с одним человеком. Возвращает её id. */
|
||||
export function createCompany(centerKey, name, personId) {
|
||||
const entry = entryOf(readAll(), centerKey);
|
||||
const id = newId();
|
||||
entry.groups[id] = { name: String(name || '').trim().slice(0, MAX_NAME), members: [], color: undefined };
|
||||
entry.assign[personId] = id;
|
||||
save(centerKey, entry);
|
||||
return id;
|
||||
}
|
||||
|
||||
/** Обновить состав и цвет узнанных компаний (чтобы узнавать их и дальше). */
|
||||
export function updateCompanySnapshots(centerKey, snapshots) {
|
||||
if (!snapshots?.length) return;
|
||||
const entry = entryOf(readAll(), centerKey);
|
||||
let changed = false;
|
||||
for (const row of snapshots) {
|
||||
const group = entry.groups[row.id];
|
||||
if (!group) continue;
|
||||
group.members = row.members;
|
||||
if (Number.isInteger(row.color)) group.color = row.color;
|
||||
changed = true;
|
||||
}
|
||||
if (changed) save(centerKey, entry);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,173 @@
|
||||
// Раскладки карты связей – на этом устройстве, отдельно для аккаунта.
|
||||
// Автоматические раскладки (rings – по близости, companies – компании по знакомствам,
|
||||
// interests – по подпискам, cities – по городам) считаются заново при каждом открытии.
|
||||
// Прежние «по группам», «Подсолнух» и «Мандала» убраны: это была та же близость другой
|
||||
// формой; сохранённые с ними карты открываются «по близости».
|
||||
// «Своя» (manual) – расстановка людей, сохранённая для каждой карты отдельно: координаты
|
||||
// относительно человека в центре плюс базовая автоматическая раскладка, по которой встают
|
||||
// люди, появившиеся на карте позже.
|
||||
import { state } from '../../state.js';
|
||||
|
||||
const LAYOUT_PREFIX = 'shine-network-layout-v1:';
|
||||
const VIEW_PREFIX = 'shine-network-view-v1:';
|
||||
const MAX_MAPS = 40; // старые раскладки вытесняются, чтобы хранилище не росло бесконечно
|
||||
|
||||
export const AUTO_LAYOUT_MODES = ['rings', 'companies', 'interests', 'cities'];
|
||||
const LAYOUT_MODES = [...AUTO_LAYOUT_MODES, 'manual'];
|
||||
|
||||
function ownerLogin() {
|
||||
return String(state.session?.login || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function readJson(key) {
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(key) || '{}');
|
||||
return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function writeJson(key, value) {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(value));
|
||||
} catch {
|
||||
// Нет места или приватный режим – раскладка проживёт до закрытия экрана.
|
||||
}
|
||||
}
|
||||
|
||||
function autoMode(value) {
|
||||
return AUTO_LAYOUT_MODES.includes(value) ? value : 'rings';
|
||||
}
|
||||
|
||||
// Раньше перетащенные точки действовали в любой раскладке. Чтобы после обновления карта
|
||||
// выглядела как прежде, такие карты считаются «своей раскладкой» поверх прежнего режима.
|
||||
function migrateLegacy(owner) {
|
||||
const view = readJson(VIEW_PREFIX + owner);
|
||||
if (view.layoutV === 2) return;
|
||||
const all = readJson(LAYOUT_PREFIX + owner);
|
||||
const previousMode = autoMode(view.mode);
|
||||
let legacy = false;
|
||||
Object.values(all).forEach((entry) => {
|
||||
if (entry && typeof entry === 'object' && !entry.base) {
|
||||
entry.base = previousMode;
|
||||
legacy = true;
|
||||
}
|
||||
});
|
||||
if (legacy) {
|
||||
writeJson(LAYOUT_PREFIX + owner, all);
|
||||
view.autoMode = previousMode;
|
||||
view.mode = 'manual';
|
||||
}
|
||||
view.layoutV = 2;
|
||||
writeJson(VIEW_PREFIX + owner, view);
|
||||
}
|
||||
|
||||
function entryOf(centerKey) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner || !centerKey) return null;
|
||||
const entry = readJson(LAYOUT_PREFIX + owner)[centerKey];
|
||||
return entry && typeof entry === 'object' && entry.points && Object.keys(entry.points).length ? entry : null;
|
||||
}
|
||||
|
||||
export function hasManualLayout(centerKey) {
|
||||
return Boolean(entryOf(centerKey));
|
||||
}
|
||||
|
||||
export function getManualLayout(centerKey) {
|
||||
const out = new Map();
|
||||
const points = entryOf(centerKey)?.points || {};
|
||||
for (const [id, point] of Object.entries(points)) {
|
||||
if (Array.isArray(point) && Number.isFinite(point[0]) && Number.isFinite(point[1])) out.set(id, { x: point[0], y: point[1] });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// По какой автоматической раскладке встают те, кого в своей раскладке ещё нет.
|
||||
export function getManualBase(centerKey) {
|
||||
return autoMode(entryOf(centerKey)?.base);
|
||||
}
|
||||
|
||||
function writeEntry(centerKey, entry) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner || !centerKey) return;
|
||||
const all = readJson(LAYOUT_PREFIX + owner);
|
||||
if (entry) all[centerKey] = entry;
|
||||
else delete all[centerKey];
|
||||
const keys = Object.keys(all);
|
||||
if (keys.length > MAX_MAPS) {
|
||||
keys.sort((a, b) => (all[a].updatedAt || 0) - (all[b].updatedAt || 0))
|
||||
.slice(0, keys.length - MAX_MAPS)
|
||||
.forEach((key) => { delete all[key]; });
|
||||
}
|
||||
writeJson(LAYOUT_PREFIX + owner, all);
|
||||
}
|
||||
|
||||
/** Сохраняет всю расстановку как «свою»; возвращает прежнюю (для «Отменить») или null. */
|
||||
export function saveManualLayout(centerKey, points, base) {
|
||||
const previous = entryOf(centerKey);
|
||||
const stored = {};
|
||||
points.forEach((point, id) => { stored[id] = [Math.round(point.x), Math.round(point.y)]; });
|
||||
writeEntry(centerKey, { points: stored, base: autoMode(base), updatedAt: Date.now() });
|
||||
return previous;
|
||||
}
|
||||
|
||||
export function setManualPoint(centerKey, id, point) {
|
||||
if (!id) return;
|
||||
const entry = entryOf(centerKey) || { points: {}, base: 'rings' };
|
||||
entry.points[id] = [Math.round(point.x), Math.round(point.y)];
|
||||
entry.updatedAt = Date.now();
|
||||
writeEntry(centerKey, entry);
|
||||
}
|
||||
|
||||
/** Удаляет свою раскладку карты; возвращает удалённую (для «Вернуть») или null. */
|
||||
export function clearManualLayout(centerKey) {
|
||||
const previous = entryOf(centerKey);
|
||||
writeEntry(centerKey, null);
|
||||
return previous;
|
||||
}
|
||||
|
||||
/** Возвращает раскладку, снятую clearManualLayout / saveManualLayout (null – удалить). */
|
||||
export function restoreManualLayout(centerKey, entry) {
|
||||
writeEntry(centerKey, entry && entry.points ? entry : null);
|
||||
}
|
||||
|
||||
export function getLayoutMode() {
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return 'rings';
|
||||
migrateLegacy(owner);
|
||||
const mode = readJson(VIEW_PREFIX + owner).mode;
|
||||
return LAYOUT_MODES.includes(mode) ? mode : 'rings';
|
||||
}
|
||||
|
||||
// Последняя выбранная автоматическая – для карт, у которых своей раскладки нет.
|
||||
export function getAutoLayoutMode() {
|
||||
const owner = ownerLogin();
|
||||
const view = readJson(VIEW_PREFIX + owner);
|
||||
return autoMode(AUTO_LAYOUT_MODES.includes(view.mode) ? view.mode : view.autoMode);
|
||||
}
|
||||
|
||||
export function setLayoutMode(mode) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return;
|
||||
const view = readJson(VIEW_PREFIX + owner);
|
||||
view.mode = LAYOUT_MODES.includes(mode) ? mode : 'rings';
|
||||
if (AUTO_LAYOUT_MODES.includes(view.mode)) view.autoMode = view.mode;
|
||||
view.layoutV = 2;
|
||||
writeJson(VIEW_PREFIX + owner, view);
|
||||
}
|
||||
|
||||
// Прочие настройки экрана на этом устройстве: карта или список, порядок списка.
|
||||
export function getViewSetting(key, fallback) {
|
||||
const owner = ownerLogin();
|
||||
const value = readJson(VIEW_PREFIX + owner)[key];
|
||||
return value === undefined ? fallback : value;
|
||||
}
|
||||
|
||||
export function setViewSetting(key, value) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return;
|
||||
const view = readJson(VIEW_PREFIX + owner);
|
||||
view[key] = value;
|
||||
writeJson(VIEW_PREFIX + owner, view);
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
// Общее контекстное меню узла (долгое нажатие) для карты связей.
|
||||
// Рендерится в #modal-root (вне масштабируемого холста), позиционируется по экранному rect узла.
|
||||
// Используется и реальным путём (network-view.js), и лабораторией (lab.js).
|
||||
|
||||
const REL_RU = {
|
||||
family: 'Семья',
|
||||
friend: 'Друг',
|
||||
business: 'Бизнес',
|
||||
contact: 'Контакт',
|
||||
self: 'Вы',
|
||||
};
|
||||
|
||||
function escapeHtml(text) {
|
||||
return String(text || '')
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
|
||||
export function relationLabelRu(relationType) {
|
||||
return REL_RU[relationType] || 'Контакт';
|
||||
}
|
||||
|
||||
/**
|
||||
* Открывает контекстное меню узла.
|
||||
* @param {Object} opts
|
||||
* @param {string} opts.login - логин/идентификатор для заголовка
|
||||
* @param {string} opts.relationType - тип связи (для подписи)
|
||||
* @param {{x:number,y:number,rect?:DOMRect}} opts.point - экранная точка/rect узла
|
||||
* @param {Array<{label:string, onClick:Function, disabled?:boolean}>} opts.actions - пункты меню
|
||||
*/
|
||||
export function openNodeMenu({ login, displayName = '', relationType, point, actions = [] } = {}) {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!(root instanceof HTMLElement)) return;
|
||||
|
||||
const itemsHtml = actions
|
||||
.map((a, i) => `<button class="ui-button fg-menu-item${a.disabled ? ' is-stub' : ''}" type="button" data-i="${i}" role="menuitem"${a.disabled ? ' disabled' : ''}>${escapeHtml(a.label)}</button>`)
|
||||
.join('');
|
||||
|
||||
root.innerHTML = `
|
||||
<div class="fg-menu-overlay" id="fg-menu-overlay">
|
||||
<div class="fg-menu" id="fg-menu" role="menu">
|
||||
<div class="fg-menu-head">
|
||||
<span class="fg-menu-login">${escapeHtml(displayName || login)}</span>${displayName && displayName !== login ? `<small class="fg-menu-secondary-login">${escapeHtml(login)}</small>` : ''}
|
||||
<span class="fg-menu-rel">${escapeHtml(relationLabelRu(relationType))}</span>
|
||||
</div>
|
||||
${itemsHtml}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const overlay = root.querySelector('#fg-menu-overlay');
|
||||
const menu = root.querySelector('#fg-menu');
|
||||
if (!(overlay instanceof HTMLElement) || !(menu instanceof HTMLElement)) { root.innerHTML = ''; return; }
|
||||
|
||||
// позиционируем рядом с узлом по его экранному rect (синхронно, без rAF — он может троттлиться)
|
||||
const rect = point?.rect;
|
||||
const px = point?.x ?? (rect ? rect.left + rect.width / 2 : window.innerWidth / 2);
|
||||
const belowY = rect ? rect.bottom + 8 : (point?.y ?? 80);
|
||||
const mw = menu.offsetWidth;
|
||||
const mh = menu.offsetHeight;
|
||||
let left = px - mw / 2;
|
||||
left = Math.max(8, Math.min(left, window.innerWidth - mw - 8));
|
||||
let top = belowY;
|
||||
if (top + mh > window.innerHeight - 8) top = Math.max(8, (rect ? rect.top : belowY) - mh - 8);
|
||||
menu.style.left = `${left}px`;
|
||||
menu.style.top = `${top}px`;
|
||||
|
||||
const close = () => { root.innerHTML = ''; };
|
||||
overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });
|
||||
menu.addEventListener('click', (e) => {
|
||||
const btn = e.target instanceof HTMLElement ? e.target.closest('[data-i]') : null;
|
||||
if (!(btn instanceof HTMLElement)) return;
|
||||
const idx = Number(btn.dataset.i);
|
||||
const action = actions[idx];
|
||||
if (!action || action.disabled) return;
|
||||
close();
|
||||
if (typeof action.onClick === 'function') action.onClick();
|
||||
});
|
||||
|
||||
return close;
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
// Кто с кем знаком, кто на что подписан и кто где живёт – данные для «Компаний», «Интересов»
|
||||
// и «Городов».
|
||||
// Собираются по одному запросу на человека, поэтому не перезапрашиваются при каждом открытии:
|
||||
// для своей карты лежат на устройстве, для чужих – в памяти, пока открыто приложение.
|
||||
// Сервер не трогаем: знакомства – из графа связей каждого человека, подписки – из списка
|
||||
// «Подписки» его профиля (публичные каналы), город – из параметра city его профиля.
|
||||
import { state } from '../../state.js';
|
||||
|
||||
const PREFIX = { ties: 'shine-network-ties-v1:', subs: 'shine-network-subs-v1:', cities: 'shine-network-cities-v1:' };
|
||||
export const PEOPLE_DATA_FRESH_MS = 12 * 60 * 60 * 1000; // старше – освежаются в фоне
|
||||
const TYPE_CODE = { close_friend: 3, family: 3, friend: 2, contact: 1 };
|
||||
const CODE_TYPE = { 3: 'close_friend', 2: 'friend', 1: 'contact' };
|
||||
|
||||
const memory = new Map(); // `${kind}|${owner}|${center}` → запись
|
||||
|
||||
function ownerLogin() {
|
||||
return String(state.session?.login || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function persistent(centerKey) {
|
||||
return Boolean(centerKey) && centerKey === ownerLogin();
|
||||
}
|
||||
|
||||
function readStored(kind, centerKey) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner || !persistent(centerKey)) return null;
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(PREFIX[kind] + owner) || 'null');
|
||||
return raw && typeof raw === 'object' ? raw : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeStored(kind, centerKey, value) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner || !persistent(centerKey)) return;
|
||||
try {
|
||||
localStorage.setItem(PREFIX[kind] + owner, JSON.stringify(value));
|
||||
} catch {
|
||||
// Нет места – данные останутся в памяти до закрытия приложения.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Знакомства: { at, people: Map(человек → Map(знакомый → { type, mutual })) }.
|
||||
* people хранит только тех, у кого граф уже загружен (в том числе пустой).
|
||||
*/
|
||||
export function getTies(centerKey) {
|
||||
const key = `ties|${ownerLogin()}|${centerKey}`;
|
||||
if (memory.has(key)) return memory.get(key);
|
||||
const raw = readStored('ties', centerKey);
|
||||
if (!raw || typeof raw.people !== 'object') return null;
|
||||
const people = new Map();
|
||||
for (const [id, list] of Object.entries(raw.people)) {
|
||||
const near = new Map();
|
||||
if (Array.isArray(list)) {
|
||||
list.forEach((row) => {
|
||||
if (Array.isArray(row) && row[0]) near.set(String(row[0]), { type: CODE_TYPE[row[1]] || 'contact', mutual: row[2] !== 0 });
|
||||
});
|
||||
}
|
||||
people.set(id, near);
|
||||
}
|
||||
const entry = { at: Number(raw.at) || 0, people };
|
||||
memory.set(key, entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
export function saveTies(centerKey, entry) {
|
||||
memory.set(`ties|${ownerLogin()}|${centerKey}`, entry);
|
||||
const people = {};
|
||||
entry.people.forEach((near, id) => {
|
||||
people[id] = [...near.entries()].map(([other, tie]) => [other, TYPE_CODE[tie.type] || 1, tie.mutual ? 1 : 0]);
|
||||
});
|
||||
writeStored('ties', centerKey, { at: entry.at, people });
|
||||
}
|
||||
|
||||
/**
|
||||
* Подписки: { at, of: Map(человек → [ключ канала]), info: Map(ключ → { name, owner, slug, bch, root, hash }) }.
|
||||
*/
|
||||
export function getSubs(centerKey) {
|
||||
const key = `subs|${ownerLogin()}|${centerKey}`;
|
||||
if (memory.has(key)) return memory.get(key);
|
||||
const raw = readStored('subs', centerKey);
|
||||
if (!raw || typeof raw.of !== 'object' || typeof raw.info !== 'object') return null;
|
||||
const of = new Map(Object.entries(raw.of).map(([id, list]) => [id, Array.isArray(list) ? list.map(String) : []]));
|
||||
const info = new Map(Object.entries(raw.info).map(([channel, row]) => [channel, {
|
||||
name: String(row?.n || channel),
|
||||
owner: String(row?.o || ''),
|
||||
slug: String(row?.s || ''),
|
||||
bch: String(row?.b || ''),
|
||||
root: Number(row?.r) || 0,
|
||||
hash: String(row?.h || ''),
|
||||
}]));
|
||||
const entry = { at: Number(raw.at) || 0, of, info };
|
||||
memory.set(key, entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
export function saveSubs(centerKey, entry) {
|
||||
memory.set(`subs|${ownerLogin()}|${centerKey}`, entry);
|
||||
// Каналы, которые больше никто не читает, не храним.
|
||||
const used = new Set();
|
||||
entry.of.forEach((list) => list.forEach((channel) => used.add(channel)));
|
||||
const info = {};
|
||||
entry.info.forEach((row, channel) => {
|
||||
if (used.has(channel)) info[channel] = { n: row.name, o: row.owner, s: row.slug, b: row.bch, r: row.root, h: row.hash };
|
||||
});
|
||||
writeStored('subs', centerKey, { at: entry.at, of: Object.fromEntries(entry.of), info });
|
||||
}
|
||||
|
||||
/** Города: { at, of: Map(человек → город как написан; '' – не указан) }. */
|
||||
export function getCities(centerKey) {
|
||||
const key = `cities|${ownerLogin()}|${centerKey}`;
|
||||
if (memory.has(key)) return memory.get(key);
|
||||
const raw = readStored('cities', centerKey);
|
||||
if (!raw || typeof raw.of !== 'object') return null;
|
||||
const entry = { at: Number(raw.at) || 0, of: new Map(Object.entries(raw.of).map(([id, city]) => [id, String(city || '')])) };
|
||||
memory.set(key, entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
export function saveCities(centerKey, entry) {
|
||||
memory.set(`cities|${ownerLogin()}|${centerKey}`, entry);
|
||||
writeStored('cities', centerKey, { at: entry.at, of: Object.fromEntries(entry.of) });
|
||||
}
|
||||
|
||||
// Ключ канала: владелец и короткое имя – одинаковые у всех подписчиков.
|
||||
export function channelKey(row) {
|
||||
return `${String(row?.ownerLogin || '').trim().toLowerCase()}/${String(row?.slug || '').trim().toLowerCase()}`;
|
||||
}
|
||||
|
||||
export function channelInfo(row) {
|
||||
return {
|
||||
name: String(row?.displayName || row?.slug || '').trim() || channelKey(row),
|
||||
owner: String(row?.ownerLogin || ''),
|
||||
slug: String(row?.slug || ''),
|
||||
bch: String(row?.ownerBlockchainName || ''),
|
||||
root: Number(row?.rootBlockNumber) || 0,
|
||||
hash: String(row?.rootBlockHashHex || ''),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
// «Уведомления» в настройках: звук сообщений, разрешение системных уведомлений и чаты
|
||||
// «без звука». Всё – настройки этого устройства, сервер про них не знает.
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createPersonRow } from '../components/person-row.js';
|
||||
import { authService, getRememberedDmPeer, normalizeDmChatId, rememberDmPeer } from '../state.js';
|
||||
import {
|
||||
DM_CHAT_PREFS_EVENT, formatDmMuteUntil, getMutedDmChats, setDmChatMuted,
|
||||
} from '../services/dm-chat-prefs.js';
|
||||
import { DEVICE_PREFS_EVENT, getDevicePref, setDevicePref } from '../services/device-prefs.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
|
||||
export const pageMeta = { id: 'notification-settings-view', title: 'Уведомления' };
|
||||
|
||||
function permissionState() {
|
||||
if (typeof Notification === 'undefined') return 'unsupported';
|
||||
return Notification.permission; // granted | denied | default
|
||||
}
|
||||
|
||||
export function render({ navigate, chrome } = {}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack notification-settings-screen';
|
||||
let disposed = false;
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'Уведомления',
|
||||
back: { onClick: () => navigate('settings-view') },
|
||||
}));
|
||||
|
||||
const soundTitle = document.createElement('p');
|
||||
soundTitle.className = 'nav-list__title';
|
||||
soundTitle.textContent = 'Сообщения';
|
||||
const soundList = document.createElement('div');
|
||||
soundList.className = 'nav-list';
|
||||
const soundRow = document.createElement('label');
|
||||
soundRow.className = 'nav-row nav-row--switch';
|
||||
soundRow.innerHTML = `
|
||||
<span class="nav-row__text">
|
||||
<span class="nav-row__label">Звук в открытом приложении</span>
|
||||
<span class="nav-row__hint">Короткий сигнал о новом сообщении</span>
|
||||
</span>
|
||||
<input class="switch" type="checkbox" />
|
||||
`;
|
||||
const soundSwitch = soundRow.querySelector('input');
|
||||
soundSwitch.checked = getDevicePref('dmSound', true) !== false;
|
||||
soundSwitch.addEventListener('change', () => setDevicePref('dmSound', soundSwitch.checked));
|
||||
soundList.append(soundRow);
|
||||
|
||||
// Системные уведомления – когда приложение свёрнуто или закрыто.
|
||||
const systemList = document.createElement('div');
|
||||
systemList.className = 'nav-list';
|
||||
const systemRow = document.createElement('div');
|
||||
systemRow.className = 'nav-row nav-row--action';
|
||||
systemList.append(systemRow);
|
||||
|
||||
function renderSystemRow() {
|
||||
const permission = permissionState();
|
||||
const texts = {
|
||||
granted: ['Уведомления на устройстве', 'Разрешены: придут, даже когда приложение свёрнуто'],
|
||||
denied: ['Уведомления на устройстве', 'Запрещены. Разрешите их для этого сайта в настройках браузера'],
|
||||
default: ['Уведомления на устройстве', 'Пока не разрешены – без них не узнать о сообщении, когда приложение свёрнуто'],
|
||||
unsupported: ['Уведомления на устройстве', 'Этот браузер их не поддерживает'],
|
||||
};
|
||||
const [label, hint] = texts[permission] || texts.unsupported;
|
||||
systemRow.innerHTML = `
|
||||
<span class="nav-row__text">
|
||||
<span class="nav-row__label"></span>
|
||||
<span class="nav-row__hint"></span>
|
||||
</span>
|
||||
`;
|
||||
systemRow.querySelector('.nav-row__label').textContent = label;
|
||||
systemRow.querySelector('.nav-row__hint').textContent = hint;
|
||||
if (permission === 'default') {
|
||||
const allow = document.createElement('button');
|
||||
allow.type = 'button';
|
||||
allow.className = 'primary-btn nav-row__button';
|
||||
allow.textContent = 'Разрешить';
|
||||
allow.addEventListener('click', async () => {
|
||||
allow.disabled = true;
|
||||
try {
|
||||
const result = await Notification.requestPermission();
|
||||
if (result === 'granted') showToast('Уведомления разрешены');
|
||||
} catch {
|
||||
showToast('Не удалось запросить разрешение', { kind: 'error' });
|
||||
}
|
||||
if (!disposed) renderSystemRow();
|
||||
});
|
||||
systemRow.append(allow);
|
||||
}
|
||||
}
|
||||
renderSystemRow();
|
||||
|
||||
// Чаты «без звука»: кто и до какого времени; звук возвращается кнопкой в строке.
|
||||
const mutedTitle = document.createElement('p');
|
||||
mutedTitle.className = 'nav-list__title';
|
||||
const mutedList = document.createElement('div');
|
||||
mutedList.className = 'notification-settings-muted';
|
||||
const mutedEmpty = document.createElement('p');
|
||||
mutedEmpty.className = 'meta-muted appearance-hint';
|
||||
mutedEmpty.textContent = 'Нет. Выключить звук чата можно в его меню «•••» или долгим нажатием в списке чатов.';
|
||||
let peersRequested = false;
|
||||
|
||||
function mutedRow({ chatId, until }) {
|
||||
const peer = getRememberedDmPeer(chatId) || {};
|
||||
const fullName = [peer.firstName, peer.lastName].map((part) => String(part || '').trim()).filter(Boolean).join(' ');
|
||||
const login = peer.login || chatId;
|
||||
return createPersonRow({
|
||||
login,
|
||||
name: fullName || login,
|
||||
firstName: peer.firstName,
|
||||
lastName: peer.lastName,
|
||||
avatar: peer.avatar || null,
|
||||
sub: [fullName ? `@${login}` : '', until ? formatDmMuteUntil(until) : 'навсегда'].filter(Boolean).join(' · '),
|
||||
onClick: () => navigate(`chat/${encodeURIComponent(normalizeDmChatId(chatId))}`),
|
||||
actions: [{ icon: 'bell', label: 'Включить звук', onClick: () => setDmChatMuted(chatId, false) }],
|
||||
});
|
||||
}
|
||||
|
||||
// Имена и аватары – из списка чатов; если его в этот раз не открывали, спрашиваем сервер один раз.
|
||||
async function loadPeers() {
|
||||
peersRequested = true;
|
||||
try {
|
||||
const payload = await authService.listContacts();
|
||||
if (disposed) return;
|
||||
(Array.isArray(payload?.dialogs) ? payload.dialogs : []).forEach((dialog) => rememberDmPeer({
|
||||
login: dialog?.peerLogin,
|
||||
firstName: dialog?.firstName,
|
||||
lastName: dialog?.lastName,
|
||||
avatar: dialog?.avatar,
|
||||
}));
|
||||
renderMuted();
|
||||
} catch {
|
||||
// Без имён строки остаются с логинами – этого достаточно.
|
||||
}
|
||||
}
|
||||
|
||||
function renderMuted() {
|
||||
const muted = getMutedDmChats();
|
||||
mutedTitle.textContent = muted.length ? `Чаты без звука · ${muted.length}` : 'Чаты без звука';
|
||||
mutedList.hidden = !muted.length;
|
||||
mutedEmpty.hidden = Boolean(muted.length);
|
||||
mutedList.replaceChildren(...muted.map(mutedRow));
|
||||
if (!peersRequested && muted.some(({ chatId }) => !getRememberedDmPeer(chatId))) void loadPeers();
|
||||
}
|
||||
renderMuted();
|
||||
|
||||
const onPrefs = () => { if (!disposed) renderMuted(); };
|
||||
const onDevicePrefs = () => { if (!disposed) soundSwitch.checked = getDevicePref('dmSound', true) !== false; };
|
||||
window.addEventListener(DM_CHAT_PREFS_EVENT, onPrefs);
|
||||
window.addEventListener(DEVICE_PREFS_EVENT, onDevicePrefs);
|
||||
|
||||
screen.append(soundTitle, soundList, systemList, mutedTitle, mutedList, mutedEmpty);
|
||||
screen.cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
window.removeEventListener(DM_CHAT_PREFS_EVENT, onPrefs);
|
||||
window.removeEventListener(DEVICE_PREFS_EVENT, onDevicePrefs);
|
||||
};
|
||||
return screen;
|
||||
}
|
||||
@@ -3,7 +3,9 @@ import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||||
import { makeProfileRoute, makeShineMessageRoute } from '../services/shine-routes.js';
|
||||
import { formatListTime } from '../services/channels-ux.js';
|
||||
import { formatListTime, showToast } from '../services/channels-ux.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { createErrorState, createLoadingState, createStateMessage } from '../components/feedback.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
|
||||
const CONNECTION_CLOSE_FRIEND = 10;
|
||||
@@ -19,23 +21,39 @@ const CONNECTION_OFFICIAL_UNCONFIRMED = 81;
|
||||
const profileSnapshotCache = new Map();
|
||||
const profileSnapshotPending = new Map();
|
||||
|
||||
function connectionActionLabel(typeCode) {
|
||||
// Глагол по полу из профиля автора («Добавила вас в друзья»); пока профиль не пришёл или пол
|
||||
// не указан – нейтральное «Добавил(а)».
|
||||
function byGender(gender, male, female, neutral) {
|
||||
if (gender === 'male') return male;
|
||||
if (gender === 'female') return female;
|
||||
return neutral;
|
||||
}
|
||||
|
||||
function connectionActionLabel(typeCode, gender = '') {
|
||||
const verb = (male, female) => byGender(gender, male, female, `${male}(а)`);
|
||||
switch (Number(typeCode)) {
|
||||
case CONNECTION_CLOSE_FRIEND: return 'Добавил(а) вас в близкие друзья';
|
||||
case CONNECTION_UNCLOSE_FRIEND: return 'Убрал(а) вас из близких друзей';
|
||||
case CONNECTION_FRIEND: return 'Добавил(а) вас в друзья';
|
||||
case CONNECTION_UNFRIEND: return 'Убрал(а) вас из друзей';
|
||||
case CONNECTION_SHINE_CONFIRMED: return 'Подтвердил(а), что вы сияющий';
|
||||
case CONNECTION_SHINE_UNCONFIRMED: return 'Снял(а) подтверждение «сияющий»';
|
||||
case CONNECTION_OFFICIAL_CONFIRMED: return 'Подтвердил(а) официальный статус аккаунта';
|
||||
case CONNECTION_OFFICIAL_UNCONFIRMED: return 'Снял(а) подтверждение официального статуса';
|
||||
default: return 'Изменил(а) связь с вами';
|
||||
case CONNECTION_CLOSE_FRIEND: return `${verb('Добавил', 'Добавила')} вас в близкие друзья`;
|
||||
case CONNECTION_UNCLOSE_FRIEND: return `${verb('Убрал', 'Убрала')} вас из близких друзей`;
|
||||
case CONNECTION_FRIEND: return `${verb('Добавил', 'Добавила')} вас в друзья`;
|
||||
case CONNECTION_UNFRIEND: return `${verb('Убрал', 'Убрала')} вас из друзей`;
|
||||
case CONNECTION_SHINE_CONFIRMED: return `${verb('Подтвердил', 'Подтвердила')}, что вы сияющий`;
|
||||
case CONNECTION_SHINE_UNCONFIRMED: return `${verb('Снял', 'Сняла')} подтверждение «сияющий»`;
|
||||
case CONNECTION_OFFICIAL_CONFIRMED: return `${verb('Подтвердил', 'Подтвердила')} официальный статус аккаунта`;
|
||||
case CONNECTION_OFFICIAL_UNCONFIRMED: return `${verb('Снял', 'Сняла')} подтверждение официального статуса`;
|
||||
default: return `${verb('Изменил', 'Изменила')} связь с вами`;
|
||||
}
|
||||
}
|
||||
|
||||
function eventActionLabel(typeCode) {
|
||||
if (Number(typeCode) === CONNECTION_UNFOLLOW) return 'Отписался(-ась) от вашего канала';
|
||||
return 'Подписался(-ась) на ваш канал';
|
||||
function eventActionLabel(typeCode, gender = '') {
|
||||
if (Number(typeCode) === CONNECTION_UNFOLLOW) return `${byGender(gender, 'Отписался', 'Отписалась', 'Отписался(-ась)')} от вашего канала`;
|
||||
return `${byGender(gender, 'Подписался', 'Подписалась', 'Подписался(-ась)')} на ваш канал`;
|
||||
}
|
||||
|
||||
function actionLabel(item, activeTab) {
|
||||
const gender = String(item.profile?.gender || '');
|
||||
return activeTab === 'connections'
|
||||
? connectionActionLabel(item.connectionTypeCode ?? item.sourceMsgSubType, gender)
|
||||
: eventActionLabel(item.sourceMsgSubType, gender);
|
||||
}
|
||||
|
||||
export const pageMeta = { id: 'notifications-view', title: 'Уведомления' };
|
||||
@@ -137,15 +155,15 @@ async function enrichItem(item, activeTab) {
|
||||
}
|
||||
|
||||
function renderEmpty(activeTab) {
|
||||
const card = document.createElement('article');
|
||||
card.className = 'stack notification-empty-state';
|
||||
const title = document.createElement('strong');
|
||||
title.textContent = activeTab === 'events' ? 'Пока нет событий' : activeTab === 'connections' ? 'Пока нет связей' : 'Пока нет ответов';
|
||||
const text = document.createElement('p');
|
||||
text.className = 'meta-muted';
|
||||
text.textContent = activeTab === 'events' ? 'Подписки и отписки от ваших каналов появятся здесь.' : activeTab === 'connections' ? 'Изменения дружбы и подтверждений появятся здесь.' : 'Когда кто-то ответит на ваше сообщение в канале или обсуждении, ответ появится здесь.';
|
||||
card.append(title, text);
|
||||
return card;
|
||||
return createStateMessage({
|
||||
icon: activeTab === 'events' ? 'channels' : activeTab === 'connections' ? 'network' : 'reply',
|
||||
title: activeTab === 'events' ? 'Пока нет событий' : activeTab === 'connections' ? 'Пока нет новостей о связях' : 'Пока нет ответов',
|
||||
text: activeTab === 'events'
|
||||
? 'Подписки и отписки от ваших каналов появятся здесь.'
|
||||
: activeTab === 'connections'
|
||||
? 'Когда вас добавят в друзья или подтвердят статус, это появится здесь.'
|
||||
: 'Когда кто-то ответит на ваше сообщение в канале или обсуждении, ответ появится здесь.',
|
||||
});
|
||||
}
|
||||
|
||||
function renderAvatar(item) {
|
||||
@@ -270,9 +288,7 @@ function renderItem(item, activeTab, navigate) {
|
||||
} else {
|
||||
const action = document.createElement('p');
|
||||
action.className = 'notification-card__action';
|
||||
action.textContent = activeTab === 'connections'
|
||||
? connectionActionLabel(item.connectionTypeCode ?? item.sourceMsgSubType)
|
||||
: eventActionLabel(item.sourceMsgSubType, item);
|
||||
action.textContent = actionLabel(item, activeTab);
|
||||
body.append(action);
|
||||
}
|
||||
|
||||
@@ -280,6 +296,23 @@ function renderItem(item, activeTab, navigate) {
|
||||
return row;
|
||||
}
|
||||
|
||||
// Профиль и счётчики пришли позже – обновляем строку на месте (наблюдение «прочитано» не теряется).
|
||||
function refreshItemRow(row, item, activeTab) {
|
||||
if (!row?.isConnected) return;
|
||||
row.querySelector('.notification-avatar')?.replaceWith(renderAvatar(item));
|
||||
const name = row.querySelector('.notification-card__name');
|
||||
if (name) name.textContent = renderHead(item).querySelector('.notification-card__name').textContent;
|
||||
const action = row.querySelector('.notification-card__action');
|
||||
if (action && activeTab !== 'replies') action.textContent = actionLabel(item, activeTab);
|
||||
if (activeTab === 'replies' && item.engagement && !row.querySelector('.notification-engagement')) {
|
||||
const engagement = renderEngagement(item.engagement);
|
||||
if (engagement) row.querySelector('.notification-card__body')?.append(engagement);
|
||||
}
|
||||
}
|
||||
|
||||
// Последние уведомления – только в памяти вкладки: при повторном заходе экран рисуется сразу, без пустого кадра.
|
||||
let lastNotifications = null;
|
||||
|
||||
export function render({ navigate, chrome } = {}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack notifications-screen';
|
||||
@@ -289,10 +322,20 @@ export function render({ navigate, chrome } = {}) {
|
||||
tabs.setAttribute('role', 'radiogroup');
|
||||
tabs.setAttribute('aria-label', 'Категория уведомлений');
|
||||
const tabDefs = [['replies','Ответы'],['connections','Связи'],['events','События']];
|
||||
chrome?.setTopbar(createTopBar({
|
||||
const topbar = createTopBar({
|
||||
title: 'Уведомления',
|
||||
className: 'topbar--root notifications-topbar',
|
||||
}));
|
||||
actions: [{
|
||||
icon: 'check-double',
|
||||
title: 'Прочитать все',
|
||||
ariaLabel: 'Отметить все уведомления прочитанными',
|
||||
className: 'notifications-read-all',
|
||||
onClick: () => { void markAllRead(); },
|
||||
}],
|
||||
});
|
||||
chrome?.setTopbar(topbar);
|
||||
const readAllBtn = topbar.querySelector('.notifications-read-all');
|
||||
if (readAllBtn) readAllBtn.disabled = true;
|
||||
screen.append(tabs);
|
||||
|
||||
const list = document.createElement('div');
|
||||
@@ -314,6 +357,7 @@ export function render({ navigate, chrome } = {}) {
|
||||
function updateToolbarBadge(payload) {
|
||||
const c = countsFromPayload(payload);
|
||||
state.notificationUnreadTotal = c.replies + c.connections + c.events;
|
||||
if (readAllBtn) readAllBtn.disabled = state.notificationUnreadTotal <= 0;
|
||||
const btn = document.querySelector('[data-toolbar-page="notifications-view"]');
|
||||
if (!btn) return;
|
||||
let badge = btn.querySelector('.notification-toolbar-badge');
|
||||
@@ -363,32 +407,148 @@ export function render({ navigate, chrome } = {}) {
|
||||
}, 350);
|
||||
}
|
||||
|
||||
let renderSeq = 0;
|
||||
async function renderCurrent() {
|
||||
const seq = ++renderSeq;
|
||||
observer?.disconnect(); observer=null; renderTabs(payloadCache || {});
|
||||
const tab=state.notificationsTab; const {items:raw,seenAt}=categoryData(payloadCache || {},tab); localSeen[tab]=Math.max(localSeen[tab]||0,seenAt);
|
||||
const base=raw.map(normalizeItem); if(!base.length){list.replaceChildren(renderEmpty(tab));return;}
|
||||
const items=await Promise.all(base.map(x=>enrichItem(x,tab)));
|
||||
// Список рисуется сразу – с профилями из кэша; остальное догружается в фоне и
|
||||
// обновляет строки на месте (раньше экран ждал загрузки профиля каждого автора).
|
||||
const items=base.map((x)=>({ ...x, profile: profileSnapshotCache.get(String(x.sourceLogin || '').toLowerCase()) || null }));
|
||||
const rowByItem = new Map();
|
||||
const unread=items.filter(x=>x.createdAtMs>seenAt); const old=items.filter(x=>x.createdAtMs<=seenAt);
|
||||
const nodes=[];
|
||||
const groupTitle=(text)=>{const el=document.createElement('h2');el.className='notification-group-title';el.textContent=text;return el;};
|
||||
if(unread.length) nodes.push(groupTitle(`Новые · ${unread.length}`));
|
||||
unread.forEach(x=>{const n=renderItem(x,tab,navigate);n.classList.add('notification-card--new');n.dataset.createdAtMs=String(x.createdAtMs);nodes.push(n);});
|
||||
unread.forEach(x=>{const n=renderItem(x,tab,navigate);n.classList.add('notification-card--new');n.dataset.createdAtMs=String(x.createdAtMs);rowByItem.set(x,n);nodes.push(n);});
|
||||
if(unread.length && old.length) nodes.push(groupTitle('Ранее'));
|
||||
old.forEach(x=>nodes.push(renderItem(x,tab,navigate))); list.replaceChildren(...nodes);
|
||||
old.forEach(x=>{const n=renderItem(x,tab,navigate);rowByItem.set(x,n);nodes.push(n);}); list.replaceChildren(...nodes);
|
||||
void enrichInBackground(items, tab, rowByItem, seq);
|
||||
if (tab === 'connections') void offerFriendBack(items, rowByItem, seq);
|
||||
if(unread.length && 'IntersectionObserver' in window){
|
||||
observer=new IntersectionObserver(entries=>{ entries.forEach(e=>{ if(e.isIntersecting && e.intersectionRatio>=0.5){ const ts=Number(e.target.dataset.createdAtMs||0); if(ts>0){e.target.classList.remove('notification-card--new');scheduleSeen(tab,ts);} } }); },{threshold:[0.5]});
|
||||
list.querySelectorAll('.notification-card--new').forEach(n=>observer.observe(n));
|
||||
}
|
||||
}
|
||||
|
||||
// «Добавил(а) вас в друзья», а вы ещё нет – кнопка «Дружить в ответ» прямо в уведомлении.
|
||||
// Кто у вас уже в друзьях – из одного запроса своего графа связей.
|
||||
async function offerFriendBack(items, rowByItem, seq) {
|
||||
const self = String(state.session.login || '').trim();
|
||||
const candidates = items.filter((x) => [CONNECTION_FRIEND, CONNECTION_CLOSE_FRIEND].includes(Number(x.connectionTypeCode ?? x.sourceMsgSubType)));
|
||||
if (!self || !candidates.length) return;
|
||||
let graph;
|
||||
try { graph = await authService.getUserConnectionsGraph(self); } catch { return; }
|
||||
if (seq !== renderSeq) return;
|
||||
const mine = new Set([...(graph?.outFriends || []), ...(graph?.outCloseFriends || [])].map((login) => String(login).toLowerCase()));
|
||||
const offered = new Set();
|
||||
for (const item of candidates) {
|
||||
const login = String(item.sourceLogin || '').trim();
|
||||
const key = login.toLowerCase();
|
||||
// Одна кнопка на человека – у самого свежего уведомления.
|
||||
if (!login || mine.has(key) || offered.has(key)) continue;
|
||||
offered.add(key);
|
||||
const row = rowByItem.get(item);
|
||||
const body = row?.querySelector('.notification-card__body');
|
||||
if (!body) continue;
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'secondary-btn notification-card__answer';
|
||||
button.textContent = 'Дружить в ответ';
|
||||
button.addEventListener('click', async (event) => {
|
||||
event.stopPropagation();
|
||||
button.disabled = true;
|
||||
button.textContent = 'Сохраняю…';
|
||||
try {
|
||||
await authService.setUserRelation({ login: self, toLogin: login, kind: 'friend', enabled: true, storagePwd: state.session.storagePwdInMemory });
|
||||
const done = document.createElement('span');
|
||||
done.className = 'notification-card__answered';
|
||||
done.innerHTML = `${iconHtml('check')}<span>Вы друзья</span>`;
|
||||
button.replaceWith(done);
|
||||
showToast('Теперь вы друзья');
|
||||
} catch (error) {
|
||||
button.disabled = false;
|
||||
button.textContent = 'Дружить в ответ';
|
||||
showToast(toUserMessage(error, 'Не удалось добавить в друзья.'), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
body.append(button);
|
||||
}
|
||||
}
|
||||
|
||||
async function enrichInBackground(items, tab, rowByItem, seq) {
|
||||
let cursor = 0;
|
||||
const worker = async () => {
|
||||
while (cursor < items.length) {
|
||||
const item = items[cursor++];
|
||||
const needProfile = !item.profile;
|
||||
if (!needProfile && tab !== 'replies') continue;
|
||||
const enriched = await enrichItem(item, tab);
|
||||
if (seq !== renderSeq) return;
|
||||
refreshItemRow(rowByItem.get(item), enriched, tab);
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: 6 }, worker));
|
||||
}
|
||||
|
||||
async function markAllRead() {
|
||||
if (!payloadCache) return;
|
||||
const jobs = ['replies', 'connections', 'events'].map((category) => {
|
||||
const { items, seenAt } = categoryData(payloadCache, category);
|
||||
const maxTs = items.reduce((max, x) => Math.max(max, Number(x?.createdAtMs || 0)), 0);
|
||||
return { category, maxTs, seenAt };
|
||||
}).filter((job) => job.maxTs > job.seenAt);
|
||||
if (!jobs.length) return;
|
||||
if (readAllBtn) readAllBtn.disabled = true;
|
||||
try {
|
||||
for (const job of jobs) {
|
||||
await authService.setNotificationSeen({ login: state.session.login, category: job.category, seenAtMs: job.maxTs, storagePwd: state.session.storagePwdInMemory });
|
||||
const seenKey = job.category === 'connections' ? 'connectionsSeenAtMs' : job.category === 'events' ? 'eventsSeenAtMs' : 'repliesSeenAtMs';
|
||||
const countKey = job.category === 'connections' ? 'connectionsUnseenCount' : job.category === 'events' ? 'eventsUnseenCount' : 'repliesUnseenCount';
|
||||
payloadCache[seenKey] = job.maxTs;
|
||||
payloadCache[countKey] = 0;
|
||||
localSeen[job.category] = Math.max(localSeen[job.category] || 0, job.maxTs);
|
||||
}
|
||||
if (lastNotifications?.payload) lastNotifications = { ...lastNotifications, payload: structuredClone(payloadCache), signature: '' };
|
||||
updateToolbarBadge(payloadCache);
|
||||
await renderCurrent();
|
||||
showToast('Все уведомления прочитаны');
|
||||
} catch (error) {
|
||||
updateToolbarBadge(payloadCache);
|
||||
showToast(toUserMessage(error, 'Не удалось отметить уведомления прочитанными.'), { kind: 'error' });
|
||||
}
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const seq=++requestSeq; list.replaceChildren(renderEmpty(state.notificationsTab));
|
||||
try { payloadCache=await authService.getNotifications(); if(seq!==requestSeq)return; updateToolbarBadge(payloadCache); await renderCurrent(); }
|
||||
catch(error){ if(seq!==requestSeq)return; const card=document.createElement('article');card.className='card stack';card.innerHTML='<strong>Не удалось загрузить уведомления</strong>';const t=document.createElement('p');t.className='meta-muted';t.textContent=error?.message||'Ошибка запроса к серверу';card.append(t);list.replaceChildren(card);}
|
||||
const seq=++requestSeq;
|
||||
const login = state.session.login;
|
||||
const cached = lastNotifications?.login === login ? lastNotifications : null;
|
||||
if (cached) { payloadCache = structuredClone(cached.payload); void renderCurrent(); }
|
||||
else { renderTabs({}); if (!list.childElementCount) list.replaceChildren(createLoadingState({ label: 'Загружаю уведомления' })); }
|
||||
try {
|
||||
const fresh=await authService.getNotifications(); if(seq!==requestSeq)return;
|
||||
const signature = JSON.stringify(fresh);
|
||||
lastNotifications = { login, payload: structuredClone(fresh), signature };
|
||||
updateToolbarBadge(fresh);
|
||||
if (cached?.signature === signature) return;
|
||||
payloadCache=fresh; await renderCurrent();
|
||||
}
|
||||
catch(error){
|
||||
if(seq!==requestSeq)return;
|
||||
if (payloadCache) { showToast(toUserMessage(error, 'Не удалось обновить уведомления.'), { kind: 'error' }); return; }
|
||||
list.replaceChildren(createErrorState({
|
||||
title: 'Не удалось загрузить уведомления',
|
||||
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
||||
onRetry: () => { list.replaceChildren(); void load(); },
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
if (!['replies','connections','events'].includes(state.notificationsTab)) state.notificationsTab='replies';
|
||||
screen.cleanup = () => {
|
||||
renderSeq += 1; // фоновая догрузка профилей больше не трогает экран
|
||||
requestSeq += 1;
|
||||
observer?.disconnect();
|
||||
Object.values(pendingSeenTimers).forEach((timer) => clearTimeout(timer));
|
||||
};
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { actionErrorText, toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { profile } from '../mock-data.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import {
|
||||
@@ -34,10 +37,10 @@ function shineStatusLabel(value) {
|
||||
return 'Не указано';
|
||||
}
|
||||
|
||||
// Ошибка – понятным сообщением внизу экрана, а не окном со стеком вызовов
|
||||
// (подробности остаются в журнале приложения).
|
||||
function showLocalErrorAlert(prefix, error) {
|
||||
const message = error?.message || 'Неизвестная ошибка';
|
||||
const stack = error?.stack ? `\n\nStack:\n${error.stack}` : '';
|
||||
window.alert(`${prefix}: ${message}${stack}`);
|
||||
showToast(`${prefix}. ${toUserMessage(error, 'Попробуйте ещё раз.')}`, { kind: 'error' });
|
||||
}
|
||||
|
||||
function genderLabel(value) {
|
||||
@@ -241,7 +244,8 @@ export function render({ navigate, chrome }) {
|
||||
? { ar: String(currentAvatar.txId || currentAvatar.ar || '').trim(), sha256Hex: String(currentAvatar?.sha256Hex || '').trim().toLowerCase() }
|
||||
: null,
|
||||
size: 'xl',
|
||||
className: 'profile-avatar',
|
||||
// Как в карточке профиля: без стеклянного кольца, которое вылезало за край экрана.
|
||||
className: 'profile-avatar avatar-plain',
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -293,7 +297,7 @@ export function render({ navigate, chrome }) {
|
||||
});
|
||||
}
|
||||
|
||||
function openFieldEditModal({ label, value, placeholder = '', maxLength = 300, multiline = false }) {
|
||||
function openFieldEditModal({ label, value, placeholder = '', maxLength = 300, multiline = false, suggestions = null }) {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!root) return Promise.resolve(null);
|
||||
root.innerHTML = `
|
||||
@@ -313,7 +317,8 @@ export function render({ navigate, chrome }) {
|
||||
maxlength="${Number(maxLength || 300)}"
|
||||
placeholder="${escapeHtml(placeholder || `Введите ${label.toLowerCase()}`)}"
|
||||
value="${escapeHtml(String(value || ''))}"
|
||||
/>`}
|
||||
${suggestions?.length ? 'list="profile-field-edit-suggestions" autocomplete="off"' : ''}
|
||||
/>${suggestions?.length ? `<datalist id="profile-field-edit-suggestions">${suggestions.map((item) => `<option value="${escapeHtml(item)}"></option>`).join('')}</datalist>` : ''}`}
|
||||
<div class="meta-muted">До ${Number(maxLength || 300)} символов.</div>
|
||||
<div class="form-actions-grid">
|
||||
<button class="secondary-btn" id="profile-field-edit-cancel" type="button">Отмена</button>
|
||||
@@ -626,8 +631,8 @@ export function render({ navigate, chrome }) {
|
||||
status.textContent = '';
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Не удалось загрузить параметры: ${error.message || 'ошибка сети'}`;
|
||||
showLocalErrorAlert('Ошибка загрузки параметров профиля', error);
|
||||
status.textContent = actionErrorText('Не удалось загрузить параметры', error);
|
||||
showLocalErrorAlert('Не удалось загрузить профиль', error);
|
||||
} finally {
|
||||
reloadBtn.disabled = false;
|
||||
accountRoleBtn.disabled = false;
|
||||
@@ -663,7 +668,7 @@ export function render({ navigate, chrome }) {
|
||||
}
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = error?.message || 'Не удалось открыть мастер аватара.';
|
||||
status.textContent = actionErrorText('Не удалось открыть мастер аватара', error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -691,8 +696,9 @@ export function render({ navigate, chrome }) {
|
||||
await refreshProfileSnapshot();
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Не удалось изменить ${statusKey}: ${error.message || 'ошибка сети'}`;
|
||||
showLocalErrorAlert(`Ошибка изменения ${statusKey}`, error);
|
||||
const what = isAccountRole ? 'тип аккаунта' : 'сияние';
|
||||
status.textContent = `Не удалось изменить ${what}. ${toUserMessage(error, 'Попробуйте ещё раз.')}`;
|
||||
showLocalErrorAlert(`Не удалось изменить ${what}`, error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -706,10 +712,11 @@ export function render({ navigate, chrome }) {
|
||||
placeholder: field.placeholder || '',
|
||||
maxLength: field.maxLength || 300,
|
||||
multiline: Boolean(field.multiline),
|
||||
suggestions: field.suggestions,
|
||||
});
|
||||
if (entered === null) return;
|
||||
if (String(entered).length > Number(field.maxLength || 300)) {
|
||||
window.alert(`Максимальная длина поля «${field.label}» – ${Number(field.maxLength || 300)} символов.`);
|
||||
showToast(`В поле «${field.label}» – не больше ${Number(field.maxLength || 300)} символов.`, { kind: 'info' });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -721,8 +728,8 @@ export function render({ navigate, chrome }) {
|
||||
await refreshProfileSnapshot();
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Не удалось изменить ${field.key}: ${error.message || 'ошибка сети'}`;
|
||||
showLocalErrorAlert(`Ошибка изменения ${field.key}`, error);
|
||||
status.textContent = `Не удалось изменить поле «${field.label}». ${toUserMessage(error, 'Попробуйте ещё раз.')}`;
|
||||
showLocalErrorAlert(`Не удалось изменить поле «${field.label}»`, error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -738,15 +745,15 @@ export function render({ navigate, chrome }) {
|
||||
await refreshProfileSnapshot();
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Не удалось изменить пол: ${error.message || 'ошибка сети'}`;
|
||||
showLocalErrorAlert('Ошибка изменения пола', error);
|
||||
status.textContent = `Не удалось изменить пол. ${toUserMessage(error, 'Попробуйте ещё раз.')}`;
|
||||
showLocalErrorAlert('Не удалось изменить пол', error);
|
||||
}
|
||||
}
|
||||
|
||||
async function onAddRelativeClick() {
|
||||
const sessionLogin = String(login || '').trim();
|
||||
if (!sessionLogin) {
|
||||
window.alert('Для добавления связи нужен активный логин.');
|
||||
showToast('Для добавления связи нужен вход в аккаунт.', { kind: 'error' });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -785,17 +792,19 @@ export function render({ navigate, chrome }) {
|
||||
targetCard = await loadUserProfileCard(inputLogin);
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Пользователь не найден: ${error.message || 'unknown'}`;
|
||||
showLocalErrorAlert('Ошибка выбора пользователя', error);
|
||||
status.textContent = actionErrorText('Не удалось найти пользователя', error);
|
||||
showLocalErrorAlert('Не удалось выбрать пользователя', error);
|
||||
return;
|
||||
}
|
||||
|
||||
const targetLogin = String(targetCard?.login || inputLogin).trim();
|
||||
const targetGender = normalizeGender(targetCard?.gender || PROFILE_GENDER_UNKNOWN);
|
||||
const relationLabel = relationAccusativeLabel(relationType, targetGender);
|
||||
const confirmed = window.confirm(
|
||||
`Добавить пользователя ${targetLogin} как ${relationLabel}?`,
|
||||
);
|
||||
const confirmed = await confirmDialog({
|
||||
title: 'Добавить связь?',
|
||||
text: `Добавить ${targetLogin} как ${relationLabel}?`,
|
||||
confirmLabel: 'Добавить',
|
||||
});
|
||||
if (!confirmed) return;
|
||||
|
||||
status.className = 'status-line';
|
||||
@@ -816,8 +825,8 @@ export function render({ navigate, chrome }) {
|
||||
status.textContent = `Связь добавлена: ${targetLogin} как ${relationLabel}.`;
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Не удалось добавить связь: ${error.message || 'ошибка сети'}`;
|
||||
showLocalErrorAlert('Ошибка добавления связи', error);
|
||||
status.textContent = actionErrorText('Не удалось добавить связь', error);
|
||||
showLocalErrorAlert('Не удалось добавить связь', error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,30 +4,47 @@ import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { loadUserProfileCard } from '../services/user-connections.js';
|
||||
import { profileCardHtml, profileTileHtml } from '../components/profile-card.js';
|
||||
import { openShareSheet } from '../components/share-sheet.js';
|
||||
import { createErrorState, createLoadingState } from '../components/feedback.js';
|
||||
import { makeProfileRoute } from '../services/shine-routes.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'profile-view', title: 'Профиль' };
|
||||
|
||||
// Последняя загруженная карточка своего профиля: при повторном заходе показываем её сразу и тихо обновляем.
|
||||
const cardCache = new Map();
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
const login = String(state.session.login || profile.login || '').trim();
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack user-profile-screen';
|
||||
|
||||
// Ссылка на свой профиль – самое частое «поделиться» в соцсети.
|
||||
const shareProfile = () => {
|
||||
const url = new URL(window.location.href);
|
||||
url.pathname = `/${makeProfileRoute(login)}`;
|
||||
url.search = '';
|
||||
url.hash = '';
|
||||
const name = [card?.firstName, card?.lastName].map((part) => String(part || '').trim()).filter(Boolean).join(' ');
|
||||
openShareSheet({ title: 'Поделиться профилем', kicker: name ? `${name} · @${login}` : `@${login}`, text: 'Профиль в Сиянии', url: url.toString() });
|
||||
};
|
||||
const topbar = createTopBar({
|
||||
title: 'Профиль',
|
||||
className: 'topbar--root user-profile-header',
|
||||
actions: [{ icon: 'share', title: 'Поделиться профилем', ariaLabel: 'Поделиться профилем', className: 'profile-share-btn', onClick: shareProfile }],
|
||||
});
|
||||
chrome?.setTopbar(topbar);
|
||||
|
||||
const status = document.createElement('div');
|
||||
status.className = 'status-line user-profile-status';
|
||||
status.textContent = 'Загрузка профиля...';
|
||||
status.className = 'user-profile-status';
|
||||
let card = cardCache.get(login.toLowerCase()) || null;
|
||||
// Первый заход – спиннер, но только если профиль грузится заметно долго.
|
||||
if (!card) status.append(createLoadingState({ label: 'Загружаю профиль' }));
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'user-profile-body';
|
||||
screen.append(status, body);
|
||||
|
||||
let card = null;
|
||||
|
||||
function renderProfile() {
|
||||
if (!card) return;
|
||||
body.innerHTML = profileCardHtml({
|
||||
@@ -51,9 +68,10 @@ export function render({ navigate, chrome }) {
|
||||
avatar: card.avatar,
|
||||
size: 'xl',
|
||||
className: 'user-profile-hero-avatar',
|
||||
official: card.accountRole === 'primary',
|
||||
}));
|
||||
|
||||
status.textContent = '';
|
||||
status.replaceChildren();
|
||||
}
|
||||
|
||||
body.addEventListener('click', (event) => {
|
||||
@@ -83,14 +101,29 @@ export function render({ navigate, chrome }) {
|
||||
status.textContent = 'Локальный тестовый режим.';
|
||||
return;
|
||||
}
|
||||
card = await loadUserProfileCard(login);
|
||||
const fresh = await loadUserProfileCard(login);
|
||||
if (!screen.isConnected && card) return;
|
||||
// Та же карточка – не перерисовываем, иначе аватар и счётчики мигают.
|
||||
if (card && JSON.stringify(card) === JSON.stringify(fresh)) return;
|
||||
card = fresh;
|
||||
cardCache.set(login.toLowerCase(), card);
|
||||
renderProfile();
|
||||
}
|
||||
|
||||
refresh().catch((error) => {
|
||||
status.className = 'status-line user-profile-status is-unavailable';
|
||||
status.textContent = `Ошибка: ${error?.message || 'unknown'}`;
|
||||
});
|
||||
renderProfile();
|
||||
|
||||
const showLoadError = (error) => {
|
||||
if (card) return;
|
||||
status.replaceChildren(createErrorState({
|
||||
title: 'Не удалось загрузить профиль',
|
||||
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
||||
onRetry: () => {
|
||||
status.replaceChildren(createLoadingState({ label: 'Загружаю профиль', delayMs: 0 }));
|
||||
refresh().catch(showLoadError);
|
||||
},
|
||||
}));
|
||||
};
|
||||
refresh().catch(showLoadError);
|
||||
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
prepareAddProfileLogin,
|
||||
switchToSavedProfile,
|
||||
} from '../state.js';
|
||||
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'profiles-view', title: 'Профили' };
|
||||
|
||||
@@ -51,7 +52,7 @@ export function render({navigate, chrome}) {
|
||||
navigate('login-view');
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Не удалось начать добавление профиля: ${error?.message || 'unknown'}`;
|
||||
status.textContent = actionErrorText('Не удалось начать добавление профиля', error);
|
||||
addButton.disabled = false;
|
||||
}
|
||||
});
|
||||
@@ -73,7 +74,7 @@ export function render({navigate, chrome}) {
|
||||
reloadTo('/start');
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Не удалось закрыть профили: ${error?.message || 'unknown'}`;
|
||||
status.textContent = actionErrorText('Не удалось закрыть профили', error);
|
||||
closeAllButton.disabled = false;
|
||||
}
|
||||
});
|
||||
@@ -109,7 +110,7 @@ export function render({navigate, chrome}) {
|
||||
reloadTo('/profile');
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Не удалось переключить профиль: ${error?.message || 'unknown'}`;
|
||||
status.textContent = actionErrorText('Не удалось переключить профиль', error);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -141,7 +142,7 @@ export function render({navigate, chrome}) {
|
||||
renderList();
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Не удалось закрыть профиль: ${error?.message || 'unknown'}`;
|
||||
status.textContent = actionErrorText('Не удалось закрыть профиль', error);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ export const REGISTRATION_FAQ_TOPICS = [
|
||||
'Ключ восстановления (Recovery key) нужен для восстановления и самых критичных операций с учётной записью. Его приватная часть никогда не сохраняется на устройстве и при необходимости временно вычисляется из пароля.',
|
||||
'Ключ блокчейна постоянно хранится на авторизованном устройстве. Он подписывает записи и действия в блокчейне Сияния и является исходным ключом для штатных пользовательских кошельков.',
|
||||
'Ключ доступа (client key) также постоянно хранится на устройстве. Он используется для входа на сервер, работы устройства и защищённых личных сообщений.',
|
||||
'Сейчас после обычного входа оба рабочих ключа — ключ блокчейна и ключ доступа — сохраняются автоматически. Отдельного ограниченного режима в текущей версии нет.',
|
||||
'Сейчас после обычного входа оба рабочих ключа – ключ блокчейна и ключ доступа – сохраняются автоматически. Отдельного ограниченного режима в текущей версии нет.',
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import {
|
||||
isSessionInvalidError,
|
||||
refreshSessions,
|
||||
@@ -95,7 +97,7 @@ export function render({navigate, chrome}) {
|
||||
return;
|
||||
}
|
||||
setAuthError(error.message);
|
||||
window.alert(error.message);
|
||||
showToast(toUserMessage(error, 'Действие не выполнено. Попробуйте ещё раз.'), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
listCard.append(item);
|
||||
@@ -115,7 +117,7 @@ export function render({navigate, chrome}) {
|
||||
return;
|
||||
}
|
||||
setAuthError(error.message);
|
||||
window.alert(error.message);
|
||||
showToast(toUserMessage(error, 'Действие не выполнено. Попробуйте ещё раз.'), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -135,7 +137,7 @@ export function render({navigate, chrome}) {
|
||||
return;
|
||||
}
|
||||
setAuthError(error.message);
|
||||
window.alert(error.message);
|
||||
showToast(toUserMessage(error, 'Действие не выполнено. Попробуйте ещё раз.'), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { authService } from '../state.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { renderAvatar, renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { renderAvatar } from '../components/avatar-image.js';
|
||||
import { createPersonRow } from '../components/person-row.js';
|
||||
import { createLoadingState, createStateMessage } from '../components/feedback.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { makeShineChannelRoute, makeProfileRoute } from '../services/shine-routes.js';
|
||||
|
||||
export const pageMeta = {
|
||||
@@ -57,28 +60,18 @@ function channelRow(item, navigate) {
|
||||
return row;
|
||||
}
|
||||
|
||||
// Человек в результатах – той же строкой, что в Связях и чатах; «Написать» – сразу отсюда.
|
||||
function personRow(person, navigate) {
|
||||
const login = String(person?.login || '').trim();
|
||||
const displayName = String(person?.displayName || '').trim();
|
||||
const row = document.createElement('button');
|
||||
row.type = 'button';
|
||||
row.className = 'shine-search-result';
|
||||
row.append(renderUserAvatar({ login, avatar: person.avatarAr ? { ar: person.avatarAr } : null, size: 'lg', className: 'avatar' }));
|
||||
const text = document.createElement('span');
|
||||
text.className = 'shine-search-result__text';
|
||||
const title = document.createElement('strong');
|
||||
title.className = 'shine-search-result__title';
|
||||
title.textContent = displayName || `@${login}`;
|
||||
text.append(title);
|
||||
if (displayName) {
|
||||
const address = document.createElement('span');
|
||||
address.className = 'shine-search-result__address';
|
||||
address.textContent = `@${login}`;
|
||||
text.append(address);
|
||||
}
|
||||
row.append(text);
|
||||
row.addEventListener('click', () => navigate(makeProfileRoute(login)));
|
||||
return row;
|
||||
return createPersonRow({
|
||||
login,
|
||||
name: displayName || login,
|
||||
avatar: person.avatarAr ? { ar: person.avatarAr } : null,
|
||||
sub: displayName && displayName !== login ? `@${login}` : '',
|
||||
onClick: () => navigate(makeProfileRoute(login)),
|
||||
actions: [{ icon: 'message', label: 'Написать', onClick: () => navigate(`chat/${encodeURIComponent(login)}`) }],
|
||||
});
|
||||
}
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
@@ -91,7 +84,7 @@ export function render({ navigate, chrome }) {
|
||||
|
||||
const search = document.createElement('input');
|
||||
search.type = 'search';
|
||||
search.className = 'input shine-search-input';
|
||||
search.className = 'search-field__input shine-search-input';
|
||||
search.placeholder = 'Название канала, @автор или автор/канал';
|
||||
search.maxLength = 120;
|
||||
search.autocomplete = 'off';
|
||||
@@ -101,23 +94,28 @@ export function render({ navigate, chrome }) {
|
||||
search.value = initialQuery;
|
||||
|
||||
const tabs = document.createElement('div');
|
||||
tabs.className = 'shine-search-tabs';
|
||||
tabs.setAttribute('role', 'tablist');
|
||||
tabs.className = 'tabs tabs--three shine-search-tabs';
|
||||
tabs.setAttribute('role', 'radiogroup');
|
||||
const buttons = [['all', 'Все'], ['channels', 'Каналы'], ['people', 'Люди']].map(([id, label]) => {
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'shine-search-tab';
|
||||
btn.className = 'tab-btn shine-search-tab';
|
||||
btn.textContent = label;
|
||||
btn.dataset.tab = id;
|
||||
btn.setAttribute('role', 'tab');
|
||||
btn.setAttribute('role', 'radio');
|
||||
btn.setAttribute('aria-checked', String(id === 'all'));
|
||||
tabs.append(btn);
|
||||
return btn;
|
||||
});
|
||||
|
||||
// Подсказка и итог – одной строкой; загрузка и «ничего не найдено» – общим видом в списке.
|
||||
const status = document.createElement('p');
|
||||
status.className = 'shine-search-status';
|
||||
status.setAttribute('role', 'status');
|
||||
status.textContent = 'Введите имя канала, его адрес или логин пользователя.';
|
||||
const field = document.createElement('label');
|
||||
field.className = 'search-field shine-search-field';
|
||||
field.innerHTML = `<span class="search-field__icon" aria-hidden="true">${iconHtml('search')}</span>`;
|
||||
const list = document.createElement('div');
|
||||
list.className = 'shine-search-results';
|
||||
|
||||
@@ -140,9 +138,7 @@ export function render({ navigate, chrome }) {
|
||||
|
||||
const renderResults = () => {
|
||||
buttons.forEach((button) => {
|
||||
const active = button.dataset.tab === selectedTab;
|
||||
button.classList.toggle('is-active', active);
|
||||
button.setAttribute('aria-selected', String(active));
|
||||
button.setAttribute('aria-checked', String(button.dataset.tab === selectedTab));
|
||||
});
|
||||
list.replaceChildren();
|
||||
const query = search.value.trim();
|
||||
@@ -154,8 +150,12 @@ export function render({ navigate, chrome }) {
|
||||
if (selectedTab !== 'channels') appendSection('Люди', people, personRow);
|
||||
const shown = (selectedTab === 'people' ? people.length
|
||||
: selectedTab === 'channels' ? channels.length : channels.length + people.length);
|
||||
if (error && !shown) status.textContent = error;
|
||||
else status.textContent = shown ? `Показано: ${shown}` : 'Ничего не найдено. Попробуйте другое название.';
|
||||
status.textContent = '';
|
||||
if (error && !shown) {
|
||||
list.append(createStateMessage({ kind: 'error', icon: 'alert', title: 'Поиск не удался', text: error }));
|
||||
} else if (!shown) {
|
||||
list.append(createStateMessage({ icon: 'search', title: 'Ничего не найдено', text: 'Попробуйте другое название или логин.' }));
|
||||
}
|
||||
};
|
||||
|
||||
const runSearch = async () => {
|
||||
@@ -166,7 +166,8 @@ export function render({ navigate, chrome }) {
|
||||
renderResults();
|
||||
return;
|
||||
}
|
||||
status.textContent = 'Ищем…';
|
||||
status.textContent = '';
|
||||
if (!list.childElementCount) list.replaceChildren(createLoadingState({ label: 'Ищу' }));
|
||||
const userQuery = query.replace(/^@/, '').trim();
|
||||
const requests = [authService.searchChannels(query, { limit: 10 })];
|
||||
if (userQuery && !userQuery.includes('/')) requests.push(authService.searchPeople(userQuery, { limit: 10 }));
|
||||
@@ -190,8 +191,9 @@ export function render({ navigate, chrome }) {
|
||||
if (timer) clearTimeout(timer);
|
||||
++seq; // Устаревший ответ не должен подменить новый ввод.
|
||||
channels = []; people = []; error = '';
|
||||
list.replaceChildren();
|
||||
status.textContent = search.value.trim() ? 'Ищем…' : 'Введите название или адрес.';
|
||||
// Прежние результаты остаются до прихода новых – без мелькания на каждую букву.
|
||||
if (!search.value.trim()) list.replaceChildren();
|
||||
status.textContent = search.value.trim() ? '' : 'Введите название или адрес.';
|
||||
rememberQueryInAddress();
|
||||
timer = setTimeout(() => { timer = null; void runSearch(); }, SEARCH_DELAY_MS);
|
||||
};
|
||||
@@ -208,7 +210,8 @@ export function render({ navigate, chrome }) {
|
||||
selectedTab = btn.dataset.tab;
|
||||
renderResults();
|
||||
}));
|
||||
screen.append(search, tabs, status, list);
|
||||
field.append(search);
|
||||
screen.append(field, tabs, status, list);
|
||||
screen.cleanup = () => {
|
||||
disposed = true;
|
||||
++seq;
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { saveEntrySettings, state } from '../state.js';
|
||||
import { checkServerAvailabilityByKey, resolveAndCheckShineServerLogin } from '../services/server-health-service.js';
|
||||
|
||||
@@ -174,7 +176,7 @@ export function render({navigate, chrome}) {
|
||||
await saveEntrySettings(draft);
|
||||
navigate('settings-servers-view');
|
||||
} catch (error) {
|
||||
window.alert(error?.message || 'Не удалось сохранить настройки серверов блокчейнов.');
|
||||
showToast(toUserMessage(error, 'Не удалось сохранить настройки серверов блокчейнов.'), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { addAppLogEntry, authService, closeSavedProfile, state } from '../state.js';
|
||||
import { isDeveloperToolsEnabled } from '../services/feature-settings.js';
|
||||
import { getThemeMode, setThemeMode } from '../services/theme-service.js';
|
||||
import { openSheet } from '../components/sheet.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { PALETTE_PRESETS, getPaletteSettings, getThemeMode } from '../services/theme-service.js';
|
||||
import {
|
||||
canInstallPwa,
|
||||
isStandalonePwaMode,
|
||||
@@ -12,56 +13,95 @@ import {
|
||||
|
||||
export const pageMeta = { id: 'settings-view', title: 'Настройки' };
|
||||
|
||||
// Номер сборки вида 20261013040000 – это дата и время: показываем «13.10.2026, 04:00».
|
||||
function formatBuildStamp(rawValue) {
|
||||
const value = String(rawValue || '').trim();
|
||||
if (!/^\d{14}$/.test(value)) return value;
|
||||
const yyyy = value.slice(0, 4);
|
||||
const mm = value.slice(4, 6);
|
||||
const dd = value.slice(6, 8);
|
||||
const hh = value.slice(8, 10);
|
||||
const min = value.slice(10, 12);
|
||||
const ss = value.slice(12, 14);
|
||||
return `${yyyy}-${mm}-${dd}/${hh}:${min}__${ss}`;
|
||||
return `${value.slice(6, 8)}.${value.slice(4, 6)}.${value.slice(0, 4)}, ${value.slice(8, 10)}:${value.slice(10, 12)}`;
|
||||
}
|
||||
|
||||
function formatVersionForUi(rawValue) {
|
||||
const value = String(rawValue || '').trim();
|
||||
if (!value) return 'n/a';
|
||||
const formatted = formatBuildStamp(value);
|
||||
if (formatted && formatted !== value) {
|
||||
return `${formatted} (${value})`;
|
||||
}
|
||||
if (formatted && formatted !== value) return formatted;
|
||||
return value;
|
||||
}
|
||||
|
||||
// Сервер отвечает версией на Ping (или GetServerInfo у старых серверов).
|
||||
async function loadServerVersion() {
|
||||
try {
|
||||
const pingResp = await authService.ws.request('Ping', { ts: Date.now() }, 7000);
|
||||
const value = String(pingResp?.payload?.serverVersion || pingResp?.serverVersion || '').trim();
|
||||
if (value) return value;
|
||||
} catch {
|
||||
// ниже – запасной запрос
|
||||
}
|
||||
const infoResp = await authService.ws.request('GetServerInfo', {});
|
||||
return String(infoResp?.payload?.version || '').trim();
|
||||
}
|
||||
|
||||
// «О приложении»: версии клиента, сборки и сервера – и кнопка скопировать их для поддержки.
|
||||
function openAboutSheet() {
|
||||
let disposed = false;
|
||||
return openSheet({
|
||||
title: 'О приложении',
|
||||
className: 'about-sheet',
|
||||
onClose: () => { disposed = true; },
|
||||
content: () => {
|
||||
const list = document.createElement('div');
|
||||
list.className = 'nav-list';
|
||||
const rows = [
|
||||
['Версия приложения', formatVersionForUi(window.__SHINE_CLIENT_VERSION__)],
|
||||
['Сборка', formatVersionForUi(window.__SHINE_BUILD_HASH__)],
|
||||
['Сервер', 'Узнаю…'],
|
||||
['Сервер доступа', String(state.entrySettings?.shineServerLogin || '').trim() || '—'],
|
||||
];
|
||||
const values = rows.map(([label, value]) => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'nav-row nav-row--static';
|
||||
row.innerHTML = '<span class="nav-row__hint"></span><span class="nav-row__label"></span>';
|
||||
row.querySelector('.nav-row__hint').textContent = label;
|
||||
row.querySelector('.nav-row__label').textContent = value;
|
||||
list.append(row);
|
||||
return row.querySelector('.nav-row__label');
|
||||
});
|
||||
void loadServerVersion()
|
||||
.then((value) => { if (!disposed) values[2].textContent = formatVersionForUi(value) || '—'; })
|
||||
.catch(() => { if (!disposed) values[2].textContent = 'Нет связи с сервером'; });
|
||||
const copy = document.createElement('button');
|
||||
copy.type = 'button';
|
||||
copy.className = 'secondary-btn about-sheet__copy';
|
||||
copy.textContent = 'Скопировать сведения';
|
||||
copy.addEventListener('click', async () => {
|
||||
const text = rows.map(([label], index) => `${label}: ${values[index].textContent}`).join('\n');
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
showToast('Сведения скопированы');
|
||||
} catch {
|
||||
showToast('Не удалось скопировать', { kind: 'error' });
|
||||
}
|
||||
});
|
||||
const box = document.createElement('div');
|
||||
box.className = 'stack';
|
||||
box.append(list, copy);
|
||||
return box;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const THEME_LABELS = { system: 'авто', light: 'светлая', dark: 'тёмная' };
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
let isDisposed = false;
|
||||
let aboutSheet = null;
|
||||
|
||||
const topbar = createTopBar({
|
||||
title: 'Настройки',
|
||||
back: { label: '←', onClick: () => navigate('profile-view') },
|
||||
});
|
||||
const themeButton = document.createElement('button');
|
||||
themeButton.type = 'button';
|
||||
themeButton.className = 'settings-theme-cycle';
|
||||
themeButton.title = 'Переключить тему оформления';
|
||||
themeButton.setAttribute('aria-label', 'Переключить тему оформления');
|
||||
const modes = ['light', 'dark', 'system'];
|
||||
const themeNames = { light: '☀️ Светлая', dark: '🌙 Тёмная', system: '◐ Авто' };
|
||||
const updateThemeButton = () => {
|
||||
const mode = getThemeMode();
|
||||
themeButton.textContent = themeNames[mode] || themeNames.system;
|
||||
themeButton.setAttribute('aria-label', `Тема: ${themeButton.textContent}. Нажмите для переключения`);
|
||||
};
|
||||
themeButton.addEventListener('click', () => {
|
||||
const index = modes.indexOf(getThemeMode());
|
||||
setThemeMode(modes[(index + 1) % modes.length]);
|
||||
updateThemeButton();
|
||||
});
|
||||
updateThemeButton();
|
||||
topbar.querySelector('.topbar__right')?.append(themeButton);
|
||||
chrome?.setTopbar(topbar);
|
||||
|
||||
// Скрытый вход в «Дополнительные настройки»: пять быстрых нажатий на заголовок.
|
||||
@@ -79,23 +119,36 @@ export function render({navigate, chrome}) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'stack settings-sections';
|
||||
const row = (id, label, hint) => `<button class="nav-row" type="button" id="${id}"><span class="nav-row__label">${label}</span>${hint ? `<span class="nav-row__hint">${hint}</span>` : ''}</button>`;
|
||||
const palette = PALETTE_PRESETS[getPaletteSettings().preset]?.label || '';
|
||||
const appearanceHint = `Тема: ${THEME_LABELS[getThemeMode()] || 'авто'}${palette ? ` · цвета «${palette}»` : ''}`;
|
||||
card.innerHTML = `
|
||||
<div class="nav-list">
|
||||
${row('settings-appearance', 'Оформление', appearanceHint)}
|
||||
${row('settings-notifications', 'Уведомления', 'Звук, разрешение, чаты без звука')}
|
||||
${row('settings-language', 'Язык / Language', 'Русский')}
|
||||
</div>
|
||||
<div class="nav-list">
|
||||
${row('settings-device', 'Устройства', 'Сеансы и подключение устройств')}
|
||||
${row('settings-my-blockchain', 'Мой блокчейн', 'История записей, файлы и внешнее устройство')}
|
||||
${row('settings-servers', 'Настройки серверов', 'Сервер доступа и серверы блокчейнов')}
|
||||
${row('settings-access-keys', 'Ключи и пароли', 'Просмотр ключей и смена пароля')}
|
||||
${row('settings-language', 'Язык / Language', 'Русский')}
|
||||
</div>
|
||||
<div class="nav-list" id="settings-install-list" hidden></div>
|
||||
<div class="nav-list">
|
||||
${row('settings-developer', 'Настройки разработчика', 'Цветовая схема и инструменты разработчика')}
|
||||
${row('settings-about', 'О приложении', `Версия ${window.__SHINE_CLIENT_VERSION__ || '—'}`)}
|
||||
${row('settings-developer', 'Настройки разработчика', 'Инструменты и журнал приложения')}
|
||||
</div>
|
||||
<div class="nav-list">
|
||||
<button class="nav-row nav-row--danger" type="button" id="settings-signout"><span class="nav-row__label">Выйти из аккаунта</span></button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
card.querySelector('#settings-appearance').addEventListener('click', () => navigate('appearance-view'));
|
||||
card.querySelector('#settings-notifications').addEventListener('click', () => navigate('notification-settings-view'));
|
||||
card.querySelector('#settings-about').addEventListener('click', () => {
|
||||
aboutSheet?.close();
|
||||
aboutSheet = openAboutSheet();
|
||||
});
|
||||
card.querySelector('#settings-device').addEventListener('click', () => navigate('device-view'));
|
||||
card.querySelector('#settings-my-blockchain').addEventListener('click', () => navigate('my-blockchain-view'));
|
||||
card.querySelector('#settings-servers').addEventListener('click', () => navigate('settings-servers-view'));
|
||||
@@ -160,56 +213,10 @@ export function render({navigate, chrome}) {
|
||||
|
||||
screen.append(card);
|
||||
|
||||
if (isDeveloperToolsEnabled()) {
|
||||
const versionCard = document.createElement('div');
|
||||
versionCard.className = 'card stack';
|
||||
|
||||
const title = document.createElement('p');
|
||||
title.className = 'field-label';
|
||||
title.textContent = 'Версии';
|
||||
|
||||
const clientVersion = document.createElement('p');
|
||||
clientVersion.className = 'meta-muted';
|
||||
clientVersion.textContent = `Клиент: ${formatVersionForUi(window.__SHINE_CLIENT_VERSION__)}`;
|
||||
|
||||
const uiBuild = document.createElement('p');
|
||||
uiBuild.className = 'meta-muted';
|
||||
uiBuild.textContent = `Сборка UI: ${formatVersionForUi(window.__SHINE_BUILD_HASH__)}`;
|
||||
|
||||
const serverVersion = document.createElement('p');
|
||||
serverVersion.className = 'meta-muted';
|
||||
serverVersion.textContent = 'Сервер: загружается...';
|
||||
|
||||
versionCard.append(title, clientVersion, uiBuild, serverVersion);
|
||||
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
let value = '';
|
||||
try {
|
||||
const pingResp = await authService.ws.request('Ping', { ts: Date.now() }, 7000);
|
||||
value = String(pingResp?.payload?.serverVersion || pingResp?.serverVersion || '').trim();
|
||||
} catch {
|
||||
// fallback below
|
||||
}
|
||||
|
||||
if (!value) {
|
||||
const infoResp = await authService.ws.request('GetServerInfo', {});
|
||||
value = String(infoResp?.payload?.version || '').trim();
|
||||
}
|
||||
if (!isDisposed) serverVersion.textContent = `Сервер: ${formatVersionForUi(value)}`;
|
||||
} catch {
|
||||
if (!isDisposed) {
|
||||
serverVersion.textContent = 'Сервер: недоступно';
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
screen.append(versionCard);
|
||||
}
|
||||
|
||||
screen.cleanup = () => {
|
||||
if (isDisposed) return;
|
||||
isDisposed = true;
|
||||
aboutSheet?.close();
|
||||
unsubscribeInstallAvailability();
|
||||
};
|
||||
return screen;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createLoadingState } from '../components/feedback.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { state } from '../state.js';
|
||||
import { bytesToBase58 } from '../services/crypto-utils.js';
|
||||
@@ -19,9 +20,9 @@ export function render({navigate, chrome}) {
|
||||
back: { label: '←', onClick: () => navigate('access-keys-view') },
|
||||
}));
|
||||
|
||||
const status = document.createElement('p');
|
||||
const status = document.createElement('div');
|
||||
status.className = 'meta-muted';
|
||||
status.textContent = 'Загружаем сохранённые ключи...';
|
||||
status.append(createLoadingState({ label: 'Загружаю ключи' }));
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'nav-list key-list';
|
||||
|
||||
@@ -23,20 +23,14 @@ export function render({ navigate }) {
|
||||
logoWrap.append(logo);
|
||||
|
||||
const brandBlock = document.createElement('div');
|
||||
brandBlock.className = 'stack';
|
||||
brandBlock.style.alignItems = 'center';
|
||||
brandBlock.style.gap = '22px';
|
||||
brandBlock.className = 'stack auth-brand-block';
|
||||
|
||||
const title = document.createElement('h1');
|
||||
title.className = 'auth-brand';
|
||||
title.append(createShineWordmark());
|
||||
|
||||
const siteName = document.createElement('p');
|
||||
siteName.className = 'meta-muted';
|
||||
siteName.style.margin = '0';
|
||||
siteName.style.fontSize = '18px';
|
||||
siteName.style.letterSpacing = '0.045em';
|
||||
siteName.style.lineHeight = '1.25';
|
||||
siteName.className = 'meta-muted auth-site-name';
|
||||
siteName.textContent = window.location.host || window.location.hostname || 'shineup.me';
|
||||
|
||||
brandBlock.append(title, siteName);
|
||||
@@ -73,5 +67,23 @@ export function render({ navigate }) {
|
||||
|
||||
actions.append(loginButton, registerButton, languageButton, settingsButton);
|
||||
screen.append(logoWrap, brandBlock, actions);
|
||||
// Экран монтируется сразу после render – тогда и подхватываем анимацию знака с заставки.
|
||||
queueMicrotask(() => continueSplashAnimations(logoWrap));
|
||||
return screen;
|
||||
}
|
||||
|
||||
// Заставка рисует тот же знак: продолжаем её сияние с той же фазы, чтобы при смене не было скачка.
|
||||
function continueSplashAnimations(logoWrap) {
|
||||
const splashWrap = document.querySelector('#initial-splash .auth-logo-wrap');
|
||||
if (!splashWrap || !logoWrap.isConnected) return;
|
||||
const keyOf = (animation) => {
|
||||
const target = animation.effect?.target;
|
||||
const part = target?.classList?.contains('auth-logo') ? 'logo' : 'wrap';
|
||||
return `${part}${animation.effect?.pseudoElement || ''}|${animation.animationName || ''}`;
|
||||
};
|
||||
const source = new Map(splashWrap.getAnimations({ subtree: true }).map((animation) => [keyOf(animation), animation]));
|
||||
logoWrap.getAnimations({ subtree: true }).forEach((animation) => {
|
||||
const match = source.get(keyOf(animation));
|
||||
if (match && match.currentTime != null) animation.currentTime = match.currentTime;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { state } from '../state.js';
|
||||
import {
|
||||
createSolanaWalletFromPrivateBase58,
|
||||
@@ -8,6 +9,7 @@ import {
|
||||
transferSol,
|
||||
} from '../services/solana-wallet-service.js';
|
||||
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
||||
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'topup-view', title: 'Пополнение solana счета', showAppChrome: false };
|
||||
const DEVNET_ENDPOINT = 'https://api.devnet.solana.com';
|
||||
@@ -59,7 +61,7 @@ export function render({ navigate }) {
|
||||
copyButton.textContent = 'Скопировать';
|
||||
}, 1500);
|
||||
} catch {
|
||||
window.alert('Не удалось скопировать номер кошелька.');
|
||||
showToast('Не удалось скопировать номер кошелька – выделите его и скопируйте вручную.', { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -88,7 +90,7 @@ export function render({ navigate }) {
|
||||
testButton.addEventListener('click', async () => {
|
||||
const address = String(walletValue.value || '').trim();
|
||||
if (!address) {
|
||||
window.alert('Адрес кошелька не найден.');
|
||||
showToast('Адрес кошелька не найден.', { kind: 'error' });
|
||||
return;
|
||||
}
|
||||
if (!senderKeypair) {
|
||||
@@ -118,7 +120,7 @@ export function render({ navigate }) {
|
||||
].join('\n');
|
||||
} catch (error) {
|
||||
status.style.fontSize = '13px';
|
||||
status.textContent = `Ошибка тестового пополнения: ${error?.message || 'unknown'}`;
|
||||
status.textContent = actionErrorText('Ошибка тестового пополнения', error);
|
||||
} finally {
|
||||
testButton.disabled = false;
|
||||
}
|
||||
@@ -155,7 +157,7 @@ export function render({ navigate }) {
|
||||
const sender = await createSolanaWalletFromPrivateBase58(SENDER_PRIVATE_32_BASE58);
|
||||
senderKeypair = sender.keypair;
|
||||
} catch (error) {
|
||||
status.textContent = `Не удалось получить баланс: ${error?.message || 'unknown'}`;
|
||||
status.textContent = actionErrorText('Не удалось получить баланс', error);
|
||||
}
|
||||
})();
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// UNUSED FOR NOW: настройка дополнительного пароля для подключения другого устройства
|
||||
// сохранена в коде, но не показывается в активном UI. Текущий UX всегда без пароля.
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createLoadingState } from '../components/feedback.js';
|
||||
import { authService, setAuthError, setAuthInfo, state } from '../state.js';
|
||||
import { deriveEspPairingPasswordHash } from '../services/device-pairing-service.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
@@ -27,9 +28,9 @@ export function render({navigate, chrome}) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack';
|
||||
|
||||
const summary = document.createElement('p');
|
||||
const summary = document.createElement('div');
|
||||
summary.className = 'auth-copy';
|
||||
summary.textContent = 'Загружаем текущие настройки...';
|
||||
summary.append(createLoadingState({ label: 'Загружаю настройки' }));
|
||||
|
||||
const hint = document.createElement('p');
|
||||
hint.className = 'meta-muted';
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { createErrorState, createLoadingState, createStateMessage } from '../components/feedback.js';
|
||||
import { createPersonRow } from '../components/person-row.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { authService } from '../state.js';
|
||||
import { navigateBack } from '../router.js';
|
||||
import { userDisplayName } from '../services/user-display.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { matchesPeopleQuery } from '../services/people-search.js';
|
||||
import { avatarReferenceToRenderModel, parseAvatarReference } from '../services/avatar-reference.js';
|
||||
|
||||
export const pageMeta = { id: 'user-profile-list-view', title: 'Список' };
|
||||
@@ -17,12 +22,22 @@ const TITLES = {
|
||||
channels_owned: 'Каналы', channels_following: 'Подписки на каналы',
|
||||
};
|
||||
|
||||
function friendTabsHtml(activeKind) {
|
||||
return `
|
||||
<div class="profile-list-tabs" role="tablist" aria-label="Тип друзей">
|
||||
<button type="button" class="profile-list-tab${activeKind === 'friends' ? ' is-active' : ''}" data-friend-kind="friends" role="tab" aria-selected="${activeKind === 'friends'}">Друзья</button>
|
||||
<button type="button" class="profile-list-tab${activeKind === 'close_friends' ? ' is-active' : ''}" data-friend-kind="close_friends" role="tab" aria-selected="${activeKind === 'close_friends'}">Близкие друзья</button>
|
||||
</div>`;
|
||||
const EMPTY_TEXT = {
|
||||
friends: 'Друзей пока нет.',
|
||||
close_friends: 'Близких друзей пока нет.',
|
||||
primary_received: 'Пока никто не подтвердил.',
|
||||
primary_given: 'Пока никого не подтвердили.',
|
||||
shine_received: 'Пока никто не подтвердил.',
|
||||
shine_given: 'Пока никого не подтвердили.',
|
||||
channels_owned: 'Каналов пока нет.',
|
||||
channels_following: 'Подписок пока нет.',
|
||||
};
|
||||
|
||||
const RELATION_TEXT = { contact: 'контакт', friend: 'друг', close_friend: 'близкий друг' };
|
||||
const SEARCH_FROM = 12; // с какого размера списка появляется поиск по нему
|
||||
|
||||
function searchText(value) {
|
||||
return String(value || '').toLowerCase().replaceAll('ё', 'е').trim();
|
||||
}
|
||||
|
||||
export function render({ navigate, route, chrome }) {
|
||||
@@ -32,124 +47,158 @@ export function render({ navigate, route, chrome }) {
|
||||
const isFriendsScreen = initialKind === 'friends' || initialKind === 'close_friends';
|
||||
const isChannelsScreen = initialKind === 'channels_owned' || initialKind === 'channels_following';
|
||||
let includeDeleted = false;
|
||||
let disposed = false;
|
||||
let rows = [];
|
||||
let query = '';
|
||||
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
screen.className = 'stack profile-list-screen';
|
||||
const body = document.createElement('div');
|
||||
body.className = 'stack';
|
||||
const status = document.createElement('div');
|
||||
status.className = 'status-line';
|
||||
status.textContent = 'Загрузка...';
|
||||
body.className = 'profile-list-body';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: TITLES[initialKind] || 'Список',
|
||||
back: { label: '←', onClick: () => navigateBack() },
|
||||
back: { onClick: () => navigateBack() },
|
||||
}));
|
||||
|
||||
if (isChannelsScreen) {
|
||||
const filter = document.createElement('label');
|
||||
filter.className = 'profile-list-deleted-filter';
|
||||
filter.innerHTML = '<input type="checkbox" id="profile-list-show-deleted"> <span>Показать удалённые</span>';
|
||||
screen.append(filter);
|
||||
}
|
||||
if (isFriendsScreen) {
|
||||
const tabs = document.createElement('div');
|
||||
tabs.innerHTML = friendTabsHtml(activeKind);
|
||||
screen.append(tabs.firstElementChild);
|
||||
tabs.className = 'tabs profile-list-kind';
|
||||
tabs.setAttribute('role', 'radiogroup');
|
||||
tabs.setAttribute('aria-label', 'Кого показать');
|
||||
for (const [kind, label] of [['friends', 'Друзья'], ['close_friends', 'Близкие друзья']]) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'tab-btn';
|
||||
button.dataset.kind = kind;
|
||||
button.setAttribute('role', 'radio');
|
||||
button.setAttribute('aria-checked', String(kind === activeKind));
|
||||
button.textContent = label;
|
||||
button.addEventListener('click', () => {
|
||||
if (kind === activeKind) return;
|
||||
activeKind = kind;
|
||||
tabs.querySelectorAll('.tab-btn').forEach((el) => el.setAttribute('aria-checked', String(el.dataset.kind === activeKind)));
|
||||
void load(activeKind);
|
||||
});
|
||||
tabs.append(button);
|
||||
}
|
||||
screen.append(tabs);
|
||||
}
|
||||
screen.append(status, body);
|
||||
|
||||
if (isChannelsScreen) {
|
||||
const filter = document.createElement('div');
|
||||
filter.className = 'nav-list';
|
||||
filter.innerHTML = `
|
||||
<label class="nav-row nav-row--switch">
|
||||
<span class="nav-row__text"><span class="nav-row__label">Показать удалённые</span></span>
|
||||
<input class="switch" type="checkbox" />
|
||||
</label>`;
|
||||
filter.querySelector('input').addEventListener('change', (event) => {
|
||||
includeDeleted = Boolean(event.currentTarget.checked);
|
||||
void load(activeKind);
|
||||
});
|
||||
screen.append(filter);
|
||||
}
|
||||
|
||||
// Поиск по списку – когда людей много (у «Друзей» их бывают сотни).
|
||||
const searchWrap = document.createElement('label');
|
||||
searchWrap.className = 'search-field profile-list-search';
|
||||
searchWrap.hidden = true;
|
||||
searchWrap.innerHTML = `<span class="search-field__icon" aria-hidden="true">${iconHtml('search')}</span><input class="search-field__input" type="search" placeholder="Имя или логин" autocomplete="off" enterkeyhint="search" aria-label="Поиск по списку" />`;
|
||||
const searchInput = searchWrap.querySelector('input');
|
||||
searchInput.addEventListener('input', () => {
|
||||
query = searchText(searchInput.value);
|
||||
renderRows();
|
||||
});
|
||||
screen.append(searchWrap, body);
|
||||
|
||||
let loadGeneration = 0;
|
||||
|
||||
function renderRelationRows(rows) {
|
||||
rows.forEach((row) => {
|
||||
const el = document.createElement('button');
|
||||
el.type = 'button';
|
||||
el.className = 'ui-button card row profile-list-row';
|
||||
el.append(renderUserAvatar({
|
||||
login: row.login,
|
||||
firstName: row.firstName,
|
||||
lastName: row.lastName,
|
||||
avatar: parseAvatar(row.avatarAr),
|
||||
size: 'md',
|
||||
}));
|
||||
const fullName = userDisplayName(row);
|
||||
const t = document.createElement('div');
|
||||
t.className = 'profile-list-row-text';
|
||||
const marks = [
|
||||
row.relationType && row.relationType !== 'none' ? ({ contact: 'контакт', friend: 'друг', close_friend: 'близкий друг' }[row.relationType] || row.relationType) : '',
|
||||
row.accountRole === 'primary' ? 'основной' : row.accountRole === 'non_voting' ? 'голос не учитывается' : '',
|
||||
row.shineStatus === 'shining' ? 'сияющий' : row.shineStatus === 'not_interested' ? 'сияние неинтересно' : '',
|
||||
row.primaryConfirmed ? 'основной подтверждён ✓' : '',
|
||||
row.shineConfirmed ? 'сияющий подтверждён ✓' : '',
|
||||
].filter(Boolean).join(' · ');
|
||||
t.innerHTML = `<b>${fullName}</b><small>@${String(row.login || '')}${marks ? ` · ${marks}` : ''}</small>`;
|
||||
el.append(t);
|
||||
el.addEventListener('click', () => navigate(`SHiNE/${encodeURIComponent(row.login)}`));
|
||||
body.append(el);
|
||||
function relationRow(row) {
|
||||
const marks = [
|
||||
RELATION_TEXT[row.relationType] || '',
|
||||
row.shineStatus === 'shining' ? 'сияющий' : '',
|
||||
row.accountRole === 'primary' ? 'официальный' : '',
|
||||
row.primaryConfirmed ? 'официальный подтверждён' : '',
|
||||
row.shineConfirmed ? 'сияние подтверждено' : '',
|
||||
].filter(Boolean);
|
||||
const name = userDisplayName(row);
|
||||
const sub = [name !== row.login ? `@${row.login}` : '', ...marks].filter(Boolean).join(' · ');
|
||||
return createPersonRow({
|
||||
login: row.login,
|
||||
name,
|
||||
firstName: row.firstName,
|
||||
lastName: row.lastName,
|
||||
avatar: parseAvatar(row.avatarAr),
|
||||
official: row.accountRole === 'primary',
|
||||
ring: row.shineStatus === 'shining' ? 'shining' : (row.relationType === 'close_friend' ? 'close' : ''),
|
||||
sub,
|
||||
onClick: () => navigate(`SHiNE/${encodeURIComponent(row.login)}`),
|
||||
actions: [{ icon: 'message', label: 'Написать', onClick: () => navigate(`chat/${encodeURIComponent(row.login)}`) }],
|
||||
});
|
||||
}
|
||||
|
||||
function channelRow(row) {
|
||||
const el = document.createElement('button');
|
||||
el.type = 'button';
|
||||
el.className = 'ui-button card row profile-list-row';
|
||||
el.append(renderUserAvatar({ login: row.ownerLogin, firstName: row.displayName, lastName: '', avatar: (row.avatarAr || row.avatarSha256) ? { ar: String(row.avatarAr || ''), sha256Hex: String(row.avatarSha256 || '') } : null, size: 'md' }));
|
||||
const text = document.createElement('div');
|
||||
text.className = 'profile-list-row-text';
|
||||
const title = document.createElement('b');
|
||||
title.textContent = `${String(row.displayName || row.slug || '')}${row.deleted ? ' · удалён' : ''}`;
|
||||
const sub = document.createElement('small');
|
||||
sub.textContent = `${String(row.ownerLogin || '')} / ${String(row.slug || '')}`;
|
||||
text.append(title, sub);
|
||||
el.append(text);
|
||||
el.addEventListener('click', () => navigate(`channel/${encodeURIComponent(row.ownerBlockchainName)}/${Number(row.rootBlockNumber || 0)}/${encodeURIComponent(row.rootBlockHashHex || '')}/about`));
|
||||
return el;
|
||||
}
|
||||
|
||||
function renderRows() {
|
||||
body.replaceChildren();
|
||||
const matches = (row) => (isChannelsScreen
|
||||
? !query || searchText(`${row.displayName} ${row.slug} ${row.ownerLogin}`).includes(query)
|
||||
: matchesPeopleQuery(`${userDisplayName(row)} ${row.login}`, query));
|
||||
const visible = rows.filter(matches);
|
||||
if (!rows.length) {
|
||||
body.append(createStateMessage({ icon: isChannelsScreen ? 'channels' : 'network', title: EMPTY_TEXT[activeKind] || 'Пока никого.' }));
|
||||
return;
|
||||
}
|
||||
if (!visible.length) {
|
||||
body.append(createStateMessage({ icon: 'search', title: 'Никого не нашлось', text: 'Проверьте имя или логин.' }));
|
||||
return;
|
||||
}
|
||||
const frag = document.createDocumentFragment();
|
||||
visible.forEach((row) => frag.append(isChannelsScreen ? channelRow(row) : relationRow(row)));
|
||||
body.append(frag);
|
||||
}
|
||||
|
||||
async function load(kind) {
|
||||
const generation = ++loadGeneration;
|
||||
status.className = 'status-line';
|
||||
status.textContent = 'Загрузка...';
|
||||
body.replaceChildren();
|
||||
body.replaceChildren(createLoadingState({ label: 'Загружаю список' }));
|
||||
try {
|
||||
if (kind === 'channels_owned' || kind === 'channels_following') {
|
||||
const payload = await authService.listUserProfileChannels(login, kind === 'channels_owned' ? 'owned' : 'following', 200, 0, includeDeleted);
|
||||
if (generation !== loadGeneration) return;
|
||||
const rows = Array.isArray(payload?.channels) ? payload.channels : [];
|
||||
rows.forEach((row) => {
|
||||
const el = document.createElement('button');
|
||||
el.type = 'button';
|
||||
el.className = 'ui-button card row profile-list-row';
|
||||
el.append(renderUserAvatar({ login: row.ownerLogin, firstName: row.displayName, lastName: '', avatar: (row.avatarAr || row.avatarSha256) ? { ar: String(row.avatarAr || ''), sha256Hex: String(row.avatarSha256 || '') } : null, size: 'md' }));
|
||||
const t = document.createElement('div');
|
||||
t.className = 'profile-list-row-text';
|
||||
t.innerHTML = `<b>${String(row.displayName || row.slug || '')}${row.deleted ? ' · Удалён' : ''}</b><small>${String(row.ownerLogin || '')} / ${String(row.slug || '')}</small>`;
|
||||
el.append(t);
|
||||
el.addEventListener('click', () => navigate(`channel/${encodeURIComponent(row.ownerBlockchainName)}/${Number(row.rootBlockNumber || 0)}/${encodeURIComponent(row.rootBlockHashHex || '')}/about`));
|
||||
body.append(el);
|
||||
});
|
||||
status.textContent = rows.length ? '' : 'Список пуст.';
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = await authService.listUserProfileRelations(login, kind, 200, 0);
|
||||
if (generation !== loadGeneration) return;
|
||||
const rows = Array.isArray(payload?.users) ? payload.users : [];
|
||||
renderRelationRows(rows);
|
||||
status.textContent = rows.length ? '' : 'Список пуст.';
|
||||
} catch (e) {
|
||||
if (generation !== loadGeneration) return;
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Ошибка: ${e.message || 'unknown'}`;
|
||||
const payload = isChannelsScreen
|
||||
? await authService.listUserProfileChannels(login, kind === 'channels_owned' ? 'owned' : 'following', 200, 0, includeDeleted)
|
||||
: await authService.listUserProfileRelations(login, kind, 200, 0);
|
||||
if (disposed || generation !== loadGeneration) return;
|
||||
rows = Array.isArray(isChannelsScreen ? payload?.channels : payload?.users) ? (isChannelsScreen ? payload.channels : payload.users) : [];
|
||||
searchWrap.hidden = rows.length < SEARCH_FROM;
|
||||
renderRows();
|
||||
} catch (error) {
|
||||
if (disposed || generation !== loadGeneration) return;
|
||||
body.replaceChildren(createErrorState({
|
||||
title: 'Не удалось загрузить список',
|
||||
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
||||
onRetry: () => { void load(activeKind); },
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
if (isChannelsScreen) {
|
||||
screen.querySelector('#profile-list-show-deleted')?.addEventListener('change', (event) => {
|
||||
includeDeleted = !!event.currentTarget.checked;
|
||||
void load(activeKind);
|
||||
});
|
||||
}
|
||||
|
||||
if (isFriendsScreen) {
|
||||
screen.addEventListener('click', (event) => {
|
||||
const tab = event.target.closest('[data-friend-kind]');
|
||||
if (!tab) return;
|
||||
const nextKind = String(tab.dataset.friendKind || '');
|
||||
if (!nextKind || nextKind === activeKind) return;
|
||||
activeKind = nextKind;
|
||||
screen.querySelectorAll('[data-friend-kind]').forEach((button) => {
|
||||
const selected = button.dataset.friendKind === activeKind;
|
||||
button.classList.toggle('is-active', selected);
|
||||
button.setAttribute('aria-selected', selected ? 'true' : 'false');
|
||||
});
|
||||
void load(activeKind);
|
||||
});
|
||||
}
|
||||
screen.cleanup = () => {
|
||||
disposed = true;
|
||||
loadGeneration += 1;
|
||||
};
|
||||
|
||||
void load(activeKind);
|
||||
return screen;
|
||||
|
||||
@@ -2,10 +2,15 @@ import { createTopBar } from '../components/topbar.js';
|
||||
import { SHINE_CONNECTIONS_LOGO_SRC } from '../components/shine-logo.js';
|
||||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { state } from '../state.js';
|
||||
import { loadUserProfileCard } from '../services/user-connections.js';
|
||||
import { loadRelationsForPair, loadUserProfileCard } from '../services/user-connections.js';
|
||||
import { createErrorState, createLoadingState } from '../components/feedback.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { makeProfileLinksRoute } from '../services/shine-routes.js';
|
||||
import { navigateBack } from '../router.js';
|
||||
import { profileCardHtml, profileTileHtml } from '../components/profile-card.js';
|
||||
import { createPersonNotePreview, openPersonNoteSheet } from '../components/person-note-sheet.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { PEOPLE_NOTES_EVENT, getPersonNote } from '../services/people-notes.js';
|
||||
|
||||
export const pageMeta = { id: 'user', title: 'Профиль' };
|
||||
|
||||
@@ -32,17 +37,28 @@ export function render({ navigate, route, chrome }) {
|
||||
chrome?.setTopbar(header);
|
||||
|
||||
const status = document.createElement('div');
|
||||
status.className = 'status-line user-profile-status';
|
||||
status.textContent = 'Загрузка профиля...';
|
||||
status.className = 'user-profile-status';
|
||||
status.append(createLoadingState({ label: 'Загружаю профиль' }));
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'user-profile-body';
|
||||
screen.append(status, body);
|
||||
|
||||
let card = null;
|
||||
let disposed = false;
|
||||
let noteSheet = null;
|
||||
let relation = null; // кем человек вам приходится – для плитки «Добавить связь»
|
||||
|
||||
function openNote() {
|
||||
noteSheet?.close();
|
||||
const name = [card.firstName, card.lastName].map((v) => String(v || '').trim()).filter(Boolean).join(' ') || card.login;
|
||||
noteSheet = openPersonNoteSheet({ login: card.login, name, onClose: () => { noteSheet = null; } });
|
||||
}
|
||||
|
||||
function renderProfile() {
|
||||
if (!card) return;
|
||||
if (!card || disposed) return;
|
||||
const isSelf = card.login.toLowerCase() === selfLogin.toLowerCase();
|
||||
const note = isSelf ? null : getPersonNote(card.login);
|
||||
|
||||
body.innerHTML = profileCardHtml({
|
||||
card,
|
||||
@@ -55,6 +71,20 @@ export function render({ navigate, route, chrome }) {
|
||||
].join(''),
|
||||
});
|
||||
|
||||
// Личная заметка – сразу под кнопками действий; видна только владельцу аккаунта.
|
||||
let noteEl = createPersonNotePreview(note, { className: 'user-profile-note', onClick: openNote });
|
||||
if (noteEl) {
|
||||
noteEl.setAttribute('aria-label', `Ваша заметка: ${noteEl.textContent}. Изменить`);
|
||||
} else if (!isSelf) {
|
||||
noteEl = document.createElement('button');
|
||||
noteEl.type = 'button';
|
||||
noteEl.className = 'text-btn user-profile-note-add';
|
||||
noteEl.innerHTML = `${iconHtml('edit')}<span>Добавить личную заметку</span>`;
|
||||
noteEl.addEventListener('click', openNote);
|
||||
}
|
||||
if (noteEl) body.querySelector('.pf-tiles-wrap')?.after(noteEl);
|
||||
syncRelationTile();
|
||||
|
||||
const avatarSlot = body.querySelector('.user-profile-avatar-slot');
|
||||
avatarSlot?.append(renderUserAvatar({
|
||||
login: card.login,
|
||||
@@ -63,9 +93,41 @@ export function render({ navigate, route, chrome }) {
|
||||
avatar: card.avatar,
|
||||
size: 'xl',
|
||||
className: 'user-profile-hero-avatar',
|
||||
official: card.accountRole === 'primary',
|
||||
}));
|
||||
|
||||
status.textContent = '';
|
||||
status.replaceChildren();
|
||||
}
|
||||
|
||||
// Плитка показывает текущую связь («Друг ✓») или предлагает ответить, если человек
|
||||
// добавил вас первым; нажатие – как раньше, в управление связью.
|
||||
function syncRelationTile() {
|
||||
const tile = body.querySelector('[data-profile-action="add"]');
|
||||
if (!tile || !relation) return;
|
||||
const r = relation;
|
||||
const theyFriend = r.inFriend || r.inCloseFriend;
|
||||
let icon = 'user-plus';
|
||||
let label = 'Добавить связь';
|
||||
let hint = '';
|
||||
if (r.outCloseFriend) { icon = 'check'; label = 'Близкий друг'; }
|
||||
else if (r.outFriend) { icon = 'check'; label = 'Друг'; }
|
||||
else if (r.outContact) { icon = 'check'; label = 'Контакт'; }
|
||||
else if (theyFriend) { label = 'Дружить в ответ'; hint = 'хочет с вами дружить'; }
|
||||
else if (r.inContact) {
|
||||
label = 'Добавить в ответ';
|
||||
hint = `${card.gender === 'female' ? 'добавила' : card.gender === 'male' ? 'добавил' : 'добавил(а)'} вас в контакты`;
|
||||
}
|
||||
tile.innerHTML = `${iconHtml(icon)}<span></span>`;
|
||||
tile.querySelector('span').textContent = label;
|
||||
tile.classList.toggle('is-related', icon === 'check');
|
||||
tile.setAttribute('aria-label', icon === 'check' ? `${label}. Изменить связь` : label);
|
||||
body.querySelector('.user-profile-relation-hint')?.remove();
|
||||
if (hint) {
|
||||
const note = document.createElement('p');
|
||||
note.className = 'user-profile-relation-hint';
|
||||
note.textContent = `${[card.firstName, card.lastName].map((v) => String(v || '').trim()).filter(Boolean).join(' ') || card.login} ${hint}`;
|
||||
body.querySelector('.pf-tiles-wrap')?.before(note);
|
||||
}
|
||||
}
|
||||
|
||||
body.addEventListener('click', (event) => {
|
||||
@@ -92,15 +154,43 @@ export function render({ navigate, route, chrome }) {
|
||||
}
|
||||
});
|
||||
|
||||
const onNotesChanged = () => renderProfile();
|
||||
window.addEventListener(PEOPLE_NOTES_EVENT, onNotesChanged);
|
||||
screen.cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
window.removeEventListener(PEOPLE_NOTES_EVENT, onNotesChanged);
|
||||
noteSheet?.close();
|
||||
};
|
||||
|
||||
async function refresh() {
|
||||
card = await loadUserProfileCard(requestedLogin);
|
||||
const loaded = await loadUserProfileCard(requestedLogin);
|
||||
if (disposed) return;
|
||||
card = loaded;
|
||||
renderProfile();
|
||||
if (selfLogin && card.login.toLowerCase() !== selfLogin.toLowerCase()) {
|
||||
loadRelationsForPair({ currentLogin: selfLogin, targetLogin: card.login })
|
||||
.then((flags) => {
|
||||
if (disposed) return;
|
||||
relation = flags;
|
||||
syncRelationTile();
|
||||
})
|
||||
.catch(() => { /* без сведений о связи плитка остаётся «Добавить связь» */ });
|
||||
}
|
||||
}
|
||||
|
||||
refresh().catch((error) => {
|
||||
status.className = 'status-line user-profile-status is-unavailable';
|
||||
status.textContent = `Ошибка: ${error?.message || 'unknown'}`;
|
||||
});
|
||||
const showLoadError = (error) => {
|
||||
if (disposed) return;
|
||||
status.replaceChildren(createErrorState({
|
||||
title: 'Не удалось загрузить профиль',
|
||||
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
||||
onRetry: () => {
|
||||
status.replaceChildren(createLoadingState({ label: 'Загружаю профиль', delayMs: 0 }));
|
||||
refresh().catch(showLoadError);
|
||||
},
|
||||
}));
|
||||
};
|
||||
refresh().catch(showLoadError);
|
||||
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createErrorState, createLoadingState } from '../components/feedback.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { loadRelationsForPair, loadUserProfileCard } from '../services/user-connections.js';
|
||||
import { navigateBack } from '../router.js';
|
||||
import { escapeProfileHtml } from '../components/profile-card.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'user-relation-manage-view', title: 'Добавить связь' };
|
||||
|
||||
@@ -62,12 +65,12 @@ function socialButtonsHtml(flags = {}) {
|
||||
</button>`).join('');
|
||||
}
|
||||
|
||||
function officialBlockHtml(flags = {}) {
|
||||
function officialBlockHtml(flags = {}, targetIsOfficial = false) {
|
||||
return `
|
||||
<section class="card stack relation-manage-card relation-manage-card--official">
|
||||
<div class="relation-manage-card-head">
|
||||
<strong>Основной аккаунт</strong>
|
||||
<span>Этот аккаунт — основной</span>
|
||||
<span>${targetIsOfficial ? 'Этот аккаунт отмечен как основной' : 'Подтвердите, если это основной аккаунт этого человека'}</span>
|
||||
</div>
|
||||
<div class="relation-manage-confirmations">
|
||||
${flags.outOfficialAccount ? '<div class="relation-manage-confirmation">✓ Вы подтвердили его основной аккаунт</div>' : ''}
|
||||
@@ -79,12 +82,12 @@ function officialBlockHtml(flags = {}) {
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function shineBlockHtml(flags = {}) {
|
||||
function shineBlockHtml(flags = {}, targetIsShining = false) {
|
||||
return `
|
||||
<section class="card stack relation-manage-card relation-manage-card--shine">
|
||||
<div class="relation-manage-card-head">
|
||||
<strong>Сияющий</strong>
|
||||
<span>Этот аккаунт — сияющий</span>
|
||||
<span>${targetIsShining ? 'Этот человек отмечен как сияющий' : 'Подтвердите, если считаете этого человека сияющим'}</span>
|
||||
</div>
|
||||
<div class="relation-manage-confirmations">
|
||||
${flags.outShineConfirmed ? '<div class="relation-manage-confirmation">✓ Вы подтверждаете его сияющим</div>' : ''}
|
||||
@@ -152,8 +155,11 @@ export function render({ route, chrome }) {
|
||||
}
|
||||
|
||||
function renderBody() {
|
||||
const canPrimary = selfCard?.accountRole === 'primary' && targetCard?.accountRole === 'primary';
|
||||
const canShine = selfCard?.shineStatus === 'shining' && targetCard?.shineStatus === 'shining';
|
||||
// Те же правила, что проверяет сервер (validateConnectionVotingRights): голосует основной аккаунт,
|
||||
// за сияние – основной и сам сияющий; цель не должна отказываться от подтверждений.
|
||||
const selfPrimary = selfCard?.accountRole === 'primary';
|
||||
const canPrimary = selfPrimary && targetCard?.accountRole !== 'non_voting';
|
||||
const canShine = selfPrimary && selfCard?.shineStatus === 'shining' && targetCard?.shineStatus !== 'not_interested';
|
||||
|
||||
body.innerHTML = `
|
||||
<section class="card stack relation-manage-card relation-manage-card--social">
|
||||
@@ -166,26 +172,36 @@ export function render({ route, chrome }) {
|
||||
${socialButtonsHtml(flags)}
|
||||
</div>
|
||||
</section>
|
||||
${canPrimary ? officialBlockHtml(flags) : ''}
|
||||
${canShine ? shineBlockHtml(flags) : ''}
|
||||
${canPrimary ? officialBlockHtml(flags, targetCard?.accountRole === 'primary') : ''}
|
||||
${canShine ? shineBlockHtml(flags, targetCard?.shineStatus === 'shining') : ''}
|
||||
`;
|
||||
}
|
||||
|
||||
async function refresh({ loading = true } = {}) {
|
||||
if (loading) {
|
||||
status.className = 'status-line relation-manage-status';
|
||||
status.textContent = 'Загрузка...';
|
||||
}
|
||||
// Спиннер – только если ответ задержался, иначе он мелькает и сдвигает экран.
|
||||
const loadingTimer = loading ? window.setTimeout(() => {
|
||||
if (screen.isConnected && !body.childElementCount) status.replaceChildren(createLoadingState({ label: 'Загрузка', delayMs: 0 }));
|
||||
}, 500) : 0;
|
||||
[selfCard, targetCard, flags] = await Promise.all([
|
||||
loadUserProfileCard(selfLogin),
|
||||
loadUserProfileCard(targetLogin),
|
||||
loadRelationsForPair({ currentLogin: selfLogin, targetLogin }),
|
||||
]);
|
||||
window.clearTimeout(loadingTimer);
|
||||
renderBody();
|
||||
status.className = 'status-line relation-manage-status';
|
||||
status.textContent = '';
|
||||
}
|
||||
|
||||
const SOCIAL_DONE = {
|
||||
none: 'Связь убрана',
|
||||
contact: 'Добавлен в контакты',
|
||||
friend: 'Добавлен в друзья',
|
||||
close_friend: 'Добавлен в близкие друзья',
|
||||
};
|
||||
|
||||
// Выбор сохраняется прямо на нажатой кнопке (без строки статуса, которая сдвигала экран),
|
||||
// после сохранения – короткое сообщение и возврат на страницу пользователя.
|
||||
body.addEventListener('click', async (event) => {
|
||||
const button = event.target.closest('button');
|
||||
if (!button || busy) return;
|
||||
@@ -193,24 +209,36 @@ export function render({ route, chrome }) {
|
||||
const social = button.dataset.socialKind;
|
||||
const confirm = button.dataset.confirm;
|
||||
if (!social && !confirm) return;
|
||||
if (social && effectiveSocial(flags, 'out') === social) { navigateBack(); return; }
|
||||
|
||||
busy = true;
|
||||
body.classList.add('is-busy');
|
||||
status.className = 'status-line relation-manage-status';
|
||||
status.textContent = 'Сохранение...';
|
||||
body.querySelectorAll('button').forEach((item) => { item.disabled = true; });
|
||||
const label = button.textContent;
|
||||
button.classList.add('is-pending');
|
||||
button.textContent = 'Сохраняем…';
|
||||
|
||||
try {
|
||||
let done = '';
|
||||
if (social) {
|
||||
await changeSocial(social);
|
||||
done = SOCIAL_DONE[social] || 'Связь сохранена';
|
||||
} else if (confirm === 'official_account') {
|
||||
await setKind('official_account', !flags.outOfficialAccount);
|
||||
done = flags.outOfficialAccount ? 'Подтверждение убрано' : 'Вы подтвердили официальный аккаунт';
|
||||
} else if (confirm === 'shine_confirmed') {
|
||||
await setKind('shine_confirmed', !flags.outShineConfirmed);
|
||||
done = flags.outShineConfirmed ? 'Подтверждение убрано' : 'Вы подтвердили сияние';
|
||||
}
|
||||
await refresh({ loading: false });
|
||||
if (!screen.isConnected) return;
|
||||
showToast(done);
|
||||
navigateBack();
|
||||
} catch (error) {
|
||||
status.className = 'status-line relation-manage-status is-unavailable';
|
||||
status.textContent = `Ошибка: ${error?.message || 'Не удалось изменить связь'}`;
|
||||
if (!screen.isConnected) return;
|
||||
showToast(toUserMessage(error, 'Не удалось изменить связь'), { kind: 'error', timeoutMs: 4000 });
|
||||
button.textContent = label;
|
||||
button.classList.remove('is-pending');
|
||||
body.querySelectorAll('button').forEach((item) => { item.disabled = false; });
|
||||
} finally {
|
||||
busy = false;
|
||||
body.classList.remove('is-busy');
|
||||
@@ -223,10 +251,18 @@ export function render({ route, chrome }) {
|
||||
return screen;
|
||||
}
|
||||
|
||||
refresh().catch((error) => {
|
||||
status.className = 'status-line relation-manage-status is-unavailable';
|
||||
status.textContent = `Ошибка: ${error?.message || 'Не удалось загрузить связи'}`;
|
||||
});
|
||||
const showLoadError = (error) => {
|
||||
status.className = 'relation-manage-status';
|
||||
status.replaceChildren(createErrorState({
|
||||
title: 'Не удалось загрузить связь',
|
||||
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
||||
onRetry: () => {
|
||||
status.replaceChildren();
|
||||
refresh().catch(showLoadError);
|
||||
},
|
||||
}));
|
||||
};
|
||||
refresh().catch(showLoadError);
|
||||
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
readStoredBlockchainSnapshot,
|
||||
saveStoredBlockchainSnapshot,
|
||||
} from '../services/shine-blockchain-snapshot-service.js';
|
||||
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'wallet-view', title: 'Кошелёк' };
|
||||
|
||||
@@ -695,7 +696,7 @@ export function render({navigate, chrome}) {
|
||||
setStatus('Новая пара ключей сгенерирована. Секретный ключ показан на экране один раз.');
|
||||
} catch (error) {
|
||||
if (modeToken !== activeModeToken) return;
|
||||
setStatus(`Не удалось сгенерировать пару ключей: ${error?.message || 'unknown'}`);
|
||||
setStatus(actionErrorText('Не удалось сгенерировать пару ключей', error));
|
||||
} finally {
|
||||
generateBtn.disabled = false;
|
||||
}
|
||||
@@ -878,7 +879,7 @@ export function render({navigate, chrome}) {
|
||||
setStatus(`Билет ${formatSupportTicketLabel(ticket.queueId, ticket.index)} найден. Источник Solana: ${endpoint}`);
|
||||
} catch (error) {
|
||||
result.innerHTML = `<p class="meta-muted" style="margin:0;">${String(error?.message || 'Не удалось загрузить билет')}</p>`;
|
||||
setStatus(`Не удалось посмотреть билет: ${error?.message || 'unknown'}`);
|
||||
setStatus(actionErrorText('Не удалось посмотреть билет', error));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -957,7 +958,7 @@ export function render({navigate, chrome}) {
|
||||
if (modeToken !== activeModeToken) return;
|
||||
stateCard.innerHTML = `<p class="meta-muted" style="margin:0;">${String(error?.message || 'Не удалось загрузить состояние')}</p>`;
|
||||
nextBtn.disabled = true;
|
||||
setStatus(`Не удалось загрузить условия покупки: ${error?.message || 'unknown'}`);
|
||||
setStatus(actionErrorText('Не удалось загрузить условия покупки', error));
|
||||
}
|
||||
|
||||
nextBtn?.addEventListener('click', () => {
|
||||
@@ -989,7 +990,7 @@ export function render({navigate, chrome}) {
|
||||
const stateCard = document.createElement('div');
|
||||
stateCard.className = 'card stack';
|
||||
stateCard.innerHTML = `
|
||||
<p class="meta-muted" style="margin:0;">Текущее состояние покупки загружается...</p>
|
||||
<div class="loading-state" style="--loading-delay:250ms"><span class="spinner" role="status" aria-label="Загрузка"></span></div>
|
||||
`;
|
||||
|
||||
const amountLabel = document.createElement('label');
|
||||
@@ -1140,7 +1141,7 @@ export function render({navigate, chrome}) {
|
||||
if (modeToken !== activeModeToken) return;
|
||||
stateCard.innerHTML = `<p class="meta-muted" style="margin:0;">${String(error?.message || 'Не удалось загрузить состояние')}</p>`;
|
||||
quoteCard.innerHTML = `<p class="meta-muted" style="margin:0;">${String(error?.message || 'Не удалось рассчитать цену')}</p>`;
|
||||
setStatus(`Не удалось загрузить условия покупки: ${error?.message || 'unknown'}`);
|
||||
setStatus(actionErrorText('Не удалось загрузить условия покупки', error));
|
||||
} finally {
|
||||
refreshBtn.disabled = false;
|
||||
}
|
||||
@@ -1243,7 +1244,7 @@ export function render({navigate, chrome}) {
|
||||
await refreshCore();
|
||||
} catch (error) {
|
||||
if (modeToken !== activeModeToken) return;
|
||||
setStatus(`Не удалось купить билет: ${error?.message || 'unknown'}`);
|
||||
setStatus(actionErrorText('Не удалось купить билет', error));
|
||||
} finally {
|
||||
buyBtn.disabled = false;
|
||||
}
|
||||
@@ -1269,7 +1270,7 @@ export function render({navigate, chrome}) {
|
||||
if (modeToken !== activeModeToken) return;
|
||||
setRecipientFromWallet();
|
||||
} catch (error) {
|
||||
setStatus(`Не удалось загрузить client.key: ${error?.message || 'unknown'}`);
|
||||
setStatus(actionErrorText('Не удалось загрузить client.key', error));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1424,7 +1425,7 @@ export function render({navigate, chrome}) {
|
||||
setStatus('Данные лимита и состояния блокчейна обновлены.');
|
||||
} catch (error) {
|
||||
if (modeToken !== activeModeToken) return;
|
||||
setStatus(`Не удалось обновить состояние блокчейна: ${error?.message || 'unknown'}`);
|
||||
setStatus(actionErrorText('Не удалось обновить состояние блокчейна', error));
|
||||
} finally {
|
||||
setButtonsDisabled(false);
|
||||
}
|
||||
@@ -1681,7 +1682,7 @@ export function render({navigate, chrome}) {
|
||||
} catch (error) {
|
||||
if (modeToken !== activeModeToken) return;
|
||||
publishBtn.disabled = true;
|
||||
setStatus(`Не удалось обновить состояние публикации: ${error?.message || 'unknown'}`);
|
||||
setStatus(actionErrorText('Не удалось обновить состояние публикации', error));
|
||||
} finally {
|
||||
refreshBtn.disabled = false;
|
||||
createBtn.disabled = false;
|
||||
@@ -1754,7 +1755,7 @@ export function render({navigate, chrome}) {
|
||||
await refreshState();
|
||||
} catch (error) {
|
||||
if (modeToken !== activeModeToken) return;
|
||||
setStatus(`Не удалось сделать слепок: ${error?.message || 'unknown'}`);
|
||||
setStatus(actionErrorText('Не удалось сделать слепок', error));
|
||||
} finally {
|
||||
if (modeToken === activeModeToken) {
|
||||
setButtonsDisabled(false);
|
||||
@@ -1806,7 +1807,7 @@ export function render({navigate, chrome}) {
|
||||
await refreshState();
|
||||
} catch (error) {
|
||||
if (modeToken !== activeModeToken) return;
|
||||
setStatus(`Не удалось обновить Solana: ${error?.message || 'unknown'}`);
|
||||
setStatus(actionErrorText('Не удалось обновить Solana', error));
|
||||
} finally {
|
||||
if (modeToken === activeModeToken) {
|
||||
setButtonsDisabled(false);
|
||||
@@ -1909,7 +1910,7 @@ export function render({navigate, chrome}) {
|
||||
setStatus('Баланс обновлён.');
|
||||
} catch (error) {
|
||||
if (modeToken !== activeModeToken) return;
|
||||
setStatus(`Не удалось получить баланс: ${error?.message || 'unknown'}`);
|
||||
setStatus(actionErrorText('Не удалось получить баланс', error));
|
||||
} finally {
|
||||
refreshBtn.disabled = false;
|
||||
}
|
||||
@@ -1952,7 +1953,7 @@ export function render({navigate, chrome}) {
|
||||
await refreshBalance();
|
||||
} catch (error) {
|
||||
if (modeToken !== activeModeToken) return;
|
||||
setStatus(`Ошибка перевода: ${error?.message || 'unknown'}`);
|
||||
setStatus(actionErrorText('Ошибка перевода', error));
|
||||
} finally {
|
||||
sendBtn.disabled = false;
|
||||
}
|
||||
@@ -1978,7 +1979,7 @@ export function render({navigate, chrome}) {
|
||||
} catch (error) {
|
||||
if (modeToken !== activeModeToken) return;
|
||||
addressEl.textContent = 'blockchain.key недоступен';
|
||||
setStatus(`Не удалось инициализировать кошелёк: ${error?.message || 'unknown'}`);
|
||||
setStatus(actionErrorText('Не удалось инициализировать кошелёк', error));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2066,7 +2067,7 @@ export function render({navigate, chrome}) {
|
||||
setStatus('Баланс обновлён.');
|
||||
} catch (error) {
|
||||
if (modeToken !== activeModeToken) return;
|
||||
setStatus(`Не удалось получить баланс: ${error?.message || 'unknown'}`);
|
||||
setStatus(actionErrorText('Не удалось получить баланс', error));
|
||||
} finally {
|
||||
refreshBtn.disabled = false;
|
||||
}
|
||||
@@ -2109,7 +2110,7 @@ export function render({navigate, chrome}) {
|
||||
await refreshBalance();
|
||||
} catch (error) {
|
||||
if (modeToken !== activeModeToken) return;
|
||||
setStatus(`Ошибка перевода: ${error?.message || 'unknown'}`);
|
||||
setStatus(actionErrorText('Ошибка перевода', error));
|
||||
} finally {
|
||||
sendBtn.disabled = false;
|
||||
}
|
||||
@@ -2147,7 +2148,7 @@ export function render({navigate, chrome}) {
|
||||
if (modeToken !== activeModeToken) return;
|
||||
addressEl.textContent = 'blockchain.key недоступен';
|
||||
clearArweaveSecretsInMemory();
|
||||
setStatus(`Не удалось инициализировать Arweave-кошелёк: ${error?.message || 'unknown'}`);
|
||||
setStatus(actionErrorText('Не удалось инициализировать Arweave-кошелёк', error));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+61
-4
@@ -44,6 +44,8 @@ const PRETTY_PATHS = new Map([
|
||||
['advanced-settings-view', 'settings/advanced'],
|
||||
['trusted-device-login-settings-view', 'settings/device-login'],
|
||||
['language-view', 'settings/language'],
|
||||
['appearance-view', 'settings/appearance'],
|
||||
['notification-settings-view', 'settings/notifications'],
|
||||
['app-log-view', 'settings/app-log'],
|
||||
['pwa-diagnostics-view', 'settings/pwa-diagnostics'],
|
||||
['solana-users-init-view', 'settings/solana-users-init'],
|
||||
@@ -212,6 +214,9 @@ export function parseRouteFromPath(pathname = '') {
|
||||
}
|
||||
|
||||
if (pageId === 'chat' || pageId === 'chat-view') {
|
||||
if (decodePart(segments[2] || '').toLowerCase() === 'media') {
|
||||
return { pageId: 'chat-media-view', params: { chatId: decodePart(dynamicId) } };
|
||||
}
|
||||
return { pageId: 'chat-view', params: { chatId: dynamicId ? decodeURIComponent(dynamicId) : '' } };
|
||||
}
|
||||
|
||||
@@ -344,6 +349,8 @@ export function parseRouteFromPath(pathname = '') {
|
||||
if (sub === 'advanced') return { pageId: 'advanced-settings-view', params: {} };
|
||||
if (sub === 'device-login') return { pageId: 'trusted-device-login-settings-view', params: {} };
|
||||
if (sub === 'language') return { pageId: 'language-view', params: {} };
|
||||
if (sub === 'appearance') return { pageId: 'appearance-view', params: {} };
|
||||
if (sub === 'notifications') return { pageId: 'notification-settings-view', params: {} };
|
||||
if (sub === 'app-log') return { pageId: 'app-log-view', params: {} };
|
||||
if (sub === 'pwa-diagnostics') return { pageId: 'pwa-diagnostics-view', params: {} };
|
||||
if (sub === 'solana-users-init') return { pageId: 'solana-users-init-view', params: {} };
|
||||
@@ -465,16 +472,53 @@ export function getRoute() {
|
||||
export function navigate(path) {
|
||||
const cleanPath = toPrettyPath(path);
|
||||
const nextPath = cleanPath ? `/${cleanPath}` : '/';
|
||||
if (window.location.pathname !== nextPath) {
|
||||
const fromPath = window.location.pathname;
|
||||
if (fromPath !== nextPath) {
|
||||
previousTrackedPath = currentTrackedPath;
|
||||
currentTrackedPath = nextPath;
|
||||
}
|
||||
if (window.location.pathname !== nextPath) {
|
||||
window.history.pushState({}, '', nextPath);
|
||||
if (fromPath !== nextPath) {
|
||||
// Запись помнит, откуда на неё пришли: «назад» в шапке может вернуться по истории, а не открывать страницу заново.
|
||||
window.history.pushState({ shineFrom: fromPath }, '', nextPath);
|
||||
}
|
||||
window.dispatchEvent(new PopStateEvent('popstate'));
|
||||
}
|
||||
|
||||
// Слой поверх экрана (редактор) кладёт в историю запись с тем же адресом, чтобы «назад» закрывало его.
|
||||
// Роутер разбирает такие возвраты первым: закрывает слой и не пересоздаёт экран под ним.
|
||||
const historyLayers = [];
|
||||
let ownLayerPops = 0;
|
||||
|
||||
export function openHistoryLayer(onBack) {
|
||||
const id = `${Date.now()}:${Math.random()}`;
|
||||
window.history.pushState({ ...window.history.state, shineLayer: id }, '', window.location.href);
|
||||
const layer = { onBack };
|
||||
historyLayers.push(layer);
|
||||
return {
|
||||
// Закрытие изнутри (крестик, отправка) убирает свою запись из истории.
|
||||
close() {
|
||||
const index = historyLayers.indexOf(layer);
|
||||
if (index < 0) return;
|
||||
historyLayers.splice(index, 1);
|
||||
if (window.history.state?.shineLayer === id) {
|
||||
ownLayerPops += 1;
|
||||
window.history.back();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function consumeHistoryLayerPop() {
|
||||
if (ownLayerPops > 0) {
|
||||
ownLayerPops -= 1;
|
||||
return true;
|
||||
}
|
||||
const layer = historyLayers.pop();
|
||||
if (!layer) return false;
|
||||
layer.onBack();
|
||||
return true;
|
||||
}
|
||||
|
||||
export function toPrettyPath(path) {
|
||||
const raw = String(path || '').replace(/^\/+/, '').replace(/\/+$/, '');
|
||||
if (!raw) return '';
|
||||
@@ -485,6 +529,17 @@ export function toPrettyPath(path) {
|
||||
return [prettyHead, ...tail].join('/');
|
||||
}
|
||||
|
||||
// Стрелка «назад» в шапке: если сюда пришли со страницы, которую isParent признаёт своей, – шаг по истории
|
||||
// (как стек: ответ → запись → канал), иначе переход на fallback. Повторный navigate гонял бы по кругу две страницы.
|
||||
export function navigateUp(isParent, fallback) {
|
||||
const from = String(window.history.state?.shineFrom || '');
|
||||
if (from && isParent(parseRouteFromPath(from), from)) {
|
||||
window.history.back();
|
||||
return;
|
||||
}
|
||||
navigate(fallback);
|
||||
}
|
||||
|
||||
export function navigateBack() {
|
||||
if (window.history.length <= 1) return;
|
||||
window.history.back();
|
||||
@@ -533,11 +588,13 @@ function resolveToolbarTab(pageId) {
|
||||
pageId === 'show-keys-view' ||
|
||||
pageId === 'device-session-view' ||
|
||||
pageId === 'language-view' ||
|
||||
pageId === 'appearance-view' ||
|
||||
pageId === 'notification-settings-view' ||
|
||||
pageId === 'app-log-view' ||
|
||||
pageId === 'pwa-diagnostics-view' ||
|
||||
pageId === 'solana-users-init-view'
|
||||
) return 'profile-view';
|
||||
if (pageId === 'chat-view' || pageId === 'contact-search-view') return 'messages-list';
|
||||
if (pageId === 'chat-view' || pageId === 'chat-media-view' || pageId === 'contact-search-view') return 'messages-list';
|
||||
if (pageId === 'search-view' || pageId === 'channel-view' || pageId === 'channel-about-view' || pageId === 'channel-donate-view' || pageId === 'channel-thread-view' || pageId === 'add-channel-view' || pageId === 'add-personal-public-chat-view') return 'channels-list';
|
||||
return 'profile-view';
|
||||
}
|
||||
|
||||
@@ -17,12 +17,16 @@ export function escapeHtml(text) {
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
|
||||
// Размер файла по-русски: «83 Б», «93 КБ», «1,4 МБ»; после 10 – без дробной части.
|
||||
export function formatBytes(bytes) {
|
||||
const value = Number(bytes || 0);
|
||||
if (!Number.isFinite(value) || value <= 0) return '0 B';
|
||||
if (value < 1024) return `${value} B`;
|
||||
if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`;
|
||||
return `${(value / (1024 * 1024)).toFixed(2)} MB`;
|
||||
if (!Number.isFinite(value) || value <= 0) return '0 Б';
|
||||
for (const [unit, size] of [['ГБ', 1024 ** 3], ['МБ', 1024 ** 2], ['КБ', 1024]]) {
|
||||
if (value < size) continue;
|
||||
const amount = value / size;
|
||||
return `${amount.toLocaleString('ru-RU', { maximumFractionDigits: amount >= 10 ? 0 : 1 })} ${unit}`;
|
||||
}
|
||||
return `${Math.round(value)} Б`;
|
||||
}
|
||||
|
||||
function normalizeName(name) {
|
||||
@@ -241,16 +245,18 @@ function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen }
|
||||
onOpen?.();
|
||||
});
|
||||
|
||||
// Горизонтальное фото или видео занимает свою высоту, а не рамку 20rem с пустыми полосами.
|
||||
const applyMediaLayout = (media, width, height) => {
|
||||
const isLandscape = width > 0 && height > 0 && width > height;
|
||||
media.classList.toggle('is-landscape', isLandscape);
|
||||
frame.classList.toggle('is-landscape', isLandscape);
|
||||
slide.classList.toggle('has-landscape-media', isLandscape);
|
||||
slide.parentElement?.classList.toggle('has-landscape-media', isLandscape);
|
||||
};
|
||||
const bindImageLayout = (img) => {
|
||||
img.addEventListener('load', () => {
|
||||
frame.classList.add('is-loaded');
|
||||
const naturalWidth = Number(img.naturalWidth || 0);
|
||||
const naturalHeight = Number(img.naturalHeight || 0);
|
||||
const isLandscape = naturalWidth > 0 && naturalHeight > 0 && naturalWidth > naturalHeight;
|
||||
img.classList.toggle('is-landscape', isLandscape);
|
||||
frame.classList.toggle('is-landscape', isLandscape);
|
||||
slide.classList.toggle('has-landscape-media', isLandscape);
|
||||
slide.parentElement?.classList.toggle('has-landscape-media', isLandscape);
|
||||
applyMediaLayout(img, Number(img.naturalWidth || 0), Number(img.naturalHeight || 0));
|
||||
}, { once: true });
|
||||
};
|
||||
|
||||
@@ -280,6 +286,7 @@ function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen }
|
||||
const videoSize = formatBytes(item.size);
|
||||
info.textContent = videoSize;
|
||||
video.addEventListener('loadedmetadata', () => {
|
||||
applyMediaLayout(video, Number(video.videoWidth || 0), Number(video.videoHeight || 0));
|
||||
const duration = formatVideoDuration(video.duration);
|
||||
info.textContent = duration ? `${videoSize} · ${duration}` : videoSize;
|
||||
// Metadata сама по себе не гарантирует первого кадра. Переход к самому
|
||||
@@ -381,10 +388,14 @@ export function createAttachmentCarouselElement(attachments = [], {
|
||||
authorLogin = '',
|
||||
solanaEndpoint = '',
|
||||
fallbackServerLogin = '',
|
||||
// Свой источник файла: async (item) => ({ url, objectUrl }). Нужен личным сообщениям,
|
||||
// где вложение зашифровано и описано не S:att, а своим тех-блоком (без sha256).
|
||||
resolveUrl = null,
|
||||
} = {}) {
|
||||
const items = (Array.isArray(attachments) ? attachments : [])
|
||||
.slice(0, MAX_MESSAGE_ATTACHMENTS)
|
||||
.map((raw) => {
|
||||
if (resolveUrl) return raw && typeof raw === 'object' ? { ...raw, name: normalizeName(raw.name), size: Number(raw.size || 0) } : null;
|
||||
try {
|
||||
return normalizeAttachment(raw);
|
||||
} catch {
|
||||
@@ -425,7 +436,7 @@ export function createAttachmentCarouselElement(attachments = [], {
|
||||
const getResolved = (itemIndex) => {
|
||||
if (resolved.has(itemIndex)) return Promise.resolve(resolved.get(itemIndex));
|
||||
if (pending.has(itemIndex)) return pending.get(itemIndex);
|
||||
const promise = resolveAttachmentDisplayUrl(items[itemIndex], options)
|
||||
const promise = Promise.resolve(resolveUrl ? resolveUrl(items[itemIndex]) : resolveAttachmentDisplayUrl(items[itemIndex], options))
|
||||
.then((value) => {
|
||||
resolved.set(itemIndex, value);
|
||||
pending.delete(itemIndex);
|
||||
|
||||
@@ -8,3 +8,18 @@ export function restoreChannelPosition(value) {
|
||||
const root = document.getElementById('app-screen');
|
||||
if (root && Number.isFinite(value)) root.scrollTop = value;
|
||||
}
|
||||
|
||||
// «Открыть обсуждение» из ленты ведёт сразу в редактор ответа: лента отмечает путь, обсуждение забирает отметку один раз.
|
||||
let replyOnOpenPath = '';
|
||||
const normalizePath = (path) => {
|
||||
const raw = String(path || '').split(/[?#]/)[0];
|
||||
let decoded = raw;
|
||||
try { decoded = decodeURIComponent(raw); } catch { /* оставляем как есть */ }
|
||||
return decoded.replace(/^\/+|\/+$/g, '').toLowerCase();
|
||||
};
|
||||
export function requestReplyEditorOnOpen(path) { replyOnOpenPath = normalizePath(path); }
|
||||
export function consumeReplyEditorOnOpen(path) {
|
||||
const match = Boolean(replyOnOpenPath) && replyOnOpenPath === normalizePath(path);
|
||||
replyOnOpenPath = '';
|
||||
return match;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const TOAST_HOST_ID = 'shine-toast-host';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
const TOAST_HOST_ID = 'shine-toast-host';
|
||||
|
||||
const rtf = (() => {
|
||||
try {
|
||||
@@ -93,6 +94,22 @@ export function formatListTime(timestampMs) {
|
||||
return new Intl.DateTimeFormat('ru-RU', { day: '2-digit', month: '2-digit', year: '2-digit' }).format(dt);
|
||||
}
|
||||
|
||||
// Возраст записи в шапке поста и ответа: «сейчас», «5 мин», «2 ч», «3 д», потом «12 окт», в прошлом году «12 окт 2025».
|
||||
export function formatShortAge(timestampMs) {
|
||||
const ts = toNumber(timestampMs);
|
||||
if (!ts) return '';
|
||||
const ageMinutes = Math.max(0, Math.floor((Date.now() - ts) / 60000));
|
||||
if (ageMinutes < 1) return 'сейчас';
|
||||
if (ageMinutes < 60) return `${ageMinutes} мин`;
|
||||
const ageHours = Math.floor(ageMinutes / 60);
|
||||
if (ageHours < 24) return `${ageHours} ч`;
|
||||
const ageDays = Math.floor(ageHours / 24);
|
||||
if (ageDays < 7) return `${ageDays} д`;
|
||||
const dt = new Date(ts);
|
||||
const day = `${dt.getDate()} ${SHORT_MONTHS[dt.getMonth()]}`;
|
||||
return dt.getFullYear() === new Date().getFullYear() ? day : `${day} ${dt.getFullYear()}`;
|
||||
}
|
||||
|
||||
export function formatRelativeTime(timestampMs) {
|
||||
const ts = toNumber(timestampMs);
|
||||
if (!ts) return '–';
|
||||
@@ -137,27 +154,87 @@ function ensureToastHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
export function showToast(message, { kind = 'success', timeoutMs = 2500 } = {}) {
|
||||
// Тост встаёт над нижним меню и панелью ввода (что из них выше), а не поверх них.
|
||||
function placeToastHost(host) {
|
||||
const tops = ['toolbar-slot', 'composer-slot']
|
||||
.map((id) => document.getElementById(id))
|
||||
.filter((el) => el && !el.hidden && el.offsetHeight > 0)
|
||||
.map((el) => el.getBoundingClientRect().top);
|
||||
const viewportBottom = window.visualViewport ? window.visualViewport.height + window.visualViewport.offsetTop : window.innerHeight;
|
||||
const edge = tops.length ? Math.min(...tops, viewportBottom) : viewportBottom;
|
||||
host.style.bottom = `${Math.max(12, Math.round(window.innerHeight - edge + 12))}px`;
|
||||
}
|
||||
|
||||
const TOAST_ICONS = { success: 'check', error: 'alert', info: 'info' };
|
||||
|
||||
/**
|
||||
* Короткое сообщение внизу экрана. kind: 'success' (галочка), 'error' (восклицание, дольше
|
||||
* висит), 'info' (i). action – { label, onClick } – кнопка справа («Повторить», «Отменить»).
|
||||
* Одинаковое сообщение подряд не дублируется – показанное просто продлевается.
|
||||
*/
|
||||
export function showToast(message, { kind = 'success', timeoutMs = 2500, action = null } = {}) {
|
||||
const text = String(message || '').trim();
|
||||
if (!text) return;
|
||||
const safeKind = TOAST_ICONS[kind] ? kind : 'success';
|
||||
|
||||
const host = ensureToastHost();
|
||||
placeToastHost(host);
|
||||
const same = [...host.children].find((el) => el.dataset.text === text && !el.classList.contains('is-hiding'));
|
||||
if (same?.restartToast) {
|
||||
same.restartToast();
|
||||
return;
|
||||
}
|
||||
while (host.children.length >= 3) host.firstElementChild.remove();
|
||||
|
||||
const toast = document.createElement('div');
|
||||
toast.className = `toast toast--${kind}`;
|
||||
toast.textContent = text;
|
||||
host.append(toast);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
toast.classList.add('is-visible');
|
||||
});
|
||||
toast.className = `toast toast--${safeKind}`;
|
||||
toast.dataset.text = text;
|
||||
toast.setAttribute('role', safeKind === 'error' ? 'alert' : 'status');
|
||||
const icon = document.createElement('span');
|
||||
icon.className = 'toast__icon';
|
||||
icon.setAttribute('aria-hidden', 'true');
|
||||
icon.innerHTML = iconHtml(TOAST_ICONS[safeKind]);
|
||||
const body = document.createElement('span');
|
||||
body.className = 'toast__text';
|
||||
body.textContent = text;
|
||||
toast.append(icon, body);
|
||||
|
||||
let timer = 0;
|
||||
const hide = () => {
|
||||
window.clearTimeout(timer);
|
||||
if (toast.classList.contains('is-hiding')) return;
|
||||
toast.classList.remove('is-visible');
|
||||
toast.classList.add('is-hiding');
|
||||
setTimeout(() => toast.remove(), 220);
|
||||
};
|
||||
if (action?.label && typeof action.onClick === 'function') {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'toast__action';
|
||||
button.textContent = action.label;
|
||||
button.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
hide();
|
||||
action.onClick();
|
||||
});
|
||||
toast.append(button);
|
||||
}
|
||||
// Касание закрывает сообщение раньше времени.
|
||||
toast.addEventListener('click', hide);
|
||||
host.append(toast);
|
||||
requestAnimationFrame(() => {
|
||||
toast.classList.add('is-visible');
|
||||
});
|
||||
|
||||
setTimeout(hide, Math.max(1200, Number(timeoutMs) || 2500));
|
||||
// Время на чтение: ошибки и длинный текст висят дольше.
|
||||
const base = Math.max(1200, Number(timeoutMs) || 2500);
|
||||
const forReading = 1500 + text.length * 45;
|
||||
const duration = Math.min(8000, Math.max(base, safeKind === 'error' ? Math.max(4000, forReading) : Math.min(forReading, base * 1.6)));
|
||||
toast.restartToast = () => {
|
||||
window.clearTimeout(timer);
|
||||
timer = window.setTimeout(hide, duration);
|
||||
};
|
||||
toast.restartToast();
|
||||
}
|
||||
|
||||
export function softHaptic(duration = 15) {
|
||||
@@ -217,6 +294,27 @@ export function createSkeletonCard(className = '') {
|
||||
return card;
|
||||
}
|
||||
|
||||
// Заглушка в форме настоящих экранов: 'list' – строки списка (круглый аватар, название, подпись),
|
||||
// 'post' – записи как в ленте и обсуждении (аватар слева, имя, две строки текста).
|
||||
export function createSkeletonRows(kind = 'list', count = 4) {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = `skeleton-rows skeleton-rows--${kind}`;
|
||||
wrap.setAttribute('aria-busy', 'true');
|
||||
wrap.setAttribute('aria-label', 'Загрузка');
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'skeleton-row';
|
||||
row.innerHTML = kind === 'post'
|
||||
? '<span class="skeleton-avatar"></span><span class="skeleton-body"><span class="skeleton-line w-40"></span><span class="skeleton-line w-90"></span><span class="skeleton-line w-70"></span></span>'
|
||||
: '<span class="skeleton-avatar"></span><span class="skeleton-body"><span class="skeleton-line w-40"></span><span class="skeleton-line w-70"></span></span>';
|
||||
wrap.append(row);
|
||||
}
|
||||
return wrap;
|
||||
}
|
||||
|
||||
// Показать заглушку, только если загрузка заметно затянулась: быстрый ответ не должен мигать заглушкой.
|
||||
export const SKELETON_DELAY_MS = 500;
|
||||
|
||||
export function normalizeChannelDescription(value) {
|
||||
const text = String(value == null ? '' : value).trim().replace(/\s+/g, ' ');
|
||||
if (!text) return '';
|
||||
@@ -276,3 +374,37 @@ export async function longPressFeel(el, delayMs = 130) {
|
||||
await new Promise((resolve) => setTimeout(resolve, Math.max(60, Number(delayMs) || 130)));
|
||||
if (node) node.classList.remove('is-long-press');
|
||||
}
|
||||
|
||||
// Репост в блокчейне ещё дорабатывается (обещан скоро) – кнопка уже на месте, как четвёртая в ряду действий.
|
||||
// Когда появится, здесь вызывать настоящий обработчик.
|
||||
export const REPOSTS_ENABLED = false;
|
||||
export function notifyRepostSoon() {
|
||||
showToast('Репосты скоро появятся', { kind: 'info' });
|
||||
}
|
||||
|
||||
// Общая карточка «не удалось загрузить»: короткий заголовок, причина в пару строк и крупная кнопка снизу.
|
||||
export function createLoadErrorCard({ title, message, onRetry, secondary = null }) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack channels-status';
|
||||
const heading = document.createElement('strong');
|
||||
heading.textContent = title;
|
||||
const details = document.createElement('p');
|
||||
details.className = 'meta-muted';
|
||||
// Под текстом и так кнопка «Повторить» – совет «повторите попытку» в тексте лишний.
|
||||
details.textContent = String(message || '').replace(/\s*Повторите попытку[^.]*\.?\s*$/u, '').trim();
|
||||
const retry = document.createElement('button');
|
||||
retry.type = 'button';
|
||||
retry.className = 'primary-btn';
|
||||
retry.textContent = 'Повторить';
|
||||
retry.addEventListener('click', onRetry);
|
||||
card.append(heading, details, retry);
|
||||
if (secondary) {
|
||||
const extra = document.createElement('button');
|
||||
extra.type = 'button';
|
||||
extra.className = 'secondary-btn';
|
||||
extra.textContent = secondary.label;
|
||||
extra.addEventListener('click', secondary.onClick);
|
||||
card.append(extra);
|
||||
}
|
||||
return card;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
// Город в профиле (параметр city): подсказки при вводе и приведение разных написаний к одному
|
||||
// городу – для раскладки «Города» на карте связей. Город пишется свободным текстом, поэтому
|
||||
// «Москва», «москва», «г. Москва» и «мск» – это один город, а «Питер» и «СПб» – Санкт-Петербург.
|
||||
|
||||
export const CITY_PARAM = 'city';
|
||||
export const CITY_MAX_LENGTH = 60;
|
||||
|
||||
// Подсказки при вводе: крупные города России и столицы соседних стран. Это только подсказки –
|
||||
// написать можно любой город.
|
||||
export const CITY_SUGGESTIONS = [
|
||||
'Москва', 'Санкт-Петербург', 'Новосибирск', 'Екатеринбург', 'Казань', 'Нижний Новгород', 'Челябинск',
|
||||
'Красноярск', 'Самара', 'Уфа', 'Ростов-на-Дону', 'Омск', 'Краснодар', 'Воронеж', 'Пермь', 'Волгоград',
|
||||
'Саратов', 'Тюмень', 'Тольятти', 'Ижевск', 'Барнаул', 'Ульяновск', 'Иркутск', 'Хабаровск', 'Ярославль',
|
||||
'Владивосток', 'Махачкала', 'Томск', 'Оренбург', 'Кемерово', 'Новокузнецк', 'Рязань', 'Набережные Челны',
|
||||
'Астрахань', 'Пенза', 'Киров', 'Липецк', 'Чебоксары', 'Калининград', 'Тула', 'Ставрополь', 'Курск', 'Сочи',
|
||||
'Улан-Удэ', 'Тверь', 'Магнитогорск', 'Иваново', 'Брянск', 'Белгород', 'Сургут', 'Владимир', 'Архангельск',
|
||||
'Чита', 'Калуга', 'Смоленск', 'Волжский', 'Якутск', 'Саранск', 'Вологда', 'Курган', 'Орёл', 'Мурманск',
|
||||
'Петрозаводск', 'Кострома', 'Новороссийск', 'Йошкар-Ола', 'Таганрог', 'Сыктывкар', 'Нальчик', 'Псков',
|
||||
'Великий Новгород', 'Горно-Алтайск', 'Симферополь', 'Севастополь', 'Минск', 'Алматы', 'Астана', 'Ташкент',
|
||||
'Бишкек', 'Тбилиси', 'Ереван', 'Баку', 'Белград',
|
||||
];
|
||||
|
||||
// Сокращения и разговорные названия.
|
||||
const ALIASES = new Map([
|
||||
['мск', 'москва'], ['msk', 'москва'], ['moscow', 'москва'],
|
||||
['спб', 'санкт петербург'], ['питер', 'санкт петербург'], ['петербург', 'санкт петербург'], ['spb', 'санкт петербург'],
|
||||
['saint petersburg', 'санкт петербург'], ['st petersburg', 'санкт петербург'], ['ленинград', 'санкт петербург'],
|
||||
['екб', 'екатеринбург'], ['ебург', 'екатеринбург'], ['нск', 'новосибирск'], ['новосиб', 'новосибирск'],
|
||||
['нн', 'нижний новгород'], ['нижний', 'нижний новгород'], ['ростов', 'ростов на дону'], ['кзн', 'казань'],
|
||||
['калинин', 'калининград'], ['влад', 'владивосток'], ['челны', 'набережные челны'],
|
||||
]);
|
||||
|
||||
// Ключ города для группировки: без регистра, «ё», «г.» и дефисов; сокращения – полностью.
|
||||
export function cityKey(value) {
|
||||
let text = String(value || '').trim().toLowerCase().replaceAll('ё', 'е');
|
||||
text = text.replace(/^(г\.|г\s|город\s)\s*/u, '').replace(/[.,;]+$/u, '');
|
||||
text = text.replace(/[-–—]/gu, ' ').replace(/\s+/gu, ' ').trim();
|
||||
return ALIASES.get(text) || text;
|
||||
}
|
||||
|
||||
const CANONICAL = new Map(CITY_SUGGESTIONS.map((name) => [cityKey(name), name]));
|
||||
|
||||
/**
|
||||
* Как показать город: известный – по-правильному («Санкт-Петербург»), иначе – самое частое
|
||||
* написание среди тех, кто его указал.
|
||||
* @param {string} key – cityKey
|
||||
* @param {string[]} spellings – как город написали люди
|
||||
*/
|
||||
export function cityLabel(key, spellings = []) {
|
||||
if (CANONICAL.has(key)) return CANONICAL.get(key);
|
||||
const counts = new Map();
|
||||
spellings.forEach((text) => {
|
||||
const clean = String(text || '').trim().replace(/\s+/gu, ' ');
|
||||
if (clean) counts.set(clean, (counts.get(clean) || 0) + 1);
|
||||
});
|
||||
const best = [...counts.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))[0];
|
||||
if (best) return best[0];
|
||||
return key ? key[0].toUpperCase() + key.slice(1) : '';
|
||||
}
|
||||
|
||||
// Для показа в профиле: «г. казань» → «Казань», «спб» → «Санкт-Петербург».
|
||||
export function displayCity(value) {
|
||||
const key = cityKey(value);
|
||||
return key ? cityLabel(key, [String(value || '').trim()]) : '';
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// Настройки этого устройства (не аккаунта): звук сообщений и т. п. Хранятся в localStorage;
|
||||
// в приватном режиме живут до закрытия вкладки.
|
||||
const STORAGE_KEY = 'shine-device-prefs-v1';
|
||||
export const DEVICE_PREFS_EVENT = 'shine-device-prefs-updated';
|
||||
|
||||
let memory = null;
|
||||
|
||||
function readAll() {
|
||||
if (memory) return memory;
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}');
|
||||
memory = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
||||
} catch {
|
||||
memory = {};
|
||||
}
|
||||
return memory;
|
||||
}
|
||||
|
||||
export function getDevicePref(name, fallback) {
|
||||
const value = readAll()[name];
|
||||
return value === undefined ? fallback : value;
|
||||
}
|
||||
|
||||
export function setDevicePref(name, value) {
|
||||
const all = { ...readAll(), [name]: value };
|
||||
memory = all;
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(all));
|
||||
} catch {
|
||||
// Нет места или приватный режим – настройка действует до перезагрузки.
|
||||
}
|
||||
window.dispatchEvent(new CustomEvent(DEVICE_PREFS_EVENT, { detail: { name, value } }));
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
// Настройки личных чатов на этом устройстве: «без звука» (навсегда или до срока) и «закреплён».
|
||||
// Сервер про них не знает: хранятся в localStorage отдельно для каждого аккаунта.
|
||||
// Список «без звука» дублируется в Cache Storage, чтобы его видел service worker:
|
||||
// push о новом сообщении от такого собеседника не показывается, пока приложение закрыто.
|
||||
import { normalizeDmChatId, state } from '../state.js';
|
||||
|
||||
const STORAGE_PREFIX = 'shine-dm-chat-prefs-v1:';
|
||||
const SW_CACHE_NAME = 'shine-dm-prefs';
|
||||
const SW_CACHE_URL = '/__shine/dm-muted.json';
|
||||
export const DM_CHAT_PREFS_EVENT = 'shine-dm-chat-prefs-updated';
|
||||
|
||||
function ownerLogin() {
|
||||
return String(state.session?.login || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
// muted – список собеседников; mutedUntil – срок (мс) для тех, у кого звук выключен на время.
|
||||
// Нет срока – «без звука» навсегда (так же понимают список и прежние версии приложения).
|
||||
function parsePrefs(raw) {
|
||||
const untilRaw = raw?.mutedUntil && typeof raw.mutedUntil === 'object' ? raw.mutedUntil : {};
|
||||
// Без прототипа: логин вроде «constructor» не должен находить чужие свойства.
|
||||
const mutedUntil = Object.create(null);
|
||||
Object.entries(untilRaw).forEach(([id, until]) => {
|
||||
if (Number(until) > 0) mutedUntil[id] = Number(until);
|
||||
});
|
||||
return {
|
||||
muted: Array.isArray(raw?.muted) ? raw.muted.map(String) : [],
|
||||
pinned: Array.isArray(raw?.pinned) ? raw.pinned.map(String) : [],
|
||||
mutedUntil,
|
||||
};
|
||||
}
|
||||
|
||||
function readPrefs() {
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return parsePrefs(null);
|
||||
try {
|
||||
return parsePrefs(JSON.parse(localStorage.getItem(STORAGE_PREFIX + owner) || '{}'));
|
||||
} catch {
|
||||
return parsePrefs(null);
|
||||
}
|
||||
}
|
||||
|
||||
// Чей срок «без звука» ещё не вышел: { собеседник: срок, 0 – навсегда }.
|
||||
function activeMutes(prefs, now = Date.now()) {
|
||||
const result = Object.create(null);
|
||||
prefs.muted.forEach((id) => {
|
||||
const until = Number(prefs.mutedUntil[id] || 0);
|
||||
if (!until || until > now) result[id] = until;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
function writePrefs(prefs) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return;
|
||||
// Истёкшие сроки при записи убираются, чтобы список не копился.
|
||||
const active = activeMutes(prefs);
|
||||
const next = {
|
||||
muted: prefs.muted.filter((id) => id in active),
|
||||
pinned: prefs.pinned,
|
||||
mutedUntil: Object.fromEntries(Object.entries(active).filter(([, until]) => until > 0)),
|
||||
};
|
||||
try {
|
||||
localStorage.setItem(STORAGE_PREFIX + owner, JSON.stringify(next));
|
||||
} catch {
|
||||
// Приватный режим или переполненное хранилище: настройка проживёт до перезагрузки вкладки.
|
||||
}
|
||||
void syncMutedForServiceWorker();
|
||||
scheduleExpiry(next);
|
||||
window.dispatchEvent(new CustomEvent(DM_CHAT_PREFS_EVENT));
|
||||
}
|
||||
|
||||
// Когда срок «без звука» выходит, пока приложение открыто, списки и шапка чата узнают об этом
|
||||
// тем же событием, что и о ручном включении звука.
|
||||
let expiryTimer = 0;
|
||||
function scheduleExpiry(prefs = readPrefs()) {
|
||||
if (expiryTimer) window.clearTimeout(expiryTimer);
|
||||
expiryTimer = 0;
|
||||
const now = Date.now();
|
||||
const nearest = Math.min(...Object.values(activeMutes(prefs, now)).filter((until) => until > now));
|
||||
if (!Number.isFinite(nearest)) return;
|
||||
expiryTimer = window.setTimeout(() => {
|
||||
expiryTimer = 0;
|
||||
void syncMutedForServiceWorker();
|
||||
window.dispatchEvent(new CustomEvent(DM_CHAT_PREFS_EVENT));
|
||||
scheduleExpiry();
|
||||
}, Math.min(nearest - now + 250, 2 ** 31 - 1));
|
||||
}
|
||||
|
||||
function ensureExpiryScheduled(prefs) {
|
||||
if (!expiryTimer) scheduleExpiry(prefs);
|
||||
}
|
||||
|
||||
// Все аккаунты этого устройства: push приходит с toLogin, и worker сверяет пару «кому – от кого».
|
||||
// Формат для worker: { владелец: { собеседник: срок в мс, 0 – навсегда } }.
|
||||
async function syncMutedForServiceWorker() {
|
||||
try {
|
||||
if (!globalThis.caches) return;
|
||||
const muted = {};
|
||||
const now = Date.now();
|
||||
for (let i = 0; i < localStorage.length; i += 1) {
|
||||
const key = localStorage.key(i) || '';
|
||||
if (!key.startsWith(STORAGE_PREFIX)) continue;
|
||||
const active = activeMutes(parsePrefs(JSON.parse(localStorage.getItem(key) || '{}')), now);
|
||||
if (Object.keys(active).length) muted[key.slice(STORAGE_PREFIX.length)] = active;
|
||||
}
|
||||
const cache = await caches.open(SW_CACHE_NAME);
|
||||
await cache.put(SW_CACHE_URL, new Response(JSON.stringify(muted), { headers: { 'Content-Type': 'application/json' } }));
|
||||
} catch {
|
||||
// Без Cache Storage «без звука» действует только пока приложение открыто.
|
||||
}
|
||||
}
|
||||
|
||||
function toggleIn(listName, chatId, enabled) {
|
||||
const id = normalizeDmChatId(chatId);
|
||||
if (!id) return;
|
||||
const prefs = readPrefs();
|
||||
const rest = prefs[listName].filter((x) => x !== id);
|
||||
prefs[listName] = enabled ? [id, ...rest] : rest;
|
||||
return { id, prefs };
|
||||
}
|
||||
|
||||
export function isDmChatMuted(chatId) {
|
||||
const prefs = readPrefs();
|
||||
ensureExpiryScheduled(prefs);
|
||||
return normalizeDmChatId(chatId) in activeMutes(prefs);
|
||||
}
|
||||
|
||||
// Срок «без звука»: null – звук включён, 0 – выключен навсегда, иначе время (мс), когда включится.
|
||||
export function getDmChatMutedUntil(chatId) {
|
||||
const active = activeMutes(readPrefs());
|
||||
const id = normalizeDmChatId(chatId);
|
||||
return id in active ? active[id] : null;
|
||||
}
|
||||
|
||||
// untilMs – когда звук включится сам; 0 – «навсегда».
|
||||
export function setDmChatMuted(chatId, muted, { untilMs = 0 } = {}) {
|
||||
const result = toggleIn('muted', chatId, muted);
|
||||
if (!result) return;
|
||||
const { id, prefs } = result;
|
||||
if (muted && Number(untilMs) > Date.now()) prefs.mutedUntil[id] = Number(untilMs);
|
||||
else delete prefs.mutedUntil[id];
|
||||
writePrefs(prefs);
|
||||
}
|
||||
|
||||
export function isDmChatPinned(chatId) {
|
||||
return readPrefs().pinned.includes(normalizeDmChatId(chatId));
|
||||
}
|
||||
|
||||
export function setDmChatPinned(chatId, pinned) {
|
||||
const result = toggleIn('pinned', chatId, pinned);
|
||||
if (result) writePrefs(result.prefs);
|
||||
}
|
||||
|
||||
// Порядок закреплённых: последний закреплённый – выше всех.
|
||||
export function getPinnedDmChats() {
|
||||
return readPrefs().pinned;
|
||||
}
|
||||
|
||||
// Чаты «без звука» – для списка в настройках уведомлений: [{ chatId, until }], until 0 – навсегда.
|
||||
export function getMutedDmChats() {
|
||||
const prefs = readPrefs();
|
||||
ensureExpiryScheduled(prefs);
|
||||
return Object.entries(activeMutes(prefs)).map(([chatId, until]) => ({ chatId, until }));
|
||||
}
|
||||
|
||||
// «до 14:30», «до завтра, 9:00», «до 20 октября, 9:00»; для «навсегда» – пустая строка.
|
||||
export function formatDmMuteUntil(until, now = new Date()) {
|
||||
const value = Number(until || 0);
|
||||
if (!value) return '';
|
||||
const date = new Date(value);
|
||||
const time = date.toLocaleTimeString('ru-RU', { hour: 'numeric', minute: '2-digit' });
|
||||
const startOfDay = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
|
||||
const days = Math.round((startOfDay(date) - startOfDay(now)) / 86400000);
|
||||
if (days <= 0) return `до ${time}`;
|
||||
if (days === 1) return `до завтра, ${time}`;
|
||||
return `до ${date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long' })}, ${time}`;
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
// Загрузка истории личной переписки с сервера страницами и разбор её в локальный state.
|
||||
// Нужна и ленте чата (подгрузка вверх), и поиску по переписке, и экрану «Медиа и файлы».
|
||||
import { addAppLogEntry, addSignedMessageToChat, authService, normalizeDmChatId, state } from '../state.js';
|
||||
import { loadEncryptedUserSecrets } from './key-vault.js';
|
||||
|
||||
export const DM_HISTORY_PAGE_SIZE = 50;
|
||||
|
||||
// Чаты, история которых в этой вкладке загружена до самого начала: новые сообщения дальше
|
||||
// приходят по WebSocket, и повторно листать сервер не нужно.
|
||||
const fullyLoadedChats = new Set();
|
||||
const fullLoads = new Map();
|
||||
|
||||
// Ключ с владельцем: после входа в другой аккаунт той же вкладкой история грузится заново.
|
||||
function loadKey(chatId) {
|
||||
return `${String(state.session?.login || '').trim().toLowerCase()}|${normalizeDmChatId(chatId)}`;
|
||||
}
|
||||
|
||||
export function isDmHistoryFullyLoaded(chatId) {
|
||||
return fullyLoadedChats.has(loadKey(chatId));
|
||||
}
|
||||
|
||||
export function markDmHistoryFullyLoaded(chatId) {
|
||||
fullyLoadedChats.add(loadKey(chatId));
|
||||
}
|
||||
|
||||
// baseKey и messageKey: «from|to|timeMs|nonce».
|
||||
export function parseBaseKey(baseKey) {
|
||||
const raw = String(baseKey || '').trim();
|
||||
const parts = raw.split('|');
|
||||
if (parts.length < 4) return null;
|
||||
const fromLogin = parts[0] || '';
|
||||
const toLogin = parts[1] || '';
|
||||
const timeMs = Number(parts[2] || 0);
|
||||
const nonce = Number(parts[3] || 0);
|
||||
if (!fromLogin || !toLogin || !Number.isFinite(timeMs) || !Number.isFinite(nonce)) return null;
|
||||
return { fromLogin, toLogin, timeMs, nonce };
|
||||
}
|
||||
|
||||
// Время сообщения: из ключа (оно подписано), для ещё не отправленных – из временного id.
|
||||
export function resolveMessageTimeMs(msg) {
|
||||
const base = parseBaseKey(msg?.baseKey);
|
||||
if (base?.timeMs && Number.isFinite(base.timeMs) && base.timeMs > 0) return base.timeMs;
|
||||
|
||||
const messageKey = String(msg?.messageKey || '').trim();
|
||||
if (messageKey) {
|
||||
const parts = messageKey.split('|');
|
||||
const timeMs = Number(parts[2] || 0);
|
||||
if (parts.length >= 4 && Number.isFinite(timeMs) && timeMs > 0) return timeMs;
|
||||
}
|
||||
|
||||
const tempId = String(msg?.tempId || '').trim();
|
||||
if (tempId.startsWith('tmp-')) {
|
||||
const ts = Number(tempId.split('-')[1] || 0);
|
||||
if (Number.isFinite(ts) && ts > 0) return ts;
|
||||
}
|
||||
|
||||
const fallback = Number(msg?.createdAtMs || 0);
|
||||
if (Number.isFinite(fallback) && fallback > 0) return fallback;
|
||||
return 0;
|
||||
}
|
||||
|
||||
export async function mergeDirectMessagesPage(chatId, payloadMessages) {
|
||||
const items = Array.isArray(payloadMessages) ? [...payloadMessages] : [];
|
||||
items.sort((a, b) => Number(a?.timeMs || 0) - Number(b?.timeMs || 0));
|
||||
// Ключ расшифровки достаём из хранилища один раз на страницу: по сообщению это занимало
|
||||
// ~25 мс (расшифровка контейнера ключей), и страница из 50 сообщений грузилась секунду.
|
||||
let clientPrivatePkcs8B64 = '';
|
||||
if (items.length) {
|
||||
try {
|
||||
const secrets = await loadEncryptedUserSecrets(state.session.login, state.session.storagePwdInMemory);
|
||||
clientPrivatePkcs8B64 = String(secrets?.clientKey || '').trim();
|
||||
} catch {
|
||||
// Расшифровка ниже сама сообщит, чего не хватает.
|
||||
}
|
||||
}
|
||||
for (const item of items) {
|
||||
const blobB64 = String(item?.blobB64 || '').trim();
|
||||
const messageKey = String(item?.messageKey || '').trim();
|
||||
if (!blobB64 || !messageKey) continue;
|
||||
try {
|
||||
const parsed = authService.parseSignedMessageBlob(blobB64);
|
||||
let text = '';
|
||||
try {
|
||||
const decrypted = await authService.decryptSignedMessageContent({
|
||||
parsed,
|
||||
login: state.session.login,
|
||||
storagePwd: state.session.storagePwdInMemory,
|
||||
clientPrivatePkcs8B64,
|
||||
});
|
||||
text = String(decrypted?.text || '');
|
||||
} catch (error) {
|
||||
text = `Нерасшифрованное сообщение (${error?.message || 'decrypt failed'})`;
|
||||
}
|
||||
addSignedMessageToChat({
|
||||
chatId,
|
||||
messageKey,
|
||||
baseKey: String(item?.baseKey || parsed?.baseKey || ''),
|
||||
from: Number(parsed?.messageType || 0) === 2 ? 'out' : 'in',
|
||||
text,
|
||||
messageType: Number(parsed?.messageType || item?.messageType || 0),
|
||||
unread: false,
|
||||
readAtMs: Number(item?.readAtMs || 0),
|
||||
rawBlobB64: blobB64,
|
||||
revisionTimeMs: Number(item?.revisionTimeMs || parsed?.revisionTimeMs || 0),
|
||||
deliveryState: String(item?.deliveryState || ''),
|
||||
});
|
||||
} catch (error) {
|
||||
addAppLogEntry({
|
||||
level: 'warn',
|
||||
source: 'dm-history',
|
||||
message: 'Не удалось обработать сообщение из истории DM',
|
||||
details: { chatId, messageKey, error: error?.message || 'unknown' },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Листает историю от новых к старым до конца. onPage получает число загруженных страниц
|
||||
// (для подписи «Загружаю историю…»). Параллельные вызовы для одного чата делят одну загрузку.
|
||||
export function loadFullDmHistory(chatId, { onPage } = {}) {
|
||||
const id = normalizeDmChatId(chatId);
|
||||
const key = loadKey(id);
|
||||
if (fullyLoadedChats.has(key)) return Promise.resolve({ peer: null });
|
||||
if (fullLoads.has(key)) return fullLoads.get(key);
|
||||
const run = (async () => {
|
||||
let beforeTimeMs = 0;
|
||||
let beforeMessageKey = '';
|
||||
let peer = null;
|
||||
for (let page = 1; ; page += 1) {
|
||||
const payload = await authService.getDirectMessages({
|
||||
peerLogin: id,
|
||||
limit: DM_HISTORY_PAGE_SIZE,
|
||||
beforeTimeMs,
|
||||
beforeMessageKey,
|
||||
});
|
||||
peer = peer || payload?.peer || null;
|
||||
await mergeDirectMessagesPage(id, payload?.messages || []);
|
||||
onPage?.(page);
|
||||
const nextTime = Number(payload?.nextBeforeTimeMs || 0);
|
||||
const nextKey = String(payload?.nextBeforeMessageKey || '').trim();
|
||||
// Сервер без курсора или курсор не сдвинулся – дальше листать нечего.
|
||||
if (!payload?.hasMore || (!nextTime && !nextKey) || (nextTime === beforeTimeMs && nextKey === beforeMessageKey)) break;
|
||||
beforeTimeMs = nextTime;
|
||||
beforeMessageKey = nextKey;
|
||||
}
|
||||
fullyLoadedChats.add(key);
|
||||
return { peer };
|
||||
})();
|
||||
fullLoads.set(key, run);
|
||||
run.finally(() => fullLoads.delete(key)).catch(() => {});
|
||||
return run;
|
||||
}
|
||||
@@ -72,7 +72,7 @@ function makeFrame({ prevHash, back32Hash=ZERO_HASH, blockNumber, type, subType,
|
||||
export const KEY_ROTATION_REASONS = Object.freeze([
|
||||
{ code:1, label:'Обычная смена пароля / ключей' },
|
||||
{ code:2, label:'Возможная компрометация ключей' },
|
||||
{ code:3, label:'Подтверждённая компрометация — откат истории' },
|
||||
{ code:3, label:'Подтверждённая компрометация – откат истории' },
|
||||
{ code:4, label:'Восстановление доступа' },
|
||||
]);
|
||||
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
// Последние загруженные данные экранов каналов и обсуждений – только в памяти вкладки.
|
||||
// При возврате на экран он сразу рисуется из кэша, а свежие данные подтягиваются тихо.
|
||||
import { state } from '../state.js';
|
||||
|
||||
const MAX_ENTRIES = 60;
|
||||
const entries = new Map();
|
||||
|
||||
function fullKey(kind, key) {
|
||||
return `${String(state.session.login || '').toLowerCase()}|${kind}|${String(key || '').toLowerCase()}`;
|
||||
}
|
||||
|
||||
export function readPageData(kind, key) {
|
||||
const id = fullKey(kind, key);
|
||||
const entry = entries.get(id);
|
||||
if (!entry) return null;
|
||||
// Свежепрочитанное поднимаем в конец, чтобы вытеснялось давно не открытое.
|
||||
entries.delete(id);
|
||||
entries.set(id, entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
export function writePageData(kind, key, data) {
|
||||
const id = fullKey(kind, key);
|
||||
const signature = safeSignature(data);
|
||||
entries.delete(id);
|
||||
entries.set(id, { data, signature, savedAt: Date.now() });
|
||||
while (entries.size > MAX_ENTRIES) entries.delete(entries.keys().next().value);
|
||||
return signature;
|
||||
}
|
||||
|
||||
export function pageDataAge(kind, key) {
|
||||
const entry = entries.get(fullKey(kind, key));
|
||||
return entry ? Date.now() - entry.savedAt : Infinity;
|
||||
}
|
||||
|
||||
export function dropPageData(kind, key) {
|
||||
entries.delete(fullKey(kind, key));
|
||||
}
|
||||
|
||||
// Подпись нужна, чтобы не перерисовывать экран, если сервер вернул то же самое.
|
||||
export function safeSignature(data) {
|
||||
try {
|
||||
return JSON.stringify(data);
|
||||
} catch {
|
||||
return `${Date.now()}:${Math.random()}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// Личные заметки о людях: текст и цветная метка, видны только владельцу аккаунта.
|
||||
// Пока хранятся на этом устройстве (localStorage, отдельно для каждого аккаунта) и на сервер
|
||||
// не уходят. Формат одной записи – { text, mark, updatedAt }: его же можно будет шифровать
|
||||
// и синхронизировать между устройствами, когда появится серверное хранилище.
|
||||
import { state } from '../state.js';
|
||||
|
||||
const STORAGE_PREFIX = 'shine-people-notes-v1:';
|
||||
const MAX_TEXT = 2000;
|
||||
export const PEOPLE_NOTES_EVENT = 'shine-people-notes-updated';
|
||||
|
||||
// Цвет метки задаёт CSS (--note-mark-<id>), здесь только порядок и подписи для экранного диктора.
|
||||
export const NOTE_MARKS = [
|
||||
{ id: 'green', label: 'Зелёная метка' },
|
||||
{ id: 'yellow', label: 'Жёлтая метка' },
|
||||
{ id: 'red', label: 'Красная метка' },
|
||||
{ id: 'blue', label: 'Синяя метка' },
|
||||
{ id: 'violet', label: 'Фиолетовая метка' },
|
||||
];
|
||||
const MARK_IDS = new Set(NOTE_MARKS.map((mark) => mark.id));
|
||||
|
||||
function ownerLogin() {
|
||||
return String(state.session?.login || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function personKey(login) {
|
||||
return String(login || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function readAll() {
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return {};
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(STORAGE_PREFIX + owner) || '{}');
|
||||
return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function writeAll(all) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return;
|
||||
try {
|
||||
localStorage.setItem(STORAGE_PREFIX + owner, JSON.stringify(all));
|
||||
} catch {
|
||||
// Приватный режим или переполненное хранилище: заметка проживёт до перезагрузки вкладки.
|
||||
}
|
||||
window.dispatchEvent(new CustomEvent(PEOPLE_NOTES_EVENT));
|
||||
}
|
||||
|
||||
function normalizeNote(raw) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const text = String(raw.text || '').slice(0, MAX_TEXT);
|
||||
const mark = MARK_IDS.has(raw.mark) ? raw.mark : '';
|
||||
if (!text.trim() && !mark) return null;
|
||||
return { text, mark, updatedAt: Number(raw.updatedAt) || 0 };
|
||||
}
|
||||
|
||||
export function getPersonNote(login) {
|
||||
return normalizeNote(readAll()[personKey(login)]);
|
||||
}
|
||||
|
||||
// Пустой текст без метки удаляет заметку.
|
||||
export function setPersonNote(login, { text = '', mark = '' } = {}) {
|
||||
const key = personKey(login);
|
||||
if (!key) return;
|
||||
const all = readAll();
|
||||
const note = normalizeNote({ text, mark, updatedAt: Date.now() });
|
||||
if (note) all[key] = note;
|
||||
else delete all[key];
|
||||
writeAll(all);
|
||||
}
|
||||
|
||||
// Все заметки аккаунта: логин → запись. Карта связей читает их одним вызовом.
|
||||
export function getAllPersonNotes() {
|
||||
const out = new Map();
|
||||
for (const [key, raw] of Object.entries(readAll())) {
|
||||
const note = normalizeNote(raw);
|
||||
if (note) out.set(key, note);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const PERSON_NOTE_MAX_TEXT = MAX_TEXT;
|
||||
@@ -0,0 +1,20 @@
|
||||
// Поиск людей в списках на устройстве: совпадение с началом любого слова имени или логина.
|
||||
// «анна» находит «Анну Гусеву» и anna_guseva, но не «Жанну»; «гус ан» – тоже Анну Гусеву.
|
||||
// Регистр и «ё» не важны, «@» в начале запроса не мешает.
|
||||
|
||||
export function normalizeSearchText(value) {
|
||||
return String(value || '').toLowerCase().replaceAll('ё', 'е').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} text – всё, по чему ищется человек: имя, фамилия, логин
|
||||
* @param {string} query – как ввели (нормализуется здесь же)
|
||||
*/
|
||||
export function matchesPeopleQuery(text, query) {
|
||||
const parts = normalizeSearchText(query).replace(/^@/, '').split(/\s+/).filter(Boolean);
|
||||
if (!parts.length) return true;
|
||||
const hay = normalizeSearchText(text);
|
||||
// Слова целиком («q_tester1») и их части по «_», «.», «-», «@».
|
||||
const words = new Set([...hay.split(/\s+/), ...hay.split(/[\s@_.-]+/)].filter(Boolean));
|
||||
return parts.every((part) => [...words].some((word) => word.startsWith(part)));
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
DEFAULT_SHINE_SERVER_HTTP,
|
||||
resolveShineServerForUserLogin,
|
||||
} from './shine-server-resolver.js';
|
||||
import { state } from '../state.js';
|
||||
|
||||
const ACCESS_SERVER_CACHE_TTL_MS = 60_000;
|
||||
const accessServerCache = new Map();
|
||||
@@ -158,9 +159,14 @@ export async function resolvePublicFileUrl({
|
||||
solanaEndpoint,
|
||||
fallbackServerLogin = '',
|
||||
} = {}) {
|
||||
const currentServerUrl = publicFileUrl(DEFAULT_SHINE_SERVER_HTTP, sha256);
|
||||
if (await publicFileExists(currentServerUrl)) {
|
||||
return currentServerUrl;
|
||||
// Сначала – сервер, к которому подключены сейчас (у большинства читателей он же сервер автора),
|
||||
// затем сервер сборки по умолчанию; только потом ищем сервер автора через его PDA.
|
||||
const nearbyBases = [...new Set([state.entrySettings?.shineServerHttp, DEFAULT_SHINE_SERVER_HTTP]
|
||||
.map((base) => String(base || '').trim().replace(/\/$/, ''))
|
||||
.filter(Boolean))];
|
||||
for (const base of nearbyBases) {
|
||||
const url = publicFileUrl(base, sha256);
|
||||
if (await publicFileExists(url)) return url;
|
||||
}
|
||||
|
||||
const cleanLogin = String(authorLogin || '').trim().toLowerCase();
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// Прокрутить к элементу только его ленту (ближайший прокручиваемый контейнер).
|
||||
// element.scrollIntoView двигает ещё и все внешние контейнеры и видимую область браузера:
|
||||
// при открытой клавиатуре это уводило шапку за верхний край экрана – в поиске по переписке
|
||||
// пропадали «раньше/позже», после ответа в обсуждении – заголовок.
|
||||
|
||||
function findScrollContainer(node) {
|
||||
for (let el = node?.parentElement; el; el = el.parentElement) {
|
||||
const { overflowY } = getComputedStyle(el);
|
||||
if ((overflowY === 'auto' || overflowY === 'scroll') && el.scrollHeight > el.clientHeight) return el;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Element} node
|
||||
* @param {{ container?: Element|null, block?: 'start'|'center'|'end', behavior?: 'auto'|'smooth' }} [opts]
|
||||
*/
|
||||
export function scrollNodeIntoContainer(node, { container = null, block = 'center', behavior = 'auto' } = {}) {
|
||||
if (!node) return;
|
||||
const host = container || findScrollContainer(node);
|
||||
if (!host) return;
|
||||
const hostRect = host.getBoundingClientRect();
|
||||
const nodeRect = node.getBoundingClientRect();
|
||||
let delta;
|
||||
if (block === 'start') delta = nodeRect.top - hostRect.top;
|
||||
else if (block === 'end') delta = nodeRect.bottom - hostRect.bottom;
|
||||
else delta = nodeRect.top - hostRect.top - (host.clientHeight - nodeRect.height) / 2;
|
||||
const top = Math.max(0, Math.min(host.scrollHeight - host.clientHeight, host.scrollTop + delta));
|
||||
if (behavior === 'smooth' && typeof host.scrollTo === 'function') host.scrollTo({ top, behavior: 'smooth' });
|
||||
else host.scrollTop = top;
|
||||
}
|
||||
@@ -1,3 +1,10 @@
|
||||
import { isDeveloperToolsEnabled } from './feature-settings.js';
|
||||
|
||||
// Сетевые ошибки браузера (fetch, загрузка файла) – одним понятным текстом.
|
||||
const NETWORK_ERROR_RE = /failed to fetch|networkerror|network error|load failed|network request failed|net::err_|err_internet_disconnected/;
|
||||
const NO_CONNECTION_TEXT = 'Нет связи с сервером. Проверьте интернет и попробуйте ещё раз.';
|
||||
const HAS_CYRILLIC_RE = /[а-яё]/i;
|
||||
|
||||
function extractCode(message = '') {
|
||||
const match = String(message || '').match(/\(([A-Z0-9_]+)\)\s*$/i);
|
||||
return match ? String(match[1]).toUpperCase() : '';
|
||||
@@ -35,7 +42,11 @@ export function toUserMessage(error, fallback = 'Действие не выпо
|
||||
text.includes('websocket закрыто') ||
|
||||
text.includes('соединение websocket закрыто')
|
||||
) {
|
||||
return 'Сервер недоступен. Проверьте, что backend запущен, и повторите попытку.';
|
||||
return NO_CONNECTION_TEXT;
|
||||
}
|
||||
|
||||
if (NETWORK_ERROR_RE.test(text)) {
|
||||
return NO_CONNECTION_TEXT;
|
||||
}
|
||||
|
||||
if (text.includes('таймаут') || text.includes('timeout waiting')) {
|
||||
@@ -152,3 +163,28 @@ export function toUserMessage(error, fallback = 'Действие не выпо
|
||||
if (!raw) return fallback;
|
||||
return raw;
|
||||
}
|
||||
|
||||
// Ошибка действия для тоста или строки статуса: что не получилось и, если её можно объяснить
|
||||
// человеку, – почему. «Не удалось удалить чат. Нет связи с сервером…» вместо
|
||||
// «Не удалось удалить чат: TypeError: Failed to fetch». Технический текст остаётся в журнале,
|
||||
// а на экране виден только с включёнными инструментами разработчика.
|
||||
export function actionErrorText(action, error) {
|
||||
const raw = String(error?.message || '').trim();
|
||||
const human = toUserMessage(error, '');
|
||||
if (human && human !== raw) return `${action}. ${human}`;
|
||||
if (raw && HAS_CYRILLIC_RE.test(raw)) {
|
||||
return /^(не удалось|ошибка|нельзя|сначала)/i.test(raw) ? raw : `${action}: ${raw}`;
|
||||
}
|
||||
if (raw && isDeveloperToolsEnabled()) return `${action}: ${raw}`;
|
||||
return `${action}. Попробуйте ещё раз.`;
|
||||
}
|
||||
|
||||
// Микрофон и камера (getUserMedia): у этих ошибок смысл несёт имя, а не текст. Имена общие
|
||||
// для разных API браузера, поэтому разбираются только там, где запрашивали микрофон/камеру.
|
||||
export function mediaAccessErrorText(error) {
|
||||
const name = String(error?.name || '');
|
||||
if (name === 'NotAllowedError' || name === 'SecurityError') return 'Нет доступа к микрофону или камере. Разрешите его в настройках браузера.';
|
||||
if (name === 'NotFoundError' || name === 'OverconstrainedError') return 'Микрофон или камера не найдены.';
|
||||
if (name === 'NotReadableError' || name === 'AbortError') return 'Микрофон или камера заняты другим приложением.';
|
||||
return '';
|
||||
}
|
||||
|
||||
@@ -251,6 +251,7 @@ export async function loadUserProfileCard(login) {
|
||||
blockchainName: normalizeLogin(user.blockchainName),
|
||||
firstName: fields.first_name || '',
|
||||
lastName: fields.last_name || '',
|
||||
city: fields.city || '',
|
||||
address: fields.address || '',
|
||||
web: fields.web || '',
|
||||
phone: fields.phone || '',
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import { authService, state } from '../state.js';
|
||||
import { validateArweaveTxId, validateSha256Hex } from './arweave-file-service.js';
|
||||
import { buildAvatarReference, parseAvatarReference } from './avatar-reference.js';
|
||||
import { CITY_MAX_LENGTH, CITY_PARAM, CITY_SUGGESTIONS } from './cities.js';
|
||||
|
||||
export const profileFieldDefs = [
|
||||
{ key: 'first_name', readKeys: ['first_name'], label: 'Имя', placeholder: 'Введите имя' },
|
||||
{ key: 'last_name', readKeys: ['last_name'], label: 'Фамилия', placeholder: 'Введите фамилию' },
|
||||
{ key: 'address', readKeys: ['address'], label: 'Адрес', placeholder: 'Город, улица, дом' },
|
||||
// Город виден в профиле и собирает знакомых в раскладке «Города» на карте связей.
|
||||
{ key: CITY_PARAM, readKeys: [CITY_PARAM], label: 'Город', placeholder: 'Например, Казань', maxLength: CITY_MAX_LENGTH, suggestions: CITY_SUGGESTIONS },
|
||||
{ key: 'address', readKeys: ['address'], label: 'Адрес', placeholder: 'Улица, дом' },
|
||||
{ key: 'web', readKeys: ['web'], label: 'Ссылки', placeholder: 'Сайт, профиль или другая ссылка' },
|
||||
{ key: 'phone', readKeys: ['phone'], label: 'Телефон', placeholder: '+7 ...' },
|
||||
{ key: 'about', readKeys: ['about'], label: 'О себе', placeholder: 'Коротко расскажите о себе', maxLength: 160, multiline: true },
|
||||
@@ -107,6 +110,7 @@ export async function loadProfileSnapshot(login) {
|
||||
placeholder: field.placeholder,
|
||||
maxLength: Number(field.maxLength || 300),
|
||||
multiline: Boolean(field.multiline),
|
||||
suggestions: Array.isArray(field.suggestions) ? field.suggestions : null,
|
||||
value: latest?.value || '',
|
||||
timeMs: latest?.timeMs || 0,
|
||||
});
|
||||
|
||||
+33
-14
@@ -660,20 +660,6 @@ export function getChatMessages(chatId) {
|
||||
return state.chats[normalizedChatId];
|
||||
}
|
||||
|
||||
export function addChatMessage(chatId, text) {
|
||||
const message = text.trim();
|
||||
if (!message) return;
|
||||
getChatMessages(chatId).push({
|
||||
from: 'out',
|
||||
text: message,
|
||||
firstTick: false,
|
||||
secondTick: false,
|
||||
unread: false,
|
||||
createdAtMs: Date.now(),
|
||||
});
|
||||
sortChatMessagesInPlace(chatId);
|
||||
}
|
||||
|
||||
export function addSystemChatMessage(chatId, text, { from = 'out', kind = 'system' } = {}) {
|
||||
const message = String(text || '').trim();
|
||||
if (!message) return;
|
||||
@@ -723,6 +709,17 @@ export function addOutgoingPendingMessage(chatId, text) {
|
||||
return tempId;
|
||||
}
|
||||
|
||||
// Неотправленное сообщение убирается из ленты: текст возвращается в поле ввода или отправка
|
||||
// повторяется – и в ленте не остаётся «часиков», которые уже никогда не станут галочкой.
|
||||
export function removeOutgoingPending(tempId) {
|
||||
if (!tempId) return;
|
||||
Object.keys(state.chats || {}).forEach((chatId) => {
|
||||
const list = getChatMessages(chatId);
|
||||
const index = list.findIndex((item) => item?.tempId === tempId);
|
||||
if (index >= 0) list.splice(index, 1);
|
||||
});
|
||||
}
|
||||
|
||||
export function markOutgoingSent(tempId, {
|
||||
messageKey = '',
|
||||
baseKey = '',
|
||||
@@ -981,6 +978,28 @@ export function setContacts(list) {
|
||||
state.contacts = Array.isArray(list) ? [...list] : [];
|
||||
}
|
||||
|
||||
// Что уже известно о собеседнике (связь, имя, аватар) – из списка чатов или прошлого открытия.
|
||||
// Шапка чата рисуется сразу с этими данными, а не ждёт ответа сервера.
|
||||
const dmPeerCache = new Map();
|
||||
|
||||
export function rememberDmPeer(peer) {
|
||||
const login = String(peer?.login || peer?.peerLogin || '').trim();
|
||||
if (!login) return;
|
||||
const key = login.toLowerCase();
|
||||
const next = { ...(dmPeerCache.get(key) || {}) };
|
||||
['firstName', 'lastName', 'shineStatus', 'relationType'].forEach((field) => {
|
||||
if (peer[field] != null) next[field] = String(peer[field]);
|
||||
});
|
||||
if (peer.avatar !== undefined) next.avatar = peer.avatar && typeof peer.avatar === 'object' ? { ...peer.avatar } : null;
|
||||
next.login = login;
|
||||
dmPeerCache.set(key, next);
|
||||
}
|
||||
|
||||
export function getRememberedDmPeer(login) {
|
||||
const peer = dmPeerCache.get(String(login || '').trim().toLowerCase());
|
||||
return peer ? { ...peer } : null;
|
||||
}
|
||||
|
||||
function toText(value) {
|
||||
if (typeof value === 'string') return value;
|
||||
if (value == null) return '';
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
/* Второстепенное действие: прозрачная, тонкая рамка, текст цвета «вторичного действия». */
|
||||
.secondary-btn { color: var(--action); background: transparent; border: 1px solid var(--border-control); }
|
||||
.destructive-btn { color: var(--danger); }
|
||||
:is(.ui-button, .primary-btn, .secondary-btn, .destructive-btn, .ghost-btn, .icon-btn, .text-btn, .shine-btn):hover { filter: brightness(.96); }
|
||||
@media (hover: hover) { :is(.ui-button, .primary-btn, .secondary-btn, .destructive-btn, .ghost-btn, .icon-btn, .text-btn, .shine-btn):hover { filter: brightness(.96); } }
|
||||
:is(.ui-button, .primary-btn, .secondary-btn, .destructive-btn, .ghost-btn, .icon-btn, .text-btn, .shine-btn):active { filter: brightness(.9); }
|
||||
:is(.ui-button, .primary-btn, .secondary-btn, .destructive-btn, .ghost-btn, .icon-btn, .text-btn, .shine-btn):focus-visible { outline: 2px solid var(--focus-ring); outline-offset: 2px; }
|
||||
:is(.ui-button, .primary-btn, .secondary-btn, .destructive-btn, .ghost-btn, .icon-btn, .text-btn, .shine-btn):disabled { opacity: .5; cursor: not-allowed; filter: none; }
|
||||
@@ -73,7 +73,8 @@
|
||||
font-size: 22px;
|
||||
line-height: 1;
|
||||
}
|
||||
.screen-content:is(.filled-action-buttons, .settings-bordered-actions) .shine-btn.shine-btn--settings:hover { background: var(--surface-selected); }
|
||||
.screen-content:is(.filled-action-buttons, .settings-bordered-actions) .shine-btn.shine-btn--settings:active { background: var(--surface-selected); }
|
||||
@media (hover: hover) { .screen-content:is(.filled-action-buttons, .settings-bordered-actions) .shine-btn.shine-btn--settings:hover { background: var(--surface-selected); } }
|
||||
.screen-content:is(.filled-action-buttons, .settings-bordered-actions) .shine-btn.shine-btn--settings strong { font-weight: var(--weight-bold); }
|
||||
.screen-content:is(.filled-action-buttons, .settings-bordered-actions) .shine-btn.shine-btn--settings .meta-muted { color: var(--text-secondary); font-size: var(--text-xs); font-weight: 400; }
|
||||
.screen-content:is(.filled-action-buttons, .settings-bordered-actions) .shine-btn.shine-btn--settings.shine-btn--danger { justify-content: center; padding-right: 14px; color: var(--danger); }
|
||||
|
||||
@@ -328,7 +328,8 @@
|
||||
background: var(--surface);
|
||||
cursor: pointer;
|
||||
}
|
||||
.ar-attachment-file-picker:hover { border-color: var(--accent); }
|
||||
.ar-attachment-file-picker:active { border-color: var(--accent); }
|
||||
@media (hover: hover) { .ar-attachment-file-picker:hover { border-color: var(--accent); } }
|
||||
.ar-attachment-file-picker:focus-within { outline: 2px solid var(--focus-ring); outline-offset: 2px; }
|
||||
.ar-attachment-file-input { position: absolute; width: 1px; height: 1px; opacity: 0; pointer-events: none; }
|
||||
.ar-attachment-file-btn {
|
||||
|
||||
@@ -59,9 +59,11 @@
|
||||
}
|
||||
|
||||
|
||||
.call-minimized-bar-text:hover {
|
||||
color: var(--text-primary);
|
||||
filter: brightness(1.12);
|
||||
@media (hover: hover) {
|
||||
.call-minimized-bar-text:hover {
|
||||
color: var(--text-primary);
|
||||
filter: brightness(1.12);
|
||||
}
|
||||
}
|
||||
|
||||
.call-minimized-bar-text:active {
|
||||
@@ -118,13 +120,15 @@
|
||||
}
|
||||
|
||||
|
||||
.call-icon-btn:hover {
|
||||
color: var(--text-primary);
|
||||
background: transparent;
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
transform: translateY(-1px);
|
||||
filter: brightness(1.12);
|
||||
@media (hover: hover) {
|
||||
.call-icon-btn:hover {
|
||||
color: var(--text-primary);
|
||||
background: transparent;
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
transform: translateY(-1px);
|
||||
filter: brightness(1.12);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -446,13 +450,15 @@
|
||||
}
|
||||
|
||||
|
||||
.call-accept-btn:hover {
|
||||
color: var(--text-primary);
|
||||
background: transparent;
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
transform: translateY(-1px);
|
||||
filter: brightness(1.12);
|
||||
@media (hover: hover) {
|
||||
.call-accept-btn:hover {
|
||||
color: var(--text-primary);
|
||||
background: transparent;
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
transform: translateY(-1px);
|
||||
filter: brightness(1.12);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -123,6 +123,17 @@
|
||||
.channel-editor__author { display: flex; align-items: center; gap: 12px; font-size: .875rem; }
|
||||
.channel-editor__author .avatar { width: 40px; height: 40px; min-width: 40px; min-height: 40px; }
|
||||
.channel-editor__context-toggle[hidden] { display: none; }
|
||||
.channel-editor__chain { display: grid; gap: 0; margin: 0; padding: 0; list-style: none; }
|
||||
.channel-editor__chain-item { position: relative; display: grid; grid-template-columns: 40px minmax(0, 1fr); column-gap: 12px; padding-bottom: 16px; }
|
||||
/* Линия от аватара вниз – к следующему звену и к автору ответа. */
|
||||
.channel-editor__chain-item::after { content: ''; position: absolute; top: 44px; bottom: -2px; left: 19px; border-left: 2px solid var(--border-control); }
|
||||
.channel-editor__chain-item .avatar.channel-editor__chain-avatar { width: 40px; height: 40px; min-width: 40px; min-height: 40px; }
|
||||
.channel-editor__chain-main { min-width: 0; }
|
||||
.channel-editor__chain-head { display: flex; align-items: baseline; gap: 6px; min-height: 22px; }
|
||||
.channel-editor__chain-head strong { font-size: .9375rem; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.channel-editor__chain-head span { flex-shrink: 0; color: var(--text-secondary); font-size: .875rem; }
|
||||
.channel-editor__chain-main p { margin: 2px 0 0; color: var(--text-primary); font-size: .9375rem; line-height: 1.4375rem; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.channel-editor__author.is-chained { margin-top: -4px; }
|
||||
.channel-editor__attach[hidden], .channel-editor__clear[hidden] { display: none; }
|
||||
|
||||
.channel-editor__attachment {
|
||||
@@ -155,33 +166,20 @@
|
||||
|
||||
.channel-editor__footer {
|
||||
min-height: calc(68px + env(safe-area-inset-bottom));
|
||||
padding: 12px 16px calc(12px + env(safe-area-inset-bottom));
|
||||
padding: 12px 16px calc(12px + env(safe-area-inset-bottom)) 8px;
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
border-top: 1px solid var(--border-subtle);
|
||||
background: var(--background);
|
||||
}
|
||||
|
||||
.channel-editor__attach,
|
||||
.channel-editor__submit {
|
||||
min-height: 44px;
|
||||
padding: 0 14px;
|
||||
border-radius: 12px;
|
||||
padding: 0 18px;
|
||||
border-radius: 22px;
|
||||
}
|
||||
|
||||
.channel-editor__attach {
|
||||
width: 44px;
|
||||
padding: 0;
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
color: var(--accent);
|
||||
border: 1px solid var(--border-control);
|
||||
background: var(--surface);
|
||||
}
|
||||
.channel-editor__attach svg { width: 22px; height: 22px; stroke-width: 1.9; }
|
||||
|
||||
.channel-editor__submit {
|
||||
color: var(--on-accent);
|
||||
background: var(--accent);
|
||||
@@ -193,7 +191,6 @@
|
||||
background: var(--surface-selected);
|
||||
}
|
||||
|
||||
.channel-editor__footer.has-extra { grid-template-columns: auto auto minmax(0, 1fr) auto; }
|
||||
.channel-editor__type { display: block; min-width: 0; }
|
||||
.channel-editor__type-select { min-height: 44px; width: auto; max-width: 9.5rem; padding-left: 12px; border-radius: 12px; font-size: .875rem; }
|
||||
|
||||
@@ -217,11 +214,6 @@
|
||||
}
|
||||
|
||||
@media (max-width: 400px) {
|
||||
.channel-editor__footer.has-extra { grid-template-columns: auto minmax(0, 1fr) auto; row-gap: 8px; }
|
||||
.channel-editor__footer.has-extra .channel-editor__type { grid-row: 1; grid-column: 1 / 3; }
|
||||
.channel-editor__footer.has-extra .channel-editor__counter { grid-row: 1; grid-column: 3; }
|
||||
.channel-editor__footer.has-extra .channel-editor__attach { grid-row: 2; grid-column: 1; }
|
||||
.channel-editor__footer.has-extra .channel-editor__submit { grid-row: 2; grid-column: 3; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
@@ -231,3 +223,37 @@
|
||||
.channel-editor__author-text small { color: var(--text-secondary); font-size: .75rem; }
|
||||
.channel-editor__draft { justify-self: end; color: var(--text-secondary); font-size: .75rem; }
|
||||
.channel-editor__close svg { width: 24px; height: 24px; }
|
||||
|
||||
/* Поле ввода как в Threads: без рамки, в колонке справа от аватара – под именем (и строкой «В канал …»); вложения – ниже текста. */
|
||||
.channel-editor__author { align-items: flex-start; }
|
||||
.channel-editor__author-text { flex: 1; padding-top: 1px; }
|
||||
.channel-editor__compose { display: grid; gap: 8px; margin-top: 4px; }
|
||||
.channel-editor__compose .channel-editor__input { flex: none; min-height: 24px; padding: 0; border: 0; border-radius: 0; background: transparent; line-height: 24px; }
|
||||
.channel-editor__compose .channel-editor__input:focus-visible { border: 0; }
|
||||
.channel-editor__compose .channel-editor__error:empty { display: none; }
|
||||
/* Нижняя панель: «прикрепить» и тип записи слева, счётчик (только у предела) и отправка – справа; ничего не вылезает за край. */
|
||||
.channel-editor__footer { display: flex; align-items: center; gap: 8px; }
|
||||
.channel-editor__footer .channel-editor__attach { flex: none; width: 44px; height: 44px; padding: 0; display: grid; place-items: center; border: 0; border-radius: 50%; background: transparent; color: var(--accent); }
|
||||
.channel-editor__footer .channel-editor__attach:active { background: var(--surface-selected); }
|
||||
@media (hover: hover) { .channel-editor__footer .channel-editor__attach:hover { background: var(--surface-selected); } }
|
||||
.channel-editor__footer .channel-editor__attach svg { width: 24px; height: 24px; }
|
||||
.channel-editor__footer .channel-editor__type { flex: 0 1 auto; min-width: 0; }
|
||||
.channel-editor__footer .channel-editor__type-select { width: 100%; max-width: 9.5rem; min-width: 0; text-overflow: ellipsis; }
|
||||
/* Колонка редактора не должна раздуваться содержимым шире экрана. */
|
||||
.channel-editor { grid-template-columns: minmax(0, 1fr); }
|
||||
.channel-editor__footer, .channel-editor__body { min-width: 0; }
|
||||
.channel-editor__footer .channel-editor__counter { margin-left: auto; }
|
||||
.channel-editor__footer .channel-editor__counter.is-hidden { display: none; }
|
||||
.channel-editor__footer .channel-editor__counter.is-hidden + .channel-editor__submit { margin-left: auto; }
|
||||
.channel-editor__footer .channel-editor__submit { flex: none; }
|
||||
/* Миниатюры картинок и видео – лентой, крестик в углу. */
|
||||
.channel-editor__compose .channel-editor__attachments { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.channel-editor__compose .channel-editor__attachment { flex: 1 1 100%; }
|
||||
.channel-editor__thumb { position: relative; width: 120px; height: 150px; overflow: hidden; border: 1px solid var(--border-subtle); border-radius: 12px; background: var(--surface-selected); }
|
||||
.channel-editor__thumb img, .channel-editor__thumb video { display: block; width: 100%; height: 100%; object-fit: cover; }
|
||||
.channel-editor__thumb-remove { position: absolute; top: 6px; right: 6px; width: 28px; height: 28px; padding: 0; display: grid; place-items: center; border: 0; border-radius: 50%; background: rgb(0 0 0 / .6); color: #fff; cursor: pointer; }
|
||||
.channel-editor__thumb-remove svg { width: 16px; height: 16px; }
|
||||
.channel-editor__thumb--video::after { content: ''; position: absolute; left: 8px; bottom: 8px; width: 24px; height: 24px; border-radius: 50%; background: rgb(0 0 0 / .6) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M9 7v10l8-5z' fill='white'/%3E%3C/svg%3E") center / 18px no-repeat; pointer-events: none; }
|
||||
.channel-editor__header-end { justify-self: end; display: flex; align-items: center; }
|
||||
.channel-editor__header-end .channel-editor__clear { min-height: 44px; padding: 0 4px; }
|
||||
.channel-editor__header-end [hidden] { display: none; }
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
.chip-row::-webkit-scrollbar { display: none; }
|
||||
.chip-row[hidden] { display: none; }
|
||||
|
||||
.chip,
|
||||
.fg-filter-chip {
|
||||
@@ -33,8 +34,12 @@
|
||||
-webkit-backdrop-filter: none;
|
||||
transition: background-color var(--duration-fast) ease, color var(--duration-fast) ease, border-color var(--duration-fast) ease;
|
||||
}
|
||||
.chip:hover,
|
||||
.fg-filter-chip:hover { color: var(--text-primary); }
|
||||
.chip:active,
|
||||
.fg-filter-chip:active { color: var(--text-primary); }
|
||||
@media (hover: hover) {
|
||||
.chip:hover,
|
||||
.fg-filter-chip:hover { color: var(--text-primary); }
|
||||
}
|
||||
.chip[aria-pressed='true'],
|
||||
.chip.is-active,
|
||||
.fg-filter-chip.is-active {
|
||||
@@ -47,10 +52,7 @@
|
||||
.chip:focus-visible,
|
||||
.fg-filter-chip:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: 2px; }
|
||||
|
||||
.chip-row--bleed {
|
||||
margin-inline: calc(-1 * var(--page-gutter));
|
||||
padding-inline: var(--page-gutter);
|
||||
scroll-padding-inline: var(--page-gutter);
|
||||
-webkit-mask-image: linear-gradient(to right, #000 calc(100% - 28px), transparent);
|
||||
mask-image: linear-gradient(to right, #000 calc(100% - 28px), transparent);
|
||||
}
|
||||
.chip[hidden] { display: none; }
|
||||
|
||||
/* Значок в чипе – по размеру текста, что бы ни задала страница. */
|
||||
.chip svg { flex: 0 0 auto; width: 16px; height: 16px; }
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
.compose-field__emoji svg { width: 22px; height: 22px; }
|
||||
.compose-send { width: 44px; height: 44px; min-width: 44px; padding: 0; display: grid; place-items: center; border: 0; border-radius: 50%; background: var(--accent); color: var(--on-accent); cursor: pointer; }
|
||||
.compose-send svg { width: 22px; height: 22px; stroke-width: 2.2; }
|
||||
.compose-send:hover:not(:disabled) { background: var(--accent-hover); }
|
||||
@media (hover: hover) { .compose-send:hover:not(:disabled) { background: var(--accent-hover); } }
|
||||
.compose-send:active:not(:disabled) { background: var(--accent-pressed); }
|
||||
.compose-send:disabled { background: var(--disabled-bg); color: var(--disabled-text); cursor: default; }
|
||||
.compose-send:focus-visible, .compose-field__emoji:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: 2px; }
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
.dropdown-backdrop { position: fixed; inset: 0; z-index: var(--z-overlay); pointer-events: auto; background: var(--scrim); }
|
||||
.dropdown-menu { position: fixed; z-index: var(--z-dropdown); display: grid; gap: 2px; padding: 6px; min-width: 196px; max-width: calc(100vw - 20px); max-height: calc(100dvh - 20px); overflow-y: auto; border: 1px solid var(--border-control); border-radius: 14px; background: var(--surface); color: var(--text-primary); box-shadow: var(--shadow); pointer-events: auto; }
|
||||
.dropdown-menu__item { width: 100%; min-height: 44px; padding: 8px 10px; display: flex; align-items: center; gap: 10px; border: 0; border-radius: 8px; background: transparent; color: var(--text-primary); font: inherit; font-size: .875rem; line-height: 1.4; text-align: left; cursor: pointer; }
|
||||
.dropdown-menu__item:hover { background: var(--surface-raised); }
|
||||
@media (hover: hover) { .dropdown-menu__item:hover { background: var(--surface-raised); } }
|
||||
.dropdown-menu__item.is-selected { background: var(--surface-selected); }
|
||||
.dropdown-menu__item:active { background: var(--surface-selected); }
|
||||
.dropdown-menu__item:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: -2px; }
|
||||
@@ -13,3 +13,8 @@
|
||||
.dropdown-menu__icon { color: var(--text-secondary); }
|
||||
.dropdown-menu__item.is-danger .dropdown-menu__icon { color: var(--danger); }
|
||||
.dropdown-menu__divider { height: 1px; margin: 5px 8px; background: var(--border-subtle); }
|
||||
.dropdown-menu__text { min-width: 0; display: grid; gap: 1px; }
|
||||
.dropdown-menu__hint { color: var(--text-secondary); font-size: .75rem; line-height: 1.3; }
|
||||
.dropdown-menu__chevron { margin-left: auto; padding-left: 6px; display: inline-flex; color: var(--text-secondary); }
|
||||
.dropdown-menu__chevron svg { width: 16px; height: 16px; }
|
||||
.dropdown-menu__back { min-height: 40px; color: var(--text-secondary); font-weight: 600; }
|
||||
|
||||
@@ -105,13 +105,15 @@
|
||||
}
|
||||
|
||||
|
||||
.emoji-picker-tab:hover,
|
||||
.emoji-picker-item:hover {
|
||||
color: var(--text-primary);
|
||||
background: transparent;
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
filter: brightness(1.12);
|
||||
@media (hover: hover) {
|
||||
.emoji-picker-tab:hover,
|
||||
.emoji-picker-item:hover {
|
||||
color: var(--text-primary);
|
||||
background: transparent;
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
filter: brightness(1.12);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
/* Общие состояния экрана (js/components/feedback.js): спиннер, загрузка с задержкой,
|
||||
* «пусто» и ошибка с «Повторить». */
|
||||
|
||||
.spinner {
|
||||
display: inline-block;
|
||||
flex: 0 0 auto;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid color-mix(in srgb, var(--text-secondary) 26%, transparent);
|
||||
border-top-color: var(--accent);
|
||||
animation: spinner-spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
.spinner--sm { width: 16px; height: 16px; }
|
||||
.spinner--lg { width: 28px; height: 28px; border-width: 2.5px; }
|
||||
|
||||
@keyframes spinner-spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* Появляется только если ждать дольше --loading-delay: быстрые загрузки не мелькают. */
|
||||
.loading-state {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: var(--space-6) 0;
|
||||
opacity: 0;
|
||||
animation: loading-state-in 180ms ease forwards;
|
||||
animation-delay: var(--loading-delay, 350ms);
|
||||
}
|
||||
|
||||
@keyframes loading-state-in {
|
||||
to { opacity: 1; }
|
||||
}
|
||||
|
||||
.state-message {
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
gap: var(--space-2);
|
||||
max-width: 340px;
|
||||
margin: 0 auto;
|
||||
padding: var(--space-6) var(--space-4);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.state-message__icon {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
margin-bottom: var(--space-1);
|
||||
border-radius: 50%;
|
||||
color: var(--text-secondary);
|
||||
background: var(--surface-raised);
|
||||
}
|
||||
|
||||
.state-message__icon svg {
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
}
|
||||
|
||||
.state-message--error .state-message__icon {
|
||||
color: var(--danger);
|
||||
background: color-mix(in srgb, var(--danger) 13%, transparent);
|
||||
}
|
||||
|
||||
.state-message__title {
|
||||
margin: 0;
|
||||
color: var(--text-primary);
|
||||
font-size: var(--text-md);
|
||||
font-weight: var(--weight-bold);
|
||||
}
|
||||
|
||||
.state-message__text {
|
||||
margin: 0;
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--text-sm);
|
||||
line-height: var(--leading-sm, 1.45);
|
||||
}
|
||||
|
||||
.state-message__action {
|
||||
margin-top: var(--space-2);
|
||||
min-width: 160px;
|
||||
}
|
||||
|
||||
/* Короткие сообщения внизу (showToast в services/channels-ux.js): над нижним меню и полем
|
||||
* ввода (bottom задаёт JS), значок по смыслу, касание закрывает. */
|
||||
.toast-host {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: calc(90px + env(safe-area-inset-bottom));
|
||||
z-index: 140;
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
gap: 8px;
|
||||
padding: 0 var(--page-gutter);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.toast {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
max-width: min(100%, 440px);
|
||||
min-height: 44px;
|
||||
padding: 10px 14px;
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: 14px;
|
||||
background: var(--surface-raised);
|
||||
box-shadow: var(--shadow);
|
||||
color: var(--text-primary);
|
||||
font-size: var(--text-sm);
|
||||
line-height: 1.35;
|
||||
pointer-events: auto;
|
||||
cursor: default;
|
||||
opacity: 0;
|
||||
transform: translateY(8px) scale(0.98);
|
||||
transition: opacity 180ms ease, transform 220ms cubic-bezier(0.2, 0.8, 0.2, 1);
|
||||
}
|
||||
|
||||
.toast.is-visible {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.toast.is-hiding {
|
||||
opacity: 0;
|
||||
transform: translateY(4px);
|
||||
}
|
||||
|
||||
.toast__icon {
|
||||
flex: 0 0 auto;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
color: var(--success);
|
||||
}
|
||||
|
||||
.toast__icon svg {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
.toast--error .toast__icon { color: var(--danger); }
|
||||
.toast--info .toast__icon { color: var(--accent); }
|
||||
|
||||
.toast__text {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.toast__action {
|
||||
flex: 0 0 auto;
|
||||
margin: -6px -6px -6px 2px;
|
||||
padding: 8px 8px;
|
||||
border: 0;
|
||||
border-radius: 10px;
|
||||
background: none;
|
||||
color: var(--accent);
|
||||
font: inherit;
|
||||
font-weight: var(--weight-bold);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.toast__action:active {
|
||||
background: var(--surface-selected);
|
||||
}
|
||||
@media (hover: hover) {
|
||||
.toast__action:hover {
|
||||
background: var(--surface-selected);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.spinner { animation-duration: 1.6s; }
|
||||
.loading-state { animation: none; opacity: 1; }
|
||||
.toast { transition: none; transform: none; }
|
||||
}
|
||||
@@ -69,9 +69,11 @@
|
||||
}
|
||||
|
||||
.media-viewer__btn svg { width: 22px; height: 22px; }
|
||||
.media-viewer__btn:hover { background: rgb(255 255 255 / 12%); }
|
||||
.media-viewer__btn:active { background: rgb(255 255 255 / 12%); }
|
||||
@media (hover: hover) { .media-viewer__btn:hover { background: rgb(255 255 255 / 12%); } }
|
||||
.media-viewer__btn--round { background: rgb(255 255 255 / 16%); }
|
||||
.media-viewer__btn--round:hover { background: rgb(255 255 255 / 26%); }
|
||||
.media-viewer__btn--round:active { background: rgb(255 255 255 / 26%); }
|
||||
@media (hover: hover) { .media-viewer__btn--round:hover { background: rgb(255 255 255 / 26%); } }
|
||||
.media-viewer__btn:focus-visible,
|
||||
.media-viewer__nav:focus-visible { outline: 2px solid #fff; outline-offset: -2px; }
|
||||
|
||||
|
||||
@@ -6,18 +6,20 @@
|
||||
.modal-dialog { position: absolute; left: 16px; right: 16px; bottom: 24px; display: grid; gap: 12px; box-shadow: var(--shadow); }
|
||||
.modal { position: fixed; inset: 0; background: var(--scrim); display: grid; place-items: center; padding: 16px; z-index: 60; }
|
||||
.modal-card { width: min(100%, 560px); max-height: calc(100dvh - 32px); overflow-y: auto; color: var(--text-primary); background: var(--surface); border: 1px solid var(--border-subtle); border-radius: 20px; padding: 20px; box-shadow: var(--shadow); }
|
||||
.toast-host { position: fixed; left: 0; right: 0; bottom: calc(18px + env(safe-area-inset-bottom)); display: grid; justify-items: center; gap: 8px; z-index: 140; pointer-events: none; }
|
||||
.toast { max-width: min(92vw,420px); padding: 12px 16px; border-radius: 12px; color: var(--text-primary); background: var(--surface); box-shadow: var(--shadow); border: 1px solid var(--border-subtle); opacity: 0; transition: opacity 160ms; }
|
||||
.toast.is-visible { opacity: 1; }
|
||||
.toast.is-hiding { opacity: 0; }
|
||||
.toast.toast--error { color: var(--danger); }
|
||||
.skeleton-card { display: grid; gap: 12px; }
|
||||
.skeleton-line { height: 12px; border-radius: 6px; background: var(--surface-selected); animation: skeleton-pulse 1.2s ease-in-out infinite alternate; }
|
||||
.skeleton-line.w-40 { width: 40%; }
|
||||
.skeleton-line.w-70 { width: 70%; }
|
||||
.skeleton-line.w-90 { width: 90%; }
|
||||
.skeleton-rows { display: grid; }
|
||||
.skeleton-row { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 12px; align-items: center; padding: 12px 0; border-bottom: 1px solid var(--border-subtle); }
|
||||
.skeleton-rows--post .skeleton-row { align-items: start; padding: 16px 0; }
|
||||
.skeleton-avatar { width: 48px; height: 48px; border-radius: 50%; background: var(--surface-selected); animation: skeleton-pulse 1.2s ease-in-out infinite alternate; }
|
||||
.skeleton-rows--post .skeleton-avatar { width: 36px; height: 36px; }
|
||||
.skeleton-body { display: grid; gap: 10px; }
|
||||
.skeleton-body .skeleton-line { display: block; }
|
||||
@keyframes skeleton-pulse { to { opacity: .4; } }
|
||||
@media (prefers-reduced-motion: reduce) { .skeleton-line, .toast { animation: none; transition: none; } }
|
||||
@media (prefers-reduced-motion: reduce) { .skeleton-line { animation: none; transition: none; } }
|
||||
|
||||
@media (max-width: 599px) {
|
||||
.modal { place-items: end stretch; padding: 0; }
|
||||
@@ -46,7 +48,8 @@
|
||||
.sheet__title { margin: 0; font-size: 1rem; }
|
||||
.sheet__close { width: 36px; height: 36px; min-width: 36px; padding: 0; display: grid; place-items: center; border: 0; border-radius: 10px; background: transparent; color: var(--text-secondary); }
|
||||
.sheet__close svg { width: 22px; height: 22px; }
|
||||
.sheet__close:hover { background: var(--surface-raised); color: var(--text-primary); }
|
||||
.sheet__close:active { background: var(--surface-raised); color: var(--text-primary); }
|
||||
@media (hover: hover) { .sheet__close:hover { background: var(--surface-raised); color: var(--text-primary); } }
|
||||
.sheet__body { display: grid; gap: 12px; font-size: .875rem; line-height: 1.3125rem; }
|
||||
.sheet__body > p { margin: 0; }
|
||||
.sheet__footer { display: flex; gap: 8px; margin-top: 18px; }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* Меню-список: группа строк «название / подсказка / ›» — для переходов по разделам
|
||||
* (кошелёк, настройки разработчика и т. п.). Для действий без перехода — обычные кнопки. */
|
||||
.nav-list { display: grid; border: 1px solid var(--border-subtle); border-radius: var(--radius-lg); background: var(--surface); overflow: hidden; }
|
||||
.nav-list[hidden] { display: none; }
|
||||
.nav-list__title { margin: var(--space-2) 0 var(--space-1); color: var(--text-secondary); font-size: var(--text-xs); line-height: var(--leading-xs); font-weight: var(--weight-bold); }
|
||||
.nav-row {
|
||||
width: 100%;
|
||||
@@ -21,7 +22,8 @@
|
||||
}
|
||||
.nav-row:first-child { border-top: 0; }
|
||||
.nav-row::after { content: '›'; position: absolute; right: 16px; top: 50%; transform: translateY(-50%); color: var(--text-secondary); font-size: 22px; line-height: 1; }
|
||||
.nav-row:hover { background: var(--surface-selected); }
|
||||
.nav-row:active { background: var(--surface-selected); }
|
||||
@media (hover: hover) { .nav-row:hover { background: var(--surface-selected); } }
|
||||
.nav-row:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: -2px; }
|
||||
.nav-row__label { font-size: var(--text-md); line-height: var(--leading-md); font-weight: var(--weight-medium); }
|
||||
.nav-row__hint { color: var(--text-secondary); font-size: var(--text-xs); line-height: var(--leading-xs); }
|
||||
@@ -30,7 +32,25 @@
|
||||
.nav-row__label.is-empty { color: var(--text-secondary); font-weight: 400; }
|
||||
|
||||
.nav-list > .nav-row.profile-param-item { margin: 0; border-radius: 0; background: transparent; box-shadow: none; }
|
||||
.nav-list > .nav-row.profile-param-item:hover { background: var(--surface-selected); }
|
||||
.nav-list > .nav-row.profile-param-item:active { background: var(--surface-selected); }
|
||||
@media (hover: hover) { .nav-list > .nav-row.profile-param-item:hover { background: var(--surface-selected); } }
|
||||
|
||||
.language-row::after { content: none; }
|
||||
.language-row[aria-checked='true']::after { content: '✓'; color: var(--accent); font-size: 18px; font-weight: var(--weight-bold); }
|
||||
|
||||
/* Строка с переключателем (<label class="nav-row nav-row--switch">): подпись слева,
|
||||
* .switch справа, без «›». */
|
||||
.nav-row--switch { grid-template-columns: minmax(0, 1fr) auto; align-items: center; column-gap: 12px; padding-right: 14px; }
|
||||
.nav-row--switch::after { content: none; }
|
||||
.nav-row__text { display: grid; gap: 2px; min-width: 0; }
|
||||
/* Строка-сведение без перехода (версия, состояние разрешения). */
|
||||
.nav-row--static { cursor: default; padding-right: 14px; }
|
||||
.nav-row--static::after { content: none; }
|
||||
.nav-row--static:active { background: transparent; }
|
||||
@media (hover: hover) { .nav-row--static:hover { background: transparent; } }
|
||||
/* Строка с кнопкой справа («Разрешить», «Включить звук»). */
|
||||
.nav-row--action { grid-template-columns: minmax(0, 1fr) auto; align-items: center; column-gap: 12px; padding-right: 10px; cursor: default; }
|
||||
.nav-row--action::after { content: none; }
|
||||
.nav-row--action:active { background: transparent; }
|
||||
@media (hover: hover) { .nav-row--action:hover { background: transparent; } }
|
||||
.nav-row__button { min-height: 36px; padding: 0 14px; border-radius: var(--radius-pill); font-size: var(--text-sm); font-weight: var(--weight-bold); }
|
||||
|
||||
@@ -20,7 +20,8 @@
|
||||
border-radius: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.palette-editor__role:hover { background: var(--surface-selected); }
|
||||
.palette-editor__role:active { background: var(--surface-selected); }
|
||||
@media (hover: hover) { .palette-editor__role:hover { background: var(--surface-selected); } }
|
||||
.palette-editor__role input[type='color'] {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
/* Заметка о человеке (js/components/person-note-sheet.js): шторка редактирования
|
||||
и короткий блок с текстом заметки на карте связей и в профиле. */
|
||||
|
||||
:root {
|
||||
--note-mark-green: #5cd68c;
|
||||
--note-mark-yellow: #f5cd50;
|
||||
--note-mark-red: #ff6868;
|
||||
--note-mark-blue: #60aaff;
|
||||
--note-mark-violet: #be8cff;
|
||||
}
|
||||
|
||||
:root[data-theme='light'] {
|
||||
--note-mark-green: #248c52;
|
||||
--note-mark-yellow: #be8c0a;
|
||||
--note-mark-red: #c8303c;
|
||||
--note-mark-blue: #2864d2;
|
||||
--note-mark-violet: #7846d2;
|
||||
}
|
||||
|
||||
.person-note__hint {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.person-note__text {
|
||||
width: 100%;
|
||||
min-height: 110px;
|
||||
resize: vertical;
|
||||
font: inherit;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.person-note__label {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.person-note__marks {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.person-note__mark {
|
||||
position: relative;
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
padding: 0;
|
||||
border: 2px solid var(--border-control);
|
||||
border-radius: 50%;
|
||||
background: var(--surface);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* «Без метки» – перечёркнутый круг. */
|
||||
.person-note__mark[data-mark='']::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 4px;
|
||||
bottom: 4px;
|
||||
width: 2px;
|
||||
background: var(--border-control);
|
||||
transform: translateX(-50%) rotate(45deg);
|
||||
}
|
||||
|
||||
.person-note__mark[data-mark='green'] { background: var(--note-mark-green); border-color: var(--note-mark-green); }
|
||||
.person-note__mark[data-mark='yellow'] { background: var(--note-mark-yellow); border-color: var(--note-mark-yellow); }
|
||||
.person-note__mark[data-mark='red'] { background: var(--note-mark-red); border-color: var(--note-mark-red); }
|
||||
.person-note__mark[data-mark='blue'] { background: var(--note-mark-blue); border-color: var(--note-mark-blue); }
|
||||
.person-note__mark[data-mark='violet'] { background: var(--note-mark-violet); border-color: var(--note-mark-violet); }
|
||||
|
||||
.person-note__mark[aria-checked='true'] {
|
||||
box-shadow: 0 0 0 3px var(--surface), 0 0 0 5px var(--accent);
|
||||
}
|
||||
|
||||
.person-note__mark:focus-visible {
|
||||
outline: 2px solid var(--focus-ring);
|
||||
outline-offset: 4px;
|
||||
}
|
||||
|
||||
.person-note-preview {
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 3;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
border: 0;
|
||||
border-left: 3px solid var(--border-control);
|
||||
border-radius: 4px 10px 10px 4px;
|
||||
background: var(--surface-raised);
|
||||
color: var(--text-primary);
|
||||
font: inherit;
|
||||
font-size: 13.5px;
|
||||
line-height: 1.35;
|
||||
text-align: left;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
button.person-note-preview {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button.person-note-preview:focus-visible {
|
||||
outline: 2px solid var(--focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.person-note-preview[data-mark='green'] { border-left-color: var(--note-mark-green); }
|
||||
.person-note-preview[data-mark='yellow'] { border-left-color: var(--note-mark-yellow); }
|
||||
.person-note-preview[data-mark='red'] { border-left-color: var(--note-mark-red); }
|
||||
.person-note-preview[data-mark='blue'] { border-left-color: var(--note-mark-blue); }
|
||||
.person-note-preview[data-mark='violet'] { border-left-color: var(--note-mark-violet); }
|
||||
@@ -0,0 +1,217 @@
|
||||
/* Строка человека в списках (js/components/person-row.js) – как строка списка чатов:
|
||||
* аватар 48 px, имя, строка под ним, разделитель от текста, действия справа. */
|
||||
|
||||
.person-row {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-height: 68px;
|
||||
background: linear-gradient(var(--border-subtle), var(--border-subtle)) right bottom / calc(100% - 64px) 1px no-repeat;
|
||||
/* Строки за экраном не отрисовываются – список на сотни людей остаётся лёгким. */
|
||||
content-visibility: auto;
|
||||
contain-intrinsic-size: auto 68px;
|
||||
}
|
||||
|
||||
.person-row:last-child {
|
||||
background: none;
|
||||
}
|
||||
|
||||
.person-row__main {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
min-height: 68px;
|
||||
/* Слева запас под кольцо аватара: content-visibility обрезает всё, что за краем строки. */
|
||||
padding: 10px 0 10px 4px;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition: background-color var(--duration-fast) ease;
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.person-row__main:hover {
|
||||
background-color: color-mix(in srgb, var(--surface) 66%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
.person-row__main:active {
|
||||
background-color: var(--surface-selected);
|
||||
}
|
||||
|
||||
.person-row__main:focus-visible {
|
||||
outline: 2px solid var(--focus-ring);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.person-row__avatar {
|
||||
position: relative;
|
||||
flex: 0 0 48px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
}
|
||||
|
||||
.person-row__avatar .avatar.avatar-md {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
min-width: 48px;
|
||||
min-height: 48px;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
/* Близкие и сияющие – цветное кольцо, как на карте связей и в чатах. */
|
||||
.person-row--close .person-row__avatar .avatar {
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 0 0 2px var(--background), 0 0 0 4px var(--rel-family);
|
||||
}
|
||||
|
||||
.person-row--shining .person-row__avatar .avatar {
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 0 0 2px var(--background), 0 0 0 4px var(--rel-shining);
|
||||
}
|
||||
|
||||
.person-row__mark {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
z-index: 5;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid var(--background);
|
||||
background: var(--note-mark-green);
|
||||
}
|
||||
|
||||
.person-row__mark[data-mark='yellow'] { background: var(--note-mark-yellow); }
|
||||
.person-row__mark[data-mark='red'] { background: var(--note-mark-red); }
|
||||
.person-row__mark[data-mark='blue'] { background: var(--note-mark-blue); }
|
||||
.person-row__mark[data-mark='violet'] { background: var(--note-mark-violet); }
|
||||
.person-row__mark[data-mark='note'] {
|
||||
background: var(--background);
|
||||
box-shadow: inset 0 0 0 2px var(--text-secondary);
|
||||
}
|
||||
|
||||
.person-row__text {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.person-row__name {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.person-row__name-text {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: var(--text-md);
|
||||
font-weight: var(--weight-bold);
|
||||
}
|
||||
|
||||
.person-row__tag {
|
||||
color: var(--accent);
|
||||
font-weight: var(--weight-medium);
|
||||
}
|
||||
|
||||
.person-row__sub,
|
||||
.person-row__note {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
.person-row__note {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.person-row__action {
|
||||
flex: 0 0 auto;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
margin-left: 2px;
|
||||
border-radius: 50%;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.person-row__action:active {
|
||||
color: var(--accent);
|
||||
background: var(--surface);
|
||||
}
|
||||
@media (hover: hover) {
|
||||
.person-row__action:hover {
|
||||
color: var(--accent);
|
||||
background: var(--surface);
|
||||
}
|
||||
}
|
||||
|
||||
.person-row__action svg {
|
||||
width: 21px;
|
||||
height: 21px;
|
||||
}
|
||||
|
||||
/* Главное действие строки («Дружить в ответ») – цветом, чтобы его было видно среди прочих. */
|
||||
.person-row__action--primary {
|
||||
color: var(--accent);
|
||||
background: color-mix(in srgb, var(--accent) 14%, transparent);
|
||||
}
|
||||
|
||||
.person-row__action:disabled {
|
||||
cursor: progress;
|
||||
}
|
||||
|
||||
.person-list-section {
|
||||
padding: var(--space-4) 0 var(--space-1) 4px;
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--text-xs);
|
||||
line-height: var(--leading-xs);
|
||||
font-weight: var(--weight-bold);
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
|
||||
/* «Показать всех · 40» под свёрнутым разделом списка. */
|
||||
.list-more {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
min-height: 52px;
|
||||
padding: 0 0 0 4px;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--accent);
|
||||
font: inherit;
|
||||
font-size: var(--text-sm);
|
||||
font-weight: var(--weight-bold);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.list-more svg {
|
||||
flex: 0 0 auto;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
margin: 0 26px 0 14px;
|
||||
}
|
||||
|
||||
.list-more:focus-visible {
|
||||
outline: 2px solid var(--focus-ring);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
@@ -148,13 +148,52 @@ label.meta-muted[for] {
|
||||
}
|
||||
|
||||
|
||||
.status-line.is-available {
|
||||
color: var(--success);
|
||||
/* Итог действия в форме: ошибка и успех – плашкой со значком (как тосты), не просто
|
||||
* цветным текстом; пустая строка места не занимает. */
|
||||
.status-line.is-available,
|
||||
.status-line.is-unavailable {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--radius-md);
|
||||
color: var(--text-primary);
|
||||
line-height: 1.4;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.status-line.is-available {
|
||||
background: color-mix(in srgb, var(--success) 12%, transparent);
|
||||
}
|
||||
|
||||
.status-line.is-unavailable {
|
||||
background: color-mix(in srgb, var(--danger) 12%, transparent);
|
||||
}
|
||||
|
||||
.status-line.is-available::before,
|
||||
.status-line.is-unavailable::before {
|
||||
content: "";
|
||||
flex: 0 0 auto;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
margin-top: 0.5px;
|
||||
background: currentColor;
|
||||
-webkit-mask: var(--status-line-icon) center / contain no-repeat;
|
||||
mask: var(--status-line-icon) center / contain no-repeat;
|
||||
}
|
||||
|
||||
.status-line.is-available::before {
|
||||
color: var(--success);
|
||||
--status-line-icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m5 12.5 4.5 4.5L19 7.5'/%3E%3C/svg%3E");
|
||||
}
|
||||
|
||||
.status-line.is-unavailable::before {
|
||||
color: var(--danger);
|
||||
--status-line-icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round'%3E%3Ccircle cx='12' cy='12' r='9'/%3E%3Cpath d='M12 7.5v5.5M12 16.4v.1'/%3E%3C/svg%3E");
|
||||
}
|
||||
|
||||
.status-line:empty {
|
||||
display: none;
|
||||
}
|
||||
|
||||
|
||||
@@ -308,9 +347,11 @@ label.meta-muted[for] {
|
||||
}
|
||||
|
||||
|
||||
.page-label-toggle:hover {
|
||||
background: transparent;
|
||||
filter: brightness(1.12);
|
||||
@media (hover: hover) {
|
||||
.page-label-toggle:hover {
|
||||
background: transparent;
|
||||
filter: brightness(1.12);
|
||||
}
|
||||
}
|
||||
|
||||
.page-label-toggle:active {
|
||||
@@ -592,13 +633,15 @@ body { overflow-x: hidden; }
|
||||
background: var(--surface);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.search-field[hidden] { display: none; }
|
||||
.search-field:focus-within { border-color: var(--focus-ring); box-shadow: 0 0 0 1px var(--focus-ring); }
|
||||
.search-field__icon { display: inline-flex; }
|
||||
.search-field__icon svg { width: 20px; height: 20px; }
|
||||
.search-field__input { width: 100%; min-width: 0; height: 42px; border: 0; outline: 0; color: var(--text-primary); background: transparent; font-size: 16px; }
|
||||
.search-field__input::placeholder { color: color-mix(in srgb, var(--text-secondary) 62%, var(--surface)); }
|
||||
.search-field__action { min-height: 36px; padding: 0 12px; border: 0; border-radius: var(--radius-sm); color: var(--accent); background: transparent; font: inherit; font-size: var(--text-sm); font-weight: var(--weight-bold); cursor: pointer; }
|
||||
.search-field__action:hover { background: var(--surface-selected); }
|
||||
.search-field__action:active { background: var(--surface-selected); }
|
||||
@media (hover: hover) { .search-field__action:hover { background: var(--surface-selected); } }
|
||||
.search-field__action:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: 0; }
|
||||
|
||||
.empty-note { padding: var(--space-5) var(--space-4); text-align: center; color: var(--text-secondary); font-size: var(--text-sm); line-height: var(--leading-sm, 1.45); }
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user