SHA256
Compare commits
4
Commits
| Author | SHA256 | Date | |
|---|---|---|---|
|
|
13693a0a53 | ||
|
|
451280edd2 | ||
|
|
c997057a37 | ||
|
|
f8900e531a |
@@ -43,8 +43,9 @@
|
||||
- Этот файл считать основной справкой (single source of truth) по деплою и первичной инициализации Solana-регистрации в текущем проекте.
|
||||
- Актуальная архитектурная справка по устройству Solana-программ, PDA-счетам, ролям DAO и движению средств находится в:
|
||||
- `docs/Solana_Architecture/README.md`
|
||||
- Документ формата пользовательской PDA-записи `shine_users` находится в:
|
||||
- `shine-solana/shine/doc/formats/shine-user-pda-format-v.1.0.md`
|
||||
- Документы формата пользовательской PDA-записи `shine_users`:
|
||||
- текущий: `shine-solana/shine/doc/formats/shine-user-pda-format-v.1.2.md`;
|
||||
- legacy: `shine-solana/shine/doc/formats/shine-user-pda-format-v.1.0.md`.
|
||||
- Актуальная документация по серверному модулю синхронизации Solana users находится в:
|
||||
- `docs/Solana/SOLANA_USERS_SYNC_MODULE_DESIGN.md`
|
||||
- При любом изменении логики серверной синхронизации `shine_users`, её таблиц PostgreSQL, checkpoint-механизма, startup/lifecycle или deploy-настроек обязательно обновлять:
|
||||
|
||||
@@ -52,113 +52,84 @@ function readStrU8(bytes, cursorRef) {
|
||||
|
||||
function parseServerFieldsFromUserPda(dataBytes) {
|
||||
const bytes = dataBytes instanceof Uint8Array ? dataBytes : new Uint8Array(dataBytes || []);
|
||||
if (bytes.length < 5) throw new Error('Некорректный формат PDA');
|
||||
if (bytes.length < 9) throw new Error('Некорректный формат PDA');
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
const cursorRef = { value: 0 };
|
||||
const readU16 = () => { if (cursorRef.value + 2 > bytes.length) throw new Error('Повреждённый формат PDA'); const v = view.getUint16(cursorRef.value, true); cursorRef.value += 2; return v; };
|
||||
const readU32 = () => { if (cursorRef.value + 4 > bytes.length) throw new Error('Повреждённый формат PDA'); const v = view.getUint32(cursorRef.value, true); cursorRef.value += 4; return v; };
|
||||
const readU64 = () => { if (cursorRef.value + 8 > bytes.length) throw new Error('Повреждённый формат PDA'); const v = view.getBigUint64(cursorRef.value, true); cursorRef.value += 8; return v; };
|
||||
const magic = new TextDecoder().decode(readBytes(bytes, cursorRef, 5));
|
||||
if (magic !== 'SHiNE') throw new Error('Некорректный формат PDA');
|
||||
cursorRef.value += 1; // format_major
|
||||
cursorRef.value += 1; // format_minor
|
||||
cursorRef.value += 2; // record_len
|
||||
const formatMajor = readU8(bytes, cursorRef);
|
||||
const formatMinor = readU8(bytes, cursorRef);
|
||||
if (formatMajor !== 1 || formatMinor !== 2) throw new Error(`Неподдерживаемый формат PDA ${formatMajor}.${formatMinor}`);
|
||||
const recordLen = readU16();
|
||||
if (recordLen < 73 || recordLen > bytes.length) throw new Error('Некорректный record_len PDA');
|
||||
cursorRef.value += 8; // created_at_ms
|
||||
cursorRef.value += 8; // updated_at_ms
|
||||
cursorRef.value += 4; // record_number
|
||||
cursorRef.value += 32; // prev_record_hash
|
||||
readStrU8(bytes, cursorRef); // login
|
||||
const login = readStrU8(bytes, cursorRef);
|
||||
const blocksCount = readU8(bytes, cursorRef);
|
||||
|
||||
let isServer = false;
|
||||
let serverAddress = '';
|
||||
let accessServers = [];
|
||||
let recoveryKey32 = null;
|
||||
let rootKey32 = null;
|
||||
let clientKey32 = null;
|
||||
let blockchainKey32 = null;
|
||||
let blockchainName = '';
|
||||
let homeserverSessions = [];
|
||||
let forkCount = 0;
|
||||
|
||||
for (let i = 0; i < blocksCount; i += 1) {
|
||||
const blockType = readU8(bytes, cursorRef);
|
||||
cursorRef.value += 1; // block_version
|
||||
|
||||
if (blockType === 0 || blockType === 1 || blockType === 2) {
|
||||
const blockVersion = readU8(bytes, cursorRef);
|
||||
if (blockVersion !== 0) throw new Error('Неподдерживаемая версия блока PDA');
|
||||
if (blockType === 1 || blockType === 2) {
|
||||
const key32 = readBytes(bytes, cursorRef, 32);
|
||||
if (blockType === 0) recoveryKey32 = key32;
|
||||
if (blockType === 1) rootKey32 = key32;
|
||||
if (blockType === 2) clientKey32 = key32;
|
||||
else clientKey32 = key32;
|
||||
continue;
|
||||
}
|
||||
|
||||
const payloadLen = readU16();
|
||||
const payloadEnd = cursorRef.value + payloadLen;
|
||||
if (payloadEnd > recordLen - 64) throw new Error('Повреждённый variable block PDA');
|
||||
|
||||
if (blockType === 3) {
|
||||
const count = readU8(bytes, cursorRef);
|
||||
for (let j = 0; j < count; j += 1) {
|
||||
cursorRef.value += 1;
|
||||
const currentBlockchainName = readStrU8(bytes, cursorRef);
|
||||
const currentBlockchainKey32 = readBytes(bytes, cursorRef, 32);
|
||||
if (!blockchainKey32) {
|
||||
blockchainKey32 = currentBlockchainKey32;
|
||||
blockchainName = currentBlockchainName;
|
||||
}
|
||||
cursorRef.value += 8 + 8 + 4 + 32 + 64;
|
||||
const arPresent = readU8(bytes, cursorRef);
|
||||
if (arPresent === 1) readStrU8(bytes, cursorRef);
|
||||
forkCount = readU16();
|
||||
if (forkCount < 1) throw new Error('BlockchainRegistry пуст');
|
||||
for (let j = 0; j < forkCount; j += 1) {
|
||||
blockchainKey32 = readBytes(bytes, cursorRef, 32);
|
||||
readU64(); // created_at_ms fork
|
||||
readU32(); // paid_limit_bytes
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (blockType === 30) {
|
||||
isServer = readU8(bytes, cursorRef) === 1;
|
||||
if (isServer) {
|
||||
cursorRef.value += 1; // address_format_type
|
||||
cursorRef.value += 1; // address_format_version
|
||||
serverAddress = readStrU8(bytes, cursorRef);
|
||||
const syncCount = readU8(bytes, cursorRef);
|
||||
for (let j = 0; j < syncCount; j += 1) readStrU8(bytes, cursorRef);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (blockType === 40) {
|
||||
} else if (blockType === 30) {
|
||||
const addressCount = readU8(bytes, cursorRef);
|
||||
if (addressCount !== 1) throw new Error('PDA 1.2 допускает ровно один адрес сервера');
|
||||
readU8(bytes, cursorRef); // address_format_type
|
||||
readU8(bytes, cursorRef); // address_format_version
|
||||
serverAddress = readStrU8(bytes, cursorRef);
|
||||
} else if (blockType === 40) {
|
||||
const accessCount = readU8(bytes, cursorRef);
|
||||
if (accessCount > 1) throw new Error('PDA 1.2 допускает максимум один access server');
|
||||
accessServers = [];
|
||||
for (let j = 0; j < accessCount; j += 1) accessServers.push(readStrU8(bytes, cursorRef));
|
||||
continue;
|
||||
}
|
||||
if (blockType === 50) {
|
||||
cursorRef.value += 1;
|
||||
const sessionsCount = readU8(bytes, cursorRef);
|
||||
for (let j = 0; j < sessionsCount; j += 1) {
|
||||
const sessionType = readU8(bytes, cursorRef);
|
||||
const sessionVersion = readU8(bytes, cursorRef);
|
||||
const sessionName = readStrU8(bytes, cursorRef);
|
||||
const sessionPubKey32 = readBytes(bytes, cursorRef, 32);
|
||||
if (sessionType === 100) {
|
||||
homeserverSessions.push({
|
||||
sessionType,
|
||||
sessionVersion,
|
||||
sessionName,
|
||||
sessionPubKeyBase58: new PublicKey(sessionPubKey32).toBase58(),
|
||||
sessionPubKeyB64: `ed25519/${btoa(String.fromCharCode(...sessionPubKey32))}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (blockType === 70) {
|
||||
cursorRef.value += 1;
|
||||
continue;
|
||||
}
|
||||
throw new Error(`Неизвестный блок PDA: ${blockType}`);
|
||||
cursorRef.value = payloadEnd;
|
||||
}
|
||||
|
||||
if (!rootKey32 || !clientKey32 || !blockchainKey32) throw new Error('PDA 1.2 не содержит обязательные ключи');
|
||||
return {
|
||||
isServer,
|
||||
isServer: Boolean(serverAddress),
|
||||
serverAddress: normalizeHostLike(serverAddress),
|
||||
accessServers: accessServers.map((value) => normalizeServerLogin(value)).filter(Boolean),
|
||||
publicKeys: {
|
||||
recoveryKeyBase58: recoveryKey32 ? new PublicKey(recoveryKey32).toBase58() : '',
|
||||
rootKeyBase58: rootKey32 ? new PublicKey(rootKey32).toBase58() : '',
|
||||
clientKeyBase58: clientKey32 ? new PublicKey(clientKey32).toBase58() : '',
|
||||
blockchainKeyBase58: blockchainKey32 ? new PublicKey(blockchainKey32).toBase58() : '',
|
||||
blockchainName,
|
||||
recoveryKeyBase58: '',
|
||||
rootKeyBase58: new PublicKey(rootKey32).toBase58(),
|
||||
clientKeyBase58: new PublicKey(clientKey32).toBase58(),
|
||||
blockchainKeyBase58: new PublicKey(blockchainKey32).toBase58(),
|
||||
blockchainName: `${normalizeServerLogin(login)}-${String(forkCount).padStart(3, '0')}`,
|
||||
},
|
||||
homeserverSessions,
|
||||
homeserverSessions: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+7
-15
@@ -18,15 +18,11 @@ SHiNE-server — серверная часть мессенджера SHiNE: Web
|
||||
|
||||
## Настройка сервера в Solana (Solana PDA)
|
||||
|
||||
Серверный аккаунт SHiNE регистрируется в Solana в виде `user_pda` с флагом `is_server=true`.
|
||||
В PDA хранятся:
|
||||
Серверный аккаунт SHiNE регистрируется как обычный `user_pda` формата 1.2 с присутствующим `ServerProfileBlock`. Отдельного `is_server` в PDA нет: наличие server profile означает, что аккаунт объявляет серверный endpoint.
|
||||
|
||||
- **адрес сервера** (URL WebSocket/HTTPS, например `https://shineup.me/ws`);
|
||||
- **список серверов синхронизации** (`sync_servers`) — логины SHiNE-аккаунтов серверов-партнёров,
|
||||
с которыми синхронизируются пользовательские блокчейны;
|
||||
- **корневой ключ** сервера (`root_key`).
|
||||
PDA 1.2 сейчас допускает **один** адрес сервера (`address_format_type + address_format_version + address`). Бинарный блок использует count/array, чтобы будущая версия протокола могла увеличить лимит без смены структуры блока. Прямой список `sync_servers` удалён: пользовательские blockchain синхронизируются через Arweave.
|
||||
|
||||
Клиенты читают PDA напрямую из Solana, чтобы узнать адрес сервера и при необходимости подключиться.
|
||||
Клиенты читают server PDA из Solana, получают опубликованный endpoint и подключаются к нему. Межсерверная доставка DM через access-server routing остаётся отдельным механизмом.
|
||||
|
||||
**Управление серверной PDA выполняется через Web-панель администратора:**
|
||||
|
||||
@@ -36,10 +32,9 @@ shine-UI/server-ui.html
|
||||
|
||||
Страницы:
|
||||
- `shine-UI/server-ui/create-server-pda.html` — первичная регистрация серверного аккаунта;
|
||||
- `shine-UI/server-ui/update-server-pda.html` — обновление адреса или списка sync_servers.
|
||||
- `shine-UI/server-ui/update-server-pda.html` — обновление адреса сервера.
|
||||
|
||||
Для регистрации нужен полный keyBundle (root + device + blockchain).
|
||||
Для обновления — только root + device (blockchain-ключ не нужен).
|
||||
PDA 1.2 использует три постоянные роли ключей: `root` (cold recovery), `blockchain` (обычный authority и подпись блоков) и `client` (клиент/кошелёк). Обычный update авторизуется активным последним blockchain key; root используется для recovery и может менять root.
|
||||
|
||||
Актуальные адреса программ Solana (devnet):
|
||||
- `shine_users`: `SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6`
|
||||
@@ -47,12 +42,9 @@ shine-UI/server-ui.html
|
||||
|
||||
Подробнее: `docs/Инициализация_Solana_регистрации/README.md`
|
||||
|
||||
## Синхронизация с партнёрскими серверами
|
||||
## Синхронизация пользовательских blockchain
|
||||
|
||||
Сервер должен синхронизировать блоки пользовательских блокчейнов с
|
||||
серверами-партнёрами из `sync_servers`. DM между партнёрами не реплицируются:
|
||||
они доставляются только на первый access-сервер получателя.
|
||||
Детали: `docs/Blockchain/sync-between-servers.md`
|
||||
Прямой peer-to-peer blockchain sync через `sync_servers` отключён. Сервер восстанавливает и синхронизирует пользовательские записи через Arweave. Код старого peer-sync пока может оставаться как inert legacy, но не должен включаться в runtime.
|
||||
|
||||
## Деплой
|
||||
|
||||
|
||||
@@ -23,6 +23,46 @@ public final class KeyEncodingUtil {
|
||||
|
||||
private KeyEncodingUtil() {}
|
||||
|
||||
public static String encodeBase58(byte[] input) {
|
||||
if (input == null || input.length == 0) {
|
||||
return "";
|
||||
}
|
||||
byte[] copy = java.util.Arrays.copyOf(input, input.length);
|
||||
int zeros = 0;
|
||||
while (zeros < copy.length && copy[zeros] == 0) {
|
||||
zeros++;
|
||||
}
|
||||
byte[] encoded = new byte[copy.length * 2];
|
||||
int outputStart = encoded.length;
|
||||
int inputStart = zeros;
|
||||
while (inputStart < copy.length) {
|
||||
int remainder = divmod58(copy, inputStart);
|
||||
if (copy[inputStart] == 0) {
|
||||
inputStart++;
|
||||
}
|
||||
encoded[--outputStart] = (byte) BASE58_ALPHABET.charAt(remainder);
|
||||
}
|
||||
while (outputStart < encoded.length && encoded[outputStart] == (byte) BASE58_ALPHABET.charAt(0)) {
|
||||
outputStart++;
|
||||
}
|
||||
while (--zeros >= 0) {
|
||||
encoded[--outputStart] = (byte) BASE58_ALPHABET.charAt(0);
|
||||
}
|
||||
return new String(encoded, outputStart, encoded.length - outputStart, java.nio.charset.StandardCharsets.US_ASCII);
|
||||
}
|
||||
|
||||
public static String base58KeyToBase64_32(String rawKey) {
|
||||
if (rawKey == null) {
|
||||
return null;
|
||||
}
|
||||
String value = rawKey.trim();
|
||||
if (value.isEmpty()) {
|
||||
return value;
|
||||
}
|
||||
byte[] decoded = tryDecodeBase58_32(value);
|
||||
return decoded == null ? value : Base64.getEncoder().encodeToString(decoded);
|
||||
}
|
||||
|
||||
public static String normalizeKeyToBase64_32(String rawKey) {
|
||||
if (rawKey == null) {
|
||||
return null;
|
||||
@@ -102,6 +142,17 @@ public final class KeyEncodingUtil {
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int divmod58(byte[] number, int startAt) {
|
||||
int remainder = 0;
|
||||
for (int i = startAt; i < number.length; i++) {
|
||||
int digit256 = number[i] & 0xFF;
|
||||
int temp = remainder * 256 + digit256;
|
||||
number[i] = (byte) (temp / 58);
|
||||
remainder = temp % 58;
|
||||
}
|
||||
return remainder;
|
||||
}
|
||||
|
||||
private static int divmod256(byte[] number58, int startAt) {
|
||||
int remainder = 0;
|
||||
for (int i = startAt; i < number58.length; i++) {
|
||||
|
||||
+17
-11
@@ -8,7 +8,6 @@ import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* Доступ к актуальной PostgreSQL-таблице пользователей, поддерживаемой sync-модулем.
|
||||
@@ -61,28 +60,35 @@ public final class SolanaUserPdaCurrentDAO {
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve a current user by the 32-byte Ed25519 blockchain key used as ANS-104 owner. */
|
||||
/** Resolve a user/fork by the 32-byte Ed25519 blockchain key used as ANS-104 owner. */
|
||||
public SolanaUserPdaCurrentEntry getByBlockchainKey(byte[] owner32) throws SQLException {
|
||||
if (owner32 == null || owner32.length != 32) return null;
|
||||
String wanted = Base64.getEncoder().encodeToString(owner32);
|
||||
String wanted = KeyEncodingUtil.encodeBase58(owner32);
|
||||
String sql = """
|
||||
SELECT login, blockchain_name, blockchain_key, paid_limit_bytes
|
||||
FROM solana_user_pda_current
|
||||
SELECT
|
||||
u.login,
|
||||
u.login || '-' || LPAD(((fork_item.value ->> 'forkIndex')::integer + 1)::text, 3, '0') AS blockchain_name,
|
||||
fork_item.value ->> 'blockchainKey' AS blockchain_key,
|
||||
(fork_item.value ->> 'paidLimitBytes')::bigint AS paid_limit_bytes
|
||||
FROM solana_user_pda_current u
|
||||
CROSS JOIN LATERAL jsonb_array_elements(COALESCE(NULLIF(u.blockchain_forks_json, ''), '[]')::jsonb) AS fork_item(value)
|
||||
WHERE fork_item.value ->> 'blockchainKey' = ?
|
||||
LIMIT 1
|
||||
""";
|
||||
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(sql); ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
SolanaUserPdaCurrentEntry e = mapRow(rs);
|
||||
if (wanted.equals(e.getBlockchainKey())) return e;
|
||||
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, wanted);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (!rs.next()) return null;
|
||||
return mapRow(rs);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private SolanaUserPdaCurrentEntry mapRow(ResultSet rs) throws SQLException {
|
||||
SolanaUserPdaCurrentEntry entry = new SolanaUserPdaCurrentEntry();
|
||||
entry.setLogin(rs.getString("login"));
|
||||
entry.setBlockchainName(rs.getString("blockchain_name"));
|
||||
entry.setBlockchainKey(KeyEncodingUtil.normalizeKeyToBase64_32(rs.getString("blockchain_key")));
|
||||
entry.setBlockchainKey(KeyEncodingUtil.base58KeyToBase64_32(rs.getString("blockchain_key")));
|
||||
entry.setPaidLimitBytes(rs.getLong("paid_limit_bytes"));
|
||||
return entry;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
-- Turbo/direct-Arweave transport no longer stores root transaction IDs for user DataItems.
|
||||
ALTER TABLE blocks
|
||||
DROP COLUMN IF EXISTS arweave_root_tx_id;
|
||||
|
||||
ALTER TABLE arweave_block_import_queue
|
||||
DROP COLUMN IF EXISTS root_tx_id;
|
||||
-- PDA 1.2: keep the complete append-only blockchain-key/fork history alongside the active compatibility columns.
|
||||
ALTER TABLE solana_user_pda_current
|
||||
ADD COLUMN IF NOT EXISTS blockchain_forks_json TEXT NOT NULL DEFAULT '[]';
|
||||
|
||||
UPDATE db_schema_version
|
||||
SET schema_version=25,
|
||||
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT)
|
||||
WHERE id=1;
|
||||
SET schema_version = 25,
|
||||
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
|
||||
WHERE id = 1;
|
||||
|
||||
@@ -84,6 +84,7 @@ CREATE TABLE IF NOT EXISTS solana_user_pda_current (
|
||||
blockchain_name TEXT NOT NULL,
|
||||
blockchain_key TEXT NOT NULL,
|
||||
paid_limit_bytes BIGINT NOT NULL,
|
||||
blockchain_forks_json TEXT NOT NULL DEFAULT '[]',
|
||||
used_bytes BIGINT NOT NULL,
|
||||
last_block_number INTEGER NOT NULL,
|
||||
last_block_hash TEXT NOT NULL,
|
||||
@@ -500,6 +501,7 @@ CREATE TABLE IF NOT EXISTS blocks (
|
||||
data_item_id BYTEA NOT NULL,
|
||||
arweave_publish_pending BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
arweave_published_at_ms BIGINT,
|
||||
arweave_root_tx_id TEXT,
|
||||
edited_by_block_number INTEGER CHECK (edited_by_block_number IS NULL OR edited_by_block_number >= 0),
|
||||
line_code INTEGER CHECK (line_code IS NULL OR line_code >= 0),
|
||||
prev_line_number INTEGER CHECK (prev_line_number IS NULL OR prev_line_number >= 0),
|
||||
@@ -534,6 +536,7 @@ VALUES (1, 0, 0) ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS arweave_block_import_queue (
|
||||
data_item_id BYTEA PRIMARY KEY,
|
||||
root_tx_id TEXT NOT NULL,
|
||||
block_height BIGINT NOT NULL,
|
||||
raw_data_item BYTEA NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
@@ -2079,7 +2082,7 @@ CREATE INDEX IF NOT EXISTS idx_solana_user_pda_current_archive_pending
|
||||
WHERE archive_head_tx_id <> '';
|
||||
|
||||
INSERT INTO db_schema_version(id,schema_version,updated_at_ms)
|
||||
VALUES(1,25,CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT))
|
||||
VALUES(1,24,CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT))
|
||||
ON CONFLICT(id) DO UPDATE SET schema_version=EXCLUDED.schema_version, updated_at_ms=EXCLUDED.updated_at_ms;
|
||||
|
||||
COMMIT;
|
||||
|
||||
+118
-169
@@ -28,7 +28,6 @@ public final class SolanaUserPdaImportService {
|
||||
private static final HttpClient HTTP = HttpClient.newHttpClient();
|
||||
private static final String MAGIC = "SHiNE";
|
||||
private static final int MAX_EFFECTIVE_ACCESS_SERVERS = 1;
|
||||
private static final int ARCHIVE_HEAD_PAYLOAD_BYTES = 64;
|
||||
|
||||
private SolanaUserPdaImportService() {}
|
||||
|
||||
@@ -55,8 +54,7 @@ public final class SolanaUserPdaImportService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Чтение server PDA по логину сервера. Используется сервером при старте,
|
||||
* чтобы получить актуальный server_address и список sync_servers.
|
||||
* Чтение server PDA 1.2 по логину сервера. В 1.2 разрешён ровно один endpoint.
|
||||
*/
|
||||
public static ParsedServerProfile fetchServerProfileByLogin(String loginRaw) throws Exception {
|
||||
String login = normalizeLogin(loginRaw);
|
||||
@@ -156,9 +154,16 @@ public final class SolanaUserPdaImportService {
|
||||
}
|
||||
|
||||
private static ParsedSolanaUser parseUserPda(byte[] raw) {
|
||||
if (raw == null || raw.length < 128) return null;
|
||||
if (raw == null || raw.length < 9) return null;
|
||||
if (!MAGIC.equals(new String(raw, 0, 5, StandardCharsets.UTF_8))) return null;
|
||||
int major = u8(raw, 5);
|
||||
int minor = u8(raw, 6);
|
||||
if (major != 1 || minor != 2) return null;
|
||||
return parseUserPdaV12(raw);
|
||||
}
|
||||
|
||||
private static ParsedSolanaUser parseUserPdaV12(byte[] raw) {
|
||||
if (raw == null || raw.length < 128) return null;
|
||||
int recordLen = u16le(raw, 7);
|
||||
if (recordLen < 73 || recordLen > raw.length) return null;
|
||||
|
||||
@@ -167,228 +172,166 @@ public final class SolanaUserPdaImportService {
|
||||
c += 8; // updated_at_ms
|
||||
c += 4; // record_number
|
||||
c += 32; // prev_record_hash
|
||||
if (c >= recordLen) return null;
|
||||
|
||||
int loginLen = u8(raw, c++);
|
||||
if (loginLen <= 0 || c + loginLen > recordLen) return null;
|
||||
String login = new String(raw, c, loginLen, StandardCharsets.UTF_8);
|
||||
c += loginLen;
|
||||
if (c >= recordLen) return null;
|
||||
|
||||
int blocksCount = u8(raw, c++);
|
||||
String blockchainName = null;
|
||||
byte[] blockchainKey32 = null;
|
||||
byte[] clientKey32 = null;
|
||||
long paidLimitBytes = 0L;
|
||||
List<ParsedSessionRecord> sessions = new ArrayList<>();
|
||||
int forkCount = 0;
|
||||
List<String> accessServers = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < blocksCount; i++) {
|
||||
if (c + 2 > recordLen) return null;
|
||||
int blockType = u8(raw, c++);
|
||||
int blockVer = u8(raw, c++);
|
||||
if (blockVer != 0) return null;
|
||||
|
||||
if (blockType == 0) {
|
||||
c += 32; // recovery_key
|
||||
} else if (blockType == 1) {
|
||||
c += 32;
|
||||
} else if (blockType == 2) {
|
||||
if (blockType == 1) {
|
||||
if (c + 32 > recordLen) return null;
|
||||
c += 32; // root_key
|
||||
continue;
|
||||
}
|
||||
if (blockType == 2) {
|
||||
if (c + 32 > recordLen) return null;
|
||||
clientKey32 = slice(raw, c, 32);
|
||||
c += 32;
|
||||
} else if (blockType == 3) {
|
||||
int count = u8(raw, c++);
|
||||
for (int j = 0; j < count; j++) {
|
||||
c += 1; // blockchain_type
|
||||
int bchLen = u8(raw, c++);
|
||||
blockchainName = new String(raw, c, bchLen, StandardCharsets.UTF_8);
|
||||
c += bchLen;
|
||||
blockchainKey32 = slice(raw, c, 32);
|
||||
c += 32;
|
||||
paidLimitBytes = u64le(raw, c);
|
||||
c += 8;
|
||||
c += 8; // used_bytes
|
||||
c += 4; // last_block_number
|
||||
c += 32; // last_block_hash
|
||||
c += 64; // last_block_signature
|
||||
int arweavePresent = u8(raw, c++);
|
||||
if (arweavePresent == 1) {
|
||||
int arLen = u8(raw, c++);
|
||||
c += arLen;
|
||||
} else if (arweavePresent != 0) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
} else if (blockType == 30) {
|
||||
int isServer = u8(raw, c++);
|
||||
if (isServer == 1) {
|
||||
c += 1; // address_format_type
|
||||
c += 1; // address_format_version
|
||||
int addrLen = u8(raw, c++);
|
||||
c += addrLen;
|
||||
int syncCount = u8(raw, c++);
|
||||
for (int j = 0; j < syncCount; j++) {
|
||||
int n = u8(raw, c++);
|
||||
c += n;
|
||||
}
|
||||
} else if (isServer != 0) {
|
||||
return null;
|
||||
}
|
||||
} else if (blockType == 40) {
|
||||
int accessCount = u8(raw, c++);
|
||||
for (int j = 0; j < accessCount; j++) {
|
||||
int n = u8(raw, c++);
|
||||
String accessServerLogin = new String(raw, c, n, StandardCharsets.UTF_8);
|
||||
c += n;
|
||||
String normalizedAccessServerLogin = normalizeLogin(accessServerLogin);
|
||||
if (normalizedAccessServerLogin == null || accessServers.contains(normalizedAccessServerLogin)) {
|
||||
continue;
|
||||
}
|
||||
if (accessServers.size() < MAX_EFFECTIVE_ACCESS_SERVERS) {
|
||||
accessServers.add(normalizedAccessServerLogin);
|
||||
}
|
||||
}
|
||||
} else if (blockType == 50) {
|
||||
int sessionsMode = u8(raw, c++);
|
||||
if (sessionsMode != 1 && sessionsMode != 10) return null;
|
||||
int sessionsCount = u8(raw, c++);
|
||||
if (sessionsCount > 64) return null;
|
||||
for (int j = 0; j < sessionsCount; j++) {
|
||||
int sessionType = u8(raw, c++);
|
||||
int sessionVersion = u8(raw, c++);
|
||||
int n = u8(raw, c++);
|
||||
String sessionName = new String(raw, c, n, StandardCharsets.UTF_8);
|
||||
c += n;
|
||||
byte[] sessionPubKey32 = slice(raw, c, 32);
|
||||
c += 32;
|
||||
sessions.add(new ParsedSessionRecord(
|
||||
sessionType,
|
||||
sessionVersion,
|
||||
sessionName,
|
||||
sessionPubKey32
|
||||
));
|
||||
}
|
||||
} else if (blockType == 70) {
|
||||
c += 1;
|
||||
} else if (blockType == 100) {
|
||||
c += ARCHIVE_HEAD_PAYLOAD_BYTES;
|
||||
} else {
|
||||
return null;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c > recordLen) return null;
|
||||
if (c + 2 > recordLen) return null;
|
||||
int payloadLen = u16le(raw, c);
|
||||
c += 2;
|
||||
int payloadEnd = c + payloadLen;
|
||||
if (payloadEnd < c || payloadEnd > recordLen) return null;
|
||||
|
||||
if (blockType == 3) {
|
||||
if (c + 2 > payloadEnd) return null;
|
||||
forkCount = u16le(raw, c);
|
||||
c += 2;
|
||||
if (forkCount <= 0) return null;
|
||||
for (int j = 0; j < forkCount; j++) {
|
||||
if (c + 44 > payloadEnd) return null;
|
||||
blockchainKey32 = slice(raw, c, 32);
|
||||
c += 32;
|
||||
c += 8; // fork created_at_ms
|
||||
paidLimitBytes = u32le(raw, c);
|
||||
c += 4;
|
||||
}
|
||||
if (c != payloadEnd) return null;
|
||||
} else if (blockType == 30) {
|
||||
// Server profile is not needed for auth parsing; validate/skip its payload.
|
||||
c = payloadEnd;
|
||||
} else if (blockType == 40) {
|
||||
if (c >= payloadEnd) return null;
|
||||
int accessCount = u8(raw, c++);
|
||||
if (accessCount > 1) return null;
|
||||
for (int j = 0; j < accessCount; j++) {
|
||||
if (c >= payloadEnd) return null;
|
||||
int n = u8(raw, c++);
|
||||
if (c + n > payloadEnd) return null;
|
||||
String accessServerLogin = new String(raw, c, n, StandardCharsets.UTF_8);
|
||||
c += n;
|
||||
String normalized = normalizeLogin(accessServerLogin);
|
||||
if (normalized != null && !accessServers.contains(normalized)
|
||||
&& accessServers.size() < MAX_EFFECTIVE_ACCESS_SERVERS) {
|
||||
accessServers.add(normalized);
|
||||
}
|
||||
}
|
||||
if (c != payloadEnd) return null;
|
||||
} else {
|
||||
// Unknown variable PDA 1.2 block: forward-compatible skip by payload_len.
|
||||
c = payloadEnd;
|
||||
}
|
||||
c = payloadEnd;
|
||||
}
|
||||
|
||||
if (blockchainName == null || blockchainKey32 == null || clientKey32 == null) return null;
|
||||
if (blockchainKey32 == null || clientKey32 == null || forkCount <= 0) return null;
|
||||
String blockchainName = login + "-" + String.format(Locale.ROOT, "%03d", forkCount);
|
||||
return new ParsedSolanaUser(
|
||||
login,
|
||||
blockchainName,
|
||||
Base64.getEncoder().encodeToString(blockchainKey32),
|
||||
Base64.getEncoder().encodeToString(clientKey32),
|
||||
paidLimitBytes,
|
||||
sessions,
|
||||
List.of(),
|
||||
accessServers
|
||||
);
|
||||
}
|
||||
|
||||
private static ParsedServerProfile parseServerProfile(byte[] raw) {
|
||||
if (raw == null || raw.length < 128) return null;
|
||||
if (!MAGIC.equals(new String(raw, 0, 5, StandardCharsets.UTF_8))) return null;
|
||||
|
||||
private static ParsedServerProfile parseServerProfile(byte[] raw) {
|
||||
if (raw == null || raw.length < 9) return null;
|
||||
if (!MAGIC.equals(new String(raw, 0, 5, StandardCharsets.UTF_8))) return null;
|
||||
int major = u8(raw, 5);
|
||||
int minor = u8(raw, 6);
|
||||
if (major != 1 || minor != 2) return null;
|
||||
return parseServerProfileV12(raw);
|
||||
}
|
||||
|
||||
private static ParsedServerProfile parseServerProfileV12(byte[] raw) {
|
||||
if (raw == null || raw.length < 128) return null;
|
||||
int recordLen = u16le(raw, 7);
|
||||
if (recordLen < 73 || recordLen > raw.length) return null;
|
||||
|
||||
int c = 9;
|
||||
c += 8; // created_at_ms
|
||||
c += 8; // updated_at_ms
|
||||
c += 4; // record_number
|
||||
c += 32; // prev_record_hash
|
||||
|
||||
int c = 9 + 8 + 8 + 4 + 32;
|
||||
if (c >= recordLen) return null;
|
||||
int loginLen = u8(raw, c++);
|
||||
if (loginLen <= 0 || c + loginLen > recordLen) return null;
|
||||
String login = new String(raw, c, loginLen, StandardCharsets.UTF_8);
|
||||
c += loginLen;
|
||||
|
||||
if (c >= recordLen) return null;
|
||||
int blocksCount = u8(raw, c++);
|
||||
|
||||
boolean isServer = false;
|
||||
String serverAddress = "";
|
||||
List<String> syncServers = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < blocksCount; i++) {
|
||||
if (c + 2 > recordLen) return null;
|
||||
int blockType = u8(raw, c++);
|
||||
int blockVer = u8(raw, c++);
|
||||
if (blockVer != 0) return null;
|
||||
|
||||
if (blockType == 0 || blockType == 1 || blockType == 2) {
|
||||
if (blockType == 1 || blockType == 2) {
|
||||
if (c + 32 > recordLen) return null;
|
||||
c += 32;
|
||||
} else if (blockType == 3) {
|
||||
int count = u8(raw, c++);
|
||||
for (int j = 0; j < count; j++) {
|
||||
c += 1; // blockchain_type
|
||||
int bchLen = u8(raw, c++);
|
||||
c += bchLen;
|
||||
c += 32; // blockchain pubkey
|
||||
c += 8; // paid_limit_bytes
|
||||
c += 8; // used_bytes
|
||||
c += 4; // last_block_number
|
||||
c += 32; // last_block_hash
|
||||
c += 64; // last_block_signature
|
||||
int arweavePresent = u8(raw, c++);
|
||||
if (arweavePresent == 1) {
|
||||
int arLen = u8(raw, c++);
|
||||
c += arLen;
|
||||
} else if (arweavePresent != 0) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
} else if (blockType == 30) {
|
||||
int isServerValue = u8(raw, c++);
|
||||
if (isServerValue == 1) {
|
||||
isServer = true;
|
||||
continue;
|
||||
}
|
||||
if (c + 2 > recordLen) return null;
|
||||
int payloadLen = u16le(raw, c);
|
||||
c += 2;
|
||||
int payloadEnd = c + payloadLen;
|
||||
if (payloadEnd < c || payloadEnd > recordLen) return null;
|
||||
|
||||
if (blockType == 30) {
|
||||
if (c >= payloadEnd) return null;
|
||||
int addressCount = u8(raw, c++);
|
||||
if (addressCount != 1) return null;
|
||||
for (int j = 0; j < addressCount; j++) {
|
||||
if (c + 3 > payloadEnd) return null;
|
||||
c += 1; // address_format_type
|
||||
c += 1; // address_format_version
|
||||
int addrLen = u8(raw, c++);
|
||||
serverAddress = new String(raw, c, addrLen, StandardCharsets.UTF_8);
|
||||
c += addrLen;
|
||||
int syncCount = u8(raw, c++);
|
||||
for (int j = 0; j < syncCount; j++) {
|
||||
int n = u8(raw, c++);
|
||||
String syncLogin = new String(raw, c, n, StandardCharsets.UTF_8);
|
||||
c += n;
|
||||
syncServers.add(normalizeLogin(syncLogin));
|
||||
int n = u8(raw, c++);
|
||||
if (c + n > payloadEnd) return null;
|
||||
String address = new String(raw, c, n, StandardCharsets.UTF_8);
|
||||
c += n;
|
||||
if (!isServer) {
|
||||
isServer = true;
|
||||
serverAddress = address;
|
||||
}
|
||||
} else if (isServerValue != 0) {
|
||||
return null;
|
||||
}
|
||||
} else if (blockType == 40) {
|
||||
int accessCount = u8(raw, c++);
|
||||
for (int j = 0; j < accessCount; j++) {
|
||||
int n = u8(raw, c++);
|
||||
c += n;
|
||||
}
|
||||
} else if (blockType == 50) {
|
||||
int sessionsMode = u8(raw, c++);
|
||||
if (sessionsMode != 1 && sessionsMode != 10) return null;
|
||||
int sessionsCount = u8(raw, c++);
|
||||
if (sessionsCount > 64) return null;
|
||||
for (int j = 0; j < sessionsCount; j++) {
|
||||
c += 1; // session_type
|
||||
c += 1; // session_version
|
||||
int n = u8(raw, c++);
|
||||
c += n;
|
||||
c += 32;
|
||||
}
|
||||
} else if (blockType == 70) {
|
||||
c += 1;
|
||||
} else if (blockType == 100) {
|
||||
c += ARCHIVE_HEAD_PAYLOAD_BYTES;
|
||||
} else {
|
||||
return null;
|
||||
if (c != payloadEnd) return null;
|
||||
}
|
||||
|
||||
if (c > recordLen) return null;
|
||||
c = payloadEnd;
|
||||
}
|
||||
|
||||
return new ParsedServerProfile(login, isServer, serverAddress, syncServers);
|
||||
return new ParsedServerProfile(login, isServer, serverAddress, List.of());
|
||||
}
|
||||
|
||||
|
||||
private static String normalizeLogin(String login) {
|
||||
if (login == null) return null;
|
||||
String s = login.trim();
|
||||
@@ -400,6 +343,12 @@ public final class SolanaUserPdaImportService {
|
||||
private static int u16le(byte[] b, int o) {
|
||||
return (b[o] & 0xFF) | ((b[o + 1] & 0xFF) << 8);
|
||||
}
|
||||
private static long u32le(byte[] b, int o) {
|
||||
return ((long) b[o] & 0xFFL)
|
||||
| (((long) b[o + 1] & 0xFFL) << 8)
|
||||
| (((long) b[o + 2] & 0xFFL) << 16)
|
||||
| (((long) b[o + 3] & 0xFFL) << 24);
|
||||
}
|
||||
private static long u64le(byte[] b, int o) {
|
||||
long out = 0L;
|
||||
for (int i = 0; i < 8; i++) out |= ((long) (b[o + i] & 0xFF)) << (8 * i);
|
||||
|
||||
+2
-1
@@ -63,7 +63,8 @@ public final class AddBlockSyncService {
|
||||
}
|
||||
|
||||
private static boolean isEnabled() {
|
||||
return AppConfig.getInstance().getBoolean("blockchain.sync.enabled", true);
|
||||
// Legacy peer replication is disabled in PDA 1.2; Arweave is the synchronization source.
|
||||
return false;
|
||||
}
|
||||
|
||||
private void replicate(String blockchainName, int blockNumber) throws Exception {
|
||||
|
||||
+144
-993
File diff suppressed because it is too large
Load Diff
+31
-70
@@ -415,9 +415,12 @@ public final class SolanaUsersSyncService
|
||||
List<ParsedTxEnvelope> envelopes =
|
||||
new ArrayList<>();
|
||||
|
||||
Set<String> updatePdaAddresses =
|
||||
Set<String> exactFetchPdaAddresses =
|
||||
new LinkedHashSet<>();
|
||||
|
||||
Map<String, String> latestRelevantSignatureByPda =
|
||||
new LinkedHashMap<>();
|
||||
|
||||
for (SolanaRpcClient.SignatureRecord signatureRecord : chronologicalSignatures) {
|
||||
|
||||
JsonNode transaction =
|
||||
@@ -436,20 +439,14 @@ public final class SolanaUsersSyncService
|
||||
);
|
||||
|
||||
if (envelope.parsedInstruction() != null
|
||||
&& envelope.parsedInstruction().kind() == ShineUsersCodec.TxKind.UPDATE_USER_PDA
|
||||
&& envelope.parsedInstruction().affectedPdaAddress() != null) {
|
||||
updatePdaAddresses.add(
|
||||
envelope.parsedInstruction()
|
||||
.affectedPdaAddress()
|
||||
);
|
||||
&& envelope.parsedInstruction().affectedPdaAddress() != null
|
||||
&& envelope.parsedInstruction().relevant()) {
|
||||
String changedPda = envelope.parsedInstruction().affectedPdaAddress();
|
||||
latestRelevantSignatureByPda.put(changedPda, envelope.signatureRecord().signature());
|
||||
exactFetchPdaAddresses.add(changedPda);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, ShineUsersCodec.UserPdaSnapshot> currentSnapshots =
|
||||
storage.getCurrentSnapshots(
|
||||
updatePdaAddresses
|
||||
);
|
||||
|
||||
List<PostgresStorageRepository.TxHistoryEntry> txEntries =
|
||||
new ArrayList<>();
|
||||
|
||||
@@ -492,71 +489,16 @@ public final class SolanaUsersSyncService
|
||||
parsedInstruction.economyConfigState();
|
||||
}
|
||||
|
||||
if (parsedInstruction.relevant()
|
||||
&& parsedInstruction.userPdaMutation() != null) {
|
||||
if (parsedInstruction.relevant()) {
|
||||
|
||||
relevant = true;
|
||||
affectedPdaAddress = parsedInstruction.affectedPdaAddress();
|
||||
affectedLogin = parsedInstruction.affectedLogin();
|
||||
|
||||
ShineUsersCodec.UserPdaSnapshot snapshot;
|
||||
lastRelevantSignature = envelope.signatureRecord().signature();
|
||||
lastRelevantSlot = envelope.signatureRecord().slot();
|
||||
|
||||
if (parsedInstruction.kind() == ShineUsersCodec.TxKind.CREATE_USER_PDA) {
|
||||
|
||||
if (economyState == null) {
|
||||
economyState =
|
||||
ShineUsersCodec.EconomyConfigState.initial();
|
||||
log.warn(
|
||||
"Economy config state was absent while processing create tx {}. Falling back to initial constants.",
|
||||
envelope.signatureRecord().signature()
|
||||
);
|
||||
}
|
||||
|
||||
snapshot =
|
||||
ShineUsersCodec.buildCreateSnapshot(
|
||||
parsedInstruction.userPdaMutation(),
|
||||
economyState,
|
||||
envelope.signatureRecord().signature(),
|
||||
envelope.signatureRecord().slot()
|
||||
);
|
||||
|
||||
} else {
|
||||
|
||||
ShineUsersCodec.UserPdaSnapshot previous =
|
||||
currentSnapshots.get(
|
||||
affectedPdaAddress
|
||||
);
|
||||
|
||||
if (previous == null) {
|
||||
throw new IllegalStateException(
|
||||
"Missing previous snapshot for update PDA " +
|
||||
affectedPdaAddress
|
||||
);
|
||||
}
|
||||
|
||||
snapshot =
|
||||
ShineUsersCodec.buildUpdateSnapshot(
|
||||
parsedInstruction.userPdaMutation(),
|
||||
previous,
|
||||
envelope.signatureRecord().signature(),
|
||||
envelope.signatureRecord().slot()
|
||||
);
|
||||
}
|
||||
|
||||
currentSnapshots.put(
|
||||
snapshot.pdaAddress(),
|
||||
snapshot
|
||||
);
|
||||
|
||||
snapshotsToPersist.add(
|
||||
snapshot
|
||||
);
|
||||
|
||||
lastRelevantSignature =
|
||||
envelope.signatureRecord().signature();
|
||||
|
||||
lastRelevantSlot =
|
||||
envelope.signatureRecord().slot();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -579,6 +521,25 @@ public final class SolanaUsersSyncService
|
||||
fetchResult.signatures()
|
||||
.get(0);
|
||||
|
||||
// PDA 1.2 содержит поля, вычисляемые программой и подписанные как единый документ.
|
||||
// Поэтому для нового формата не реконструируем байты из instruction args, а читаем
|
||||
// фактическое текущее состояние затронутых PDA из Solana.
|
||||
if (!exactFetchPdaAddresses.isEmpty()) {
|
||||
SolanaRpcClient.AccountBatchResult exactAccounts =
|
||||
rpcClient.getCurrentAccounts(exactFetchPdaAddresses, newestSeen.slot());
|
||||
for (ProgramAccountUpdate account : exactAccounts.updates()) {
|
||||
ShineUsersCodec.UserPdaSnapshot snapshot =
|
||||
ShineUsersCodec.parseUserPdaAccount(
|
||||
account.address(),
|
||||
account.slot(),
|
||||
account.dataBase64(),
|
||||
latestRelevantSignatureByPda.getOrDefault(account.address(), "")
|
||||
);
|
||||
snapshotsToPersist.removeIf(existing -> existing.pdaAddress().equals(snapshot.pdaAddress()));
|
||||
snapshotsToPersist.add(snapshot);
|
||||
}
|
||||
}
|
||||
|
||||
PostgresStorageRepository.SyncStateSnapshot newState =
|
||||
new PostgresStorageRepository.SyncStateSnapshot(
|
||||
"READY",
|
||||
|
||||
+19
-3
@@ -462,7 +462,7 @@ public final class PostgresStorageRepository
|
||||
"INSERT INTO solana_user_pda_current (" +
|
||||
"pda_address, login, normalized_login, record_number, slot, last_tx_signature, " +
|
||||
"recovery_key, root_key, client_key, blockchain_name, " +
|
||||
"blockchain_key, paid_limit_bytes, used_bytes, " +
|
||||
"blockchain_key, paid_limit_bytes, blockchain_forks_json, used_bytes, " +
|
||||
"last_block_number, last_block_hash, last_block_signature, " +
|
||||
"arweave_tx_id, archive_head_tx_id, archive_head_hash, is_server, address_format_type, " +
|
||||
"address_format_version, server_address, sync_servers_json, " +
|
||||
@@ -470,7 +470,7 @@ public final class PostgresStorageRepository
|
||||
"trusted_count, created_at_ms, updated_at_ms, " +
|
||||
"prev_record_hash, record_signature, raw_data_base64, " +
|
||||
"first_seen_at_ms, last_synced_at_ms" +
|
||||
") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " +
|
||||
") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " +
|
||||
"ON CONFLICT (pda_address) DO UPDATE SET " +
|
||||
"login = EXCLUDED.login, " +
|
||||
"normalized_login = EXCLUDED.normalized_login, " +
|
||||
@@ -483,6 +483,7 @@ public final class PostgresStorageRepository
|
||||
"blockchain_name = EXCLUDED.blockchain_name, " +
|
||||
"blockchain_key = EXCLUDED.blockchain_key, " +
|
||||
"paid_limit_bytes = EXCLUDED.paid_limit_bytes, " +
|
||||
"blockchain_forks_json = EXCLUDED.blockchain_forks_json, " +
|
||||
"used_bytes = EXCLUDED.used_bytes, " +
|
||||
"last_block_number = EXCLUDED.last_block_number, " +
|
||||
"last_block_hash = EXCLUDED.last_block_hash, " +
|
||||
@@ -595,6 +596,7 @@ public final class PostgresStorageRepository
|
||||
statement.setString(i++, snapshot.blockchainName());
|
||||
statement.setString(i++, snapshot.blockchainKey());
|
||||
statement.setLong(i++, snapshot.paidLimitBytes());
|
||||
statement.setString(i++, writeJson(snapshot.blockchainForks()));
|
||||
statement.setLong(i++, snapshot.usedBytes());
|
||||
statement.setInt(i++, snapshot.lastBlockNumber());
|
||||
statement.setString(i++, snapshot.lastBlockHash());
|
||||
@@ -652,6 +654,17 @@ public final class PostgresStorageRepository
|
||||
)
|
||||
);
|
||||
|
||||
String forksJson = resultSet.getString("blockchain_forks_json");
|
||||
List<ShineUsersCodec.BlockchainForkSnapshot> blockchainForks =
|
||||
forksJson == null || forksJson.isBlank()
|
||||
? List.of()
|
||||
: Arrays.asList(
|
||||
mapper.readValue(
|
||||
forksJson,
|
||||
ShineUsersCodec.BlockchainForkSnapshot[].class
|
||||
)
|
||||
);
|
||||
|
||||
return new ShineUsersCodec.UserPdaSnapshot(
|
||||
resultSet.getString("pda_address"),
|
||||
resultSet.getString("login"),
|
||||
@@ -684,7 +697,8 @@ public final class PostgresStorageRepository
|
||||
resultSet.getLong("updated_at_ms"),
|
||||
resultSet.getString("prev_record_hash"),
|
||||
resultSet.getString("record_signature"),
|
||||
resultSet.getString("raw_data_base64")
|
||||
resultSet.getString("raw_data_base64"),
|
||||
List.copyOf(blockchainForks)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -836,6 +850,7 @@ public final class PostgresStorageRepository
|
||||
"blockchain_name TEXT NOT NULL, " +
|
||||
"blockchain_key TEXT NOT NULL, " +
|
||||
"paid_limit_bytes BIGINT NOT NULL, " +
|
||||
"blockchain_forks_json TEXT NOT NULL DEFAULT '[]', " +
|
||||
"used_bytes BIGINT NOT NULL, " +
|
||||
"last_block_number INTEGER NOT NULL, " +
|
||||
"last_block_hash TEXT NOT NULL, " +
|
||||
@@ -872,6 +887,7 @@ public final class PostgresStorageRepository
|
||||
" OR normalized_login <> LOWER(BTRIM(login))"
|
||||
);
|
||||
|
||||
statement.executeUpdate("ALTER TABLE solana_user_pda_current ADD COLUMN IF NOT EXISTS blockchain_forks_json TEXT NOT NULL DEFAULT '[]'");
|
||||
statement.executeUpdate("ALTER TABLE solana_user_pda_current ADD COLUMN IF NOT EXISTS archive_head_tx_id TEXT NOT NULL DEFAULT ''");
|
||||
statement.executeUpdate("ALTER TABLE solana_user_pda_current ADD COLUMN IF NOT EXISTS archive_head_hash TEXT NOT NULL DEFAULT ''");
|
||||
|
||||
|
||||
@@ -74,7 +74,8 @@ public final class PeriodicBlockchainSyncService {
|
||||
}
|
||||
|
||||
private static boolean isEnabled() {
|
||||
return AppConfig.getInstance().getBoolean("blockchain.sync.enabled", true);
|
||||
// PDA 1.2 удаляет sync_servers: пользовательские блокчейны синхронизируются через Arweave.
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void runCycleSafe() {
|
||||
|
||||
@@ -22,54 +22,11 @@ public final class SyncServersBootstrapService {
|
||||
private SyncServersBootstrapService() {}
|
||||
|
||||
public static void refreshFromSolanaOrLog() {
|
||||
String serverLogin = normalize(AppConfig.getInstance().getParam(CONFIG_KEY));
|
||||
if (serverLogin == null) {
|
||||
log.warn("Sync bootstrap skipped: параметр {} не задан", CONFIG_KEY);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
SolanaUserPdaImportService.ParsedServerProfile own =
|
||||
SolanaUserPdaImportService.fetchServerProfileByLogin(serverLogin);
|
||||
if (own == null) {
|
||||
log.warn("Sync bootstrap skipped: server PDA не найдена для login={}", serverLogin);
|
||||
return;
|
||||
}
|
||||
if (!own.isServer()) {
|
||||
log.warn("Sync bootstrap skipped: PDA login={} не помечена как server", serverLogin);
|
||||
return;
|
||||
}
|
||||
|
||||
List<SyncServerEntry> entries = new ArrayList<>();
|
||||
long now = System.currentTimeMillis();
|
||||
for (String partnerLogin : own.syncServers()) {
|
||||
String normalizedPartnerLogin = normalize(partnerLogin);
|
||||
if (normalizedPartnerLogin == null) continue;
|
||||
|
||||
SolanaUserPdaImportService.ParsedServerProfile partner =
|
||||
SolanaUserPdaImportService.fetchServerProfileByLogin(normalizedPartnerLogin);
|
||||
if (partner == null) {
|
||||
log.warn("Sync bootstrap: partner PDA не найдена для login={}", normalizedPartnerLogin);
|
||||
continue;
|
||||
}
|
||||
if (!partner.isServer()) {
|
||||
log.warn("Sync bootstrap: partner login={} не является server PDA", normalizedPartnerLogin);
|
||||
continue;
|
||||
}
|
||||
|
||||
String serverAddress = safe(partner.serverAddress());
|
||||
if (serverAddress.isBlank()) {
|
||||
log.warn("Sync bootstrap: у partner login={} пустой server_address", normalizedPartnerLogin);
|
||||
continue;
|
||||
}
|
||||
|
||||
entries.add(new SyncServerEntry(normalizedPartnerLogin, serverAddress, now));
|
||||
}
|
||||
|
||||
SyncServersDAO.getInstance().replaceAll(entries);
|
||||
log.info("Sync bootstrap: сохранено {} серверов синхронизации для login={}", entries.size(), serverLogin);
|
||||
SyncServersDAO.getInstance().replaceAll(List.of());
|
||||
log.info("Legacy sync_servers disabled: blockchain synchronization uses Arweave");
|
||||
} catch (Exception e) {
|
||||
log.error("Sync bootstrap failed while loading server PDA and sync_servers from Solana", e);
|
||||
log.warn("Failed to clear legacy sync_servers table", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,11 +28,11 @@ solana.users.sync.pollIntervalSeconds=300
|
||||
sync.importUserProfileFromPartner.enabled=false
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# Прямая межсерверная синхронизация пользовательских блокчейнов
|
||||
# через sync_servers: ListBlockchainHeads/GetBlockchainBlock -> локальный AddBlock.
|
||||
# Для проверки режима Solana + Arweave без прямых связей серверов можно выключить.
|
||||
# Legacy peer-to-peer blockchain sync. В PDA 1.2 sync_servers удалён,
|
||||
# пользовательские блокчейны синхронизируются через Arweave.
|
||||
# Параметр оставлен временно для совместимости конфигураций и не активирует legacy sync.
|
||||
# ------------------------------------------------------------
|
||||
blockchain.sync.enabled=true
|
||||
blockchain.sync.enabled=false
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# Server public info
|
||||
@@ -138,14 +138,11 @@ test.freeAvatar.walletJwkPath=
|
||||
# ============================================================
|
||||
# Arweave per-user-block transport (ANS-104)
|
||||
# Test namespace: each user DataItem is signed with App=test5590.
|
||||
# Channel DataItems additionally contain c_test5590=<canonical-channel-slug>.
|
||||
# publish.mode: turbo | arweave | none
|
||||
# Channel DataItems additionally contain c=<canonical-channel-slug>.
|
||||
# ============================================================
|
||||
arweave.blocks.publish.mode=none
|
||||
arweave.blocks.publish.enabled=false
|
||||
arweave.blocks.publish.intervalMinutes=15
|
||||
arweave.blocks.publish.maxItems=10000
|
||||
|
||||
# Direct Arweave L1 fallback: server combines user DataItems into one standard ANS-104 bundle.
|
||||
arweave.blocks.publish.maxBundleBytes=134217728
|
||||
arweave.blocks.publish.gateway=https://arweave.net
|
||||
arweave.blocks.publish.walletJwkPath=
|
||||
@@ -153,18 +150,10 @@ arweave.blocks.publish.minConfirmations=0
|
||||
arweave.blocks.publish.confirmPollSeconds=30
|
||||
arweave.blocks.publish.confirmTimeoutMinutes=180
|
||||
|
||||
# Turbo: uploads each already user-signed DataItem separately, without re-signing it.
|
||||
# paidByAddress is the public Turbo payer address. If it is empty and turbo.walletJwkPath is set,
|
||||
# the Arweave payer address is derived locally from that JWK. The private key is never sent to Turbo.
|
||||
# For paid uploads of someone else's signed DataItem, Turbo Credit Share Approval must exist for its signer.
|
||||
arweave.blocks.publish.turbo.uploadUrl=https://turbo.ardrive.io/tx
|
||||
arweave.blocks.publish.turbo.paidByAddress=
|
||||
arweave.blocks.publish.turbo.walletJwkPath=
|
||||
|
||||
arweave.blocks.sync.enabled=false
|
||||
arweave.blocks.sync.intervalMinutes=15
|
||||
arweave.blocks.sync.gateway=https://turbo-gateway.com
|
||||
arweave.blocks.sync.pageSize=100
|
||||
arweave.blocks.sync.queueBatchSize=10000
|
||||
arweave.blocks.sync.startBlockHeight=0
|
||||
arweave.blocks.sync.maxDataItemBytes=8388608
|
||||
arweave.blocks.sync.maxRootBundleBytes=268435456
|
||||
|
||||
+2
-2
@@ -1,2 +1,2 @@
|
||||
client.version=1.13.0
|
||||
server.version=1.11.0
|
||||
client.version=1.14.0
|
||||
server.version=1.12.0
|
||||
|
||||
@@ -104,6 +104,12 @@ cp /path/to/SHiNE-product/application.properties ./application.properties
|
||||
|
||||
## Что пока остаётся как есть
|
||||
|
||||
- `sync_servers` сервер по-прежнему загружает из server PDA в Solana;
|
||||
- runtime-сервер уже работает только с PostgreSQL;
|
||||
- дальнейшим отдельным шагом остаются зачистка legacy-документации, переименования и перенос оставшихся прямых SQL-запросов в DAO/service.
|
||||
- runtime-сервер работает с PostgreSQL;
|
||||
- межсерверная доставка DM остаётся отдельным механизмом и не связана с blockchain sync;
|
||||
- прямой blockchain sync через `sync_servers` отключён: пользовательские блоки синхронизируются через Arweave.
|
||||
|
||||
## Совместимость с user PDA 1.2
|
||||
|
||||
После обновления `shine_users` серверный модуль `shine-server-solana-users-sync` должен обновляться вместе с программой: текущий codec принимает только PDA 1.2. Legacy PDA 1.0 не мигрируются; тестовые legacy-записи можно закрыть временной инструкцией `close_legacy_pda`.
|
||||
|
||||
Миграция PostgreSQL v25 добавляет `blockchain_forks_json`. Старые compatibility-колонки продолжают содержать активный (последний) fork, а полный список ключей fork сохраняется отдельно и используется для поиска владельца Arweave-записей по любому историческому blockchain key.
|
||||
|
||||
@@ -72,7 +72,7 @@ sudo docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}'
|
||||
|
||||
## Operational-нюанс
|
||||
|
||||
Общий Helius devnet endpoint тоже может начать ограничивать запросы, если несколько инстансов одновременно делают тяжёлый bootstrap. Если после деплоя какой-то инстанс не подтянул `sync_servers` или завис на startup sync, рестартовать сервисы по одному с паузой.
|
||||
Общий Helius devnet endpoint тоже может начать ограничивать запросы, если несколько инстансов одновременно делают тяжёлый bootstrap. Если после деплоя какой-то инстанс завис на bootstrap Arweave/Solana sync, рестартовать сервисы по одному с паузой.
|
||||
|
||||
Отдельный нюанс по web push:
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@
|
||||
- физическое соединение создаётся одно на `serverLogin`;
|
||||
- логические операции DM, settings и blockchain используют один WSS;
|
||||
- завершение `RemoteSyncSession` не закрывает физический сокет;
|
||||
- известные peer берутся из `sync_servers` и первых действующих маршрутов
|
||||
- известные peer берутся из актуальных server PDA/access-server маршрутов
|
||||
`user_access_servers_current`;
|
||||
- список перечитывается каждые 30 секунд;
|
||||
- при изменении URL соединение пересоздаётся;
|
||||
|
||||
@@ -100,8 +100,7 @@ homeserver.key:home-a -> ключ A
|
||||
homeserver.key:home-b -> ключ B
|
||||
```
|
||||
|
||||
Публичный ключ homeserver-а публикуется в `SessionsBlock` пользовательской PDA как
|
||||
`session_pub_key` с `session_type = 100`, имя — в `session_name` (формат PDA §13).
|
||||
В PDA 1.2 `SessionsBlock` удалён, поэтому homeserver-ключи больше не публикуются через user PDA. Сама детерминированная деривация ключа сохранена как отдельный механизм устройства; способ его будущей публикации/авторизации определяется отдельно от PDA 1.2.
|
||||
|
||||
> Это переименование прежней схемы `subserver.key:<имя>` → `homeserver.key:<имя>`.
|
||||
> Термин «саб-сервер» по проекту заменяется на «homeserver».
|
||||
@@ -130,8 +129,8 @@ homeserver.key:home-b -> ключ B
|
||||
- старый тестовый вариант; оставлен как legacy-скетч для сравнения и диагностики.
|
||||
|
||||
### Формат PDA (куда попадают ключи)
|
||||
- `shine-solana/shine/doc/formats/shine-user-pda-format-v.1.0.md`
|
||||
— `RootKeyBlock` §6, `ClientKeyBlock` §7, `blockchain_public_key` §9, `SessionsBlock`/`session_type=100` §13, оплата §2.1.
|
||||
- `shine-solana/shine/doc/formats/shine-user-pda-format-v.1.2.md`
|
||||
— `RootKeyBlock`, `ClientKeyBlock`, append-only `BlockchainRegistryBlock` и экономика лимита. `SessionsBlock` в PDA 1.2 отсутствует.
|
||||
|
||||
### Сервер (тестовый seed)
|
||||
- `SHiNE-server/src/test/java/test/it/cases/SeedDataPopulationHelper.java` `deriveKeysFromPassword` (~246) —
|
||||
|
||||
@@ -14,11 +14,10 @@
|
||||
- сервер проверяет формат, пользователей и подпись до сохранения;
|
||||
- повторная доставка одной ревизии идемпотентна;
|
||||
- более старая ревизия не заменяет новую;
|
||||
- у каждого пользователя действует только access_servers[0];
|
||||
- дополнительные элементы старой PDA игнорируются без fallback;
|
||||
- PDA 1.2 допускает максимум один access server; если он задан, используется единственная запись;
|
||||
- старые PDA 1.0 не участвуют в текущем runtime-протоколе;
|
||||
- DM и настройки не реплицируются между access-серверами одного пользователя;
|
||||
- sync_servers серверного PDA используются только для синхронизации
|
||||
пользовательских блокчейнов.
|
||||
- пользовательские blockchain синхронизируются через Arweave; `sync_servers` в PDA 1.2 отсутствует.
|
||||
|
||||
## 3. Типы DM
|
||||
|
||||
|
||||
@@ -567,3 +567,20 @@ SYNC_POLL_INTERVAL_SECONDS=300
|
||||
7. добавить запись в `current` и `history`;
|
||||
8. добавить periodic guard раз в 5 минут;
|
||||
9. сохранить отдельный `main` для запуска как процесса.
|
||||
|
||||
## PDA 1.2 (2026-09-25)
|
||||
|
||||
Модуль синхронизации принимает только текущую PDA 1.2. Legacy PDA 1.0 не проецируются в runtime-state и не мигрируются: их можно закрыть отдельной временной инструкцией `close_legacy_pda`.
|
||||
|
||||
Для PDA 1.2:
|
||||
|
||||
- `RecoveryKeyBlock`, sessions, trusted state, archive head и `sync_servers` отсутствуют;
|
||||
- `BlockchainRegistryBlock` содержит append-only список fork в порядке `blockchain_key + created_at_ms + paid_limit_bytes`;
|
||||
- `ServerProfileBlock` в 1.2 допускает один адрес сервера, `AccessServersBlock` — 0 или 1 access server;
|
||||
- в compatibility SQL-поля проецируется **последний** fork как активный `blockchain_key/paid_limit_bytes`;
|
||||
- полный список fork сохраняется в `blockchain_forks_json`, поэтому поиск пользователя по старому blockchain key остаётся возможным;
|
||||
- `blockchain_name` для compatibility view вычисляется как `<normalized_login>-NNN`, где `NNN` соответствует индексу fork + 1;
|
||||
- удалённые tip-поля (`used_bytes`, `last_block_*`, Arweave tx id) в PDA 1.2 больше не являются источником истины и в compatibility snapshot заполняются нейтральными значениями;
|
||||
- server profile считается присутствующим, если опубликован один server address; в старые SQL-поля временно проецируется этот адрес.
|
||||
|
||||
Create/update транзакции больше не реконструируются байт-в-байт из instruction args. После обнаружения изменения sync-модуль перечитывает фактическую текущую PDA через Solana RPC и декодирует её. Это исключает дублирование on-chain сериализации. `close_legacy_pda` не создаёт новое состояние PDA и для runtime-sync не является пользовательским update.
|
||||
|
||||
+14
-506
@@ -1,512 +1,20 @@
|
||||
# Solana user_pda: итоговый целевой формат пользовательской записи
|
||||
# SHiNE User PDA
|
||||
|
||||
Документ описывает целевой формат пользовательской PDA-записи `user_pda` для Solana-программы `shine_users`.
|
||||
Актуальный формат: **1.2**.
|
||||
|
||||
Это не формат основного блокчейна SHiNE и не документация по `AddBlock`. Основной блокчейн SHiNE описан отдельно в `docs/Blockchain/`.
|
||||
Каноническая спецификация находится в:
|
||||
|
||||
Статус документа: итоговый согласованный формат, к которому приведены `create_user_pda`, `update_user_pda` и тестовый сериализатор Solana-модуля.
|
||||
`shine-solana/shine/doc/formats/shine-user-pda-format-v.1.2.md`
|
||||
|
||||
## 1. Назначение user_pda
|
||||
Ключевые отличия от тестового 1.0:
|
||||
|
||||
`user_pda` хранит публичное состояние пользователя в Solana:
|
||||
- удалены Recovery/Sessions/Trusted/ArchiveHead и `sync_servers`;
|
||||
- root — cold recovery authority;
|
||||
- последний blockchain key — обычный authority;
|
||||
- BlockchainRegistry хранит append-only fork history: `key[32] + created_at_ms:u64 + paid_limit_bytes:u32`;
|
||||
- ServerProfile допускает один адрес в 1.2, AccessServers — 0/1 сервер;
|
||||
- variable blocks имеют `payload_len:u16` для forward compatibility;
|
||||
- create/update работают только с 1.2;
|
||||
- legacy 1.0 можно только временно закрыть `close_legacy_pda` и вернуть lamports caller-у.
|
||||
|
||||
- логин пользователя;
|
||||
- неизменяемые параметры создания записи;
|
||||
- публичный recovery-ключ пользователя;
|
||||
- корневой публичный ключ пользователя;
|
||||
- клиентский публичный ключ пользователя;
|
||||
- данные одного или нескольких пользовательских блокчейнов SHiNE;
|
||||
- серверные данные пользователя, если пользователь выступает сервером;
|
||||
- серверы доступа пользователя;
|
||||
- счетчики/лимиты;
|
||||
- подпись записи.
|
||||
|
||||
На первом этапе поддерживается один пользовательский блокчейн SHiNE, но формат блока блокчейна сразу допускает повторение таких блоков в будущем.
|
||||
|
||||
## 2. Адрес PDA
|
||||
|
||||
Адрес пользовательской PDA вычисляется по логину:
|
||||
|
||||
- seed prefix: `user_login=`;
|
||||
- второй seed: нормализованный логин в нижнем регистре;
|
||||
- program id: программа `shine_users`.
|
||||
|
||||
Один логин соответствует одной `user_pda`.
|
||||
|
||||
## 2.1. Кто оплачивает create/update PDA
|
||||
|
||||
- Инструкции `create_user_pda` и `update_user_pda` оплачиваются с `client_key`.
|
||||
- `root_key` используется для подписи unsigned части записи через Ed25519 instruction и не является fee payer.
|
||||
- Для server PDA это правило то же самое: пополнять SOL нужно на адрес `client_key`.
|
||||
|
||||
## 3. Общие правила кодирования
|
||||
|
||||
- Числа кодируются в Little Endian.
|
||||
- `u8`, `u16`, `u32`, `u64` имеют обычный фиксированный размер.
|
||||
- Публичный ключ Solana/Ed25519: 32 байта.
|
||||
- Ed25519-подпись: 64 байта.
|
||||
- SHA-256/Solana hash: 32 байта.
|
||||
- Строка переменной длины: `len: u8` + `bytes[len]` в UTF-8.
|
||||
- Arweave `tx_id`: строка переменной длины. Ожидаемая практическая длина base64url tx id - 43 байта, но формат хранит длину явно.
|
||||
- Все типизированные блоки после фиксированного заголовка начинаются с `block_type: u8` и `block_version: u8`.
|
||||
- Отдельный `block_len` у типизированных блоков не хранится: блоки парсятся по известным полям, счетчикам и строкам с `len: u8`.
|
||||
|
||||
## 4. Верхний формат записи
|
||||
|
||||
Первые 9 полей фиксированы и идут строго в указанном порядке. Это общий заголовок записи.
|
||||
|
||||
| N | Поле | Тип | Размер | Правило |
|
||||
|---|------|-----|--------|---------|
|
||||
| 1 | `magic` | bytes | 5 | Всегда `SHiNE`. |
|
||||
| 2 | `format_major` | `u8` | 1 | Для первого формата: `1`. |
|
||||
| 3 | `format_minor` | `u8` | 1 | Для первой версии нового формата: `0`. |
|
||||
| 4 | `record_len` | `u16` | 2 | Длина полезной записи от `magic` до `signature` включительно, без padding. |
|
||||
| 5 | `created_at_ms` | `u64` | 8 | Время создания записи, Unix time в миллисекундах. Не меняется. |
|
||||
| 6 | `updated_at_ms` | `u64` | 8 | Время последнего обновления записи. |
|
||||
| 7 | `record_number` | `u32` | 4 | Номер версии записи пользователя. При создании `0`, при обновлении +1. |
|
||||
| 8 | `prev_record_hash` | bytes | 32 | Хэш unsigned-части предыдущей записи. При создании 32 нулевых байта. |
|
||||
| 9 | `login` | string | `1 + len` | Логин пользователя. Не меняется. |
|
||||
|
||||
После первых 9 полей идет набор типизированных блоков:
|
||||
|
||||
```text
|
||||
UserPdaRecordV1
|
||||
- fixed_header: поля 1..9
|
||||
- blocks_count: u8
|
||||
- blocks: TypedBlock[blocks_count]
|
||||
- signature: [u8; 64]
|
||||
- padding: bytes до размера PDA, если нужен
|
||||
```
|
||||
|
||||
`blocks_count` входит в unsigned-часть записи и подписывается.
|
||||
|
||||
## 5. Типы блоков
|
||||
|
||||
Зарезервированные значения `block_type`:
|
||||
|
||||
| block_type | Блок | Назначение |
|
||||
|------------|------|------------|
|
||||
| `0` | `RecoveryKeyBlock` | Ключ восстановления пользователя. |
|
||||
| `1` | `RootKeyBlock` | Корневой ключ пользователя. |
|
||||
| `2` | `ClientKeyBlock` | Клиентский ключ пользователя. |
|
||||
| `3` | `BlockchainRegistryBlock` | Один или несколько блокчейнов пользователя. |
|
||||
| `30` | `ServerProfileBlock` | Серверные данные пользователя. |
|
||||
| `40` | `AccessServersBlock` | Серверы доступа/relay. |
|
||||
| `50` | `SessionsBlock` | Опубликованные пользовательские сессии и homeserver-ы. |
|
||||
| `70` | `TrustedStateBlock` | Счетчик trusted-связей. |
|
||||
| `100` | `ArchiveHeadBlock` | Legacy/reserved. Новый per-block ANS-104 transport не использует это поле для пользовательской истории. |
|
||||
| `255` | `ReservedBlock` | Зарезервировано, пока не используется. |
|
||||
|
||||
Правила:
|
||||
|
||||
- неизвестный `block_type` в `format_major = 1` считается ошибкой;
|
||||
- обязательные блоки: `RecoveryKeyBlock`, `RootKeyBlock`, `ClientKeyBlock`, `BlockchainRegistryBlock`;
|
||||
- необязательные блоки: `ServerProfileBlock`, `AccessServersBlock`, `SessionsBlock`, `TrustedStateBlock`, `ArchiveHeadBlock`;
|
||||
- каждый обязательный блок должен встречаться ровно один раз;
|
||||
- порядок блоков в записи фиксируется для простоты проверки:
|
||||
`RecoveryKey`, `RootKey`, `ClientKey`, `BlockchainRegistry`, `ServerProfile`, `AccessServers`, `Sessions`, `TrustedState`, `ArchiveHead`.
|
||||
|
||||
## 6. RecoveryKeyBlock
|
||||
|
||||
Recovery-ключ нужен для будущих сценариев восстановления и ротации остальных ключей. В текущей версии он только публикуется в записи и не меняется через обычный `update_user_pda`.
|
||||
|
||||
```text
|
||||
RecoveryKeyBlock
|
||||
- block_type: u8 = 0
|
||||
- block_version: u8 = 0
|
||||
- recovery_key: [u8; 32]
|
||||
```
|
||||
|
||||
Правила:
|
||||
|
||||
- при создании задается публичный recovery-ключ пользователя;
|
||||
- при обновлении `recovery_key` должен совпадать с предыдущей записью;
|
||||
- приватный `recovery.key` в PDA не хранится;
|
||||
- отдельная ротация recovery-ключа будет отдельным форматом/сценарием в будущем.
|
||||
|
||||
## 7. RootKeyBlock
|
||||
|
||||
Смена `root_key` пока не проектируется и не реализуется. Блок фиксирует только стадию `0`.
|
||||
|
||||
```text
|
||||
RootKeyBlock
|
||||
- block_type: u8 = 1
|
||||
- block_version: u8 = 0
|
||||
- root_key: [u8; 32]
|
||||
```
|
||||
|
||||
Правила:
|
||||
|
||||
- при создании задается корневой публичный ключ пользователя;
|
||||
- при обновлении `root_key` должен совпадать с предыдущей записью;
|
||||
- ротация root-key будет отдельным форматом/сценарием в будущем.
|
||||
|
||||
## 8. ClientKeyBlock
|
||||
|
||||
Смена `client_key` пока также не проектируется как отдельная ротация. В версии `0` хранится один клиентский ключ пользователя.
|
||||
|
||||
```text
|
||||
ClientKeyBlock
|
||||
- block_type: u8 = 2
|
||||
- block_version: u8 = 0
|
||||
- client_key: [u8; 32]
|
||||
```
|
||||
|
||||
Правила:
|
||||
|
||||
- при создании задается текущий клиентский публичный ключ пользователя;
|
||||
- при обновлении `client_key` должен совпадать с предыдущей записью;
|
||||
- история устройств и несколько клиентских ключей в этом формате не хранятся.
|
||||
|
||||
## 9. BlockchainRegistryBlock
|
||||
|
||||
Блок хранит данные пользовательских блокчейнов SHiNE. Сейчас используется один блокчейн, но структура сразу сделана как список.
|
||||
|
||||
```text
|
||||
BlockchainRegistryBlock
|
||||
- block_type: u8 = 3
|
||||
- block_version: u8 = 0
|
||||
- blockchain_count: u8
|
||||
- blockchain_records: BlockchainRecord[blockchain_count]
|
||||
```
|
||||
|
||||
Правила:
|
||||
|
||||
- на первом этапе `blockchain_count = 1`;
|
||||
- в будущем можно увеличить количество записей без изменения смысла `BlockchainRecord`;
|
||||
- каждый `BlockchainRecord` описывает один пользовательский SHiNE-блокчейн.
|
||||
|
||||
## 10. BlockchainRecord
|
||||
|
||||
```text
|
||||
BlockchainRecord
|
||||
- blockchain_type: u8
|
||||
- blockchain_name: string
|
||||
- blockchain_public_key: [u8; 32]
|
||||
- paid_limit_bytes: u64
|
||||
- used_bytes: u64
|
||||
- last_block_number: u32
|
||||
- last_block_hash: [u8; 32]
|
||||
- last_block_signature: [u8; 64]
|
||||
- arweave_present: u8
|
||||
- arweave_tx_id: string, только если arweave_present = 1
|
||||
```
|
||||
|
||||
`blockchain_type`:
|
||||
|
||||
| Значение | Смысл |
|
||||
|----------|-------|
|
||||
| `1` | Основной пользовательский SHiNE-блокчейн. |
|
||||
|
||||
Поля:
|
||||
|
||||
- `blockchain_name` - строковое имя пользовательского блокчейна, например `login-001`. На первом этапе для основного блокчейна пользователя используется имя вида `<login>-001`, потому что это первый блокчейн этого пользователя.
|
||||
- `blockchain_public_key` - публичный ключ блокчейна пользователя.
|
||||
- `paid_limit_bytes` - оплаченный лимит хранения/записей в байтах.
|
||||
- `used_bytes` - сколько байт уже занято в пользовательском SHiNE-блокчейне.
|
||||
- `last_block_number` - номер последнего известного блока пользовательского блокчейна.
|
||||
- `last_block_hash` - хэш последнего известного блока.
|
||||
- `last_block_signature` - подпись хэша специального сообщения о вершине блокчейна ключом `blockchain_public_key`.
|
||||
- `arweave_present` - `0`, если ссылки нет; `1`, если ссылка есть.
|
||||
- `arweave_tx_id` - Arweave transaction id, где лежит выгруженный пользовательский канал/состояние.
|
||||
|
||||
Arweave `tx_id` - обычное поле внутри записи конкретного блокчейна. Solana-программа не проверяет, что такой Arweave transaction действительно существует и содержит корректные данные; это ответственность клиента/сервера/пользователя.
|
||||
|
||||
## 11. Правила обновления BlockchainRecord
|
||||
|
||||
При обновлении записи:
|
||||
|
||||
- `blockchain_type` для существующей записи не меняется;
|
||||
- `blockchain_public_key` пока не ротируется автоматически; смена ключа требует отдельного согласованного сценария;
|
||||
- `paid_limit_bytes` может только увеличиваться или оставаться прежним;
|
||||
- при увеличении `paid_limit_bytes` пользователь платит комиссию в Solana по тарифам программы;
|
||||
- `used_bytes` может только увеличиваться или оставаться прежним;
|
||||
- `last_block_number` может только увеличиваться или оставаться прежним;
|
||||
- `used_bytes <= paid_limit_bytes`;
|
||||
- если `last_block_number` увеличился, то должны быть переданы новый `last_block_hash` и новая `last_block_signature`;
|
||||
- `last_block_signature` проверяется через Ed25519-инструкцию Solana: подпись должна соответствовать хэшу сообщения `LastBlockState` и `blockchain_public_key`;
|
||||
- в транзакции `create_user_pda` / `update_user_pda` две Ed25519-инструкции должны идти непосредственно перед вызовом `shine_users`: сначала подпись `root_key`, затем подпись `blockchain_public_key`;
|
||||
- `arweave_tx_id` можно добавить или заменить на новый, если пользователь выгрузил более актуальное состояние в Arweave;
|
||||
- уменьшать лимит, число блоков или занятый размер нельзя.
|
||||
|
||||
Сообщение `LastBlockState`, которое хэшируется и подписывается ключом `blockchain_public_key`:
|
||||
|
||||
```text
|
||||
LastBlockState
|
||||
- constant: bytes = "SHiNE_LAST_BLOCK"
|
||||
- login: string
|
||||
- blockchain_name: string
|
||||
- last_block_number: u32
|
||||
- last_block_hash: [u8; 32]
|
||||
- used_bytes: u64
|
||||
```
|
||||
|
||||
Алгоритм:
|
||||
|
||||
```text
|
||||
message = SHA-256(LastBlockState bytes)
|
||||
last_block_signature = Ed25519(blockchain_public_key, message)
|
||||
```
|
||||
|
||||
Причина проверки подписи `LastBlockState`: `root_key` управляет Solana-записью пользователя, а `blockchain_public_key` подтверждает состояние конкретного пользовательского блокчейна. Подписывается не голый хэш, а связка логина, имени блокчейна, номера последнего блока, хэша последнего блока и занятого размера.
|
||||
|
||||
## 12. ServerProfileBlock
|
||||
|
||||
Блок присутствует, если пользователь выступает сервером.
|
||||
|
||||
```text
|
||||
ServerProfileBlock
|
||||
- block_type: u8 = 30
|
||||
- block_version: u8 = 0
|
||||
- is_server: u8
|
||||
- address_format_type: u8, только если is_server = 1
|
||||
- address_format_version: u8, только если is_server = 1
|
||||
- server_address: string, только если is_server = 1
|
||||
- sync_servers_count: u8, только если is_server = 1
|
||||
- sync_servers: string[sync_servers_count], только если is_server = 1
|
||||
```
|
||||
|
||||
Правила:
|
||||
|
||||
- `is_server = 0` означает, что серверных данных нет;
|
||||
- `is_server = 1` означает, что пользователь публикует серверный профиль;
|
||||
- `address_format_type` — тип формата адреса сервера: `1` = URL-строка (например `https://shineup.me/ws`);
|
||||
- `address_format_version` — версия формата адреса, сейчас `0`;
|
||||
- `sync_servers_count` максимум `32`;
|
||||
- `server_address` - строковый адрес сервера в соответствии с `address_format_type`;
|
||||
- `sync_servers` - логины SHiNE-пользователей, зарегистрированных как серверы, с которыми этот сервер синхронизирует серверные данные и пользовательские блокчейны SHiNE. Это server-to-server список партнёров самого серверного узла, а не список серверов доставки личных сообщений для обычного пользователя. Solana-программа не обязана проверять, что эти логины действительно зарегистрированы как серверы.
|
||||
|
||||
## 13. AccessServersBlock
|
||||
|
||||
Блок хранит серверы доступа/relay для пользователя.
|
||||
|
||||
```text
|
||||
AccessServersBlock
|
||||
- block_type: u8 = 40
|
||||
- block_version: u8 = 0
|
||||
- access_servers_count: u8
|
||||
- access_servers: string[access_servers_count]
|
||||
```
|
||||
|
||||
Правила:
|
||||
|
||||
- блок может отсутствовать, если серверы доступа не заданы;
|
||||
- список может обновляться при изменении маршрутизации пользователя;
|
||||
- `access_servers` — массив логинов серверов доступа/relay. Формат массива
|
||||
сохранён для совместимости, но текущая клиентская и серверная логика использует
|
||||
только первый элемент `access_servers[0]`;
|
||||
- остальные элементы игнорируются без fallback;
|
||||
- официальный UI записывает ровно один сервер и позволяет только заменить его;
|
||||
- Solana-программа не обязана проверять, что логин действительно зарегистрирован
|
||||
как сервер.
|
||||
|
||||
## 14. SessionsBlock
|
||||
|
||||
Блок хранит опубликованные пользовательские сессии. На текущем этапе регистрация пользователя не добавляет туда записи автоматически, поэтому стандартный create/update продолжает работать с пустым списком.
|
||||
|
||||
```text
|
||||
SessionsBlock
|
||||
- block_type: u8 = 50
|
||||
- block_version: u8 = 0
|
||||
- sessions_mode: u8
|
||||
- sessions_count: u8
|
||||
- sessions: SessionRecord[sessions_count]
|
||||
```
|
||||
|
||||
`sessions_mode`:
|
||||
|
||||
| Значение | Смысл |
|
||||
|----------|-------|
|
||||
| `1` | Можно использовать и сессии, зарегистрированные в PDA, и сессии, созданные вне PDA. |
|
||||
| `10` | Зарезервировано на будущее: можно использовать только сессии, опубликованные в PDA. |
|
||||
|
||||
Сейчас рабочий режим по умолчанию: `sessions_mode = 1`. Серверная логика пока не реализует особое поведение для `10`; это задел под будущее расширение.
|
||||
|
||||
```text
|
||||
SessionRecord
|
||||
- session_type: u8
|
||||
- session_version: u8
|
||||
- session_name: string
|
||||
- session_pub_key: [u8; 32]
|
||||
```
|
||||
|
||||
`session_type`:
|
||||
|
||||
| Значение | Смысл |
|
||||
|----------|-------|
|
||||
| `1` | Обычная пользовательская сессия. |
|
||||
| `50` | Кошелёк пользователя. |
|
||||
| `100` | Homeserver пользователя. |
|
||||
|
||||
Правила:
|
||||
|
||||
- максимум `64` записей на пользователя;
|
||||
- `session_name` не пустой, максимум `64` байта;
|
||||
- `session_name` может содержать только символы `[A-Za-z0-9_]`;
|
||||
- `session_version` сейчас должна быть равна `1`;
|
||||
- внутри одного блока должны быть уникальны и `session_name`, и `session_pub_key`;
|
||||
- на текущем этапе UI и регистрация не обязаны добавлять туда записи автоматически.
|
||||
|
||||
## 15. TrustedStateBlock
|
||||
|
||||
Пока trusted-логика не реализована полностью, поэтому блок хранит только счетчик.
|
||||
|
||||
```text
|
||||
TrustedStateBlock
|
||||
- block_type: u8 = 70
|
||||
- block_version: u8 = 0
|
||||
- trusted_count: u8 = 0
|
||||
```
|
||||
|
||||
Пока блок с доверенными лицами не реализуется, потому что полный формат trusted-логики еще не составлен. В будущем trusted-связи, очереди, таймеры и подтверждения должны быть вынесены в отдельный формат.
|
||||
|
||||
## 15.1. ArchiveHeadBlock
|
||||
|
||||
Необязательный блок текущей головы серверного архива. Он используется archive-capable сервером и хранится в том же User PDA.
|
||||
|
||||
```text
|
||||
ArchiveHeadBlock
|
||||
- block_type: u8 = 100
|
||||
- block_version: u8 = 0
|
||||
- archive_tx_id: [u8; 32]
|
||||
- archive_hash: [u8; 32]
|
||||
```
|
||||
|
||||
Семантика:
|
||||
|
||||
- `archive_tx_id` — legacy/reserved поле старой archive-head схемы; новый per-block ANS-104 transport его не обновляет;
|
||||
- `archive_hash` — SHA-256 большого archive block по правилам `docs/Archive/01_PROTOCOL_v1.0.md`;
|
||||
- отсутствие block `100` означает, что аккаунт ещё не объявлял archive head;
|
||||
- обычный legacy `update_user_pda`, в instruction которого archive extension отсутствует, **обязан сохранить существующий ArchiveHeadBlock без изменений**;
|
||||
- расширенный `update_user_pda` может заменить archive head или явно очистить его; отдельной Solana instruction для архива нет.
|
||||
|
||||
`ArchiveHeadBlock` входит в unsigned bytes User PDA и тем самым покрывается обычной root-подписью записи.
|
||||
|
||||
## 16. Подпись user_pda
|
||||
|
||||
Подписывается не вся PDA целиком, а unsigned-часть записи:
|
||||
|
||||
- от `magic` до последнего байта последнего типизированного блока включительно;
|
||||
- включая `record_len`, `blocks_count`, все заголовки блоков и тела блоков;
|
||||
- без поля `signature`;
|
||||
- без padding.
|
||||
|
||||
Алгоритм:
|
||||
|
||||
```text
|
||||
message = hash(unsigned_record_bytes)
|
||||
signature = Ed25519(root_key, message)
|
||||
```
|
||||
|
||||
Solana-программа проверяет подпись через встроенную Ed25519-инструкцию. Подписантом должен быть `root_key` из `RootKeyBlock`.
|
||||
Для `shine_users` эта инструкция должна стоять в транзакции сразу перед Ed25519-инструкцией `last_block_signature` и непосредственно перед самой `create/update`-инструкцией программы.
|
||||
|
||||
Смену формата подписи сейчас не трогаем.
|
||||
|
||||
## 17. Регистрация пользователя
|
||||
|
||||
При регистрации:
|
||||
|
||||
- PDA еще не должна существовать;
|
||||
- логин проходит проверку формата и login guard;
|
||||
- `record_number = 0`;
|
||||
- `prev_record_hash = 0x00...00`;
|
||||
- `created_at_ms = updated_at_ms`;
|
||||
- обязательные блоки присутствуют;
|
||||
- создается минимум один `BlockchainRecord`;
|
||||
- новый `SessionsBlock` может присутствовать, но при обычной регистрации сейчас записывается пустой список с `sessions_mode = 1`;
|
||||
- `ArchiveHeadBlock` при регистрации не обязателен; обычный пользователь/сервер может начать публиковать архив позже;
|
||||
- стартовый `paid_limit_bytes` равен стартовому бонусу плюс оплаченный дополнительный лимит;
|
||||
- `used_bytes <= paid_limit_bytes`;
|
||||
- пользователь платит регистрационную комиссию;
|
||||
- если покупается дополнительный лимит, пользователь платит комиссию за этот лимит;
|
||||
- вся unsigned-часть записи подписана `root_key`.
|
||||
|
||||
## 18. Обновление пользователя
|
||||
|
||||
При обновлении:
|
||||
|
||||
- PDA должна существовать;
|
||||
- `login`, `created_at_ms`, `recovery_key`, `root_key`, `client_key` не меняются;
|
||||
- `record_number = previous_record_number + 1`;
|
||||
- `prev_record_hash` равен хэшу unsigned-части предыдущей записи;
|
||||
- `updated_at_ms` обновляется;
|
||||
- unsigned-часть новой записи подписана `root_key`;
|
||||
- если archive extension в instruction отсутствует (legacy client), старый `ArchiveHeadBlock` сохраняется; если extension присутствует, применяется переданное `archive_head_update`;
|
||||
- лимиты блокчейнов могут только увеличиваться;
|
||||
- занятый размер и номер последнего блока не могут уменьшаться;
|
||||
- при увеличении оплаченного лимита пользователь доплачивает комиссию;
|
||||
- Arweave `tx_id` может быть пустым или обновленным, но его содержимое Solana не валидирует.
|
||||
|
||||
## 19. Отличия от старого линейного формата
|
||||
|
||||
Старый формат после `login` хранил поля линейно:
|
||||
|
||||
- `root_key_status`;
|
||||
- `root_key`;
|
||||
- `blockchain_key_status`;
|
||||
- `blockchain_key`;
|
||||
- `client_key_status`;
|
||||
- `client_key`;
|
||||
- `chain_number`;
|
||||
- `balance`;
|
||||
- серверные поля;
|
||||
- access-серверы;
|
||||
- `trusted_count`;
|
||||
- `reserved`;
|
||||
- `signature`.
|
||||
|
||||
Новый целевой формат сохраняет первые 9 фиксированных полей как заголовок, но дальше переходит на типизированные блоки:
|
||||
|
||||
- recovery-ключ становится отдельным обязательным блоком;
|
||||
- ключи становятся отдельными блоками;
|
||||
- данные блокчейна становятся расширенным блоком со своим публичным ключом, лимитом, занятым размером, вершиной цепочки и Arweave `tx_id`;
|
||||
- серверные данные и access-серверы отделяются от данных блокчейна;
|
||||
- расширение формата делается добавлением новых версий блоков или новых `block_type`, а не вставкой полей в середину линейной записи.
|
||||
|
||||
## 20. Деривация ключей из master secret
|
||||
|
||||
Сама Solana-программа не вычисляет ключи из секрета и не хранит приватные ключи. Но текущая согласованная клиентская схема деривации для публичной версии формата фиксируется здесь как reference для UI/ESP32/внешних клиентов.
|
||||
|
||||
Базовая формула:
|
||||
|
||||
```text
|
||||
seed = SHA-256("SHiNE-key" || 0x00 || master_secret32 || 0x00 || suffix_utf8)
|
||||
```
|
||||
|
||||
Где:
|
||||
|
||||
- `master_secret32` — 32-байтовый master secret пользователя;
|
||||
- `suffix_utf8` — строка назначения ключа.
|
||||
|
||||
Согласованные suffix:
|
||||
|
||||
```text
|
||||
"recovery.key"
|
||||
"root.key"
|
||||
"blockchain.key"
|
||||
"client.key"
|
||||
```
|
||||
|
||||
Соответствие:
|
||||
|
||||
```text
|
||||
recovery.seed = SHA-256("SHiNE-key" || 0x00 || master_secret32 || 0x00 || "recovery.key")
|
||||
root.seed = SHA-256("SHiNE-key" || 0x00 || master_secret32 || 0x00 || "root.key")
|
||||
blockchain.seed = SHA-256("SHiNE-key" || 0x00 || master_secret32 || 0x00 || "blockchain.key")
|
||||
client.seed = SHA-256("SHiNE-key" || 0x00 || master_secret32 || 0x00 || "client.key")
|
||||
```
|
||||
|
||||
Далее каждая строка `seed` интерпретируется off-chain как `seed32` для отдельной пары Ed25519.
|
||||
|
||||
## 21. Что пока не входит в формат
|
||||
|
||||
Пока не проектируем:
|
||||
|
||||
- ротацию `recovery_key`;
|
||||
- ротацию `root_key`;
|
||||
- сложную ротацию `client_key`;
|
||||
- ротацию `blockchain_public_key`;
|
||||
- проверку содержимого Arweave transaction;
|
||||
- хранение полной истории пользовательского блокчейна внутри Solana;
|
||||
- подключение Solana-модуля к сборке/деплою основного сервера SHiNE.
|
||||
Формат пользовательских SHiNE/Arweave блоков этим изменением не меняется.
|
||||
|
||||
@@ -2,156 +2,33 @@
|
||||
|
||||
## Кратко
|
||||
|
||||
`shine_users` — вторая программа Solana-модуля SHiNE. Она отвечает за создание и обновление пользовательской PDA-записи, проверку подписи записи, проверку логина через `shine_login_guard` и оплату регистрации/дополнительного лимита.
|
||||
`shine_users` создаёт и обновляет пользовательскую PDA SHiNE, проверяет authority/signature, логин через `shine_login_guard` и оплату регистрации/дополнительного лимита через `shine_payments`.
|
||||
|
||||
Папка программы: `shine-solana/shine/programs/shine_users/`.
|
||||
Текущий формат пользовательской записи — **PDA 1.2**. Каноническая бинарная спецификация находится в:
|
||||
|
||||
## Текущие функции
|
||||
- `shine-solana/shine/doc/formats/shine-user-pda-format-v.1.2.md`
|
||||
- `shine-solana/shine/doc/programs/shine_users.md`
|
||||
|
||||
1. `init_users_economy_config`
|
||||
- Создает PDA с экономическими настройками пользователей.
|
||||
- Записывает стартовую регистрационную комиссию, цену шага лимита и стартовый бонус лимита.
|
||||
Эти документы являются источником истины; здесь фиксируется только архитектурное резюме.
|
||||
|
||||
2. `update_users_economy_config`
|
||||
- Обновляет экономические настройки.
|
||||
- Требует подпись `DAO_AUTHORITY` из общего deploy-конфига.
|
||||
## PDA 1.2
|
||||
|
||||
3. `create_user_pda`
|
||||
- Проверяет логин через `shine_login_guard`.
|
||||
- Проверяет структуру полей пользователя.
|
||||
- Проверяет подпись записи root-ключом пользователя.
|
||||
- Создает `user_pda` по seed `login=<normalized_login>`.
|
||||
- Переводит оплату регистрации и дополнительного лимита в `shine_payments::inflow_vault_pda`.
|
||||
Основные данные:
|
||||
|
||||
4. `update_user_pda`
|
||||
- Проверяет неизменяемые поля пользователя.
|
||||
- Проверяет `prev_hash`, новую подпись и новое состояние последнего блока.
|
||||
- При необходимости расширяет PDA.
|
||||
- Переводит оплату дополнительного лимита в `shine_payments::inflow_vault_pda`.
|
||||
- `RootKeyBlock` — cold recovery authority;
|
||||
- `ClientKeyBlock` — клиентский/кошелёчный ключ;
|
||||
- `BlockchainRegistryBlock` — append-only список fork: `blockchain_key[32] + created_at_ms:u64 + paid_limit_bytes:u32`; последний fork активен;
|
||||
- необязательный `ServerProfileBlock` — в 1.2 ровно один адрес сервера;
|
||||
- необязательный `AccessServersBlock` — в 1.2 максимум один access server.
|
||||
|
||||
## Аргументы инструкций
|
||||
Из нового формата удалены `RecoveryKeyBlock`, `SessionsBlock`, `TrustedStateBlock`, `ArchiveHeadBlock`, `sync_servers` и поля вершины пользовательского blockchain. Сами пользовательские блоки и их история живут вне PDA; долговременное хранение/синхронизация выполняется через Arweave.
|
||||
|
||||
`init_users_economy_config` аргументов не принимает.
|
||||
Обычный update выполняется активным последним blockchain key и не может менять root. Root используется для recovery и может менять root. Внутри PDA сохраняются `record_number`, `prev_record_hash` и Ed25519-подпись нового состояния.
|
||||
|
||||
`update_users_economy_config`:
|
||||
Новый обычный fork можно добавить не раньше чем через 72 часа после `created_at_ms` текущего fork; root-recovery может обойти cooldown. Клиентский timestamp принимается только в окне ±5 минут относительно Solana Clock.
|
||||
|
||||
- `registration_fee_lamports: u64`
|
||||
- `lamports_per_limit_step: u64`
|
||||
- `start_bonus_limit: u64`
|
||||
Legacy PDA 1.0 не мигрируются. Для тестовых 1.0 аккаунтов предусмотрена временная инструкция `close_legacy_pda`, возвращающая lamports вызывающему signer.
|
||||
|
||||
`create_user_pda`:
|
||||
|
||||
- `login: String`
|
||||
- `root_key: Pubkey`
|
||||
- `created_at_ms: u64`
|
||||
- `additional_limit: u64`
|
||||
- `fields: UserMutableFields`
|
||||
- `signature: Vec<u8>`
|
||||
|
||||
`update_user_pda`:
|
||||
|
||||
- `login: String`
|
||||
- `root_key: Pubkey`
|
||||
- `created_at_ms: u64`
|
||||
- `updated_at_ms: u64`
|
||||
- `version: u32`
|
||||
- `prev_hash: Vec<u8>`
|
||||
- `additional_limit: u64`
|
||||
- `fields: UserMutableFields`
|
||||
- `signature: Vec<u8>`
|
||||
|
||||
`UserMutableFields`:
|
||||
|
||||
- `client_key: Pubkey`
|
||||
- `blockchain_public_key: Pubkey`
|
||||
- `blockchain_name: String`
|
||||
- `used_bytes: u64`
|
||||
- `last_block_number: u32`
|
||||
- `last_block_hash: Vec<u8>` — ровно 32 байта
|
||||
- `last_block_signature: Vec<u8>` — ровно 64 байта
|
||||
- `arweave_tx_id: String`
|
||||
- `is_server: bool`
|
||||
- `server_key: Pubkey`
|
||||
- `server_address: String`
|
||||
- `sync_servers: Vec<String>`
|
||||
- `access_servers: Vec<String>` — формат остаётся массивом, но runtime
|
||||
использует только первый элемент
|
||||
- `trusted_count: u8`
|
||||
|
||||
## Главные PDA
|
||||
|
||||
1. `user_pda`
|
||||
- PDA записи пользователя.
|
||||
- Seed: `login=<normalized_login>`.
|
||||
- Создается отдельно для каждого логина.
|
||||
- Стартовый размер: `768` байт.
|
||||
- При обновлении может расширяться через `realloc`, но один auto-realloc ограничен `10_000` байт.
|
||||
|
||||
2. `users_economy_config_pda`
|
||||
- PDA с настройками экономики.
|
||||
- Seed: `shine_users_economy_config`.
|
||||
- Хранит регистрационную комиссию, цену шага лимита и стартовый бонус.
|
||||
- Размер PDA: `8 + 96` байт.
|
||||
|
||||
## Текущие параметры экономики
|
||||
|
||||
Параметры initial config из `programs/shine_users/src/settings.rs`:
|
||||
|
||||
| Поле | Значение | Смысл |
|
||||
| --- | --- | --- |
|
||||
| `START_REGISTRATION_FEE_LAMPORTS` | `10_000_000` | стартовая комиссия регистрации, 0.01 SOL |
|
||||
| `LIMIT_STEP` | `10_000` | шаг `additional_limit` |
|
||||
| `START_LAMPORTS_PER_LIMIT_STEP` | `100_000` | 0.0001 SOL за один шаг лимита |
|
||||
| `START_BONUS_LIMIT` | `100_000` | стартовый бесплатный лимит при регистрации |
|
||||
|
||||
`additional_limit` в create/update должен быть кратен `LIMIT_STEP`.
|
||||
|
||||
## Связь с другими программами
|
||||
|
||||
`shine_users` зависит от:
|
||||
|
||||
- `shine_login_guard` — для проверки логина при создании пользователя;
|
||||
- `shine_payments` — для вычисления и проверки `inflow_vault_pda`, куда уходят платежи.
|
||||
|
||||
`create_user_pda` делает CPI-вызов `shine_login_guard::classify_login` и принимает только результат `0`. Premium/trademark логины сейчас отклоняются ошибками `PremiumLogin` или `TrademarkLoginRequiresReview`.
|
||||
|
||||
Подпись `user_pda` и подпись состояния последнего блока проверяются через встроенную Solana Ed25519-инструкцию, которая должна идти раньше инструкции `shine_users` в той же транзакции.
|
||||
|
||||
## Деньги
|
||||
|
||||
Деньги из `shine_users` идут только в `inflow_vault_pda` программы `shine_payments`.
|
||||
|
||||
Потоки:
|
||||
|
||||
- `create_user_pda`: регистрационная комиссия + оплата `additional_limit`;
|
||||
- `update_user_pda`: оплата `additional_limit`, если она больше нуля.
|
||||
|
||||
## Ключи и управление
|
||||
|
||||
На старте удобно считать, что у программы есть отдельный управляющий ключ `key_2`.
|
||||
|
||||
Целевая модель:
|
||||
|
||||
- economy-настройки меняет DAO-authority;
|
||||
- upgrade-authority программы после проверки передается DAO;
|
||||
- пользовательские операции `create_user_pda` и `update_user_pda` остаются доступными обычным пользователям при корректных подписях и оплате.
|
||||
|
||||
## ArchiveHeadBlock (legacy/reserved)
|
||||
|
||||
Формат User PDA поддерживает необязательный `ArchiveHeadBlock` (`block_type = 100`, `block_version = 0`):
|
||||
|
||||
```text
|
||||
archive_tx_id [32]
|
||||
archive_hash [32]
|
||||
```
|
||||
|
||||
Поле `ArchiveHeadBlock` осталось в Solana/PDA как legacy/reserved для совместимости формата PDA. Новый transport пользовательских блоков не использует server-level SHINE-ARCHIVE или archive head: каждый пользовательский block публикуется как ANS-104 DataItem внутри стандартных bundles.
|
||||
|
||||
Отдельной инструкции программы для архива нет. Используется существующий `update_user_pda`. Парсер update instruction обратно совместим:
|
||||
|
||||
- legacy payload без archive extension сохраняет старый block `100`;
|
||||
- новый payload может заменить/очистить archive head;
|
||||
- итоговая полная User PDA запись, включая block `100`, покрывается обычной root-подписью.
|
||||
|
||||
Это позволяет обычным старым клиентским обновлениям профиля не стирать archive head серверного publisher-а.
|
||||
## Экономика
|
||||
|
||||
Параметры экономики хранятся в `users_economy_config_pda`. `paid_limit_bytes` каждого fork — `u32`; старые fork-записи неизменяемы, пополняется только активный fork. Подробные формулы и ограничения описаны в документации программы.
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# Замечания к серверу и UI (найдено при редизайне)
|
||||
|
||||
Код по этим пунктам не менялся.
|
||||
|
||||
## Ошибки
|
||||
|
||||
1. **Лента «Подписки» пуста у логинов с заглавными буквами** (например `User_t2_03`).
|
||||
`Net_ListSubscriptionsFeed_Handler.loadFollowedChannels` ищет `connections_state.login = ?` в исходном регистре,
|
||||
а в `connections_state` логин хранится в нижнем регистре (FK на `solana_user_pda_current.normalized_login`).
|
||||
Подписки в базе есть, но `followedChannels` пуст. Отсюда же «подписка не срабатывает» в UI:
|
||||
кнопка не меняется на «Отписаться», канал не появляется в «Подписках».
|
||||
|
||||
2. **Превью в списке чатов — «Сообщение недоступно»**, хотя в самом чате сообщения расшифровываются.
|
||||
`messages-list.js` строит превью по `dialog.lastMessageBlobB64`, `catch` глушит настоящую ошибку.
|
||||
Проверить, не бывает ли так у реальных пользователей (например, если последнее сообщение отправлено с другого устройства).
|
||||
|
||||
3. **Прямой переход по адресу** `/settings`, `/profile`, `/channels/new` при загрузке страницы уводит на «Личные».
|
||||
|
||||
4. **`?localWsPort=` теряется при навигации**: после обновления страницы UI молча подключается к `shineup.me`.
|
||||
|
||||
## Безопасность / конфигурация
|
||||
|
||||
5. **Приватный ключ web-push в репозитории**: `SHiNE-server/src/main/resources/application.properties` → `webpush.vapid.private`.
|
||||
Если он совпадает с продовым — перевыпустить и убрать из git.
|
||||
|
||||
6. По умолчанию сервер представляется логином прода `server.SHiNE.login=shineupme` — при запуске вне прода легко перепутать.
|
||||
|
||||
## На будущее
|
||||
|
||||
7. **Каждое действие перерисовывает страницу целиком** (лайк → шапка на мгновение «Канал / Загрузка…», лента перестраивается),
|
||||
отсюда «дёрганье» при переходах назад. Нужны оптимистичные обновления (лайк/ответ меняют только свой элемент),
|
||||
кэш загруженных лент между переходами, обновление без полной перерисовки.
|
||||
|
||||
8. **Кэш модулей после деплоя.** Страницы в `js/app.js` подключаются с метками `?v=…`, а `js/components/*` и `js/services/*` — без меток,
|
||||
браузер может держать старую версию. Для изменённых страниц метки подняты до `?v=202609260900`;
|
||||
для остальных модулей стоит проверить заголовки кэширования или ввести общую метку версии, как у CSS и `app.js`.
|
||||
|
||||
## Не сделано в редизайне
|
||||
|
||||
- Автопроверка серверов в настройках.
|
||||
- Число подписчиков в шапке канала (нет в API).
|
||||
+13
-1
@@ -6,6 +6,7 @@
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-visual"
|
||||
/>
|
||||
<meta name="theme-color" content="#12141f" />
|
||||
<base href="/" />
|
||||
<link rel="manifest" href="./manifest.webmanifest" />
|
||||
<link rel="icon" type="image/jpeg" href="./img/logo.jpg" />
|
||||
@@ -24,6 +25,17 @@
|
||||
document.documentElement.dataset.themeMode = mode;
|
||||
document.documentElement.dataset.theme = resolved;
|
||||
document.documentElement.style.colorScheme = resolved;
|
||||
// Своя палитра (см. js/services/theme-service.js) применяется до отрисовки, без вспышки.
|
||||
try {
|
||||
const applied = JSON.parse(localStorage.getItem('shine-ui-palette-applied-v1') || 'null');
|
||||
const colors = applied && applied[resolved];
|
||||
if (colors) {
|
||||
Object.keys(colors).forEach(function (role) {
|
||||
if (/^#[0-9a-f]{6}$/i.test(colors[role])) document.documentElement.style.setProperty('--' + role, colors[role]);
|
||||
});
|
||||
if (colors.accent) document.documentElement.style.setProperty('--focus-ring', colors.accent);
|
||||
}
|
||||
} catch {}
|
||||
}());
|
||||
</script>
|
||||
<script>
|
||||
@@ -33,7 +45,7 @@ window.__SHINE_BUILD_HASH__ = '20260901134200';
|
||||
<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/avatar.css', './styles/components/modal.css', './styles/components/attachments.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/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/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/attachments.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'];
|
||||
cssFiles.forEach((file) => {
|
||||
const link = document.createElement('link');
|
||||
link.rel = 'stylesheet';
|
||||
|
||||
+19
-18
@@ -52,37 +52,37 @@ import {
|
||||
setContacts,
|
||||
} from './state.js';
|
||||
|
||||
import * as startView from './pages/start-view.js?v=202606142105';
|
||||
import * as entrySettingsView from './pages/entry-settings-view.js?v=202606161240';
|
||||
import * as registerView from './pages/register-view.js?v=202606201650';
|
||||
import * as registrationFaqView from './pages/registration-faq-view.js?v=202606201650';
|
||||
import * as startView from './pages/start-view.js?v=202609260900';
|
||||
import * as entrySettingsView from './pages/entry-settings-view.js?v=202609260900';
|
||||
import * as registerView from './pages/register-view.js?v=202609260900';
|
||||
import * as registrationFaqView from './pages/registration-faq-view.js?v=202609260900';
|
||||
import * as registrationPaymentView from './pages/registration-payment-view.js?v=202606180940';
|
||||
import * as registrationKeysView from './pages/registration-keys-view.js';
|
||||
import * as registrationDraftKeysView from './pages/registration-draft-keys-view.js';
|
||||
import * as topupView from './pages/topup-view.js';
|
||||
import * as devnetTopupView from './pages/devnet-topup-view.js';
|
||||
import * as loginView from './pages/login-view.js?v=202606150110';
|
||||
import * as loginView from './pages/login-view.js?v=202609260900';
|
||||
import * as loginCameraView from './pages/login-camera-view.js';
|
||||
import * as loginOtherDeviceView from './pages/login-other-device-view.js?v=202606180940';
|
||||
import * as loginPasswordView from './pages/login-password-view.js?v=202606201650';
|
||||
import * as keyStorageView from './pages/key-storage-view.js';
|
||||
import * as publicSupportQueueView from './pages/public-support-queue-view.js';
|
||||
|
||||
import * as profileView from './pages/profile-view.js?v=202607150910';
|
||||
import * as profileView from './pages/profile-view.js?v=202609260900';
|
||||
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=202606281930';
|
||||
import * as walletView from './pages/wallet-view.js?v=202609260900';
|
||||
import * as settingsView from './pages/settings-view.js';
|
||||
import * as accessServersView from './pages/access-servers-view.js';
|
||||
import * as developerSettingsView from './pages/developer-settings-view.js';
|
||||
import * as advancedSettingsView from './pages/advanced-settings-view.js';
|
||||
import * as serverSettingsView from './pages/server-settings-view.js?v=202606161240';
|
||||
import * as serverSettingsView from './pages/server-settings-view.js?v=202609260900';
|
||||
import * as arweaveUploadsView from './pages/arweave-uploads-view.js';
|
||||
import * as remoteAddBlockSessionView from './pages/remote-addblock-session-view.js?v=202606281300';
|
||||
import * as deviceView from './pages/device-view.js?v=202606131435';
|
||||
import * as deviceView from './pages/device-view.js?v=202609260900';
|
||||
import * as connectDeviceView from './pages/connect-device-view.js?v=202606142055';
|
||||
import * as clientPairingView from './pages/device-pairing-view.js?v=202606180940';
|
||||
import * as trustedDeviceLoginSettingsView from './pages/trusted-device-login-settings-view.js?v=202606180930';
|
||||
import * as clientPairingView from './pages/device-pairing-view.js?v=202609260900';
|
||||
import * as trustedDeviceLoginSettingsView from './pages/trusted-device-login-settings-view.js?v=202609260900';
|
||||
import { applyThemeMode, watchSystemTheme } from './services/theme-service.js';
|
||||
import * as deviceQrView from './pages/device-qr-view.js';
|
||||
import * as deviceCameraView from './pages/device-camera-view.js';
|
||||
@@ -93,21 +93,21 @@ 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=202608221218';
|
||||
import * as messagesList from './pages/messages-list.js?v=202609260900';
|
||||
import * as contactSearchView from './pages/contact-search-view.js';
|
||||
import * as chatView from './pages/chat-view.js?v=202608221218';
|
||||
import * as chatView from './pages/chat-view.js?v=202609260900';
|
||||
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';
|
||||
import * as channelsList from './pages/channels-list.js?v=202608221218';
|
||||
import * as channelsList from './pages/channels-list.js?v=202609260900';
|
||||
import * as channelView from './pages/channel-view.js';
|
||||
import * as channelAboutView from './pages/channel-about-view.js';
|
||||
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=202608221226';
|
||||
import * as notificationsView from './pages/notifications-view.js?v=202608221354';
|
||||
import * as networkView from './pages/network-view.js?v=202609260900';
|
||||
import * as notificationsView from './pages/notifications-view.js?v=202609260900';
|
||||
|
||||
const CONVERSATION_CLEAR_NOTICE_TEXT = 'История переписки очищена с этого места';
|
||||
const DM_UNSUPPORTED_FORMAT_TEXT = 'Формат сообщения не поддерживается';
|
||||
@@ -1417,7 +1417,8 @@ function renderApp() {
|
||||
try {
|
||||
const chrome = createChromeController(showAppChrome, page.pageMeta?.shellMode);
|
||||
currentChromeCleanup = () => chrome.dispose();
|
||||
if (showAppChrome) {
|
||||
// В переписке нижняя панель прячется (pageMeta.hideToolbar), чтобы не отнимать место у сообщений.
|
||||
if (showAppChrome && !page.pageMeta?.hideToolbar) {
|
||||
mountSlot(toolbarEl, '--toolbar-height', renderToolbar(page.pageMeta.id, navigate));
|
||||
toolbarHeightObserver?.sync?.();
|
||||
}
|
||||
@@ -1449,7 +1450,7 @@ function refreshToolbarOnly() {
|
||||
&& !(pageId === 'language-view' && !state.session.isAuthorized);
|
||||
|
||||
clearSlot(toolbarEl, '--toolbar-height');
|
||||
if (showAppChrome) {
|
||||
if (showAppChrome && !page.pageMeta?.hideToolbar) {
|
||||
mountSlot(toolbarEl, '--toolbar-height', renderToolbar(page.pageMeta.id, navigate));
|
||||
}
|
||||
toolbarHeightObserver?.sync?.();
|
||||
|
||||
@@ -434,20 +434,23 @@ export function openArweaveAttachmentManager({
|
||||
const solBalance = balanceInfo ? `${escapeHtml(String(balanceInfo.solBalance ?? 0))} SOL` : '—';
|
||||
const uploadPrice = priceInfo ? `${formatTurboCredits(priceInfo.credits, 6)} credits` : '—';
|
||||
const fileSize = selectedFile ? formatBytes(selectedFile.size) : '—';
|
||||
const freeHint = selectedFile
|
||||
? (combinedUploadSize() <= getFreeTurboUploadBytesLimit() ? 'Да, бесплатно через Turbo' : 'Нет, нужен Turbo balance')
|
||||
: `До ${formatBytes(getFreeTurboUploadBytesLimit())} бесплатно`;
|
||||
const freeBadge = priceInfo?.isFree
|
||||
? ' <span style="color:#15803d;">(пока файлы до 100 KB бесплатно)</span>'
|
||||
const isFreeSize = selectedFile && combinedUploadSize() <= getFreeTurboUploadBytesLimit();
|
||||
const summary = selectedFile
|
||||
? `Размер ${escapeHtml(fileSize)} · ${isFreeSize
|
||||
? '<span class="ar-attachment-ok">бесплатно через Turbo</span>'
|
||||
: `нужен баланс Turbo: ${escapeHtml(uploadPrice)}`}`
|
||||
: '';
|
||||
mainMetaEl.innerHTML = `
|
||||
<div>Turbo-адрес: ${escapeHtml(shortAddress(turboAddress || '—'))}</div>
|
||||
<div>Turbo balance: ${escapeHtml(turboCredits)}</div>
|
||||
<div>SOL на этом ключе: ${solBalance}</div>
|
||||
<div>Размер файла: ${escapeHtml(fileSize)}</div>
|
||||
<div>SHA-256: ${escapeHtml(selectedSha256 || '—')}</div>
|
||||
<div>Цена Turbo: ${escapeHtml(uploadPrice)}${freeBadge}</div>
|
||||
<div>До ${escapeHtml(formatBytes(getFreeTurboUploadBytesLimit()))} бесплатно: ${escapeHtml(freeHint)}</div>
|
||||
${summary ? `<div class="ar-attachment-summary">${summary}</div>` : ''}
|
||||
<details class="ar-attachment-details">
|
||||
<summary>Подробнее</summary>
|
||||
<div>Turbo-адрес: ${escapeHtml(shortAddress(turboAddress || '—'))}</div>
|
||||
<div>Баланс Turbo: ${escapeHtml(turboCredits)}</div>
|
||||
<div>SOL на этом ключе: ${solBalance}</div>
|
||||
<div>SHA-256: ${escapeHtml(selectedSha256 || '—')}</div>
|
||||
<div>Цена Turbo: ${escapeHtml(uploadPrice)}</div>
|
||||
<div>Бесплатно до ${escapeHtml(formatBytes(getFreeTurboUploadBytesLimit()))}</div>
|
||||
</details>
|
||||
`;
|
||||
previewMetaEl.innerHTML = '';
|
||||
if (selectedPreviewEnabled && selectedPreviewFile) {
|
||||
@@ -628,28 +631,40 @@ export function openArweaveAttachmentManager({
|
||||
root.innerHTML = `
|
||||
<div class="modal" data-ar-attach-modal="true">
|
||||
<div class="modal-card stack ar-attachment-manager-card">
|
||||
<h3 class="modal-title">${escapeHtml(titleText)}</h3>
|
||||
<p class="meta-muted" style="margin-top:-6px; color:#15803d;">Маленькие файлы и аватары через Turbo пока загружаются бесплатно.</p>
|
||||
<div class="form-actions-grid">
|
||||
<button class="${turboMode ? 'secondary-btn' : 'primary-btn'}" type="button" data-action="switch-arweave">Загрузка используя свой Arweave кошелёк</button>
|
||||
<button class="${turboMode ? 'primary-btn' : 'secondary-btn'}" type="button" data-action="switch-turbo">Загрузить через Turbo</button>
|
||||
${canShowHistory ? `<button class="secondary-btn" type="button" data-action="history-top">${isAvatarMode ? 'Выбрать из журнала' : 'Использовать журнал загрузок'}</button>` : ''}
|
||||
${canShowExisting ? `<button class="secondary-btn" type="button" data-action="existing-top">${isAvatarMode ? 'Ввести tx id' : 'Использовать существующий в Arweave файл'}</button>` : ''}
|
||||
<div class="ar-attachment-manager-head">
|
||||
<h3 class="modal-title">${escapeHtml(titleText)}</h3>
|
||||
<button class="icon-btn ar-attachment-manager-close" type="button" data-action="cancel" aria-label="Закрыть">✕</button>
|
||||
</div>
|
||||
<div class="tabs tabs--auto" role="radiogroup" aria-label="Способ загрузки">
|
||||
<button class="tab-btn" role="radio" aria-checked="${turboMode}" type="button" data-action="switch-turbo">Turbo</button>
|
||||
<button class="tab-btn" role="radio" aria-checked="${!turboMode}" type="button" data-action="switch-arweave">Свой кошелёк Arweave</button>
|
||||
</div>
|
||||
${turboMode
|
||||
? `
|
||||
<label class="meta-muted" for="turbo-key-source">Подписывать и пополнять через</label>
|
||||
<select class="input ar-attachment-wallet-select" id="turbo-key-source"></select>
|
||||
<p class="meta-muted">Turbo использует Solana-ключ пользователя. Маленькие файлы и аватары пока бесплатно. Если файл больше, пополните Turbo со своего SOL-кошелька.</p>
|
||||
<p class="ar-attachment-note">Маленькие файлы и аватары через Turbo пока загружаются бесплатно. Для больших файлов пополните Turbo со своего SOL-кошелька.</p>
|
||||
<div class="form-field">
|
||||
<label for="turbo-key-source">Подписывать и пополнять через</label>
|
||||
<select class="select ar-attachment-wallet-select" id="turbo-key-source"></select>
|
||||
</div>
|
||||
`
|
||||
: `
|
||||
<label class="meta-muted" for="ar-attach-wallet">Кошелёк оплаты Arweave</label>
|
||||
<select class="input ar-attachment-wallet-select" id="ar-attach-wallet"></select>
|
||||
<button class="ghost-btn" type="button" data-action="add-wallet">Добавить кошелёк</button>
|
||||
${isAvatarMode ? '<p class="meta-muted">Выберите изображение. Перед загрузкой оно будет сжато до 512×512 и сохранено в истории как аватар.</p>' : (historyOnly ? '' : '<p class="meta-muted">Для надёжности лучше сначала загрузить файл в Arweave, дождаться доступности в журнале, а потом добавить его из истории загрузок.</p>')}
|
||||
<div class="form-field">
|
||||
<label for="ar-attach-wallet">Кошелёк оплаты Arweave</label>
|
||||
<select class="select ar-attachment-wallet-select" id="ar-attach-wallet"></select>
|
||||
<button class="text-btn ar-attachment-link" type="button" data-action="add-wallet">+ Добавить кошелёк</button>
|
||||
</div>
|
||||
${isAvatarMode ? '<p class="ar-attachment-note">Выберите изображение. Перед загрузкой оно будет сжато до 512×512 и сохранено в истории как аватар.</p>' : (historyOnly ? '' : '<p class="ar-attachment-note">Для надёжности лучше сначала загрузить файл в Arweave, дождаться доступности в журнале, а потом добавить его из истории загрузок.</p>')}
|
||||
`}
|
||||
${fixedFile ? '' : '<label class="meta-muted" for="ar-attach-file">Файл для загрузки</label>'}
|
||||
${fixedFile ? '' : `<input class="input" id="ar-attach-file" type="file" ${isAvatarMode ? 'accept="image/*"' : ''} />`}
|
||||
${canShowHistory || canShowExisting ? `
|
||||
<div class="ar-attachment-alt-sources">
|
||||
${canShowHistory ? `<button class="text-btn ar-attachment-link" type="button" data-action="history-top">${isAvatarMode ? 'Выбрать из журнала' : 'Из журнала загрузок'}</button>` : ''}
|
||||
${canShowExisting ? `<button class="text-btn ar-attachment-link" type="button" data-action="existing-top">${isAvatarMode ? 'Ввести tx id' : 'Уже есть в Arweave (tx id)'}</button>` : ''}
|
||||
</div>` : ''}
|
||||
${fixedFile ? '' : `<label class="ar-attachment-file-picker">
|
||||
<input class="ar-attachment-file-input" id="ar-attach-file" type="file" ${isAvatarMode ? 'accept="image/*"' : ''} />
|
||||
<span class="ar-attachment-file-btn">Выбрать файл</span>
|
||||
<span class="ar-attachment-file-name" data-file-name="true">Файл не выбран</span>
|
||||
</label>`}
|
||||
<div class="ar-attachment-meta" data-meta-main="true"></div>
|
||||
<label class="meta-muted" data-preview-option="true" hidden>
|
||||
<input type="checkbox" data-preview-toggle="true" />
|
||||
@@ -658,10 +673,9 @@ export function openArweaveAttachmentManager({
|
||||
<div class="ar-attachment-meta" data-meta-preview="true"></div>
|
||||
<p class="meta-muted inline-error" data-error="true"></p>
|
||||
<div class="form-actions-grid">
|
||||
${turboMode ? '<button class="secondary-btn" type="button" data-action="topup">Пополнить Turbo</button>' : ''}
|
||||
${turboMode ? '<button class="secondary-btn" type="button" data-action="topup">Пополнить Turbo</button>' : '<button class="secondary-btn" type="button" data-action="cancel">Отмена</button>'}
|
||||
<button class="primary-btn" type="button" data-action="upload" disabled>${escapeHtml(uploadText)}</button>
|
||||
</div>
|
||||
<button class="secondary-btn" type="button" data-action="cancel">Отмена</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
@@ -734,7 +748,7 @@ export function openArweaveAttachmentManager({
|
||||
}
|
||||
}
|
||||
|
||||
root.querySelector('[data-action="cancel"]')?.addEventListener('click', () => close(resolve, null));
|
||||
root.querySelectorAll('[data-action="cancel"]').forEach((btn) => btn.addEventListener('click', () => close(resolve, null)));
|
||||
root.querySelector('[data-action="topup"]')?.addEventListener('click', async () => {
|
||||
await promptTurboTopUp(mainMetaEl, previewMetaEl, errorEl);
|
||||
if (turboMode && selectedFile && selectedSha256) {
|
||||
@@ -745,6 +759,10 @@ export function openArweaveAttachmentManager({
|
||||
root.querySelector('[data-action="add-wallet"]')?.addEventListener('click', showAddWallet);
|
||||
}
|
||||
|
||||
fileEl?.addEventListener('change', () => {
|
||||
const nameEl = root.querySelector('[data-file-name="true"]');
|
||||
if (nameEl) nameEl.textContent = fileEl.files?.[0]?.name || 'Файл не выбран';
|
||||
});
|
||||
fileEl?.addEventListener('change', async () => {
|
||||
selectedFile = fileEl.files?.[0] || null;
|
||||
selectedSha256 = '';
|
||||
@@ -1041,7 +1059,7 @@ export function openArweaveAttachmentManager({
|
||||
<span>${escapeHtml(formatArweaveHistoryTime(item.uploadedAtMs))}</span>
|
||||
${hasAttachmentPreview(item) ? '<span class="ar-attachment-placement-flag">С превью</span>' : ''}
|
||||
<span class="ar-attachment-status ar-attachment-status--pending" data-status="${index}">Проверяем...</span>
|
||||
${item.pendingPlacement ? '<span class="ar-attachment-placement-flag">Не добавлен в SHiNE</span>' : ''}
|
||||
${item.pendingPlacement ? '<span class="ar-attachment-placement-flag">Ещё не прикреплён</span>' : ''}
|
||||
</div>
|
||||
<div class="mono-cell ar-attachment-history-txid">${escapeHtml(item.ar)}</div>
|
||||
<button class="${isSelected ? 'secondary-btn' : 'ghost-btn'}" type="button" data-pick="${index}" ${isSelected ? 'disabled' : ''}>${isSelected ? 'Уже добавлен ✓' : 'Выбрать'}</button>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
import { markArweaveAttachmentPlaced, openArweaveAttachmentManager } from './arweave-attachment-manager.js';
|
||||
import { composeMessageWithAttachments, MAX_MESSAGE_ATTACHMENTS } from '../services/attachment-format.js';
|
||||
import { state } from '../state.js';
|
||||
@@ -133,7 +134,6 @@ export function openChannelEditor({
|
||||
authorName.textContent = login || 'Гость';
|
||||
author.append(authorName);
|
||||
body.append(author);
|
||||
if (extraControl instanceof Node) body.append(extraControl);
|
||||
body.append(textarea, attachmentsBox, error, clearButton);
|
||||
|
||||
const footer = document.createElement('footer');
|
||||
@@ -141,7 +141,8 @@ export function openChannelEditor({
|
||||
const attachButton = document.createElement('button');
|
||||
attachButton.type = 'button';
|
||||
attachButton.className = 'secondary-btn channel-editor__attach';
|
||||
attachButton.textContent = 'Прикрепить';
|
||||
attachButton.innerHTML = `${iconHtml('clip')}<span class="sr-only">Прикрепить</span>`;
|
||||
attachButton.title = 'Прикрепить файл';
|
||||
attachButton.hidden = !allowAttachments;
|
||||
const counter = document.createElement('span');
|
||||
counter.className = 'channel-editor__counter';
|
||||
@@ -151,6 +152,10 @@ export function openChannelEditor({
|
||||
submitButton.textContent = submitLabel;
|
||||
submitButton.title = 'Отправить · Ctrl+Enter / ⌘+Enter';
|
||||
footer.append(attachButton);
|
||||
if (extraControl instanceof Node) {
|
||||
footer.classList.add('has-extra');
|
||||
footer.append(extraControl);
|
||||
}
|
||||
footer.append(counter, submitButton);
|
||||
dialog.append(header, body, footer);
|
||||
overlay.append(dialog);
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// Возвращает Promise<boolean>: true — подтвердили, false — отмена, Escape или тап мимо.
|
||||
export function confirmDialog({
|
||||
title = 'Подтвердите действие',
|
||||
text = '',
|
||||
confirmLabel = 'Да',
|
||||
cancelLabel = 'Отмена',
|
||||
danger = false,
|
||||
} = {}) {
|
||||
return new Promise((resolve) => {
|
||||
const opener = document.activeElement;
|
||||
const modal = document.createElement('div');
|
||||
modal.className = 'modal confirm-dialog';
|
||||
modal.innerHTML = `
|
||||
<div class="modal-card confirm-dialog__card" role="alertdialog" aria-modal="true" aria-labelledby="confirm-dialog-title">
|
||||
<h2 class="modal-title" id="confirm-dialog-title"></h2>
|
||||
<p class="confirm-dialog__text"></p>
|
||||
<div class="form-actions-grid">
|
||||
<button type="button" class="secondary-btn" data-answer="no"></button>
|
||||
<button type="button" class="${danger ? 'destructive-btn confirm-dialog__danger' : 'primary-btn'}" data-answer="yes"></button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
modal.querySelector('.modal-title').textContent = title;
|
||||
const textEl = modal.querySelector('.confirm-dialog__text');
|
||||
textEl.textContent = text;
|
||||
textEl.hidden = !text;
|
||||
modal.querySelector('[data-answer="no"]').textContent = cancelLabel;
|
||||
modal.querySelector('[data-answer="yes"]').textContent = confirmLabel;
|
||||
|
||||
const finish = (answer) => {
|
||||
document.removeEventListener('keydown', onKeydown, true);
|
||||
modal.remove();
|
||||
opener?.focus?.();
|
||||
resolve(answer);
|
||||
};
|
||||
const onKeydown = (event) => {
|
||||
if (event.key === 'Escape') { event.stopPropagation(); finish(false); }
|
||||
};
|
||||
modal.addEventListener('click', (event) => {
|
||||
if (event.target === modal) { finish(false); return; }
|
||||
const answer = event.target.closest('[data-answer]')?.dataset.answer;
|
||||
if (answer) finish(answer === 'yes');
|
||||
});
|
||||
document.addEventListener('keydown', onKeydown, true);
|
||||
document.body.append(modal);
|
||||
modal.querySelector('[data-answer="no"]').focus();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
// Редактор точной настройки палитры.
|
||||
import {
|
||||
PALETTE_PRESETS,
|
||||
PALETTE_ROLES,
|
||||
exportPalette,
|
||||
getPaletteSettings,
|
||||
importPalette,
|
||||
resolvePalette,
|
||||
resolveThemeMode,
|
||||
setPaletteSettings,
|
||||
} from '../services/theme-service.js';
|
||||
|
||||
export function openPaletteEditor({ theme = resolveThemeMode(), onClose } = {}) {
|
||||
let editTheme = theme === 'light' ? 'light' : 'dark';
|
||||
const opener = document.activeElement;
|
||||
|
||||
const modal = document.createElement('div');
|
||||
modal.className = 'modal palette-editor';
|
||||
modal.innerHTML = `
|
||||
<div class="modal-card palette-editor__card" role="dialog" aria-modal="true" aria-labelledby="palette-editor-title">
|
||||
<div class="palette-editor__head">
|
||||
<h2 class="modal-title" id="palette-editor-title">Цвета оформления</h2>
|
||||
<button class="icon-btn palette-editor__close" type="button" aria-label="Закрыть">✕</button>
|
||||
</div>
|
||||
<div class="palette-editor__section">
|
||||
<span class="palette-editor__label">Основа</span>
|
||||
<select class="input palette-editor__presets" aria-label="Готовая цветовая тема"></select>
|
||||
<div class="palette-editor__preview" aria-hidden="true"><span></span><span></span><span></span><span></span></div>
|
||||
</div>
|
||||
<div class="palette-editor__section">
|
||||
<span class="palette-editor__label">Настраиваемая тема</span>
|
||||
<div class="tabs tabs--auto" role="radiogroup" aria-label="Тема для настройки">
|
||||
<button type="button" class="tab-btn" role="radio" data-edit-theme="light">День</button>
|
||||
<button type="button" class="tab-btn" role="radio" data-edit-theme="dark">Ночь</button>
|
||||
</div>
|
||||
<p class="palette-editor__hint">Правки видны сразу. Меняется только выбранная тема.</p>
|
||||
</div>
|
||||
<div class="palette-editor__roles"></div>
|
||||
<details class="palette-editor__share">
|
||||
<summary>Поделиться палитрой</summary>
|
||||
<p class="palette-editor__hint">Скопируйте текст и отправьте команде или вставьте чужую палитру и нажмите «Применить».</p>
|
||||
<textarea class="input palette-editor__json" rows="8" spellcheck="false"></textarea>
|
||||
<p class="palette-editor__error" role="alert" hidden></p>
|
||||
<div class="palette-editor__actions">
|
||||
<button type="button" class="secondary-btn" data-action="copy">Скопировать</button>
|
||||
<button type="button" class="secondary-btn" data-action="import">Применить</button>
|
||||
</div>
|
||||
</details>
|
||||
<div class="palette-editor__actions">
|
||||
<button type="button" class="secondary-btn" data-action="reset-theme">Сбросить эту тему</button>
|
||||
<button type="button" class="primary-btn" data-action="done">Готово</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const card = modal.querySelector('.palette-editor__card');
|
||||
const presetsEl = modal.querySelector('.palette-editor__presets');
|
||||
const rolesEl = modal.querySelector('.palette-editor__roles');
|
||||
const jsonEl = modal.querySelector('.palette-editor__json');
|
||||
const errorEl = modal.querySelector('.palette-editor__error');
|
||||
|
||||
for (const [id, preset] of Object.entries(PALETTE_PRESETS)) {
|
||||
const option = document.createElement('option');
|
||||
option.value = id;
|
||||
option.textContent = preset.label;
|
||||
presetsEl.append(option);
|
||||
}
|
||||
|
||||
const update = (mutate) => {
|
||||
const settings = getPaletteSettings();
|
||||
const next = { preset: settings.preset, custom: { dark: { ...settings.custom.dark }, light: { ...settings.custom.light } } };
|
||||
mutate(next);
|
||||
setPaletteSettings(next);
|
||||
render();
|
||||
};
|
||||
|
||||
function render() {
|
||||
const settings = getPaletteSettings();
|
||||
const colors = resolvePalette(editTheme, settings);
|
||||
const custom = settings.custom[editTheme];
|
||||
presetsEl.value = settings.preset;
|
||||
modal.querySelectorAll('.palette-editor__preview span').forEach((swatch, index) => {
|
||||
swatch.style.backgroundColor = [colors.background, colors.surface, colors.accent, colors['surface-selected']][index];
|
||||
});
|
||||
modal.querySelectorAll('[data-edit-theme]').forEach((btn) => {
|
||||
btn.setAttribute('aria-checked', String(btn.dataset.editTheme === editTheme));
|
||||
});
|
||||
rolesEl.replaceChildren(...PALETTE_ROLES.map((role) => {
|
||||
const row = document.createElement('label');
|
||||
row.className = 'palette-editor__role';
|
||||
const changed = Boolean(custom[role.id]);
|
||||
row.innerHTML = `
|
||||
<input type="color" value="${colors[role.id]}" aria-label="${role.label}">
|
||||
<span class="palette-editor__role-name">${role.label}${changed ? ' <span class="palette-editor__changed">изменён</span>' : ''}</span>
|
||||
<code class="palette-editor__role-value">${colors[role.id]}</code>
|
||||
`;
|
||||
const input = row.querySelector('input');
|
||||
input.addEventListener('input', () => {
|
||||
document.documentElement.style.setProperty(`--${role.id}`, input.value);
|
||||
row.querySelector('code').textContent = input.value;
|
||||
});
|
||||
input.addEventListener('change', () => update((next) => { next.custom[editTheme][role.id] = input.value; }));
|
||||
return row;
|
||||
}));
|
||||
jsonEl.value = exportPalette();
|
||||
errorEl.hidden = true;
|
||||
}
|
||||
|
||||
const close = () => {
|
||||
document.removeEventListener('keydown', onKeydown);
|
||||
modal.remove();
|
||||
opener?.focus?.();
|
||||
onClose?.();
|
||||
};
|
||||
const onKeydown = (event) => { if (event.key === 'Escape') close(); };
|
||||
|
||||
modal.addEventListener('click', async (event) => {
|
||||
if (event.target === modal) { close(); return; }
|
||||
// data-edit-theme, а не data-theme: data-theme стоит на <html>, и closest() находил бы его при любом клике.
|
||||
const themeBtn = event.target.closest('[data-edit-theme]');
|
||||
if (themeBtn) { editTheme = themeBtn.dataset.editTheme; render(); return; }
|
||||
if (event.target.closest('.palette-editor__close')) { close(); return; }
|
||||
const action = event.target.closest('[data-action]')?.dataset.action;
|
||||
if (action === 'done') close();
|
||||
if (action === 'reset-theme') update((next) => { next.custom[editTheme] = {}; });
|
||||
if (action === 'copy') {
|
||||
try {
|
||||
await navigator.clipboard.writeText(jsonEl.value);
|
||||
} catch {
|
||||
jsonEl.select();
|
||||
}
|
||||
}
|
||||
if (action === 'import') {
|
||||
try {
|
||||
importPalette(jsonEl.value);
|
||||
render();
|
||||
} catch {
|
||||
errorEl.textContent = 'Не удалось прочитать палитру: проверьте, что текст скопирован целиком.';
|
||||
errorEl.hidden = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
presetsEl.addEventListener('change', () => update((next) => {
|
||||
next.preset = presetsEl.value;
|
||||
next.custom = { dark: {}, light: {} };
|
||||
}));
|
||||
document.addEventListener('keydown', onKeydown);
|
||||
|
||||
render();
|
||||
document.body.append(modal);
|
||||
card.querySelector('.palette-editor__close').focus();
|
||||
return close;
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// data-profile-list / data-self-profile-action / data-profile-action обрабатывают profile-view.js и user-profile-view.js.
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
|
||||
export function escapeProfileHtml(text) {
|
||||
return String(text || '')
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
|
||||
const esc = escapeProfileHtml;
|
||||
|
||||
function statusChip({ kind, label, value, active }) {
|
||||
const n = Number(value || 0);
|
||||
return `
|
||||
<button type="button" class="pf-status${active ? ' is-active' : ''}" data-profile-list="${esc(kind)}"
|
||||
aria-label="${esc(label)}: подтверждений ${n}" title="Статус «${esc(label)}». Число — сколько людей его подтвердили. Нажмите, чтобы увидеть кто.">
|
||||
<span class="pf-status-dot" aria-hidden="true"></span>${esc(label)}${n > 0 ? `<b>${n}</b>` : ''}
|
||||
</button>`;
|
||||
}
|
||||
|
||||
function statHtml({ kind, label, valueHtml, ariaLabel }) {
|
||||
return `
|
||||
<button type="button" class="pf-stat" data-profile-list="${esc(kind)}" aria-label="${esc(ariaLabel)}">
|
||||
<span class="pf-stat-value">${valueHtml}</span>
|
||||
<span class="pf-stat-label">${esc(label)}</span>
|
||||
</button>`;
|
||||
}
|
||||
|
||||
function contactRows(card) {
|
||||
return [
|
||||
['Ссылки', card?.web],
|
||||
['Телефон', card?.phone],
|
||||
['Адрес', card?.address],
|
||||
]
|
||||
.filter(([, value]) => String(value || '').trim())
|
||||
.map(([label, value]) => `
|
||||
<div class="pf-row">
|
||||
<span class="pf-row-label">${esc(label)}</span>
|
||||
<span class="pf-row-value">${esc(value)}</span>
|
||||
</div>`)
|
||||
.join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} opts
|
||||
* @param {object} opts.card карточка профиля (loadUserProfileCard)
|
||||
* @param {string} opts.login логин на случай, если в карточке его нет
|
||||
* @param {string} opts.tilesHtml плитки действий (свои/чужие)
|
||||
* @param {string} [opts.tilesWrapClass] доп. класс обёртки плиток (для меню «Добавить»)
|
||||
* @param {string} [opts.beforeTilesHtml] разметка внутри обёртки перед плитками
|
||||
*/
|
||||
export function profileCardHtml({ card, login = '', tilesHtml = '', tilesWrapClass = '', beforeTilesHtml = '', isSelf = true }) {
|
||||
const stats = card?.stats || {};
|
||||
const official = card?.accountRole === 'primary';
|
||||
const shining = card?.shineStatus === 'shining';
|
||||
const cardLogin = card?.login || login;
|
||||
const fullName = [card?.firstName, card?.lastName].map((v) => String(v || '').trim()).filter(Boolean).join(' ');
|
||||
const displayName = fullName || cardLogin || 'Профиль';
|
||||
const about = String(card?.about || '').trim();
|
||||
const spiritualPath = String(card?.spiritualPath || '').trim();
|
||||
const contacts = contactRows(card);
|
||||
const aboutRow = (about || isSelf) ? `
|
||||
<div class="pf-row pf-row--block">
|
||||
<span class="pf-row-label">О себе</span>
|
||||
<p class="pf-row-text${about ? '' : ' is-empty'}">${esc(about || 'Не заполнено')}</p>
|
||||
</div>` : '';
|
||||
const pathRow = spiritualPath ? `
|
||||
<div class="pf-row pf-row--block">
|
||||
<span class="pf-row-label">Духовный путь</span>
|
||||
<p class="pf-row-text">${esc(spiritualPath)}</p>
|
||||
</div>` : '';
|
||||
const listInner = aboutRow + contacts + pathRow;
|
||||
const listHtml = listInner.trim() ? `<div class="pf-list">${listInner}</div>` : '';
|
||||
const friends = Number(stats.friendsCount || 0);
|
||||
const statusChips = [
|
||||
(official || Number(stats.primaryReceivedCount || 0) > 0) && statusChip({ kind: 'primary_received', label: 'Официальный', value: stats.primaryReceivedCount, active: official }),
|
||||
(shining || Number(stats.shineReceivedCount || 0) > 0) && statusChip({ kind: 'shine_received', label: 'Сияющий', value: stats.shineReceivedCount, active: shining }),
|
||||
].filter(Boolean);
|
||||
const statusesHtml = statusChips.length ? `<div class="pf-statuses">${statusChips.join('')}</div>` : '';
|
||||
const closeFriends = Number(stats.closeFriendsCount || 0);
|
||||
|
||||
return `
|
||||
<div class="pf-hero${shining ? ' is-shining' : ''}" aria-label="Профиль ${esc(cardLogin)}">
|
||||
<div class="pf-avatar user-profile-avatar-slot"></div>
|
||||
<h2 class="pf-name">${esc(displayName)}</h2>
|
||||
<div class="pf-login">@${esc(cardLogin)}</div>
|
||||
${statusesHtml}
|
||||
</div>
|
||||
|
||||
<div class="pf-stats">
|
||||
${statHtml({ kind: 'friends', label: 'Друзья', valueHtml: closeFriends ? `${friends}<small> · ${closeFriends} близк.</small>` : String(friends), ariaLabel: `Друзья: ${friends}, близкие: ${closeFriends}` })}
|
||||
${statHtml({ kind: 'channels_owned', label: 'Каналы', valueHtml: String(Number(stats.ownedPublicChannelsCount || 0)), ariaLabel: `Каналы: ${Number(stats.ownedPublicChannelsCount || 0)}` })}
|
||||
${statHtml({ kind: 'channels_following', label: 'Подписки', valueHtml: String(Number(stats.followingChannelsCount || 0)), ariaLabel: `Подписки: ${Number(stats.followingChannelsCount || 0)}` })}
|
||||
</div>
|
||||
|
||||
${tilesHtml ? `
|
||||
<div class="pf-tiles-wrap user-profile-actions-wrap ${esc(tilesWrapClass)}">
|
||||
${beforeTilesHtml}
|
||||
<div class="pf-tiles user-profile-actions">${tilesHtml}</div>
|
||||
</div>` : ''}
|
||||
|
||||
${listHtml}`;
|
||||
}
|
||||
|
||||
export function profileTileHtml({ icon, label, attrs = '', iconMarkup = '' }) {
|
||||
return `<button type="button" class="pf-tile user-profile-action-btn" ${attrs}>${iconMarkup || iconHtml(icon)}<span>${esc(label)}</span></button>`;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
function resolveElement(value) {
|
||||
return typeof value === 'function' ? value() : value;
|
||||
}
|
||||
@@ -6,7 +7,7 @@ function buildArrowIcon() {
|
||||
const icon = document.createElement('span');
|
||||
icon.className = 'scroll-to-bottom-btn__icon';
|
||||
icon.setAttribute('aria-hidden', 'true');
|
||||
icon.textContent = '↓';
|
||||
icon.innerHTML = iconHtml('down');
|
||||
return icon;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,28 @@
|
||||
import { resolveToolbarActive } from '../router.js';
|
||||
import { state, authService } from '../state.js';
|
||||
import { openAuthRequiredModal } from '../services/auth-required-modal.js';
|
||||
import { iconHtml as lineIcon } from './ui-icon.js';
|
||||
import { SHINE_CONNECTIONS_LOGO_SRC } from './shine-logo.js';
|
||||
|
||||
const TOOLBAR_ICONS = {
|
||||
'messages-list': '<g transform="translate(12 12) scale(.88) translate(-11.5 -13)"><path d="M21 11.5a8.5 8.5 0 0 1-8.5 8.5H4l-2 2v-9.5A8.5 8.5 0 0 1 10.5 4H13a8 8 0 0 1 8 7.5Z"/><circle cx="8" cy="12" r="1.05" class="toolbar-svg-dot"/><circle cx="11.7" cy="12" r="1.05" class="toolbar-svg-dot"/><circle cx="15.4" cy="12" r="1.05" class="toolbar-svg-dot"/></g>',
|
||||
'channels-list': '<rect x="4" y="3" width="16" height="18" rx="3"/><path d="M8 8h8M8 12h8M8 16h5"/>',
|
||||
'notifications-view': '<path d="M6.2 16.8V11a5.8 5.8 0 0 1 11.6 0v5.8l1.7 1.7h-15Z"/><path d="M10.2 21a2 2 0 0 0 3.6 0"/>',
|
||||
'profile-view': '<circle cx="12" cy="6.8" r="3.6"/><path d="M4.4 21v-2.1a5.6 5.6 0 0 1 5.6-5.6h4a5.6 5.6 0 0 1 5.6 5.6V21Z"/>',
|
||||
};
|
||||
|
||||
const ITEMS = [
|
||||
{ pageId: 'messages-list', label: 'Личные' },
|
||||
{ pageId: 'channels-list', label: 'Каналы' },
|
||||
{ pageId: 'network-view', label: 'Связи' },
|
||||
{ pageId: 'network-view', label: 'Связи', mandala: true },
|
||||
{ pageId: 'notifications-view', label: 'Уведомления' },
|
||||
{ pageId: 'profile-view', label: 'Профиль' },
|
||||
];
|
||||
|
||||
function iconHtml(item) {
|
||||
const names = { 'messages-list': 'message', 'channels-list': 'channels', 'network-view': 'network', 'notifications-view': 'bell', 'profile-view': 'profile' };
|
||||
return lineIcon(names[item.pageId]);
|
||||
function iconHtml(item, extra = '') {
|
||||
const glyph = item.mandala
|
||||
? `<img class="toolbar-mandala" src="${SHINE_CONNECTIONS_LOGO_SRC}" alt="" aria-hidden="true" />`
|
||||
: `<svg class="toolbar-svg" viewBox="0 0 24 24" aria-hidden="true">${TOOLBAR_ICONS[item.pageId]}</svg>`;
|
||||
return `<span class="toolbar-icon${item.mandala ? ' toolbar-icon--mandala' : ''}">${glyph}${extra}</span>`;
|
||||
}
|
||||
|
||||
function normalizeCounters(payload = {}) {
|
||||
@@ -44,7 +54,7 @@ function renderBadge(btn, count, ariaLabel, extraClass = '') {
|
||||
if (!badge) {
|
||||
badge = document.createElement('span');
|
||||
badge.className = `toolbar-unread-badge${extraClass ? ` ${extraClass}` : ''}`;
|
||||
btn.append(badge);
|
||||
(btn.querySelector('.toolbar-icon') || btn).append(badge);
|
||||
}
|
||||
badge.textContent = count > 99 ? '99+' : String(count);
|
||||
badge.setAttribute('aria-label', `${ariaLabel}: ${count}`);
|
||||
@@ -127,21 +137,17 @@ export function renderToolbar(currentPageId, navigate) {
|
||||
btn.className = `toolbar-btn${item.pageId === active ? ' active' : ''}${isProfile ? ' toolbar-btn-profile' : ''}${isMessages ? ' toolbar-btn-messages' : ''}${isNetwork ? ' toolbar-btn-network' : ''}${item.hero ? ' toolbar-btn-hero' : ''}`;
|
||||
if (isProfile) {
|
||||
btn.innerHTML = `
|
||||
${iconHtml(item)}
|
||||
<span class="toolbar-label-wrap">
|
||||
<span>${item.label}</span>
|
||||
<span id="toolbar-connection-indicator" class="toolbar-connection-indicator is-unknown">
|
||||
${iconHtml(item, `<span id="toolbar-connection-indicator" class="toolbar-connection-indicator is-unknown">
|
||||
<span class="toolbar-connection-dot" aria-hidden="true"></span>
|
||||
</span>
|
||||
</span>
|
||||
</span>`)}
|
||||
<span class="sr-only">${item.label}</span>
|
||||
`;
|
||||
} else if (isNetwork) {
|
||||
btn.innerHTML = `${iconHtml(item)}<span>${item.label}</span>`;
|
||||
btn.setAttribute('aria-label', item.label);
|
||||
btn.title = item.label;
|
||||
btn.innerHTML = `${iconHtml(item)}<span class="sr-only">${item.label}</span>`;
|
||||
} else {
|
||||
btn.innerHTML = `${iconHtml(item)}<span>${item.label}</span>`;
|
||||
btn.innerHTML = `${iconHtml(item)}<span class="sr-only">${item.label}</span>`;
|
||||
}
|
||||
btn.title = item.label;
|
||||
if (isMessages) renderBadge(btn, counters.dmUnreadCount, 'Непрочитанных личных сообщений');
|
||||
if (item.pageId === 'channels-list') renderBadge(btn, counters.channelsUnreadCount, 'Непрочитанных сообщений в каналах');
|
||||
if (isNotifications) renderBadge(btn, counters.notificationsUnreadCount, 'Новых уведомлений', 'notification-toolbar-badge');
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
import { createDropdownMenu } from './dropdown-menu.js';
|
||||
|
||||
function appendNode(target, node) {
|
||||
@@ -15,6 +16,8 @@ function createActionButton(action = {}, cleanupFns) {
|
||||
|
||||
if (action.iconNode instanceof Node) {
|
||||
button.append(action.iconNode);
|
||||
} else if (action.icon) {
|
||||
button.innerHTML = iconHtml(action.icon);
|
||||
} else {
|
||||
button.textContent = String(action.label ?? '');
|
||||
}
|
||||
@@ -56,7 +59,7 @@ export function createTopBar({
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = `icon-btn topbar__back${backAction.className ? ` ${backAction.className}` : ''}`;
|
||||
button.textContent = '←';
|
||||
button.innerHTML = iconHtml('back');
|
||||
button.setAttribute('aria-label', backAction.ariaLabel || 'Назад');
|
||||
button.title = backAction.title || 'Назад';
|
||||
button.addEventListener('click', backAction.onClick);
|
||||
|
||||
@@ -7,6 +7,20 @@ const paths = {
|
||||
profile: '<circle cx="12" cy="7" r="4"/><path d="M4 21v-2a8 8 0 0 1 16 0v2"/>',
|
||||
share: '<path d="m8 12 8-8M9 4h7v7M20 14v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/>',
|
||||
search: '<circle cx="10.5" cy="10.5" r="6.5"/><path d="m16 16 5 5"/>',
|
||||
link: '<path d="M10 14a4.5 4.5 0 0 0 6.4 0l3.2-3.2a4.5 4.5 0 0 0-6.4-6.4L12 5.6"/><path d="M14 10a4.5 4.5 0 0 0-6.4 0l-3.2 3.2a4.5 4.5 0 0 0 6.4 6.4l1.2-1.2"/>',
|
||||
gift: '<rect x="3" y="8" width="18" height="5" rx="1"/><path d="M5 13v7a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-7M12 8v13M12 8S10.5 3 8 3.5 7 8 12 8Zm0 0s1.5-5 4-4.5S17 8 12 8Z"/>',
|
||||
plus: '<path d="M12 5v14M5 12h14"/>',
|
||||
check: '<path d="m5 12.5 4.5 4.5L19 7.5"/>',
|
||||
open: '<path d="M5 12h14M13 6l6 6-6 6"/>',
|
||||
chevron: '<path d="m9 6 6 6-6 6"/>',
|
||||
back: '<path d="M19 12H5M11 5l-7 7 7 7"/>',
|
||||
down: '<path d="M12 5v14M5 12l7 7 7-7"/>',
|
||||
edit: '<path d="M4 20h4L19 9a2.8 2.8 0 0 0-4-4L4 16v4Z"/><path d="m13.5 6.5 4 4"/>',
|
||||
wallet: '<path d="M4 7.5A2.5 2.5 0 0 1 6.5 5H18v3"/><rect x="4" y="8" width="16" height="11" rx="2.5"/><circle cx="16" cy="13.5" r="1.2" fill="currentColor" stroke="none"/>',
|
||||
settings: '<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1Z"/>',
|
||||
'user-plus': '<circle cx="10" cy="8" r="3.5"/><path d="M3.5 20a6.5 6.5 0 0 1 13 0M19 8v6M16 11h6"/>',
|
||||
refresh: '<path d="M20 12a8 8 0 1 1-2.3-5.6"/><path d="M20 4v4.4h-4.4"/>',
|
||||
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"/>',
|
||||
};
|
||||
|
||||
export function iconHtml(name, filled = false) {
|
||||
|
||||
@@ -177,11 +177,11 @@ function createPasswordModal() {
|
||||
<div class="stack" style="gap:0.45rem;">
|
||||
<label class="checkbox-row">
|
||||
<input type="radio" name="access-servers-key-mode" value="once" checked />
|
||||
<span>Использовать root key только сейчас</span>
|
||||
<span>Использовать главный ключ только сейчас</span>
|
||||
</label>
|
||||
<label class="checkbox-row">
|
||||
<input type="radio" name="access-servers-key-mode" value="save" />
|
||||
<span>Сохранить root key на этом устройстве</span>
|
||||
<span>Сохранить главный ключ на этом устройстве</span>
|
||||
</label>
|
||||
</div>
|
||||
<p class="meta-muted">client key при необходимости тоже будет временно восстановлен из пароля. Если выбрать сохранение, он тоже попадёт в зашифрованный контейнер устройства.</p>
|
||||
@@ -277,15 +277,9 @@ export function render({navigate, chrome}) {
|
||||
const passwordModal = createPasswordModal();
|
||||
|
||||
const introCard = document.createElement('div');
|
||||
introCard.className = 'card stack';
|
||||
introCard.className = 'settings-intro';
|
||||
introCard.innerHTML = `
|
||||
<p class="field-label">Где хранятся личные данные</p>
|
||||
<p class="meta-muted">
|
||||
Единственный сервер доступа хранит зашифрованную личную переписку пользователя и участвует в звонках.
|
||||
Всё, что публикуется в блокчейне SHiNE, доступно через любой сервер Сияния,
|
||||
а настройки и приватная переписка хранятся только на выбранном сервере.
|
||||
При смене сервера прежняя переписка и настройки автоматически не переносятся.
|
||||
</p>
|
||||
<p class="meta-muted">Сервер доступа хранит вашу зашифрованную переписку и настройки и помогает со звонками. Публичные записи доступны через любой сервер. При смене сервера переписка сама не переносится.</p>
|
||||
`;
|
||||
|
||||
const listCard = document.createElement('div');
|
||||
@@ -302,7 +296,7 @@ export function render({navigate, chrome}) {
|
||||
listBody.className = 'stack';
|
||||
const listStatus = document.createElement('p');
|
||||
listStatus.className = 'meta-muted';
|
||||
listStatus.textContent = 'Загрузка данных из PDA...';
|
||||
listStatus.textContent = 'Загрузка данных аккаунта...';
|
||||
listCard.append(listTitle, listHint, listBody, listStatus);
|
||||
|
||||
const addCard = document.createElement('div');
|
||||
@@ -323,7 +317,7 @@ export function render({navigate, chrome}) {
|
||||
suggestEl.hidden = true;
|
||||
const addStatus = document.createElement('p');
|
||||
addStatus.className = 'meta-muted';
|
||||
addStatus.textContent = 'Для изменения списка понадобится подпись root key.';
|
||||
addStatus.textContent = 'Для изменения списка понадобится подтверждение главным ключом.';
|
||||
const addButton = document.createElement('button');
|
||||
addButton.className = 'primary-btn';
|
||||
addButton.type = 'button';
|
||||
@@ -352,7 +346,7 @@ export function render({navigate, chrome}) {
|
||||
addInput.value = candidate.login;
|
||||
addStatus.textContent = `Выбран сервер @${candidate.login}${candidate.url ? ` (${candidate.url})` : ''}`;
|
||||
} else {
|
||||
addStatus.textContent = 'Для смены сервера понадобится подпись root key.';
|
||||
addStatus.textContent = 'Для смены сервера понадобится подтверждение главным ключом.';
|
||||
}
|
||||
};
|
||||
|
||||
@@ -392,7 +386,7 @@ export function render({navigate, chrome}) {
|
||||
return;
|
||||
}
|
||||
|
||||
listStatus.textContent = 'Читаем серверы доступа из Solana PDA...';
|
||||
listStatus.textContent = 'Читаем серверы доступа из записи аккаунта в Solana...';
|
||||
try {
|
||||
const parsed = await readShineUserPda({ login: sessionLogin, solanaEndpoint });
|
||||
const logins = uniqueLogins(parsed?.accessServers);
|
||||
@@ -409,8 +403,8 @@ export function render({navigate, chrome}) {
|
||||
renderServerList();
|
||||
refreshAddButton();
|
||||
listStatus.textContent = rows.length
|
||||
? 'Сервер доступа загружен из PDA.'
|
||||
: 'В PDA пользователя пока нет серверов доступа.';
|
||||
? 'Сервер доступа загружен из записи аккаунта.'
|
||||
: 'В записи аккаунта пока нет серверов доступа.';
|
||||
} catch (error) {
|
||||
currentAccessServers = [];
|
||||
renderServerList();
|
||||
@@ -439,7 +433,7 @@ export function render({navigate, chrome}) {
|
||||
const topupUrl = address ? getTopupSiteUrl(address) : '/devnet-topup';
|
||||
target.innerHTML = `
|
||||
<span style="display:block; margin-bottom:0.55rem;">
|
||||
Не хватает SOL на client key для оплаты Solana rent/fee при обновлении user PDA.
|
||||
Не хватает SOL на ключе устройства для оплаты комиссии Solana при обновлении записи аккаунта в Solana.
|
||||
</span>
|
||||
${address ? `<span style="display:block; overflow-wrap:anywhere; margin-bottom:0.55rem;">Кошелёк: ${escapeHtml(address)}</span>` : ''}
|
||||
<a class="primary-btn" href="${escapeHtml(topupUrl)}" target="_blank" rel="noopener" style="display:inline-flex; text-decoration:none;">Пополнить DEVNET кошелёк</a>
|
||||
@@ -500,10 +494,10 @@ export function render({navigate, chrome}) {
|
||||
|
||||
const passwordResult = await passwordModal?.open({
|
||||
title: 'Нужен пароль для обновления серверов доступа',
|
||||
text: 'Чтобы изменить сервер доступа, нужно подписать обновление user PDA через root key. Этот ключ не найден в локальном зашифрованном контейнере устройства.',
|
||||
text: 'Чтобы изменить сервер доступа, нужно подписать обновление записи аккаунта в Solana главным ключом. Этот ключ не найден в локальном зашифрованном контейнере устройства.',
|
||||
note: savedClient
|
||||
? 'client key уже сохранён на устройстве. Из пароля будет восстановлен только root key.'
|
||||
: 'На устройстве не хватает root key и/или client key. Они будут восстановлены из пароля аккаунта.',
|
||||
? 'Ключ устройства уже сохранён на устройстве. Из пароля будет восстановлен только главный ключ.'
|
||||
: 'На устройстве не хватает главного ключа и/или ключа устройства. Они будут восстановлены из пароля аккаунта.',
|
||||
});
|
||||
if (!passwordResult) {
|
||||
throw new Error('Операция отменена пользователем.');
|
||||
@@ -513,10 +507,10 @@ export function render({navigate, chrome}) {
|
||||
const derivedRootPublic = base64ToBytes(keyBundle.rootPair.publicKeyB64);
|
||||
const derivedClientPublic = base64ToBytes(keyBundle.clientPair.publicKeyB64);
|
||||
if (!equalBytes(derivedRootPublic, currentPda.rootKey)) {
|
||||
throw new Error('Пароль не подходит: root key не совпал с user PDA.');
|
||||
throw new Error('Пароль не подходит: главный ключ не совпал с записью аккаунта.');
|
||||
}
|
||||
if (!equalBytes(derivedClientPublic, currentPda.clientKey)) {
|
||||
throw new Error('Пароль не подходит: client key не совпал с user PDA.');
|
||||
throw new Error('Пароль не подходит: ключ устройства не совпал с записью аккаунта.');
|
||||
}
|
||||
|
||||
if (passwordResult.saveRoot) {
|
||||
@@ -544,6 +538,9 @@ export function render({navigate, chrome}) {
|
||||
if (operationBusy) return;
|
||||
|
||||
const normalizedList = uniqueLogins(nextLogins);
|
||||
if (normalizedList.length > 1) {
|
||||
throw new Error('PDA 1.2 поддерживает только один сервер доступа.');
|
||||
}
|
||||
setOperationBusy(true);
|
||||
target.textContent = String(inFlightText || 'Обновляем сервер доступа...');
|
||||
let signingMaterial = null;
|
||||
@@ -613,15 +610,15 @@ export function render({navigate, chrome}) {
|
||||
title: 'Сменить сервер доступа?',
|
||||
text: `Заменить текущий сервер доступа на @${resolved.serverLogin}?`,
|
||||
note: resolved.httpBase
|
||||
? `Адрес сервера: ${resolved.httpBase}\nПрежняя переписка и настройки автоматически не перенесутся. Изменение будет записано в Solana user PDA.`
|
||||
: 'Прежняя переписка и настройки автоматически не перенесутся. Изменение будет записано в Solana user PDA.',
|
||||
? `Адрес сервера: ${resolved.httpBase}\nПрежняя переписка и настройки автоматически не перенесутся. Изменение будет записано в записи аккаунта в Solana.`
|
||||
: 'Прежняя переписка и настройки автоматически не перенесутся. Изменение будет записано в записи аккаунта в Solana.',
|
||||
onConfirm: async () => {
|
||||
const nextList = [resolved.serverLogin];
|
||||
try {
|
||||
await updateAccessServers(nextList, {
|
||||
statusTarget: addStatus,
|
||||
successText: `Сервер доступа заменён на @${resolved.serverLogin}.`,
|
||||
inFlightText: `Обновляем PDA и меняем сервер на @${resolved.serverLogin}...`,
|
||||
inFlightText: `Обновляем запись аккаунта и меняем сервер на @${resolved.serverLogin}...`,
|
||||
});
|
||||
} catch {
|
||||
// Сообщение уже показано в статусе.
|
||||
|
||||
@@ -17,7 +17,7 @@ export const pageMeta = { id: 'add-channel-view', title: 'Создание ка
|
||||
|
||||
const CREATE_CHANNEL_FLASH_KEY = 'shine-channels-create-success';
|
||||
const CHANNEL_TYPE_PUBLIC = 1;
|
||||
const CHANNEL_LOGIN_HINT = 'Разрешены латинские буквы, цифры, _ и -. Длина: от 3 до 32 символов. Название не должно состоять только из цифр.';
|
||||
const CHANNEL_LOGIN_HINT = 'Латиница, цифры, _ и -, от 3 до 32 символов, не только цифры.';
|
||||
const CHANNEL_LOGIN_DIGITS_ONLY_HINT = 'Имя канала не должно состоять только из цифр.';
|
||||
|
||||
function persistCreateSuccessFlash(message) {
|
||||
@@ -78,6 +78,17 @@ function shortAvatarBlockchainAddress(value) {
|
||||
return raw.slice(-24);
|
||||
}
|
||||
|
||||
const TRANSLIT = {
|
||||
а: 'a', б: 'b', в: 'v', г: 'g', д: 'd', е: 'e', ё: 'e', ж: 'zh', з: 'z', и: 'i', й: 'y', к: 'k', л: 'l', м: 'm',
|
||||
н: 'n', о: 'o', п: 'p', р: 'r', с: 's', т: 't', у: 'u', ф: 'f', х: 'h', ц: 'ts', ч: 'ch', ш: 'sh', щ: 'sch',
|
||||
ъ: '', ы: 'y', ь: '', э: 'e', ю: 'yu', я: 'ya',
|
||||
};
|
||||
|
||||
function suggestChannelLogin(title) {
|
||||
const latin = Array.from(String(title || '').toLowerCase()).map((ch) => TRANSLIT[ch] ?? ch).join('');
|
||||
return latin.replace(/[^a-z0-9_-]+/g, '-').replace(/-{2,}/g, '-').replace(/^[-_]+|[-_]+$/g, '').slice(0, 32);
|
||||
}
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack channels-screen channels-screen--add';
|
||||
@@ -101,21 +112,31 @@ export function render({navigate, chrome}) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label for="channel-name">Технический логин канала</label>
|
||||
<input id="channel-name" class="input" maxlength="32" placeholder="Например: My-Channel_1" required />
|
||||
<div class="meta-muted channel-create-login-hint">${CHANNEL_LOGIN_HINT}</div>
|
||||
<div class="meta-muted channel-link-preview" id="channel-link-preview"> </div>
|
||||
<div id="channel-name-error" class="meta-muted inline-error"></div>
|
||||
<div class="form-field">
|
||||
<label for="channel-title">Название канала</label>
|
||||
<input id="channel-title" class="input" maxlength="50" placeholder="Например: Мой канал" autocomplete="off" />
|
||||
<div class="form-field__meta">
|
||||
<div id="channel-title-error" class="inline-error"></div>
|
||||
<div class="form-field__counter" id="channel-title-counter">0 / 50</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label for="channel-title">Как канал будет виден пользователям</label>
|
||||
<input id="channel-title" class="input" maxlength="50" placeholder="Например: Мой красивый канал" />
|
||||
<div class="meta-muted" id="channel-title-counter">0 / 50 символов</div>
|
||||
<div id="channel-title-error" class="meta-muted inline-error"></div>
|
||||
<div class="form-field">
|
||||
<label for="channel-name">Адрес канала</label>
|
||||
<input id="channel-name" class="input" maxlength="32" placeholder="my-channel" required autocomplete="off" autocapitalize="off" spellcheck="false" />
|
||||
<div class="form-field__hint channel-create-login-hint">${CHANNEL_LOGIN_HINT} Заполняется из названия, можно поправить.</div>
|
||||
<div class="form-field__hint channel-link-preview" id="channel-link-preview" hidden></div>
|
||||
<div id="channel-name-error" class="inline-error"></div>
|
||||
</div>
|
||||
|
||||
<label for="channel-description">Описание канала (необязательно)</label>
|
||||
<textarea id="channel-description" class="input" rows="4" maxlength="250" placeholder="Коротко о канале, до 250 символов"></textarea>
|
||||
<div class="meta-muted" id="channel-description-counter">0 / 250 символов</div>
|
||||
<div id="channel-description-error" class="meta-muted inline-error"></div>
|
||||
<div class="form-field">
|
||||
<label for="channel-description">Описание <span class="form-field__optional">необязательно</span></label>
|
||||
<textarea id="channel-description" class="input" rows="3" maxlength="250" placeholder="Коротко о канале"></textarea>
|
||||
<div class="form-field__meta">
|
||||
<div id="channel-description-error" class="inline-error"></div>
|
||||
<div class="form-field__counter" id="channel-description-counter">0 / 250</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="channel-create-error" class="meta-muted inline-error"></div>
|
||||
<div class="form-actions-grid">
|
||||
@@ -166,9 +187,11 @@ export function render({navigate, chrome}) {
|
||||
const renderChannelLinkPreview = (nameValue) => {
|
||||
const normalizedChannelName = normalizeChannelDisplayName(nameValue);
|
||||
if (!ownerBlockchainName || !normalizedChannelName) {
|
||||
linkPreviewEl.innerHTML = ' ';
|
||||
linkPreviewEl.hidden = true;
|
||||
linkPreviewEl.textContent = '';
|
||||
return;
|
||||
}
|
||||
linkPreviewEl.hidden = false;
|
||||
const directUrl = buildAbsoluteChannelUrl({
|
||||
ownerBlockchainName,
|
||||
channelName: normalizedChannelName,
|
||||
@@ -216,8 +239,8 @@ export function render({navigate, chrome}) {
|
||||
titleErrorEl.textContent = titleCheck.error;
|
||||
descriptionErrorEl.textContent = descriptionCheck.error;
|
||||
|
||||
titleCounterEl.textContent = `${Number(titleCheck.length || 0)} / 50 символов`;
|
||||
descriptionCounterEl.textContent = `${Number(descriptionCheck.length || 0)} / 250 символов`;
|
||||
titleCounterEl.textContent = `${Number(titleCheck.length || 0)} / 50`;
|
||||
descriptionCounterEl.textContent = `${Number(descriptionCheck.length || 0)} / 250`;
|
||||
|
||||
const ok = nameCheck.ok && titleCheck.ok && descriptionCheck.ok;
|
||||
submitEl.disabled = submitInFlight || !ok;
|
||||
@@ -232,16 +255,19 @@ export function render({navigate, chrome}) {
|
||||
};
|
||||
};
|
||||
|
||||
let nameEditedByHand = false;
|
||||
nameEl.addEventListener('input', () => {
|
||||
nameEditedByHand = nameEl.value.trim() !== '';
|
||||
const raw = String(nameEl.value || '');
|
||||
const sanitized = sanitizeChannelLoginInput(raw);
|
||||
if (raw !== sanitized) {
|
||||
nameEl.value = sanitized;
|
||||
window.alert(CHANNEL_LOGIN_HINT);
|
||||
}
|
||||
if (raw !== sanitized) nameEl.value = sanitized;
|
||||
updateValidation();
|
||||
if (raw !== sanitized) nameErrorEl.textContent = 'Недопустимые символы убраны: можно латиницу, цифры, _ и -.';
|
||||
});
|
||||
titleEl.addEventListener('input', () => {
|
||||
if (!nameEditedByHand) nameEl.value = suggestChannelLogin(titleEl.value);
|
||||
updateValidation();
|
||||
});
|
||||
titleEl.addEventListener('input', updateValidation);
|
||||
descriptionEl.addEventListener('input', updateValidation);
|
||||
avatarBtn.addEventListener('click', async () => {
|
||||
try {
|
||||
@@ -285,7 +311,7 @@ export function render({navigate, chrome}) {
|
||||
|
||||
const check = updateValidation();
|
||||
if (check.name && /^[0-9]+$/.test(check.name)) {
|
||||
window.alert(CHANNEL_LOGIN_DIGITS_ONLY_HINT);
|
||||
nameErrorEl.textContent = CHANNEL_LOGIN_DIGITS_ONLY_HINT;
|
||||
nameEl.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { authService, state } from '../state.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { normalizeChannelDescription } from '../services/channel-name-rules.js';
|
||||
|
||||
export const pageMeta = { id: 'add-personal-public-chat-view', title: 'Новый персональный публичный чат' };
|
||||
export const pageMeta = { id: 'add-personal-public-chat-view', title: 'Новый публичный чат' };
|
||||
|
||||
const CREATE_CHANNEL_FLASH_KEY = 'shine-channels-create-success';
|
||||
const CHANNEL_TYPE_PERSONAL = 100;
|
||||
@@ -52,7 +52,7 @@ export function render({navigate, chrome}) {
|
||||
screen.className = 'stack channels-screen channels-screen--add';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'Новый персональный публичный чат',
|
||||
title: 'Новый публичный чат',
|
||||
back: { label: '<', onClick: () => navigate('channels-list/dialogs') },
|
||||
}));
|
||||
|
||||
|
||||
@@ -32,10 +32,9 @@ export function render({ navigate, chrome }) {
|
||||
}));
|
||||
|
||||
const intro = document.createElement('div');
|
||||
intro.className = 'card stack advanced-settings-intro';
|
||||
intro.className = 'settings-intro';
|
||||
intro.innerHTML = `
|
||||
<p class="field-label">Скрытые возможности SHiNE</p>
|
||||
<p class="meta-muted">Этот экран открывается пятью быстрыми нажатиями по логотипу в обычных настройках и имеет постоянный адрес <code>/settings/advanced</code>.</p>
|
||||
<p class="meta-muted">Скрытые возможности. Экран открывается пятью быстрыми нажатиями по логотипу в настройках.</p>
|
||||
`;
|
||||
|
||||
const developerRow = createToggleRow({
|
||||
|
||||
@@ -18,17 +18,14 @@ export function render({navigate, chrome}) {
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'Лог приложения',
|
||||
back: { label: '←', onClick: () => navigate('developer-settings-view') },
|
||||
actions: [{ icon: 'refresh', title: 'Обновить лог', ariaLabel: 'Обновить лог', onClick: () => renderEntries() }],
|
||||
}));
|
||||
|
||||
const controls = document.createElement('div');
|
||||
controls.className = 'card row';
|
||||
controls.style.justifyContent = 'flex-start';
|
||||
controls.style.gap = '8px';
|
||||
controls.style.flexWrap = 'wrap';
|
||||
controls.className = 'action-pair';
|
||||
controls.innerHTML = `
|
||||
<button class="ghost-btn" type="button" data-action="refresh">Обновить</button>
|
||||
<button class="ghost-btn" type="button" data-action="copy-all">Скопировать всё</button>
|
||||
<button class="ghost-btn" type="button" data-action="clear">Очистить</button>
|
||||
<button class="secondary-btn" type="button" data-action="copy-all">Скопировать всё</button>
|
||||
<button class="destructive-btn" type="button" data-action="clear">Очистить</button>
|
||||
`;
|
||||
|
||||
const status = document.createElement('div');
|
||||
@@ -77,7 +74,7 @@ export function render({navigate, chrome}) {
|
||||
|
||||
if (!entries.length) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'card meta-muted';
|
||||
empty.className = 'empty-note';
|
||||
empty.textContent = 'Лог пока пуст.';
|
||||
list.append(empty);
|
||||
status.className = 'status-line is-available';
|
||||
@@ -117,7 +114,6 @@ export function render({navigate, chrome}) {
|
||||
status.textContent = `Записей: ${entries.length}`;
|
||||
}
|
||||
|
||||
controls.querySelector('[data-action="refresh"]').addEventListener('click', renderEntries);
|
||||
controls.querySelector('[data-action="copy-all"]').addEventListener('click', async () => {
|
||||
const entries = getAppLogEntries();
|
||||
if (!entries.length) {
|
||||
|
||||
@@ -48,7 +48,7 @@ function renderTile(item, index) {
|
||||
if (item.pendingPlacement) {
|
||||
const flag = document.createElement('span');
|
||||
flag.className = 'ar-attachment-placement-flag';
|
||||
flag.textContent = 'Не добавлен в SHiNE';
|
||||
flag.textContent = 'Ещё не прикреплён к записи';
|
||||
meta.append(flag);
|
||||
}
|
||||
|
||||
@@ -92,8 +92,8 @@ export function render({navigate, chrome}) {
|
||||
|
||||
if (!rows.length) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'card meta-muted';
|
||||
empty.textContent = 'Загруженные в этой сессии файлы появятся здесь.';
|
||||
empty.className = 'empty-note';
|
||||
empty.textContent = 'Файлов пока нет. Нажмите «+», чтобы загрузить файл заранее и прикрепить его к записи позже.';
|
||||
list.append(empty);
|
||||
return;
|
||||
}
|
||||
@@ -115,7 +115,7 @@ export function render({navigate, chrome}) {
|
||||
}
|
||||
|
||||
const topbar = createTopBar({
|
||||
title: 'Загрузка файлов в блокчейн',
|
||||
title: 'Файлы в блокчейне',
|
||||
back: { onClick: () => navigate('settings-view') },
|
||||
actions: [
|
||||
{
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { renderAvatar } from '../components/avatar-image.js';
|
||||
import { authService, setChannelsFeed, state } from '../state.js';
|
||||
import { navigateBack } from '../router.js';
|
||||
import { navigateBack, getPreviousTrackedPath } from '../router.js';
|
||||
import {
|
||||
extractLoginFromBlockchainName,
|
||||
makeProfileRoute,
|
||||
@@ -251,7 +252,7 @@ function openSupportChannelModal({ ownerLogin, ownerUser, channelTitle }) {
|
||||
|
||||
const login = String(state.session.login || '').trim();
|
||||
const storagePwd = String(state.session.storagePwdInMemory || '').trim();
|
||||
if (!login || !storagePwd) throw new Error('Для перевода нужно войти в SHiNE.');
|
||||
if (!login || !storagePwd) throw new Error('Для перевода нужно войти в Сиянии.');
|
||||
|
||||
let wallet;
|
||||
if (keyId === 'root-key') {
|
||||
@@ -410,12 +411,21 @@ function confirmUnsubscribeModal({ channelTitle }) {
|
||||
});
|
||||
}
|
||||
|
||||
function subscribersWord(count) {
|
||||
const n = Math.abs(Number(count) || 0) % 100;
|
||||
const last = n % 10;
|
||||
if (n > 10 && n < 20) return 'подписчиков';
|
||||
if (last === 1) return 'подписчик';
|
||||
if (last >= 2 && last <= 4) return 'подписчика';
|
||||
return 'подписчиков';
|
||||
}
|
||||
|
||||
export function render({ navigate, route, chrome }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack channels-screen channels-screen--channel-about';
|
||||
|
||||
const topbar = createTopBar({
|
||||
title: '',
|
||||
title: 'О канале',
|
||||
back: {
|
||||
label: '←',
|
||||
onClick: () => {
|
||||
@@ -471,61 +481,66 @@ export function render({ navigate, route, chrome }) {
|
||||
channelRootBlockHash: selector?.channelRootBlockHash,
|
||||
});
|
||||
const serverLink = buildChannelLink(shortRoute);
|
||||
const shortLink = String(serverLink || '').replace(/^https?:\/\//, '');
|
||||
const cameFromChannel = !!shortRoute && (getPreviousTrackedPath() || '').replace(/^\//, '') === String(shortRoute).replace(/^\//, '');
|
||||
const ownerName = ownerDisplayName(ownerProfile, ownerLogin);
|
||||
|
||||
const subscriptionTile = isOwnChannel ? '' : `
|
||||
<button class="channel-about-tile${isSubscribed ? ' is-active' : ''}" id="channel-about-subscription" type="button">
|
||||
${iconHtml(isSubscribed ? 'check' : 'plus')}<span>${isSubscribed ? 'Вы подписаны' : 'Подписаться'}</span>
|
||||
</button>`;
|
||||
|
||||
content.innerHTML = `
|
||||
<div class="channel-about-hero">
|
||||
<div class="channel-about-avatar-slot" id="channel-about-avatar-slot"></div>
|
||||
<h2 class="channel-about-title">${escapeHtml(cleanName)}</h2>
|
||||
<div class="channel-about-technical">${escapeHtml(ownerLogin)} / ${escapeHtml(channelName)}</div>
|
||||
<div class="channel-about-subscribers">${escapeHtml(statsText(subscribersCount))} подписчиков</div>
|
||||
<div class="channel-about-subline">@${escapeHtml(ownerLogin)} · ${escapeHtml(statsText(subscribersCount))} ${escapeHtml(subscribersWord(subscribersCount))}</div>
|
||||
</div>
|
||||
|
||||
<section class="channel-about-section">
|
||||
<h3>О канале</h3>
|
||||
<p class="channel-about-description">${escapeHtml(description || 'Описание не задано.')}</p>
|
||||
</section>
|
||||
<div class="channel-about-tiles">
|
||||
${cameFromChannel ? '' : `<button class="channel-about-tile" id="channel-about-open" type="button">${iconHtml('open')}<span>Открыть</span></button>`}
|
||||
${subscriptionTile}
|
||||
<button class="channel-about-tile" id="channel-about-support" type="button">${iconHtml('gift')}<span>Донат</span></button>
|
||||
</div>
|
||||
|
||||
<section class="channel-about-section channel-about-owner-section">
|
||||
<h3>Владелец канала</h3>
|
||||
<button class="channel-about-owner-link" id="channel-about-owner" type="button">
|
||||
<strong>${escapeHtml(ownerName)}</strong>
|
||||
<span>@${escapeHtml(ownerLogin)}</span>
|
||||
</button>
|
||||
<button class="secondary-btn channel-about-support-btn" id="channel-about-support" type="button">Донат автору</button>
|
||||
</section>
|
||||
|
||||
|
||||
<section class="channel-about-section">
|
||||
<h3>Ссылка на этом сервере</h3>
|
||||
<div class="channel-about-link-box">
|
||||
<a href="${escapeHtml(serverLink)}">${escapeHtml(serverLink)}</a>
|
||||
<button class="icon-btn channel-about-copy-btn" id="channel-about-copy" type="button" aria-label="Скопировать ссылку" title="Скопировать ссылку">⧉</button>
|
||||
<div class="channel-about-list">
|
||||
<div class="channel-about-row channel-about-row--static">
|
||||
<span class="channel-about-row-label">Описание</span>
|
||||
<p class="channel-about-description">${escapeHtml(description || 'Описание не задано.')}</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<button class="primary-btn channel-about-open-btn" id="channel-about-open" type="button">Открыть канал</button>
|
||||
${isOwnChannel ? '' : `
|
||||
<button class="${isSubscribed ? 'destructive-btn is-unsubscribe' : 'secondary-btn'} channel-about-subscription-btn" id="channel-about-subscription" type="button">
|
||||
${isSubscribed ? 'Отписаться от канала' : 'Подписаться на канал'}
|
||||
<button class="channel-about-row" id="channel-about-owner" type="button">
|
||||
<span class="channel-about-owner-avatar" id="channel-about-owner-avatar"></span>
|
||||
<span class="channel-about-row-main">
|
||||
<strong>${escapeHtml(ownerName)}</strong>
|
||||
<span class="channel-about-row-label">Владелец · @${escapeHtml(ownerLogin)}</span>
|
||||
</span>
|
||||
<span class="channel-about-row-chevron">${iconHtml('chevron')}</span>
|
||||
</button>
|
||||
`}
|
||||
<button class="channel-about-row" id="channel-about-copy-row" type="button">
|
||||
<span class="channel-about-row-main">
|
||||
<span class="channel-about-row-label">Ссылка</span>
|
||||
<span class="channel-about-link">${escapeHtml(shortLink)}</span>
|
||||
</span>
|
||||
<span class="channel-about-row-chevron" aria-hidden="true">${iconHtml('link')}</span>
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
if (String(channel?.avaAr || '').trim()) {
|
||||
const avatar = renderAvatar({
|
||||
initials: cleanName.slice(0, 1).toUpperCase() || 'К',
|
||||
avatar: { ar: String(channel.avaAr || '').trim() },
|
||||
size: 'xl',
|
||||
className: 'channel-about-avatar channel-profile-avatar',
|
||||
title: cleanName,
|
||||
alt: 'Аватар канала',
|
||||
});
|
||||
avatar.style.setProperty('--channel-avatar-size', '112px');
|
||||
content.querySelector('#channel-about-avatar-slot')?.append(avatar);
|
||||
} else {
|
||||
content.querySelector('#channel-about-avatar-slot')?.remove();
|
||||
}
|
||||
const channelAvatar = renderAvatar({
|
||||
initials: cleanName.slice(0, 1).toUpperCase() || 'К',
|
||||
avatar: String(channel?.avaAr || '').trim() ? { ar: String(channel.avaAr || '').trim() } : null,
|
||||
size: 'xl',
|
||||
className: 'channel-about-avatar channel-profile-avatar',
|
||||
title: cleanName,
|
||||
alt: 'Аватар канала',
|
||||
});
|
||||
content.querySelector('#channel-about-avatar-slot')?.append(channelAvatar);
|
||||
content.querySelector('#channel-about-owner-avatar')?.append(renderAvatar({
|
||||
initials: ownerName.slice(0, 1).toUpperCase() || '?',
|
||||
size: 'md',
|
||||
className: 'channel-about-owner-avatar-img',
|
||||
alt: '',
|
||||
}));
|
||||
|
||||
content.querySelector('#channel-about-owner')?.addEventListener('click', () => {
|
||||
const profileRoute = makeProfileRoute(ownerLogin);
|
||||
@@ -537,7 +552,7 @@ export function render({ navigate, route, chrome }) {
|
||||
content.querySelector('#channel-about-open')?.addEventListener('click', () => {
|
||||
if (shortRoute) navigate(shortRoute);
|
||||
});
|
||||
content.querySelector('#channel-about-copy')?.addEventListener('click', async () => {
|
||||
const copyLink = async () => {
|
||||
if (!serverLink) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(serverLink);
|
||||
@@ -545,7 +560,8 @@ export function render({ navigate, route, chrome }) {
|
||||
} catch (error) {
|
||||
showToast(toUserMessage(error, 'Не удалось скопировать ссылку'), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
};
|
||||
content.querySelector('#channel-about-copy-row')?.addEventListener('click', copyLink);
|
||||
|
||||
const subscriptionButton = content.querySelector('#channel-about-subscription');
|
||||
subscriptionButton?.addEventListener('click', async () => {
|
||||
|
||||
@@ -238,7 +238,7 @@ export function render({ navigate, route, chrome }) {
|
||||
|
||||
const login = String(state.session.login || '').trim();
|
||||
const storagePwd = String(state.session.storagePwdInMemory || '').trim();
|
||||
if (!login || !storagePwd) throw new Error('Для перевода нужно войти в SHiNE.');
|
||||
if (!login || !storagePwd) throw new Error('Для перевода нужно войти в Сиянии.');
|
||||
|
||||
let wallet;
|
||||
if (keyId === 'root-key') {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
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 { attachMessageMenu } from '../components/message-menu.js';
|
||||
@@ -8,6 +9,7 @@ import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import {
|
||||
animatePress,
|
||||
createSkeletonCard,
|
||||
formatRelativeTime,
|
||||
longPressFeel,
|
||||
shareOrCopyLink,
|
||||
showToast,
|
||||
@@ -25,7 +27,7 @@ import {
|
||||
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||||
import { extractLoginFromBlockchainName, makeProfileRoute, makeShineChannelRoute, makeShineMessageRoute } from '../services/shine-routes.js';
|
||||
|
||||
export const pageMeta = { id: 'channel-thread-view', title: 'Тред', shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
|
||||
export const pageMeta = { id: 'channel-thread-view', title: 'Обсуждение', hideToolbar: true, shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
|
||||
const MSG_SUBTYPE_TEXT_POST = 10;
|
||||
const MSG_SUBTYPE_TEXT_RATING = 30;
|
||||
const MSG_SUBTYPE_TEXT_ENTRYPOINT = 100;
|
||||
@@ -200,6 +202,13 @@ function allFeedSummaries() {
|
||||
});
|
||||
}
|
||||
|
||||
const channelTitleByLabel = new Map();
|
||||
|
||||
function rememberChannelTitle(label, channel) {
|
||||
const title = String(channel?.displayName || channel?.displayTitle || '').trim();
|
||||
if (label && title) channelTitleByLabel.set(label, title);
|
||||
}
|
||||
|
||||
function resolveChannelDisplayName(channelSelector) {
|
||||
const rootNumber = channelSelector?.channelRootBlockNumber ?? channelSelector?.rootBlockNumber;
|
||||
const rootHashRaw = channelSelector?.channelRootBlockHash ?? channelSelector?.rootBlockHash;
|
||||
@@ -214,7 +223,9 @@ function resolveChannelDisplayName(channelSelector) {
|
||||
&& normalizeRouteHash(summary?.channel?.channelRoot?.blockHash) === rootHash
|
||||
));
|
||||
if (!found) return '';
|
||||
return `${found.channel?.ownerLogin || 'неизвестно'}/${found.channel?.channelName || 'канал'}`;
|
||||
const label = `${found.channel?.ownerLogin || 'неизвестно'}/${found.channel?.channelName || 'канал'}`;
|
||||
rememberChannelTitle(label, found.channel);
|
||||
return label;
|
||||
}
|
||||
|
||||
function resolveChannelHeadingFromNode(node) {
|
||||
@@ -299,7 +310,9 @@ async function resolveChannelDisplayNameFromServer(channelSelector) {
|
||||
if (!row?.channel?.channelName) return '';
|
||||
|
||||
channelSelector.channelRootBlockHash = normalizeRouteHash(row?.channel?.channelRoot?.blockHash);
|
||||
return `${row.channel.ownerLogin || ownerLogin}/${row.channel.channelName}`;
|
||||
const label = `${row.channel.ownerLogin || ownerLogin}/${row.channel.channelName}`;
|
||||
rememberChannelTitle(label, row.channel);
|
||||
return label;
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
@@ -446,7 +459,7 @@ function openBlockchainDetailsModal(details, { isActive = () => true } = {}) {
|
||||
<div class="modal" id="thread-blockchain-details-modal">
|
||||
<div class="modal-card stack blockchain-details-card">
|
||||
<h3 class="modal-title">Данные блокчейна сообщения</h3>
|
||||
<p class="meta-muted">Это технические данные записи SHiNE. По ним можно увидеть цепочку автора, номер записи, хэш и подпись, если она есть в ответе сервера.</p>
|
||||
<p class="meta-muted">Это технические данные записи Сияния. По ним можно увидеть цепочку автора, номер записи, хэш и подпись, если она есть в ответе сервера.</p>
|
||||
<div class="blockchain-details-grid">
|
||||
<span>Автор</span><strong>${escapeHtml(details.authorLogin)}</strong>
|
||||
<span>Блокчейн</span><code>${escapeHtml(details.authorBlockchainName)}</code>
|
||||
@@ -702,7 +715,8 @@ function renderNodeCard(node, heading, handlers, localNumber) {
|
||||
}
|
||||
const timestamp = document.createElement('div');
|
||||
timestamp.className = 'channel-message-time';
|
||||
timestamp.textContent = node?.createdAtMs ? new Date(node.createdAtMs).toLocaleString() : '—';
|
||||
timestamp.textContent = node?.createdAtMs ? formatRelativeTime(node.createdAtMs) : '—';
|
||||
if (node?.createdAtMs) timestamp.title = new Date(node.createdAtMs).toLocaleString('ru-RU');
|
||||
authorBlock.append(title, timestamp);
|
||||
authorTile.append(avatar, authorBlock);
|
||||
headRow.append(authorTile);
|
||||
@@ -786,7 +800,7 @@ function renderNodeCard(node, heading, handlers, localNumber) {
|
||||
likeButton.innerHTML = `
|
||||
<span class="channel-action-icon" aria-hidden="true">${iconHtml('heart', isLiked)}</span>
|
||||
<span class="channel-action-label">${isPending ? 'Лайк...' : 'Лайк'}</span>
|
||||
<span class="channel-action-counter">${likes}</span>
|
||||
<span class="channel-action-counter">${Number(likes) > 0 ? likes : ''}</span>
|
||||
`;
|
||||
likeButton.setAttribute('aria-pressed', String(isLiked));
|
||||
setActionTitle(likeButton, isPending ? 'Лайк…' : `${isLiked ? 'Убрать отметку «Нравится»' : 'Нравится'}, ${likes}`);
|
||||
@@ -817,7 +831,7 @@ function renderNodeCard(node, heading, handlers, localNumber) {
|
||||
replyButton.innerHTML = `
|
||||
<span class="channel-action-icon" aria-hidden="true">${iconHtml('message')}</span>
|
||||
<span class="channel-action-label">Ответить</span>
|
||||
<span class="channel-action-counter">${replies}</span>
|
||||
<span class="channel-action-counter">${Number(replies) > 0 ? replies : ''}</span>
|
||||
`;
|
||||
setActionTitle(replyButton, 'Ответить');
|
||||
replyButton.addEventListener('click', (event) => {
|
||||
@@ -856,7 +870,7 @@ function renderNodeCard(node, heading, handlers, localNumber) {
|
||||
const discussionButton = document.createElement('button');
|
||||
discussionButton.type = 'button';
|
||||
discussionButton.className = 'ui-button channel-action-item';
|
||||
discussionButton.innerHTML = `<span class="channel-action-icon">${iconHtml('message')}</span><span>${replies}</span>`;
|
||||
discussionButton.innerHTML = `<span class="channel-action-icon">${iconHtml('message')}</span>${Number(replies) > 0 ? `<span>${replies}</span>` : ''}`;
|
||||
discussionButton.setAttribute('aria-label', `Открыть обсуждение, ответов: ${replies}`);
|
||||
discussionButton.addEventListener('click', () => handlers.onOpenThread(target));
|
||||
actions.append(likeButton, discussionButton, shareButton, replyButton);
|
||||
@@ -871,8 +885,6 @@ function renderNodeCard(node, heading, handlers, localNumber) {
|
||||
setActionTitle(originalButton, 'Оригинал');
|
||||
originalButton.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
const ok = window.confirm('Перейти к оригинальному сообщению?');
|
||||
if (!ok) return;
|
||||
const ownerLogin = extractLoginFromBlockchainName(repostTarget.blockchainName);
|
||||
if (!ownerLogin) return;
|
||||
handlers.navigate(makeShineMessageRoute({
|
||||
@@ -927,7 +939,12 @@ function renderNodeCard(node, heading, handlers, localNumber) {
|
||||
});
|
||||
menuItems.unshift({ label: 'Редактировать', action: () => editButton.click() });
|
||||
menuItems.push({ label: 'Удалить', danger: true, action: async () => {
|
||||
if (!window.confirm('Скрыть сообщение из ленты? Предыдущие версии останутся в блокчейне и истории изменений.')) return;
|
||||
if (!await confirmDialog({
|
||||
title: 'Удалить сообщение?',
|
||||
text: 'Сообщение скроется из ленты. Предыдущие версии останутся в блокчейне и в истории изменений.',
|
||||
confirmLabel: 'Удалить',
|
||||
danger: true,
|
||||
})) return;
|
||||
try { await handlers.onEdit(target, '', { isChannelPost, isDelete: true }); }
|
||||
catch (error) { if (handlers.isActive()) showToast(toUserMessage(error, 'Не удалось удалить сообщение.')); }
|
||||
} });
|
||||
@@ -1026,21 +1043,18 @@ export function render({ navigate, route, chrome }) {
|
||||
const threadHeaderButton = document.createElement('button');
|
||||
threadHeaderButton.type = 'button';
|
||||
threadHeaderButton.className = 'icon-btn channel-header-route-btn app-topbar-title-action';
|
||||
threadHeaderButton.textContent = 'Тред в канале: ...';
|
||||
const threadHeaderTitle = document.createElement('span');
|
||||
threadHeaderTitle.className = 'channel-header-title';
|
||||
threadHeaderTitle.textContent = 'Обсуждение';
|
||||
const threadHeaderChannel = document.createElement('span');
|
||||
threadHeaderChannel.className = 'channel-header-owner';
|
||||
threadHeaderChannel.textContent = '…';
|
||||
threadHeaderButton.append(threadHeaderTitle, threadHeaderChannel);
|
||||
threadHeaderButton.disabled = true;
|
||||
|
||||
const header = createTopBar({
|
||||
center: threadHeaderButton,
|
||||
back: { label: '<', onClick: () => navigate(resolveThreadPreviousInChannels(selector, activeResolvedChannelLabel)) },
|
||||
actions: [
|
||||
{
|
||||
label: '↑',
|
||||
title: 'К списку каналов',
|
||||
ariaLabel: 'К списку каналов',
|
||||
className: 'channel-thread-list-btn',
|
||||
onClick: () => navigate('channels-list'),
|
||||
},
|
||||
],
|
||||
});
|
||||
header.classList.add('channel-thread-topbar');
|
||||
chrome?.setTopbar(header);
|
||||
@@ -1050,7 +1064,7 @@ export function render({ navigate, route, chrome }) {
|
||||
statusBox.style.display = 'none';
|
||||
|
||||
const ensureActive = () => {
|
||||
if (disposed) throw new Error('Экран треда уже закрыт.');
|
||||
if (disposed) throw new Error('Экран обсуждения уже закрыт.');
|
||||
};
|
||||
|
||||
const showStatus = (message) => {
|
||||
@@ -1175,10 +1189,10 @@ export function render({ navigate, route, chrome }) {
|
||||
onShare: async (target) => {
|
||||
try {
|
||||
const routePath = buildThreadRouteFromTarget(target, selector);
|
||||
if (!routePath) throw new Error('Не удалось подготовить ссылку на тред.');
|
||||
if (!routePath) throw new Error('Не удалось подготовить ссылку на обсуждение.');
|
||||
const result = await shareOrCopyLink({
|
||||
title: 'SHiNE · Тред',
|
||||
text: 'Сообщение из треда SHiNE',
|
||||
title: 'Сияние · Обсуждение',
|
||||
text: 'Сообщение из обсуждения в Сиянии',
|
||||
url: buildAbsoluteRouteUrl(routePath),
|
||||
});
|
||||
if (disposed) return;
|
||||
@@ -1192,7 +1206,7 @@ export function render({ navigate, route, chrome }) {
|
||||
onOpenThread: (target) => {
|
||||
const routePath = buildThreadRouteFromTarget(target, selector);
|
||||
if (!routePath) {
|
||||
showStatus('Не удалось определить путь до треда.');
|
||||
showStatus('Не удалось определить ссылку на обсуждение.');
|
||||
return;
|
||||
}
|
||||
navigate(routePath);
|
||||
@@ -1264,14 +1278,14 @@ export function render({ navigate, route, chrome }) {
|
||||
showStatus('');
|
||||
selector = parseThreadSelector(route);
|
||||
activeResolvedChannelLabel = resolveChannelDisplayName(selector?.channel);
|
||||
threadHeaderButton.textContent = 'Тред в канале: ...';
|
||||
threadHeaderChannel.textContent = '…';
|
||||
threadHeaderButton.disabled = true;
|
||||
threadHeaderButton.onclick = null;
|
||||
|
||||
if (!selector) {
|
||||
const invalid = document.createElement('div');
|
||||
invalid.className = 'card meta-muted';
|
||||
invalid.textContent = 'Некорректный идентификатор треда в адресе страницы.';
|
||||
invalid.textContent = 'Обсуждение не найдено: неверная ссылка.';
|
||||
screen.append(invalid);
|
||||
return;
|
||||
}
|
||||
@@ -1382,7 +1396,8 @@ export function render({ navigate, route, chrome }) {
|
||||
const fallbackChannel = String(selector?.channel?.ownerBlockchainName || '').trim() || 'неизвестно';
|
||||
const resolvedChannelTitle = resolvedChannelLabel || fallbackChannel;
|
||||
if (threadHeaderButton) {
|
||||
threadHeaderButton.textContent = `Обсуждение · ${resolvedChannelTitle}`;
|
||||
threadHeaderChannel.textContent = `в канале «${channelTitleByLabel.get(resolvedChannelTitle) || resolvedChannelTitle}»`;
|
||||
threadHeaderButton.title = 'Открыть канал';
|
||||
threadHeaderButton.disabled = false;
|
||||
threadHeaderButton.onclick = (event) => {
|
||||
event.preventDefault();
|
||||
@@ -1422,8 +1437,8 @@ export function render({ navigate, route, chrome }) {
|
||||
composer.className = 'channel-composer';
|
||||
const reply = document.createElement('button');
|
||||
reply.type = 'button';
|
||||
reply.className = 'primary-btn';
|
||||
reply.textContent = state.session.isAuthorized ? 'Написать ответ' : 'Войти и ответить';
|
||||
reply.className = 'channel-compose-bar';
|
||||
reply.innerHTML = `<span class="channel-compose-bar__text">${state.session.isAuthorized ? 'Написать ответ…' : 'Войти и ответить'}</span><span class="channel-compose-bar__icon" aria-hidden="true">${iconHtml('plus')}</span>`;
|
||||
reply.addEventListener('click', () => {
|
||||
const parsed = parseMessageAttachments(resolveNodeText(focus));
|
||||
openReplyModal({
|
||||
@@ -1448,7 +1463,7 @@ export function render({ navigate, route, chrome }) {
|
||||
descendantsWrap.append(renderDescendants(descendants, handlers, nextNumber));
|
||||
} else {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'card meta-muted';
|
||||
empty.className = 'empty-note';
|
||||
empty.textContent = 'Пока нет ответов. Начните обсуждение.';
|
||||
descendantsWrap.append(empty);
|
||||
}
|
||||
@@ -1478,7 +1493,7 @@ export function render({ navigate, route, chrome }) {
|
||||
if (hadContent) { showStatus(toUserMessage(error, 'Не удалось обновить обсуждение.')); return; }
|
||||
const failed = document.createElement('div');
|
||||
failed.className = 'card meta-muted';
|
||||
failed.textContent = `Не удалось загрузить тред: ${toUserMessage(error, 'неизвестная ошибка')}`;
|
||||
failed.textContent = `Не удалось загрузить обсуждение: ${toUserMessage(error, 'неизвестная ошибка')}`;
|
||||
const retry = document.createElement('button');
|
||||
retry.type = 'button';
|
||||
retry.className = 'primary-btn';
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
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 { attachMessageMenu } from '../components/message-menu.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import {
|
||||
@@ -13,6 +15,9 @@ import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import {
|
||||
animatePress,
|
||||
createSkeletonCard,
|
||||
dayKey,
|
||||
formatClockTime,
|
||||
formatDayLabel,
|
||||
formatRelativeTime,
|
||||
longPressFeel,
|
||||
shareOrCopyLink,
|
||||
@@ -39,7 +44,7 @@ import {
|
||||
} from '../services/shine-routes.js';
|
||||
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
||||
|
||||
export const pageMeta = { id: 'channel-view', title: 'Канал', shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
|
||||
export const pageMeta = { id: 'channel-view', title: 'Канал', hideToolbar: true, 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;
|
||||
@@ -828,7 +833,7 @@ function openBlockchainDetailsModal(details, { isActive = () => true } = {}) {
|
||||
<div class="modal" id="blockchain-details-modal">
|
||||
<div class="modal-card stack blockchain-details-card">
|
||||
<h3 class="modal-title">Данные блокчейна сообщения</h3>
|
||||
<p class="meta-muted">Это технические данные записи SHiNE. По ним можно увидеть цепочку автора, номер записи, хэш и подпись, если она есть в ответе сервера.</p>
|
||||
<p class="meta-muted">Это технические данные записи Сияния. По ним можно увидеть цепочку автора, номер записи, хэш и подпись, если она есть в ответе сервера.</p>
|
||||
<div class="blockchain-details-grid">
|
||||
<span>Автор</span><strong>${escapeHtml(details.authorLogin)}</strong>
|
||||
<span>Блокчейн</span><code>${escapeHtml(details.authorBlockchainName)}</code>
|
||||
@@ -874,8 +879,8 @@ function renderDraftAttachments(container, attachments) {
|
||||
button.className = 'ui-button draft-attachment-chip';
|
||||
button.textContent = `${item.name} · ${item.ar}`;
|
||||
button.title = 'Нажмите, чтобы убрать вложение';
|
||||
button.addEventListener('click', () => {
|
||||
const ok = window.confirm('Отменить вложение?');
|
||||
button.addEventListener('click', async () => {
|
||||
const ok = await confirmDialog({ title: 'Убрать вложение?', text: item.name, confirmLabel: 'Убрать', danger: true });
|
||||
if (!ok) return;
|
||||
attachments.splice(index, 1);
|
||||
renderDraftAttachments(container, attachments);
|
||||
@@ -1063,7 +1068,7 @@ function openEntrypointHistoryModal({ channelTitle = '', posts = [], onSelect })
|
||||
if (list) {
|
||||
if (!items.length) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'card meta-muted';
|
||||
empty.className = 'empty-note';
|
||||
empty.textContent = 'Оглавление в этом канале пока не добавлялось.';
|
||||
list.append(empty);
|
||||
} else {
|
||||
@@ -1169,18 +1174,19 @@ function openRepostModal({ navigate, channels = [], onSubmit, isActive = () => t
|
||||
function openAddMessageModal({ channelName, onSubmit, navigate, isActive = () => true }) {
|
||||
const typeWrap = document.createElement('label');
|
||||
typeWrap.className = 'channel-editor__type';
|
||||
typeWrap.textContent = 'Тип сообщения';
|
||||
typeWrap.innerHTML = '<span class="sr-only">Тип сообщения</span>';
|
||||
const typeSelect = document.createElement('select');
|
||||
typeSelect.className = 'select';
|
||||
typeSelect.className = 'select channel-editor__type-select';
|
||||
typeSelect.title = 'Тип сообщения';
|
||||
typeSelect.innerHTML = `
|
||||
<option value="10">Публикация</option>
|
||||
<option value="${MSG_SUBTYPE_TEXT_ENTRYPOINT}">Оглавление канала</option>
|
||||
<option value="${MSG_SUBTYPE_TEXT_ENTRYPOINT}">Оглавление</option>
|
||||
`;
|
||||
typeWrap.append(typeSelect);
|
||||
|
||||
return openChannelEditor({
|
||||
id: 'channel-message-modal',
|
||||
title: 'Новое сообщение',
|
||||
title: 'Новая запись',
|
||||
submitLabel: 'Опубликовать',
|
||||
placeholder: 'Напишите сообщение',
|
||||
key: `channel-post:${channelName}`,
|
||||
@@ -1611,14 +1617,15 @@ function mapChannelMetaEvent(event, fallbackChannel) {
|
||||
};
|
||||
}
|
||||
|
||||
function renderChannelMetaEventCard(event) {
|
||||
function renderChannelMetaEventCard(event, dayLabel = '') {
|
||||
const card = document.createElement('article');
|
||||
card.className = 'card channel-system-event-card';
|
||||
const label = event.kind === 'created'
|
||||
? 'Создан канал'
|
||||
? 'Канал создан'
|
||||
: 'Изменено описание канала';
|
||||
const shownLabel = dayLabel ? `${label} · ${dayLabel.toLocaleLowerCase('ru-RU')}` : label;
|
||||
card.innerHTML = `
|
||||
<span class="channel-system-event-card__label">${escapeHtml(label)}</span>
|
||||
<span class="channel-system-event-card__label">${escapeHtml(shownLabel)}</span>
|
||||
`;
|
||||
card.addEventListener('click', () => {
|
||||
openChannelMetaDetailsModal({
|
||||
@@ -1856,6 +1863,7 @@ function renderPostCard(post, {
|
||||
const timestamp = document.createElement('div');
|
||||
timestamp.className = 'channel-message-time';
|
||||
timestamp.textContent = post.timestampMs ? formatRelativeTime(post.timestampMs) : '—';
|
||||
if (post.timestampMs) timestamp.title = new Date(post.timestampMs).toLocaleString('ru-RU');
|
||||
if (versionsTotal > 1) {
|
||||
const editedMarker = document.createElement('span');
|
||||
editedMarker.type = 'button';
|
||||
@@ -1906,6 +1914,15 @@ function renderPostCard(post, {
|
||||
navigate(makeProfileRoute(cleanLogin));
|
||||
});
|
||||
|
||||
const isOwnerPost = !!selector
|
||||
&& !isDiarySelector(selector)
|
||||
&& !!post.messageRef?.blockchainName
|
||||
&& String(post.messageRef.blockchainName).trim().toLowerCase() === String(selector.ownerBlockchainName || '').trim().toLowerCase();
|
||||
if (isOwnerPost) {
|
||||
card.classList.add('channel-message-card--owner');
|
||||
authorTile.hidden = true;
|
||||
}
|
||||
|
||||
const isDeletedMessage = String(post.body || '').trim().toLowerCase() === 'удалено';
|
||||
const parsedBody = parseMessageAttachments(post.body);
|
||||
|
||||
@@ -1990,7 +2007,7 @@ function renderPostCard(post, {
|
||||
likeButton.innerHTML = `
|
||||
<span class="channel-action-icon" aria-hidden="true">${iconHtml('heart', isLiked)}</span>
|
||||
<span class="channel-action-label">${isPending ? 'Лайк...' : 'Лайк'}</span>
|
||||
<span class="channel-action-counter">${post.likesCount || 0}</span>
|
||||
<span class="channel-action-counter">${post.likesCount || ''}</span>
|
||||
`;
|
||||
likeButton.setAttribute('aria-pressed', String(isLiked));
|
||||
setActionTitle(likeButton, isPending ? 'Лайк…' : `${isLiked ? 'Убрать отметку «Нравится»' : 'Нравится'}, ${post.likesCount || 0}`);
|
||||
@@ -2015,7 +2032,7 @@ function renderPostCard(post, {
|
||||
discussionButton.innerHTML = `
|
||||
<span class="channel-action-icon" aria-hidden="true">${iconHtml('message')}</span>
|
||||
<span class="channel-action-label">Обсуждение</span>
|
||||
<span class="channel-action-counter">${post.repliesCount || 0}</span>
|
||||
<span class="channel-action-counter">${post.repliesCount || ''}</span>
|
||||
`;
|
||||
setActionTitle(discussionButton, `Открыть обсуждение, ответов: ${post.repliesCount || 0}`);
|
||||
discussionButton.addEventListener('click', (event) => {
|
||||
@@ -2030,7 +2047,7 @@ function renderPostCard(post, {
|
||||
replyButton.innerHTML = `
|
||||
<span class="channel-action-icon" aria-hidden="true">${iconHtml('message')}</span>
|
||||
<span class="channel-action-label">Ответить</span>
|
||||
<span class="channel-action-counter">${post.repliesCount || 0}</span>
|
||||
<span class="channel-action-counter">${post.repliesCount || ''}</span>
|
||||
`;
|
||||
setActionTitle(replyButton, 'Ответить');
|
||||
replyButton.addEventListener('click', (event) => {
|
||||
@@ -2067,7 +2084,8 @@ function renderPostCard(post, {
|
||||
await onShare(route);
|
||||
});
|
||||
|
||||
actions.append(shareButton, replyButton);
|
||||
actions.append(shareButton);
|
||||
menuItems.unshift({ label: 'Ответить', action: () => replyButton.click() });
|
||||
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';
|
||||
@@ -2081,8 +2099,6 @@ function renderPostCard(post, {
|
||||
event.stopPropagation();
|
||||
const ownerLogin = extractLoginFromBlockchainName(post.targetRef.blockchainName);
|
||||
if (!ownerLogin) return;
|
||||
const ok = window.confirm('Перейти к оригинальному сообщению?');
|
||||
if (!ok) return;
|
||||
navigate(makeShineMessageRoute({
|
||||
ownerLogin,
|
||||
messageBlockchainName: post.targetRef.blockchainName,
|
||||
@@ -2135,13 +2151,28 @@ function renderPostCard(post, {
|
||||
});
|
||||
menuItems.unshift({ label: 'Редактировать', action: () => editButton.click() });
|
||||
menuItems.push({ label: 'Удалить', danger: true, action: async () => {
|
||||
if (!window.confirm('Скрыть сообщение из ленты? Предыдущие версии останутся в блокчейне и истории изменений.')) return;
|
||||
if (!await confirmDialog({
|
||||
title: 'Удалить сообщение?',
|
||||
text: 'Сообщение скроется из ленты. Предыдущие версии останутся в блокчейне и в истории изменений.',
|
||||
confirmLabel: 'Удалить',
|
||||
danger: true,
|
||||
})) return;
|
||||
try { await onEdit(post.messageRef, '', { isDelete: true }); }
|
||||
catch (error) { if (isActive()) showToast(toUserMessage(error, 'Не удалось удалить сообщение.')); }
|
||||
} });
|
||||
}
|
||||
if (versionsTotal > 1) menuItems.push({ label: 'История изменений', action: () => openMessageHistoryModal({ versions: post.versions }) });
|
||||
attachMessageMenu(card, headRow, menuItems);
|
||||
if (isOwnerPost) {
|
||||
if (post.timestampMs) timestamp.textContent = formatClockTime(post.timestampMs);
|
||||
const meta = document.createElement('div');
|
||||
meta.className = 'channel-message-meta';
|
||||
const moreButton = headRow.querySelector('.channel-message-more');
|
||||
meta.append(timestamp);
|
||||
if (moreButton) meta.append(moreButton);
|
||||
actions.append(meta);
|
||||
if (!headRow.querySelector('.channel-message-type-button')) headRow.hidden = true;
|
||||
}
|
||||
card.append(actions);
|
||||
return card;
|
||||
}
|
||||
@@ -2166,8 +2197,9 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
|
||||
|
||||
const addMessageButton = document.createElement('button');
|
||||
addMessageButton.type = 'button';
|
||||
addMessageButton.className = 'primary-btn channel-main-action channel-main-action--compose';
|
||||
addMessageButton.textContent = 'Добавить сообщение';
|
||||
addMessageButton.className = 'channel-compose-bar';
|
||||
addMessageButton.setAttribute('aria-label', 'Написать в канал');
|
||||
addMessageButton.innerHTML = `<span class="channel-compose-bar__text">Написать в канал…</span><span class="channel-compose-bar__icon" aria-hidden="true">${iconHtml('plus')}</span>`;
|
||||
addMessageButton.addEventListener('click', (event) => {
|
||||
animatePress(event.currentTarget);
|
||||
handlers.onAddMessage();
|
||||
@@ -2199,7 +2231,17 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
|
||||
});
|
||||
|
||||
if (feedItems.length) {
|
||||
let lastDayKey = '';
|
||||
feedItems.forEach((item) => {
|
||||
const itemDayKey = dayKey(item.timestampMs);
|
||||
const startsNewDay = !!itemDayKey && itemDayKey !== lastDayKey;
|
||||
if (startsNewDay) lastDayKey = itemDayKey;
|
||||
if (startsNewDay && item.type !== 'meta') {
|
||||
const separator = document.createElement('div');
|
||||
separator.className = 'channel-day-separator';
|
||||
separator.innerHTML = `<span>${escapeHtml(formatDayLabel(item.timestampMs))}</span>`;
|
||||
feed.append(separator);
|
||||
}
|
||||
if (!unreadLineInserted && item.type === 'post' && Number(item?.post?.localNumber || 0) > readCount) {
|
||||
const unreadLine = document.createElement('div');
|
||||
unreadLine.className = 'card channel-unread-line';
|
||||
@@ -2208,7 +2250,7 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
|
||||
unreadLineInserted = true;
|
||||
}
|
||||
if (item.type === 'meta') {
|
||||
feed.append(renderChannelMetaEventCard(item.event));
|
||||
feed.append(renderChannelMetaEventCard(item.event, startsNewDay ? formatDayLabel(item.timestampMs) : ''));
|
||||
return;
|
||||
}
|
||||
const row = renderPostCard(item.post, {
|
||||
@@ -2232,7 +2274,7 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
|
||||
});
|
||||
} else {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'card meta-muted';
|
||||
empty.className = 'empty-note';
|
||||
empty.textContent = channelData.isDiary
|
||||
? 'К сожалению, у вас пока еще ничего нет в Дневнике.'
|
||||
: 'Ждем ваших начинаний';
|
||||
@@ -2400,26 +2442,6 @@ export function render({ navigate, route, chrome }) {
|
||||
const aboutRoute = makeShineChannelAboutRoute(routeArgs);
|
||||
const donateRoute = makeShineChannelDonateRoute(routeArgs);
|
||||
const items = [];
|
||||
if (apiData?.isOwnChannel && !apiData?.isDiary) {
|
||||
items.push({
|
||||
label: 'Добавить сообщение',
|
||||
action: () => {
|
||||
openAddMessageModal({
|
||||
channelName: apiData?.channel?.name || '',
|
||||
navigate,
|
||||
isActive: () => !disposed,
|
||||
onSubmit: async ({ text: bodyText, msgSubType }) => {
|
||||
try {
|
||||
await onAddPost(bodyText, msgSubType);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось добавить сообщение.'));
|
||||
}
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
items.push({ label: 'О канале', action: () => { if (aboutRoute) navigate(aboutRoute); } });
|
||||
items.push({
|
||||
label: 'Оглавление',
|
||||
@@ -2479,9 +2501,6 @@ export function render({ navigate, route, chrome }) {
|
||||
try {
|
||||
const { login, storagePwd } = requireSigningSession();
|
||||
if (!apiData?.selector) throw new Error('Не удалось определить канал для подписки.');
|
||||
const targetName = `${apiData.channel?.ownerName || 'user'}/${apiData.channel?.name || 'channel'}`;
|
||||
const ok = window.confirm(`Подписаться на канал ${targetName}?`);
|
||||
if (!ok) return;
|
||||
|
||||
await authService.addBlockFollowChannel({
|
||||
login,
|
||||
@@ -2694,7 +2713,7 @@ export function render({ navigate, route, chrome }) {
|
||||
if (!routeToShare) throw new Error('Не удалось подготовить ссылку на сообщение.');
|
||||
const result = await shareOrCopyLink({
|
||||
title: 'SHiNE · Каналы',
|
||||
text: 'Тред из канала SHiNE',
|
||||
text: 'Обсуждение в Сиянии',
|
||||
url: buildAbsoluteRouteUrl(routeToShare),
|
||||
});
|
||||
if (disposed) return;
|
||||
@@ -2806,7 +2825,13 @@ export function render({ navigate, route, chrome }) {
|
||||
if (disposed) return;
|
||||
const seq = ++refreshSeq;
|
||||
const hadContent = !!screen.querySelector('.channel-feed');
|
||||
const restorePosition = hadContent ? getChannelScrollRoot()?.scrollTop : readChannelPosition(positionKey);
|
||||
// Прежнее место в ленте восстанавливаем только при возврате из обсуждения / «О канале».
|
||||
// Открытие канала из списка или другого раздела ведёт к свежим постам (или к непрочитанным).
|
||||
const previousPath = getPreviousTrackedPath() || '';
|
||||
const returnedFromChannelPage = /^\/(SHiNE|thread)\//.test(previousPath) || /\/(about|donate)$/.test(previousPath);
|
||||
const restorePosition = hadContent
|
||||
? getChannelScrollRoot()?.scrollTop
|
||||
: (returnedFromChannelPage ? readChannelPosition(positionKey) : undefined);
|
||||
if (!hadContent) clearContent();
|
||||
activeChannelData = null;
|
||||
activeOpenEntrypointHistory = null;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { channels as mockChannels } from '../mock-data.js';
|
||||
import { authService, setChannelsFeed, state } from '../state.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
@@ -5,7 +6,7 @@ import { parseMessageAttachments } from '../services/attachment-format.js';
|
||||
import {
|
||||
animatePress,
|
||||
createSkeletonCard,
|
||||
formatRelativeTime,
|
||||
formatListTime,
|
||||
readChannelNotificationsState,
|
||||
showToast,
|
||||
softHaptic,
|
||||
@@ -755,7 +756,7 @@ function mapApiChannelRow(summary, bucketKey, idx, index, notificationsState) {
|
||||
messagePreview: cleanChannelMessagePreview(lastMessage.text),
|
||||
messagesCount: Number(summary?.messagesCount || 0),
|
||||
unreadCount: Number(summary?.unreadCount || 0),
|
||||
lastMessageAt: Number(lastMessage.createdAtMs || 0),
|
||||
lastMessageAt: Number(lastMessage.createdAtMs || summary?.channel?.metaUpdatedAtMs || 0),
|
||||
isOwnChannel: isOwn,
|
||||
isSubscribed: !isOwn,
|
||||
notificationsEnabled: notificationsState[rowId] === true,
|
||||
@@ -964,12 +965,13 @@ function renderChannelMain(channel) {
|
||||
|
||||
const time = document.createElement('span');
|
||||
time.className = 'channel-row-time';
|
||||
time.textContent = channel.lastMessageAt ? formatRelativeTime(channel.lastMessageAt) : '';
|
||||
time.textContent = channel.lastMessageAt ? formatListTime(channel.lastMessageAt) : '';
|
||||
titleLine.append(title, time);
|
||||
|
||||
const technical = document.createElement('p');
|
||||
technical.className = 'channel-row-technical';
|
||||
technical.textContent = `@${channel.ownerName || 'автор'}`;
|
||||
technical.hidden = !!channel.isOwnChannel;
|
||||
|
||||
if (channel.channelDescription) {
|
||||
const desc = document.createElement('p');
|
||||
@@ -984,6 +986,7 @@ function renderChannelMain(channel) {
|
||||
const preview = document.createElement('p');
|
||||
preview.className = 'channel-row-message';
|
||||
preview.textContent = channel.messagePreview || 'Пока нет сообщений';
|
||||
if (!channel.messagePreview) preview.classList.add('is-empty');
|
||||
|
||||
previewLine.append(preview);
|
||||
|
||||
@@ -1173,7 +1176,7 @@ export function render({ navigate, route, chrome }) {
|
||||
controls.className = 'channels-list-controls';
|
||||
const searchWrap = document.createElement('div');
|
||||
searchWrap.className = 'channels-inline-search';
|
||||
searchWrap.innerHTML = '<span aria-hidden="true">⌕</span><span class="sr-only">Поиск каналов</span>';
|
||||
searchWrap.innerHTML = `<span class="channels-inline-search__icon" aria-hidden="true">${iconHtml('search')}</span><span class="sr-only">Поиск каналов</span>`;
|
||||
const searchInput = document.createElement('input');
|
||||
searchInput.type = 'search';
|
||||
searchInput.value = listState.query;
|
||||
|
||||
@@ -28,7 +28,7 @@ import {
|
||||
stopAllTwemojiAnimations,
|
||||
} from '../components/emoji-picker.js?v=202607152130';
|
||||
import { isTextToSpeechConfigured, speakTextBySettings } from '../services/speech-tools-service.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { dayKey, formatClockTime, formatDayLabel, showToast } from '../services/channels-ux.js';
|
||||
import { buildDmFileTechBlock, buildDmReplyTechBlock, parseDmTechBlocks, sanitizeUserDmTextForSend } from '../services/dm-tech-blocks.js';
|
||||
import { isDmFileTransferEnabled } from '../services/feature-settings.js';
|
||||
import {
|
||||
@@ -44,6 +44,7 @@ import { makeProfileLinksRoute, makeProfileRoute } from '../services/shine-route
|
||||
export const pageMeta = {
|
||||
id: 'chat-view',
|
||||
title: 'Чат',
|
||||
hideToolbar: true,
|
||||
shellMode: {
|
||||
topFade: true,
|
||||
bottomFade: true,
|
||||
@@ -81,7 +82,7 @@ function chatRelationLabel(value) {
|
||||
case 'close_friend': return 'Близкий друг';
|
||||
case 'friend': return 'Друг';
|
||||
case 'contact': return 'Контакт';
|
||||
default: return 'Не в контактах';
|
||||
default: return '';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,7 +118,9 @@ function createChatHeaderParts(login, navigate) {
|
||||
const lastName = String(currentPeer?.lastName || '').trim();
|
||||
const fullName = [firstName, lastName].filter(Boolean).join(' ');
|
||||
nameEl.textContent = fullName || cleanLogin;
|
||||
metaEl.textContent = `${cleanLogin} · ${chatRelationLabel(currentPeer?.relationType)}`;
|
||||
const relation = chatRelationLabel(currentPeer?.relationType);
|
||||
metaEl.textContent = [fullName ? `@${cleanLogin}` : '', relation].filter(Boolean).join(' · ');
|
||||
metaEl.hidden = !metaEl.textContent;
|
||||
const avatar = renderUserAvatar({
|
||||
login: cleanLogin,
|
||||
firstName,
|
||||
@@ -1058,7 +1061,19 @@ function renderLog(
|
||||
const messages = getChatMessages(chatId);
|
||||
let unreadSeparatorInserted = false;
|
||||
const separatorMessageKey = String(unreadSeparatorMessageKey || '').trim();
|
||||
let lastDayKey = '';
|
||||
messages.forEach((msg) => {
|
||||
const msgTimeMs = resolveMessageTimeMs(msg);
|
||||
const msgDayKey = dayKey(msgTimeMs);
|
||||
if (msgDayKey && msgDayKey !== lastDayKey) {
|
||||
lastDayKey = msgDayKey;
|
||||
const daySep = document.createElement('div');
|
||||
daySep.className = 'dm-day-separator';
|
||||
const dayLabel = document.createElement('span');
|
||||
dayLabel.textContent = formatDayLabel(msgTimeMs);
|
||||
daySep.append(dayLabel);
|
||||
list.append(daySep);
|
||||
}
|
||||
const isUnreadBoundary = showUnreadSeparator
|
||||
&& !unreadSeparatorInserted
|
||||
&& separatorMessageKey
|
||||
@@ -1176,7 +1191,8 @@ function renderLog(
|
||||
|
||||
const timeNode = document.createElement('span');
|
||||
timeNode.className = 'bubble-time';
|
||||
timeNode.textContent = formatMessageTime(resolveMessageTimeMs(msg));
|
||||
timeNode.textContent = formatClockTime(resolveMessageTimeMs(msg));
|
||||
timeNode.title = formatMessageTime(resolveMessageTimeMs(msg));
|
||||
metaNode.append(timeNode);
|
||||
|
||||
const status = resolveDeliveryStatus(messages, msg);
|
||||
@@ -1812,7 +1828,7 @@ export function render({ navigate, route, chrome }) {
|
||||
updateSendButtonMode();
|
||||
const denied = error?.name === 'NotAllowedError' || error?.name === 'SecurityError';
|
||||
showToast(
|
||||
denied ? 'Нужно разрешить SHiNE доступ к микрофону.' : (error?.message || 'Не удалось начать запись'),
|
||||
denied ? 'Нужно разрешить Сиянию доступ к микрофону.' : (error?.message || 'Не удалось начать запись'),
|
||||
{ kind: 'error', timeoutMs: 2600 },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
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';
|
||||
@@ -65,15 +66,17 @@ export function render({navigate, chrome}) {
|
||||
let searchSeq = 0;
|
||||
|
||||
const input = document.createElement('input');
|
||||
input.className = 'input dm-input contact-search-input';
|
||||
input.className = 'search-field__input contact-search-input';
|
||||
input.type = 'text';
|
||||
input.name = 'contact';
|
||||
input.placeholder = 'Введите начало логина';
|
||||
input.placeholder = 'Логин или его начало';
|
||||
input.setAttribute('aria-label', 'Логин для поиска');
|
||||
input.enterKeyHint = 'search';
|
||||
input.autocomplete = 'off';
|
||||
input.maxLength = 80;
|
||||
|
||||
const resultsCard = document.createElement('section');
|
||||
resultsCard.className = 'card stack contact-search-results-card';
|
||||
resultsCard.className = 'stack contact-search-results';
|
||||
resultsCard.hidden = true;
|
||||
|
||||
const status = document.createElement('p');
|
||||
@@ -143,13 +146,13 @@ export function render({navigate, chrome}) {
|
||||
searchTimer = window.setTimeout(() => {
|
||||
searchTimer = 0;
|
||||
void runSearch();
|
||||
}, 2000);
|
||||
}, 500);
|
||||
};
|
||||
|
||||
const searchButton = document.createElement('button');
|
||||
searchButton.className = 'primary-btn dm-send-btn';
|
||||
searchButton.className = 'search-field__action';
|
||||
searchButton.type = 'button';
|
||||
searchButton.textContent = 'Поиск';
|
||||
searchButton.textContent = 'Найти';
|
||||
searchButton.addEventListener('click', async () => {
|
||||
if (searchTimer) {
|
||||
window.clearTimeout(searchTimer);
|
||||
@@ -161,19 +164,21 @@ export function render({navigate, chrome}) {
|
||||
input.addEventListener('input', () => {
|
||||
scheduleSearch();
|
||||
});
|
||||
input.addEventListener('keydown', (event) => {
|
||||
if (event.key !== 'Enter') return;
|
||||
event.preventDefault();
|
||||
searchButton.click();
|
||||
});
|
||||
|
||||
const controls = document.createElement('div');
|
||||
controls.className = 'contact-search-actions';
|
||||
controls.append(searchButton);
|
||||
|
||||
const formCard = document.createElement('section');
|
||||
formCard.className = 'card stack contact-search-form-card';
|
||||
formCard.append(input, controls);
|
||||
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);
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'Поиск контактов',
|
||||
title: 'Найти человека',
|
||||
back: { label: '←', onClick: () => navigate('messages-list') },
|
||||
}));
|
||||
screen.append(
|
||||
|
||||
@@ -207,7 +207,7 @@ async function forceUiUpdateNow() {
|
||||
function showClientUpdateHelp() {
|
||||
window.alert(
|
||||
'Если UI не обновился:\n\n'
|
||||
+ '1) Закройте вкладки с SHiNE.\n'
|
||||
+ '1) Закройте вкладки с Сиянием.\n'
|
||||
+ `2) Откройте chrome://settings/siteData и удалите данные для ${defaultServerAddress}.\n`
|
||||
+ '3) Если приложение установлено как PWA — удалите его с устройства.\n'
|
||||
+ `4) Откройте ${defaultServerHttp} заново и выполните вход.\n`
|
||||
@@ -256,17 +256,17 @@ export function render({navigate, chrome}) {
|
||||
}));
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack settings-developer-card';
|
||||
card.className = 'nav-list settings-developer-card';
|
||||
card.innerHTML = `
|
||||
<button class="shine-btn shine-btn--settings" type="button" id="settings-force-ui-update">Принудительно обновить UI</button>
|
||||
<button class="shine-btn shine-btn--settings" type="button" id="settings-force-update-help">Клиент не обновляется?</button>
|
||||
<button class="shine-btn shine-btn--settings" type="button" id="settings-ui-error-reporting">Отправлять ошибки на сервер</button>
|
||||
<button class="shine-btn shine-btn--settings" type="button" id="settings-solana-users-init">Solana: init регистрации</button>
|
||||
<button class="shine-btn shine-btn--settings" type="button" id="settings-solana-rpc-check">Solana: проверить public RPC</button>
|
||||
<button class="shine-btn shine-btn--settings" type="button" id="settings-app-log">Лог приложения</button>
|
||||
<button class="shine-btn shine-btn--settings" type="button" id="settings-pwa-diagnostics">Диагностика PWA / Push</button>
|
||||
<button class="shine-btn shine-btn--settings" type="button" id="settings-pwa-install">Как установить PWA</button>
|
||||
<button class="shine-btn shine-btn--settings" type="button" id="settings-upload-avatar">Загрузить аватар</button>
|
||||
<button class="nav-row" type="button" id="settings-force-ui-update"><span class="nav-row__label">Принудительно обновить UI</span></button>
|
||||
<button class="nav-row" type="button" id="settings-force-update-help"><span class="nav-row__label">Клиент не обновляется?</span></button>
|
||||
<button class="nav-row" type="button" id="settings-ui-error-reporting"><span class="nav-row__label">Отправлять ошибки на сервер</span></button>
|
||||
<button class="nav-row" type="button" id="settings-solana-users-init"><span class="nav-row__label">Solana: первичная настройка регистрации</span></button>
|
||||
<button class="nav-row" type="button" id="settings-solana-rpc-check"><span class="nav-row__label">Solana: проверить публичный узел</span></button>
|
||||
<button class="nav-row" type="button" id="settings-app-log"><span class="nav-row__label">Лог приложения</span></button>
|
||||
<button class="nav-row" type="button" id="settings-pwa-diagnostics"><span class="nav-row__label">Диагностика PWA / Push</span></button>
|
||||
<button class="nav-row" type="button" id="settings-pwa-install"><span class="nav-row__label">Установка на главный экран</span></button>
|
||||
<button class="nav-row" type="button" id="settings-upload-avatar"><span class="nav-row__label">Загрузить аватар</span></button>
|
||||
`;
|
||||
|
||||
const appLogBtn = card.querySelector('#settings-app-log');
|
||||
@@ -307,16 +307,22 @@ export function render({navigate, chrome}) {
|
||||
}
|
||||
});
|
||||
|
||||
// Меняем только подпись строки: textContent на самой кнопке стирал .nav-row__label, и строка выбивалась по кеглю.
|
||||
const setPwaLabel = (text) => {
|
||||
const labelEl = pwaInstallBtn.querySelector('.nav-row__label');
|
||||
if (labelEl) labelEl.textContent = text;
|
||||
else pwaInstallBtn.textContent = text;
|
||||
};
|
||||
const syncPwaButtonLabel = () => {
|
||||
if (isStandalonePwaMode()) {
|
||||
pwaInstallBtn.textContent = 'PWA установлено (проверить WebPush)';
|
||||
setPwaLabel('Приложение установлено — проверить уведомления');
|
||||
return;
|
||||
}
|
||||
if (canInstallPwa()) {
|
||||
pwaInstallBtn.textContent = 'Зарегистрировать PWA';
|
||||
setPwaLabel('Установить как приложение');
|
||||
return;
|
||||
}
|
||||
pwaInstallBtn.textContent = 'Как установить PWA';
|
||||
setPwaLabel('Установка на главный экран');
|
||||
};
|
||||
|
||||
const unsubscribeInstallAvailability = onPwaInstallAvailabilityChange(() => {
|
||||
|
||||
@@ -250,7 +250,7 @@ export function render({navigate, chrome}) {
|
||||
passwordDialog.style.inset = '0';
|
||||
passwordDialog.style.zIndex = '30';
|
||||
passwordDialog.innerHTML = `
|
||||
<div style="position:absolute; inset:0; background:rgba(5,9,16,0.72); backdrop-filter:blur(4px);" data-action="close-dialog"></div>
|
||||
<div style="position:absolute; inset:0; background:var(--scrim); backdrop-filter:blur(4px);" data-action="close-dialog"></div>
|
||||
<div class="card stack" style="position:absolute; left:50%; top:24px; width:min(calc(100vw - 32px), 360px); transform:translateX(-50%); gap:12px; box-shadow:var(--shadow);">
|
||||
<div class="stack" style="gap:6px;">
|
||||
<p class="field-label" id="pairing-dialog-title">Задать дополнительный пароль</p>
|
||||
@@ -292,7 +292,7 @@ export function render({navigate, chrome}) {
|
||||
dialogOverlay.style.inset = '0';
|
||||
dialogOverlay.style.zIndex = '2';
|
||||
dialogOverlay.innerHTML = `
|
||||
<div style="position:absolute; inset:0; background:rgba(5,9,16,0.78);"></div>
|
||||
<div style="position:absolute; inset:0; background:var(--scrim);"></div>
|
||||
<div class="card stack" style="position:absolute; left:50%; top:50%; width:min(calc(100% - 32px), 320px); transform:translate(-50%, -50%); gap:12px; box-shadow:var(--shadow);">
|
||||
<p class="field-label" id="pairing-dialog-overlay-title">Ошибка</p>
|
||||
<p class="meta-muted" id="pairing-dialog-overlay-text"></p>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import {
|
||||
isSessionInvalidError,
|
||||
@@ -11,24 +12,49 @@ import {
|
||||
export const pageMeta = { id: 'device-view', title: 'Устройства' };
|
||||
|
||||
function formatSessionType(sessionType) {
|
||||
if (Number(sessionType) === 100) return 'Homeserver';
|
||||
if (Number(sessionType) === 50) return 'Wallet';
|
||||
if (Number(sessionType) === 1) return 'Client';
|
||||
return `Type ${Number(sessionType) || 0}`;
|
||||
if (Number(sessionType) === 100) return 'Домашний сервер';
|
||||
if (Number(sessionType) === 50) return 'Кошелёк';
|
||||
if (Number(sessionType) === 1) return 'Приложение';
|
||||
return `Тип ${Number(sessionType) || 0}`;
|
||||
}
|
||||
|
||||
// «Mozilla/5.0 (X11; Linux x86_64) … Chrome/139 …» → «Chrome · Linux».
|
||||
function describeClient(userAgent) {
|
||||
const ua = String(userAgent || '');
|
||||
if (!ua) return 'Неизвестное устройство';
|
||||
const browser = /Edg\//.test(ua) ? 'Edge'
|
||||
: /OPR\/|Opera/.test(ua) ? 'Opera'
|
||||
: /Firefox\//.test(ua) ? 'Firefox'
|
||||
: /YaBrowser\//.test(ua) ? 'Яндекс Браузер'
|
||||
: /Chrome\//.test(ua) ? 'Chrome'
|
||||
: /Safari\//.test(ua) ? 'Safari'
|
||||
: '';
|
||||
const os = /iPhone/.test(ua) ? 'iPhone'
|
||||
: /iPad/.test(ua) ? 'iPad'
|
||||
: /Android/.test(ua) ? 'Android'
|
||||
: /Windows/.test(ua) ? 'Windows'
|
||||
: /Mac OS X|Macintosh/.test(ua) ? 'macOS'
|
||||
: /Linux|X11/.test(ua) ? 'Linux'
|
||||
: '';
|
||||
const parts = [browser, os].filter(Boolean);
|
||||
return parts.length ? parts.join(' · ') : ua.slice(0, 40);
|
||||
}
|
||||
|
||||
// «сегодня, 02:20» / «вчера, 23:10» / «24 сентября, 18:05».
|
||||
function formatSessionTime(ms) {
|
||||
return new Date(ms).toLocaleString('ru-RU', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
});
|
||||
const date = new Date(ms);
|
||||
const time = date.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
|
||||
const startOf = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
|
||||
const days = Math.round((startOf(new Date()) - startOf(date)) / 86400000);
|
||||
if (days === 0) return `сегодня, ${time}`;
|
||||
if (days === 1) return `вчера, ${time}`;
|
||||
const sameYear = date.getFullYear() === new Date().getFullYear();
|
||||
const day = date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long', ...(sameYear ? {} : { year: 'numeric' }) });
|
||||
return `${day}, ${time}`;
|
||||
}
|
||||
|
||||
function formatOnlineStatus(onlineOnThisServer) {
|
||||
return onlineOnThisServer ? 'Online now' : 'Offline';
|
||||
return onlineOnThisServer ? 'в сети' : 'не в сети';
|
||||
}
|
||||
|
||||
function sortSessionsByOnline(sessions = []) {
|
||||
@@ -47,15 +73,15 @@ export function render({navigate, chrome}) {
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'Устройства',
|
||||
back: { label: '←', onClick: () => navigate('settings-view') },
|
||||
actions: [{ icon: 'refresh', title: 'Обновить список сеансов', ariaLabel: 'Обновить список сеансов', id: 'reload-sessions', onClick: () => reloadSessions() }],
|
||||
}));
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'card stack';
|
||||
actions.className = 'nav-list';
|
||||
actions.innerHTML = `
|
||||
<button class="shine-btn shine-btn--settings settings-bordered-btn" type="button" id="reload-sessions-btn">Обновить сессии</button>
|
||||
<button class="shine-btn shine-btn--settings settings-bordered-btn" type="button" id="pair-by-code-btn">Подключить по коду</button>
|
||||
<button class="shine-btn shine-btn--settings settings-bordered-btn" type="button" id="connect-device-btn">Другие способы подключения</button>
|
||||
<button class="shine-btn shine-btn--settings settings-bordered-btn" type="button" id="show-keys-btn">Показать ключи</button>
|
||||
<button class="nav-row" type="button" id="pair-by-code-btn"><span class="nav-row__label">Подключить по коду</span><span class="nav-row__hint">Войти на другом устройстве по короткому коду</span></button>
|
||||
<button class="nav-row" type="button" id="connect-device-btn"><span class="nav-row__label">Другие способы подключения</span></button>
|
||||
<button class="nav-row" type="button" id="show-keys-btn"><span class="nav-row__label">Ключи этого устройства</span></button>
|
||||
`;
|
||||
|
||||
actions.querySelector('#pair-by-code-btn').addEventListener('click', () => navigate('device-pairing-view'));
|
||||
@@ -63,7 +89,7 @@ export function render({navigate, chrome}) {
|
||||
actions.querySelector('#show-keys-btn').addEventListener('click', () => navigate('show-keys-view'));
|
||||
|
||||
const sessionsBlock = document.createElement('div');
|
||||
sessionsBlock.className = 'card stack';
|
||||
sessionsBlock.className = 'stack device-sessions';
|
||||
|
||||
const buildList = () => {
|
||||
sessionsBlock.innerHTML = '';
|
||||
@@ -75,22 +101,25 @@ export function render({navigate, chrome}) {
|
||||
const item = document.createElement('button');
|
||||
item.className = 'ui-button session-item';
|
||||
item.type = 'button';
|
||||
const sessionTypeText = formatSessionType(session.sessionType);
|
||||
const sessionPlatformText = session.clientPlatform ? ` · ${session.clientPlatform}` : '';
|
||||
const isWebClient = Number(session.sessionType) === 1 && /web/i.test(String(session.clientPlatform || ''));
|
||||
const sessionTypeText = isWebClient ? 'Браузер' : formatSessionType(session.sessionType);
|
||||
const sessionPlatformText = !isWebClient && session.clientPlatform ? ` · ${session.clientPlatform}` : '';
|
||||
const onlineStatusText = formatOnlineStatus(!!session.onlineOnThisServer);
|
||||
const onlineStatusClass = session.onlineOnThisServer ? 'session-status session-status--online' : 'session-status';
|
||||
item.innerHTML = `
|
||||
<div class="row" style="align-items:flex-start;">
|
||||
<div class="stack" style="gap:4px; text-align:left;">
|
||||
<strong>${session.clientInfoFromClient || 'unknown client'}</strong>
|
||||
<span class="meta-muted"><strong>Type:</strong> ${sessionTypeText}${sessionPlatformText}</span>
|
||||
<span class="${onlineStatusClass}"><strong>Status:</strong> ${onlineStatusText}</span>
|
||||
<span class="meta-muted">${session.geo || 'unknown'}</span>
|
||||
</div>
|
||||
<span class="session-item__main">
|
||||
<strong class="session-item__title"></strong>
|
||||
<span class="meta-muted">${sessionTypeText}${sessionPlatformText} · <span class="${onlineStatusClass}">${onlineStatusText}</span></span>
|
||||
${session.geo && session.geo !== 'unknown' ? '<span class="meta-muted session-item__geo"></span>' : ''}
|
||||
</span>
|
||||
<span class="session-item__side">
|
||||
<span class="meta-muted">${formatSessionTime(session.lastAuthenticatedAtMs || Date.now())}</span>
|
||||
</div>
|
||||
${isCurrent ? '<div><span class="session-current-badge">Текущий сеанс</span></div>' : ''}
|
||||
</span>
|
||||
`;
|
||||
item.querySelector('.session-item__title').textContent = describeClient(session.clientInfoFromClient);
|
||||
item.title = String(session.clientInfoFromClient || '');
|
||||
const geoEl = item.querySelector('.session-item__geo');
|
||||
if (geoEl) geoEl.textContent = session.geo;
|
||||
item.addEventListener('click', () => navigate(`device-session-view/${session.sessionId}`));
|
||||
return item;
|
||||
};
|
||||
@@ -103,60 +132,36 @@ export function render({navigate, chrome}) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentMenu = document.createElement('div');
|
||||
currentMenu.className = 'stack';
|
||||
currentMenu.innerHTML = '<p class="meta-muted">Текущий сеанс</p>';
|
||||
currentMenu.append(createSessionItem(current, true));
|
||||
|
||||
const endCurrentSessionBtn = document.createElement('button');
|
||||
endCurrentSessionBtn.className = 'shine-btn shine-btn--settings settings-bordered-btn';
|
||||
endCurrentSessionBtn.type = 'button';
|
||||
endCurrentSessionBtn.textContent = 'Завершить текущую сессию';
|
||||
endCurrentSessionBtn.addEventListener('click', async () => {
|
||||
const confirmed = window.confirm('Хотите завершить текущую сессию?');
|
||||
if (!confirmed) return;
|
||||
|
||||
try {
|
||||
await terminateCurrentSession({
|
||||
infoMessage: 'Текущая сессия завершена, данные на устройстве очищены.',
|
||||
closeServerSession: true,
|
||||
});
|
||||
} catch (error) {
|
||||
if (!isSessionInvalidError(error)) {
|
||||
setAuthError(error.message);
|
||||
window.alert(error.message);
|
||||
return;
|
||||
}
|
||||
await terminateCurrentSession({
|
||||
infoMessage: 'Текущая сессия завершена, данные на устройстве очищены.',
|
||||
});
|
||||
}
|
||||
});
|
||||
currentMenu.append(endCurrentSessionBtn);
|
||||
|
||||
const othersMenu = document.createElement('div');
|
||||
othersMenu.className = 'stack';
|
||||
othersMenu.innerHTML = '<p class="meta-muted">Остальные сеансы</p>';
|
||||
const groupTitle = (text) => {
|
||||
const title = document.createElement('p');
|
||||
title.className = 'nav-list__title';
|
||||
title.textContent = text;
|
||||
return title;
|
||||
};
|
||||
const currentList = document.createElement('div');
|
||||
currentList.className = 'nav-list';
|
||||
currentList.append(createSessionItem(current, true));
|
||||
sessionsBlock.append(groupTitle('Это устройство'), currentList, groupTitle('Другие сеансы'));
|
||||
|
||||
if (others.length === 0) {
|
||||
const empty = document.createElement('p');
|
||||
empty.className = 'meta-muted';
|
||||
empty.className = 'empty-note';
|
||||
empty.textContent = 'Других сеансов нет.';
|
||||
othersMenu.append(empty);
|
||||
sessionsBlock.append(empty);
|
||||
} else {
|
||||
others.forEach((session) => {
|
||||
othersMenu.append(createSessionItem(session, false));
|
||||
});
|
||||
const othersList = document.createElement('div');
|
||||
othersList.className = 'nav-list';
|
||||
others.forEach((session) => othersList.append(createSessionItem(session, false)));
|
||||
sessionsBlock.append(othersList);
|
||||
}
|
||||
|
||||
sessionsBlock.append(currentMenu, othersMenu);
|
||||
};
|
||||
|
||||
actions.querySelector('#reload-sessions-btn').addEventListener('click', async () => {
|
||||
async function reloadSessions() {
|
||||
try {
|
||||
await refreshSessions();
|
||||
buildList();
|
||||
setAuthInfo('Список сессий обновлён.');
|
||||
setAuthInfo('Список сеансов обновлён.');
|
||||
showToast('Список сеансов обновлён');
|
||||
} catch (error) {
|
||||
if (isSessionInvalidError(error)) {
|
||||
await terminateCurrentSession({
|
||||
@@ -165,9 +170,9 @@ export function render({navigate, chrome}) {
|
||||
return;
|
||||
}
|
||||
setAuthError(error.message);
|
||||
window.alert(error.message);
|
||||
showToast(error.message, { kind: 'error' });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
buildList();
|
||||
screen.append(actions, sessionsBlock);
|
||||
|
||||
@@ -58,7 +58,7 @@ export function render() {
|
||||
amountHint.style.fontSize = '22px';
|
||||
amountHint.style.fontWeight = '800';
|
||||
amountHint.style.lineHeight = '1.25';
|
||||
amountHint.style.color = '#1fc97a';
|
||||
amountHint.style.color = 'var(--success)';
|
||||
amountHint.style.textAlign = 'center';
|
||||
amountHint.textContent = '';
|
||||
|
||||
@@ -69,7 +69,7 @@ export function render() {
|
||||
balanceHint.style.margin = '0';
|
||||
balanceHint.style.textAlign = 'center';
|
||||
balanceHint.style.fontSize = '14px';
|
||||
balanceHint.style.color = 'rgba(255,255,255,0.9)';
|
||||
balanceHint.style.color = 'var(--text-primary)';
|
||||
balanceHint.textContent = '';
|
||||
|
||||
const closeHint = document.createElement('p');
|
||||
@@ -79,7 +79,7 @@ export function render() {
|
||||
closeHint.style.fontSize = '26px';
|
||||
closeHint.style.fontWeight = '800';
|
||||
closeHint.style.lineHeight = '1.25';
|
||||
closeHint.style.color = '#1fc97a';
|
||||
closeHint.style.color = 'var(--success)';
|
||||
closeHint.style.textAlign = 'center';
|
||||
closeHint.textContent = 'Можете закрыть эту страницу и продолжить регистрацию.';
|
||||
|
||||
@@ -140,7 +140,7 @@ export function render() {
|
||||
status.textContent = `Транзакция прошла.\nSignature: ${tx.signature}`;
|
||||
status.style.fontSize = '13px';
|
||||
status.style.fontWeight = '500';
|
||||
status.style.color = 'rgba(255,255,255,0.88)';
|
||||
status.style.color = 'var(--text-secondary)';
|
||||
fillBtn.style.display = 'none';
|
||||
actions.style.display = 'none';
|
||||
amountHint.style.display = '';
|
||||
|
||||
@@ -11,7 +11,7 @@ export const pageMeta = { id: 'entry-settings-view', title: 'Настройки
|
||||
|
||||
const SERVER_FIELDS = [
|
||||
{ key: 'solanaServer', label: 'Адрес Solana сервера' },
|
||||
{ key: 'shineServerLogin', label: 'Логин сервера Сияние' },
|
||||
{ key: 'shineServerLogin', label: 'Сервер Сияния' },
|
||||
{ key: 'arweaveServer', label: 'Адрес сервера Arweave' },
|
||||
];
|
||||
|
||||
@@ -50,7 +50,7 @@ export function render({ navigate }) {
|
||||
controls.className = 'row wrap-row';
|
||||
|
||||
const checkButton = document.createElement('button');
|
||||
checkButton.className = 'shine-btn shine-btn--settings server-check-btn';
|
||||
checkButton.className = 'secondary-btn server-check-btn';
|
||||
checkButton.type = 'button';
|
||||
checkButton.textContent = 'Проверить';
|
||||
|
||||
@@ -132,7 +132,7 @@ export function render({ navigate }) {
|
||||
|
||||
if (isLocalDemoAvailable()) {
|
||||
const localDemoButton = document.createElement('button');
|
||||
localDemoButton.className = 'shine-btn shine-btn--settings preauth-local-demo-btn';
|
||||
localDemoButton.className = 'secondary-btn preauth-local-demo-btn';
|
||||
localDemoButton.type = 'button';
|
||||
localDemoButton.textContent = 'Открыть локальный тестовый режим';
|
||||
localDemoButton.addEventListener('click', () => {
|
||||
@@ -143,7 +143,7 @@ export function render({ navigate }) {
|
||||
}
|
||||
|
||||
const serverUiButton = document.createElement('button');
|
||||
serverUiButton.className = 'shine-btn shine-btn--settings';
|
||||
serverUiButton.className = 'secondary-btn';
|
||||
serverUiButton.type = 'button';
|
||||
serverUiButton.textContent = 'Настроить свой сервер';
|
||||
serverUiButton.addEventListener('click', () => {
|
||||
@@ -152,13 +152,13 @@ export function render({ navigate }) {
|
||||
});
|
||||
|
||||
const cancelButton = document.createElement('button');
|
||||
cancelButton.className = 'shine-btn shine-btn--settings';
|
||||
cancelButton.className = 'secondary-btn';
|
||||
cancelButton.type = 'button';
|
||||
cancelButton.textContent = 'Отмена';
|
||||
cancelButton.addEventListener('click', () => navigate('start-view'));
|
||||
|
||||
const saveButton = document.createElement('button');
|
||||
saveButton.className = 'shine-btn shine-btn--primary';
|
||||
saveButton.className = 'primary-btn';
|
||||
saveButton.type = 'button';
|
||||
saveButton.textContent = 'Сохранить';
|
||||
saveButton.addEventListener('click', async () => {
|
||||
|
||||
@@ -40,7 +40,7 @@ export function render({ navigate }) {
|
||||
</div>
|
||||
<div class="key-card stack">
|
||||
<label class="checkbox-row"><span class="field-label">Blockchain Key</span></label>
|
||||
<p class="meta-muted key-storage-option__description">Используется для подписи ваших действий и записей в блокчейне SHiNE.</p>
|
||||
<p class="meta-muted key-storage-option__description">Используется для подписи ваших действий и записей в блокчейне Сияния.</p>
|
||||
<input class="input" type="text" value="${state.keyStorage.blockchainKey}" />
|
||||
</div>
|
||||
<div class="key-card stack">
|
||||
|
||||
@@ -14,55 +14,38 @@ export function render({navigate, chrome}) {
|
||||
const returnPage = resolveReturnPage();
|
||||
let pendingLanguage = state.entrySettings.language === 'en' ? 'en' : 'ru';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
const topbar = createTopBar({
|
||||
title: 'Язык / Language',
|
||||
back: { label: '←', onClick: () => {
|
||||
sessionStorage.removeItem('shine-language-return-page');
|
||||
navigate(returnPage);
|
||||
} },
|
||||
}));
|
||||
});
|
||||
const embedTopbar = !state.session.isAuthorized;
|
||||
if (!embedTopbar) chrome?.setTopbar(topbar);
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack language-choice-card';
|
||||
card.innerHTML = `
|
||||
<p class="meta-muted language-choice-hint">Выберите язык интерфейса</p>
|
||||
<div class="language-segmented-control" role="radiogroup" aria-label="Язык интерфейса">
|
||||
<button class="language-segment${pendingLanguage === 'ru' ? ' is-selected' : ''}" type="button" data-language="ru" role="radio" aria-checked="${pendingLanguage === 'ru'}">Русский</button>
|
||||
<button class="language-segment${pendingLanguage === 'en' ? ' is-selected' : ''}" type="button" data-language="en" role="radio" aria-checked="${pendingLanguage === 'en'}">English</button>
|
||||
<span class="language-segmented-thumb" aria-hidden="true"></span>
|
||||
</div>
|
||||
<div class="language-choice-actions">
|
||||
<button class="shine-btn shine-btn--settings" type="button" data-action="cancel">Отмена</button>
|
||||
<button class="shine-btn shine-btn--primary" type="button" data-action="ok">OK</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const syncSelection = () => {
|
||||
card.dataset.language = pendingLanguage;
|
||||
card.querySelectorAll('[data-language]').forEach((item) => {
|
||||
const selected = item.dataset.language === pendingLanguage;
|
||||
item.classList.toggle('is-selected', selected);
|
||||
item.setAttribute('aria-checked', String(selected));
|
||||
card.className = 'nav-list language-list';
|
||||
card.setAttribute('role', 'radiogroup');
|
||||
card.setAttribute('aria-label', 'Язык интерфейса / Interface language');
|
||||
[['ru', 'Русский'], ['en', 'English']].forEach(([code, label]) => {
|
||||
const row = document.createElement('button');
|
||||
row.type = 'button';
|
||||
row.className = 'nav-row language-row';
|
||||
row.setAttribute('role', 'radio');
|
||||
row.setAttribute('aria-checked', String(pendingLanguage === code));
|
||||
row.innerHTML = `<span class="nav-row__label"></span>`;
|
||||
row.querySelector('.nav-row__label').textContent = label;
|
||||
row.addEventListener('click', () => {
|
||||
pendingLanguage = code;
|
||||
saveEntryLanguage(code);
|
||||
sessionStorage.removeItem('shine-language-return-page');
|
||||
navigate(returnPage);
|
||||
});
|
||||
};
|
||||
syncSelection();
|
||||
|
||||
card.querySelectorAll('[data-language]').forEach((button) => {
|
||||
button.addEventListener('click', () => {
|
||||
pendingLanguage = button.dataset.language === 'en' ? 'en' : 'ru';
|
||||
syncSelection();
|
||||
});
|
||||
});
|
||||
card.querySelector('[data-action="cancel"]')?.addEventListener('click', () => {
|
||||
sessionStorage.removeItem('shine-language-return-page');
|
||||
navigate(returnPage);
|
||||
});
|
||||
card.querySelector('[data-action="ok"]')?.addEventListener('click', () => {
|
||||
saveEntryLanguage(pendingLanguage);
|
||||
sessionStorage.removeItem('shine-language-return-page');
|
||||
navigate(returnPage);
|
||||
card.append(row);
|
||||
});
|
||||
|
||||
if (embedTopbar) screen.append(topbar);
|
||||
screen.append(card);
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ export function render({ navigate }) {
|
||||
const remoteText = document.createElement('p');
|
||||
remoteText.className = 'auth-copy';
|
||||
const serverLoginEl = document.createElement('strong');
|
||||
const textBefore = document.createTextNode('Этот пользователь SHiNE зарегистрирован на другом сервере доступа: ');
|
||||
const textBefore = document.createTextNode('Этот пользователь Сияния зарегистрирован на другом сервере доступа: ');
|
||||
remoteText.append(textBefore, serverLoginEl, document.createTextNode('. Для входа перейдите на его сервер.'));
|
||||
|
||||
const serverLinkEl = document.createElement('a');
|
||||
@@ -111,11 +111,11 @@ export function render({ navigate }) {
|
||||
const resolution = String(resolved?.resolution || '').trim().toUpperCase();
|
||||
|
||||
if (resolution === 'NOT_FOUND') {
|
||||
setStatus(status, 'Пользователь с таким логином не зарегистрирован в SHiNE.');
|
||||
setStatus(status, 'Пользователь с таким логином не зарегистрирован в Сиянии.');
|
||||
return;
|
||||
}
|
||||
if (resolution === 'NO_ACCESS_SERVER') {
|
||||
setStatus(status, 'Пользователь зарегистрирован в SHiNE, но для него не найден действующий сервер доступа.');
|
||||
setStatus(status, 'Пользователь зарегистрирован в Сиянии, но для него не найден действующий сервер доступа.');
|
||||
return;
|
||||
}
|
||||
if (resolution === 'REMOTE') {
|
||||
@@ -155,7 +155,7 @@ export function render({ navigate }) {
|
||||
|
||||
screen.append(
|
||||
createTopBar({
|
||||
title: '',
|
||||
title: 'Вход',
|
||||
back: {
|
||||
label: '←',
|
||||
onClick: async () => {
|
||||
|
||||
@@ -8,21 +8,13 @@ import {
|
||||
terminateCurrentSession,
|
||||
} from '../state.js';
|
||||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { createOverflowDots } from '../components/overflow-dots.js';
|
||||
import { createDropdownMenu } from '../components/dropdown-menu.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createShineConnectionsLogo } from '../components/shine-logo.js';
|
||||
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||||
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
||||
import { formatRelativeTime } from '../services/channels-ux.js';
|
||||
import { formatListTime } from '../services/channels-ux.js';
|
||||
|
||||
export const pageMeta = { id: 'messages-list', title: 'Личные сообщения' };
|
||||
const PREVIEW_MAX_LEN = 200;
|
||||
const SVG_CHEVRON = `
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<path d="M9 6l6 6-6 6"></path>
|
||||
</svg>
|
||||
`;
|
||||
const DM_BLOB_PREVIEW_CACHE = new Map();
|
||||
const DM_BLOB_PREVIEW_PENDING = new Map();
|
||||
const dmAvatarSnapshotCache = new Map();
|
||||
@@ -119,6 +111,8 @@ function clipPreviewText(text, maxLen = PREVIEW_MAX_LEN) {
|
||||
return `${normalized.slice(0, maxLen - 1)}…`;
|
||||
}
|
||||
|
||||
const DM_PREVIEW_ENCRYPTED = 'Зашифрованное сообщение';
|
||||
|
||||
async function resolveDialogPreview(dialog) {
|
||||
const localText = clipPreviewText(String(dialog?.lastMessageText || '').trim());
|
||||
if (localText) return localText;
|
||||
@@ -131,6 +125,9 @@ async function resolveDialogPreview(dialog) {
|
||||
String(state.session.storagePwdInMemory || '').trim(),
|
||||
].join('|');
|
||||
|
||||
// После перезагрузки пароля хранилища в памяти нет — расшифровать нечем. Не кэшируем,
|
||||
// чтобы превью появилось, когда пароль снова будет введён.
|
||||
if (!String(state.session.storagePwdInMemory || '').trim()) return DM_PREVIEW_ENCRYPTED;
|
||||
if (DM_BLOB_PREVIEW_CACHE.has(cacheKey)) return DM_BLOB_PREVIEW_CACHE.get(cacheKey);
|
||||
if (DM_BLOB_PREVIEW_PENDING.has(cacheKey)) return DM_BLOB_PREVIEW_PENDING.get(cacheKey);
|
||||
|
||||
@@ -149,7 +146,7 @@ async function resolveDialogPreview(dialog) {
|
||||
DM_BLOB_PREVIEW_CACHE.set(cacheKey, result);
|
||||
return result;
|
||||
} catch {
|
||||
const fallback = 'Сообщение недоступно';
|
||||
const fallback = DM_PREVIEW_ENCRYPTED;
|
||||
DM_BLOB_PREVIEW_CACHE.set(cacheKey, fallback);
|
||||
return fallback;
|
||||
} finally {
|
||||
@@ -185,7 +182,7 @@ function latestLocalDialogMessage(peerLogin) {
|
||||
}
|
||||
|
||||
function formatChatRowTime(ts) {
|
||||
return formatRelativeTime(ts);
|
||||
return formatListTime(ts);
|
||||
}
|
||||
|
||||
function compareChatRows(a, b) {
|
||||
@@ -201,63 +198,45 @@ 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';
|
||||
const brand = document.createElement('div');
|
||||
brand.className = 'dm-head-brand';
|
||||
const logoWrap = document.createElement('span');
|
||||
logoWrap.className = 'dm-head-logo-wrap';
|
||||
logoWrap.setAttribute('aria-hidden', 'true');
|
||||
logoWrap.append(createShineConnectionsLogo({ className: 'dm-head-logo' }));
|
||||
brand.append(logoWrap);
|
||||
|
||||
let currentChatFilter = 'all';
|
||||
const filterTitle = document.createElement('button');
|
||||
filterTitle.type = 'button';
|
||||
filterTitle.className = 'dm-head-filter-title';
|
||||
filterTitle.textContent = 'Чаты';
|
||||
const filterLabels = {
|
||||
all: 'Чаты',
|
||||
close_friend: 'Близкие друзья',
|
||||
friend: 'Друзья',
|
||||
contact: 'Контакты',
|
||||
none: 'Новые',
|
||||
};
|
||||
const CHAT_FILTERS = [
|
||||
['all', 'Все'],
|
||||
['close_friend', 'Близкие'],
|
||||
['friend', 'Друзья'],
|
||||
['contact', 'Контакты'],
|
||||
['none', 'Новые'],
|
||||
];
|
||||
let reloadForFilter = () => {};
|
||||
const chatFilterMenu = createDropdownMenu({
|
||||
transparent: true,
|
||||
anchorEl: filterTitle,
|
||||
placement: 'bottom-start',
|
||||
leftShift: 72,
|
||||
minWidth: 225,
|
||||
items: [
|
||||
{ label: 'Все чаты', action: () => { currentChatFilter = 'all'; filterTitle.textContent = filterLabels.all; reloadForFilter(); } },
|
||||
{ label: 'Близкие друзья', action: () => { currentChatFilter = 'close_friend'; filterTitle.textContent = filterLabels.close_friend; reloadForFilter(); } },
|
||||
{ label: 'Друзья', action: () => { currentChatFilter = 'friend'; filterTitle.textContent = filterLabels.friend; reloadForFilter(); } },
|
||||
{ label: 'Контакты', action: () => { currentChatFilter = 'contact'; filterTitle.textContent = filterLabels.contact; reloadForFilter(); } },
|
||||
{ label: 'Новые', action: () => { currentChatFilter = 'none'; filterTitle.textContent = filterLabels.none; reloadForFilter(); } },
|
||||
],
|
||||
const filterRow = document.createElement('div');
|
||||
filterRow.className = 'chip-row chip-row--bleed dm-filter-row';
|
||||
filterRow.setAttribute('role', 'toolbar');
|
||||
filterRow.setAttribute('aria-label', 'Фильтр чатов');
|
||||
CHAT_FILTERS.forEach(([value, label]) => {
|
||||
const chip = document.createElement('button');
|
||||
chip.type = 'button';
|
||||
chip.className = 'chip';
|
||||
chip.dataset.filter = value;
|
||||
chip.textContent = label;
|
||||
chip.setAttribute('aria-pressed', String(value === currentChatFilter));
|
||||
chip.addEventListener('click', () => {
|
||||
if (currentChatFilter === value) return;
|
||||
currentChatFilter = value;
|
||||
filterRow.querySelectorAll('.chip').forEach((el) => el.setAttribute('aria-pressed', String(el.dataset.filter === value)));
|
||||
reloadForFilter();
|
||||
});
|
||||
filterRow.append(chip);
|
||||
});
|
||||
|
||||
const searchIconHtml = `
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<circle cx="11" cy="11" r="6.5"></circle>
|
||||
<path d="M16 16l4 4"></path>
|
||||
</svg>
|
||||
`;
|
||||
const head = createTopBar({
|
||||
left: brand,
|
||||
center: filterTitle,
|
||||
title: 'Чаты',
|
||||
className: 'topbar--root',
|
||||
actions: [
|
||||
{
|
||||
iconNode: createOverflowDots(),
|
||||
title: 'Меню чатов',
|
||||
ariaLabel: 'Меню чатов',
|
||||
className: 'messages-topbar-menu-btn topbar-overflow-action--raised',
|
||||
menu: {
|
||||
minWidth: 210,
|
||||
items: [
|
||||
{ label: 'Поиск пользователей', iconHtml: searchIconHtml, action: () => navigate('contact-search-view') },
|
||||
],
|
||||
},
|
||||
icon: 'search',
|
||||
title: 'Найти человека',
|
||||
ariaLabel: 'Найти человека',
|
||||
className: 'messages-search-btn',
|
||||
onClick: () => navigate('contact-search-view'),
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -269,9 +248,7 @@ function renderRow(item) {
|
||||
const row = document.createElement('article');
|
||||
row.className = 'list-item dm-dialog-card';
|
||||
const relationFlag = normalizeRelationFlag(item.relationFlag);
|
||||
const relationBadge = relationFlag === 'none'
|
||||
? 'не в контактах'
|
||||
: relationLabel(relationFlag);
|
||||
const relationBadge = relationFlag === 'none' ? '' : relationLabel(relationFlag);
|
||||
const avatarEl = createDmAvatar(item.peerLogin, {
|
||||
avatar: item.avatar,
|
||||
firstName: item.firstName,
|
||||
@@ -280,19 +257,19 @@ function renderRow(item) {
|
||||
avatarEl.classList.add('avatar');
|
||||
const avatarWrap = document.createElement('div');
|
||||
avatarWrap.className = 'dm-av dm-av--default';
|
||||
if (relationFlag !== 'none') row.classList.add(`dm-card--${relationFlag === 'close_friend' ? 'family' : 'contact'}`);
|
||||
avatarWrap.append(avatarEl);
|
||||
row.innerHTML = `
|
||||
<div class="dm-row-main">
|
||||
<div class="dm-row-titleline dm-row-titlewrap">
|
||||
<strong class="dm-row-title"></strong>
|
||||
<span class="dm-contact-note">${relationBadge}</span>
|
||||
${relationBadge ? `<span class="dm-contact-note dm-contact-note--${relationFlag}">${relationBadge}</span>` : ''}
|
||||
</div>
|
||||
<p class="dm-row-last-message"></p>
|
||||
</div>
|
||||
<div class="dm-row-meta-col">
|
||||
<div class="dm-row-meta-line">
|
||||
${item.lastMessageTimeMs ? '<span class="dm-row-time"></span>' : '<span class="dm-row-time dm-row-time--empty"></span>'}
|
||||
<span class="dm-chevron">${SVG_CHEVRON}</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>'}
|
||||
</div>
|
||||
@@ -310,6 +287,7 @@ function renderRow(item) {
|
||||
void resolveDialogPreview(item).then((text) => {
|
||||
if (!previewEl?.isConnected) return;
|
||||
previewEl.textContent = String(text || '').trim() || 'Диалог пока пуст.';
|
||||
previewEl.classList.toggle('is-encrypted', text === DM_PREVIEW_ENCRYPTED);
|
||||
});
|
||||
row.addEventListener('click', () => navigate(`chat/${encodeURIComponent(normalizeDmChatId(item.peerLogin))}`));
|
||||
return row;
|
||||
@@ -387,20 +365,13 @@ function renderRow(item) {
|
||||
|
||||
if (!rows.length) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'card meta-muted';
|
||||
empty.textContent = 'Пока нет диалогов';
|
||||
empty.className = 'empty-note';
|
||||
empty.textContent = 'Пока нет переписок. Найдите человека через поиск вверху.';
|
||||
list.append(empty);
|
||||
return;
|
||||
}
|
||||
|
||||
let dividerInserted = false;
|
||||
rows.forEach((item) => {
|
||||
if (!dividerInserted && normalizeRelationFlag(item.relationFlag) === 'none' && list.childNodes.length > 0) {
|
||||
const divider = document.createElement('div');
|
||||
divider.className = 'dm-divider';
|
||||
list.append(divider);
|
||||
dividerInserted = true;
|
||||
}
|
||||
list.append(renderRow(item));
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -444,12 +415,10 @@ function renderRow(item) {
|
||||
reloadForFilter = () => { void loadList(); };
|
||||
|
||||
chrome?.setTopbar(head);
|
||||
screen.append(list);
|
||||
screen.append(filterRow, list);
|
||||
loadList();
|
||||
|
||||
screen.cleanup = () => {
|
||||
chatFilterMenu.destroy();
|
||||
};
|
||||
screen.cleanup = () => {};
|
||||
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createOverflowDots } from '../components/overflow-dots.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { makeProfileRoute } from '../services/shine-routes.js';
|
||||
import { makeProfileLinksRoute } from '../services/shine-routes.js';
|
||||
@@ -358,7 +357,7 @@ async function buildSecondLevelEngineModel(baseModel, getGraph) {
|
||||
.filter(Boolean);
|
||||
if (failedParents.length) {
|
||||
const sample = failedParents.slice(0, 3).map((node) => node.login || node.id).join(', ');
|
||||
throw new Error(`X2: не удалось загрузить связи ${failedParents.length} из ${directFriends.length} друзей${sample ? ` (${sample})` : ''}`);
|
||||
throw new Error(`Друзья друзей: не удалось загрузить связи ${failedParents.length} из ${directFriends.length} друзей${sample ? ` (${sample})` : ''}`);
|
||||
}
|
||||
|
||||
// ФАЗА 3. Из уже полностью полученных графов собираем кандидатов второго уровня и все рёбра.
|
||||
@@ -930,16 +929,16 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
|
||||
function updateHistoryChip() {
|
||||
if (!(historyChip instanceof HTMLButtonElement)) return;
|
||||
historyChip.textContent = historyDepth > 0 ? `История ${historyDepth}` : 'История';
|
||||
historyChip.textContent = historyDepth > 0 ? `Недавние · ${historyDepth}` : 'Недавние';
|
||||
historyChip.classList.toggle('is-active', historyDepth > 0);
|
||||
historyChip.setAttribute('aria-pressed', historyDepth > 0 ? 'true' : 'false');
|
||||
historyChip.disabled = x2Enabled;
|
||||
historyChip.setAttribute('aria-disabled', x2Enabled ? 'true' : 'false');
|
||||
historyChip.title = x2Enabled
|
||||
? 'X2 показывает отдельную карту и временно не использует историю.'
|
||||
? '«Друзья друзей» показывают отдельную карту — недавние временно не используются.'
|
||||
: (historyDepth > 0
|
||||
? `Хранить предыдущих центров: ${historyDepth}. Нажмите для следующего значения.`
|
||||
: 'История выключена. Нажмите, чтобы хранить 1 предыдущий центр.');
|
||||
? `На карте остаются последние ${historyDepth} человека, через которых вы переходили. Нажмите, чтобы изменить.`
|
||||
: 'Недавние выключены. Нажмите, чтобы на карте оставался предыдущий человек.');
|
||||
}
|
||||
|
||||
function cycleHistoryDepth() {
|
||||
@@ -956,7 +955,7 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
if (!(x2Chip instanceof HTMLButtonElement)) return;
|
||||
x2Chip.classList.toggle('is-active', x2Enabled);
|
||||
x2Chip.setAttribute('aria-pressed', x2Enabled ? 'true' : 'false');
|
||||
x2Chip.title = x2Enabled ? 'Показаны друзья друзей. Нажмите, чтобы выключить X2.' : 'Показать друзей друзей.';
|
||||
x2Chip.title = x2Enabled ? 'Показаны друзья друзей. Нажмите, чтобы скрыть.' : 'Показать друзей друзей.';
|
||||
updateHistoryChip();
|
||||
}
|
||||
|
||||
@@ -1289,26 +1288,16 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
}
|
||||
|
||||
|
||||
const searchIconHtml = `
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<circle cx="11" cy="11" r="6.5"></circle>
|
||||
<path d="M16 16l4 4"></path>
|
||||
</svg>
|
||||
`;
|
||||
const header = createTopBar({
|
||||
title: 'Связи',
|
||||
className: 'topbar--root',
|
||||
actions: [
|
||||
{
|
||||
iconNode: createOverflowDots(),
|
||||
title: 'Меню связей',
|
||||
ariaLabel: 'Открыть меню связей',
|
||||
className: 'chat-header-icon-btn network-header-menu-btn',
|
||||
menu: {
|
||||
minWidth: 220,
|
||||
items: [
|
||||
{ label: 'Найти пользователя', iconHtml: searchIconHtml, action: openSearchModal },
|
||||
],
|
||||
},
|
||||
icon: 'search',
|
||||
title: 'Найти пользователя',
|
||||
ariaLabel: 'Найти пользователя',
|
||||
className: 'network-search-btn',
|
||||
onClick: openSearchModal,
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -1365,7 +1354,7 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
x2Chip = document.createElement('button');
|
||||
x2Chip.type = 'button';
|
||||
x2Chip.className = 'fg-filter-chip fg-x2-chip';
|
||||
x2Chip.textContent = 'X2';
|
||||
x2Chip.textContent = 'Друзья друзей';
|
||||
x2Chip.addEventListener('click', () => { void toggleX2(); });
|
||||
filterBar.append(x2Chip);
|
||||
updateX2Chip();
|
||||
|
||||
@@ -106,8 +106,27 @@ function easeOutCubic(t) {
|
||||
return 1 - x * x * x;
|
||||
}
|
||||
|
||||
const RELATION_COLORS_LIGHT = {
|
||||
family: 'rgba(184, 92, 20, 0.9)',
|
||||
friend: 'rgba(38, 96, 196, 0.9)',
|
||||
close_friend: 'rgba(38, 96, 196, 0.98)',
|
||||
business: 'rgba(108, 62, 200, 0.9)',
|
||||
contact: 'rgba(92, 98, 121, 0.75)',
|
||||
};
|
||||
|
||||
function isLightTheme() {
|
||||
return document.documentElement.dataset.theme === 'light';
|
||||
}
|
||||
|
||||
function shineStroke() {
|
||||
return isLightTheme()
|
||||
? { halo: '#0a7fb3', core: '#06567a', blend: 'normal' }
|
||||
: { halo: '#00e5ff', core: '#dffaff', blend: 'screen' };
|
||||
}
|
||||
|
||||
function relationColor(relationType) {
|
||||
return RELATION_COLORS[relationType] || RELATION_COLORS.contact;
|
||||
const palette = isLightTheme() ? RELATION_COLORS_LIGHT : RELATION_COLORS;
|
||||
return palette[relationType] || palette.contact;
|
||||
}
|
||||
|
||||
function resolveAvatarPhotoSrc(src) {
|
||||
@@ -1057,8 +1076,9 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
|
||||
// 3-й уровень: тонкая нить В ЦВЕТЕ СВЯЗИ (видна при раскрытии). Сияющая — светится (ореол+ядро).
|
||||
if (pe > 0.02) {
|
||||
if (shine) {
|
||||
parts.push(`<path d="${d}" fill="none" stroke="#00e5ff" stroke-width="2.6" stroke-linecap="round" opacity="${(0.42 * pe * sp).toFixed(2)}" filter="url(#fg-plasma-blur2)" style="mix-blend-mode:screen" />`);
|
||||
parts.push(`<path d="${d}" fill="none" stroke="#dffaff" stroke-width="1.1" stroke-linecap="round" opacity="${(0.85 * pe * sp).toFixed(2)}" />`);
|
||||
const ss = shineStroke();
|
||||
parts.push(`<path d="${d}" fill="none" stroke="${ss.halo}" stroke-width="2.6" stroke-linecap="round" opacity="${(0.42 * pe * sp).toFixed(2)}" filter="url(#fg-plasma-blur2)" style="mix-blend-mode:${ss.blend}" />`);
|
||||
parts.push(`<path d="${d}" fill="none" stroke="${ss.core}" stroke-width="1.1" stroke-linecap="round" opacity="${(0.85 * pe * sp).toFixed(2)}" />`);
|
||||
} else {
|
||||
parts.push(`<path d="${d}" fill="none" stroke="${relationColor(n.relationType)}" stroke-width="0.8" stroke-linecap="round" opacity="${(0.34 * pe * sp).toFixed(2)}" />`);
|
||||
}
|
||||
@@ -1067,8 +1087,9 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
|
||||
// 2-й уровень: связь В ЦВЕТЕ ТИПА (семья/друзья/...). Сияющая связь — светящаяся линия.
|
||||
if (pe > 0.02) {
|
||||
if (shine) {
|
||||
parts.push(`<path d="${d}" fill="none" stroke="#00e5ff" stroke-width="3.2" stroke-linecap="round" opacity="${(0.46 * pe * sp).toFixed(2)}" filter="url(#fg-plasma-blur2)" style="mix-blend-mode:screen" />`);
|
||||
parts.push(`<path d="${d}" fill="none" stroke="#dffaff" stroke-width="1.3" stroke-linecap="round" opacity="${(0.9 * pe * sp).toFixed(2)}" />`);
|
||||
const ss = shineStroke();
|
||||
parts.push(`<path d="${d}" fill="none" stroke="${ss.halo}" stroke-width="3.2" stroke-linecap="round" opacity="${(0.46 * pe * sp).toFixed(2)}" filter="url(#fg-plasma-blur2)" style="mix-blend-mode:${ss.blend}" />`);
|
||||
parts.push(`<path d="${d}" fill="none" stroke="${ss.core}" stroke-width="1.3" stroke-linecap="round" opacity="${(0.9 * pe * sp).toFixed(2)}" />`);
|
||||
} else {
|
||||
parts.push(`<path d="${d}" fill="none" stroke="${relationColor(n.relationType)}" stroke-width="1.0" stroke-linecap="round" opacity="${(0.42 * pe * sp).toFixed(2)}" />`);
|
||||
}
|
||||
|
||||
@@ -158,7 +158,7 @@ function renderEmpty(activeTab) {
|
||||
title.textContent = activeTab === 'events' ? 'Пока нет событий' : activeTab === 'connections' ? 'Пока нет связей' : 'Пока нет ответов';
|
||||
const text = document.createElement('p');
|
||||
text.className = 'meta-muted';
|
||||
text.textContent = activeTab === 'events' ? 'Подписки и отписки от ваших каналов появятся здесь.' : activeTab === 'connections' ? 'Изменения дружбы и подтверждений появятся здесь.' : 'Когда кто-то ответит на ваше сообщение в канале или треде, ответ появится здесь.';
|
||||
text.textContent = activeTab === 'events' ? 'Подписки и отписки от ваших каналов появятся здесь.' : activeTab === 'connections' ? 'Изменения дружбы и подтверждений появятся здесь.' : 'Когда кто-то ответит на ваше сообщение в канале или обсуждении, ответ появится здесь.';
|
||||
card.append(title, text);
|
||||
return card;
|
||||
}
|
||||
@@ -322,12 +322,15 @@ export function render({ navigate, chrome } = {}) {
|
||||
screen.className = 'stack notifications-screen';
|
||||
|
||||
const tabs = document.createElement('div');
|
||||
tabs.className = 'notification-feed-tabs app-top-tabs';
|
||||
tabs.className = 'tabs tabs--three notification-feed-tabs';
|
||||
tabs.setAttribute('role', 'radiogroup');
|
||||
tabs.setAttribute('aria-label', 'Категория уведомлений');
|
||||
const tabDefs = [['replies','Ответы'],['connections','Связи'],['events','События']];
|
||||
chrome?.setTopbar(createTopBar({
|
||||
center: tabs,
|
||||
className: 'notifications-topbar',
|
||||
title: 'Уведомления',
|
||||
className: 'topbar--root notifications-topbar',
|
||||
}));
|
||||
screen.append(tabs);
|
||||
|
||||
const list = document.createElement('div');
|
||||
list.className = 'stack notifications-list';
|
||||
@@ -352,15 +355,22 @@ export function render({ navigate, chrome } = {}) {
|
||||
if (!btn) return;
|
||||
let badge = btn.querySelector('.notification-toolbar-badge');
|
||||
if (state.notificationUnreadTotal <= 0) { badge?.remove(); return; }
|
||||
if (!badge) { badge = document.createElement('span'); badge.className = 'toolbar-unread-badge notification-toolbar-badge'; btn.append(badge); }
|
||||
if (!badge) { badge = document.createElement('span'); badge.className = 'toolbar-unread-badge notification-toolbar-badge'; (btn.querySelector('.toolbar-icon') || btn).append(badge); }
|
||||
badge.textContent = state.notificationUnreadTotal > 99 ? '99+' : String(state.notificationUnreadTotal);
|
||||
}
|
||||
|
||||
function renderTabs(payload) {
|
||||
const counts = countsFromPayload(payload);
|
||||
tabs.replaceChildren(...tabDefs.map(([key,label]) => {
|
||||
const b=document.createElement('button'); b.type='button'; b.className=`fg-filter-chip notification-tab-btn ${state.notificationsTab===key?'is-active':''}`; b.dataset.tab=key; b.setAttribute('aria-selected',state.notificationsTab===key?'true':'false');
|
||||
b.textContent = counts[key] > 0 ? `${label} ${counts[key]}` : label;
|
||||
const b=document.createElement('button'); b.type='button'; b.className='tab-btn notification-tab-btn'; b.dataset.tab=key; b.setAttribute('role','radio'); b.setAttribute('aria-checked',state.notificationsTab===key?'true':'false');
|
||||
b.textContent = label;
|
||||
if (counts[key] > 0) {
|
||||
const count = document.createElement('span');
|
||||
count.className = 'tab-count';
|
||||
count.textContent = counts[key] > 99 ? '99+' : String(counts[key]);
|
||||
count.setAttribute('aria-label', `новых: ${counts[key]}`);
|
||||
b.append(count);
|
||||
}
|
||||
b.addEventListener('click',()=>{ if(state.notificationsTab===key)return; state.notificationsTab=key; renderCurrent(); });
|
||||
return b;
|
||||
}));
|
||||
|
||||
@@ -114,7 +114,7 @@ export function render({ navigate, chrome }) {
|
||||
);
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack';
|
||||
card.className = 'stack profile-edit-card';
|
||||
|
||||
const topRow = document.createElement('div');
|
||||
topRow.className = 'row';
|
||||
@@ -127,14 +127,14 @@ export function render({ navigate, chrome }) {
|
||||
<div class="profile-identity-line profile-identity-login">${String(login || '').trim() || 'unknown'}</div>
|
||||
</div>
|
||||
</div>
|
||||
<button class="primary-btn" type="button" data-reload="true">Обновить</button>
|
||||
<button class="secondary-btn profile-edit-reload" type="button" data-reload="true" hidden>Обновить</button>
|
||||
`;
|
||||
|
||||
const badgesRow = document.createElement('div');
|
||||
badgesRow.className = 'row';
|
||||
badgesRow.className = 'chip-row profile-edit-statuses';
|
||||
badgesRow.innerHTML = `
|
||||
<button class="badge profile-toggle-btn is-no" type="button" data-status="account_role">Аккаунт: Не указано</button>
|
||||
<button class="badge profile-toggle-btn is-no" type="button" data-status="shine">Сияние: Не указано</button>
|
||||
<button class="chip profile-toggle-btn is-no" type="button" data-status="account_role">Тип аккаунта: Не указано</button>
|
||||
<button class="chip profile-toggle-btn is-no" type="button" data-status="shine">Сияние: Не указано</button>
|
||||
`;
|
||||
|
||||
const status = document.createElement('div');
|
||||
@@ -142,16 +142,13 @@ export function render({ navigate, chrome }) {
|
||||
status.textContent = 'Загрузка параметров...';
|
||||
|
||||
const listWrap = document.createElement('div');
|
||||
listWrap.className = 'stack profile-param-list';
|
||||
listWrap.className = 'nav-list profile-param-list';
|
||||
|
||||
const relativesCard = document.createElement('div');
|
||||
relativesCard.className = 'card stack';
|
||||
relativesCard.innerHTML = `
|
||||
<div class="profile-param-value"><b>Друзья</b></div>
|
||||
<div class="meta-muted">
|
||||
Добавьте пользователя в друзья или в близкие друзья.
|
||||
Родственные типы связей сохранены в протоколе, но пока скрыты из интерфейса.
|
||||
</div>
|
||||
<div class="meta-muted">Добавьте человека в друзья или в близкие друзья.</div>
|
||||
<button class="secondary-btn" type="button" data-add-relative="true">Добавить друга</button>
|
||||
`;
|
||||
|
||||
@@ -250,7 +247,7 @@ export function render({ navigate, chrome }) {
|
||||
|
||||
function updateStatusesUi() {
|
||||
if (accountRoleBtn) {
|
||||
accountRoleBtn.textContent = `Аккаунт: ${accountRoleLabel(currentAccountRole)}`;
|
||||
accountRoleBtn.textContent = `Тип аккаунта: ${accountRoleLabel(currentAccountRole)}`;
|
||||
accountRoleBtn.classList.remove('is-no', 'is-yes-official', 'is-yes-shine', 'is-not-interested');
|
||||
accountRoleBtn.classList.add(currentAccountRole === PROFILE_ACCOUNT_ROLE_PRIMARY ? 'is-yes-official' : 'is-no');
|
||||
}
|
||||
@@ -582,22 +579,22 @@ export function render({ navigate, chrome }) {
|
||||
function renderFields(fields) {
|
||||
listWrap.innerHTML = '';
|
||||
fields.forEach((field) => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'card profile-param-item row';
|
||||
const row = document.createElement('button');
|
||||
row.type = 'button';
|
||||
row.className = 'nav-row profile-param-item';
|
||||
row.dataset.editField = field.key;
|
||||
row.style.cursor = 'pointer';
|
||||
const value = String(field.value || '').trim() || 'не заполнено';
|
||||
const isNameField = field.key === 'first_name' || field.key === 'last_name';
|
||||
const valueClass = isNameField ? 'profile-param-value profile-param-value-small' : 'profile-param-value';
|
||||
row.innerHTML = `<div class="${valueClass}"><b>${field.label}</b>: ${escapeHtml(value)}</div>`;
|
||||
const value = String(field.value || '').trim();
|
||||
row.innerHTML = `<span class="nav-row__hint">${escapeHtml(field.label)}</span><span class="nav-row__label${value ? '' : ' is-empty'}">${escapeHtml(value || 'Не заполнено')}</span>`;
|
||||
listWrap.append(row);
|
||||
|
||||
if (field.key === 'last_name') {
|
||||
const genderRow = document.createElement('div');
|
||||
genderRow.className = 'card profile-param-item row';
|
||||
const genderRow = document.createElement('button');
|
||||
genderRow.type = 'button';
|
||||
genderRow.className = 'nav-row profile-param-item';
|
||||
genderRow.dataset.editGender = 'true';
|
||||
genderRow.style.cursor = 'pointer';
|
||||
genderRow.innerHTML = `<div class="profile-param-value"><b>Пол</b>: <span data-gender-value>${escapeHtml(genderLabel(currentGender))}</span></div>`;
|
||||
const genderText = genderLabel(currentGender);
|
||||
const genderEmpty = genderText === 'Не указан';
|
||||
genderRow.innerHTML = `<span class="nav-row__hint">Пол</span><span class="nav-row__label${genderEmpty ? ' is-empty' : ''}" data-gender-value>${escapeHtml(genderEmpty ? 'Не указан' : genderText)}</span>`;
|
||||
listWrap.append(genderRow);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,104 +1,20 @@
|
||||
import { profile } from '../mock-data.js';
|
||||
import { state } from '../state.js';
|
||||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { createOverflowDots } from '../components/overflow-dots.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { loadUserProfileCard } from '../services/user-connections.js';
|
||||
import { profileCardHtml, profileTileHtml } from '../components/profile-card.js';
|
||||
|
||||
export const pageMeta = { id: 'profile-view', title: 'Профиль' };
|
||||
|
||||
function escapeHtml(text) {
|
||||
return String(text || '')
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
|
||||
function metricHtml({ kind, label, value, glow = false, positionClass = '' }) {
|
||||
const numericValue = Number(value || 0);
|
||||
return `
|
||||
<button
|
||||
type="button"
|
||||
class="user-profile-metric ${positionClass}${glow ? ' is-glowing' : ''}"
|
||||
data-profile-list="${escapeHtml(kind)}"
|
||||
aria-label="${escapeHtml(label)}: ${numericValue}"
|
||||
>
|
||||
<span class="user-profile-metric-circle">${numericValue}</span>
|
||||
<span class="user-profile-metric-label">${escapeHtml(label)}</span>
|
||||
</button>`;
|
||||
}
|
||||
|
||||
function friendsMetricHtml(stats = {}) {
|
||||
const friends = Number(stats.friendsCount || 0);
|
||||
const closeFriends = Number(stats.closeFriendsCount || 0);
|
||||
return `
|
||||
<button
|
||||
type="button"
|
||||
class="user-profile-metric is-social-metric is-friends-combined"
|
||||
data-profile-list="friends"
|
||||
aria-label="Друзья: ${friends}; близкие друзья: ${closeFriends}"
|
||||
>
|
||||
<span class="user-profile-metric-value-combined">${closeFriends} / ${friends}</span>
|
||||
<span class="user-profile-metric-label">Друзья</span>
|
||||
</button>`;
|
||||
}
|
||||
|
||||
function hasContacts(card) {
|
||||
return [card?.web, card?.phone, card?.address].some((value) => String(value || '').trim());
|
||||
}
|
||||
|
||||
function spiritualPathDetailHtml(card) {
|
||||
const value = String(card?.spiritualPath || '').trim();
|
||||
return `<div class="user-profile-detail-copy${value ? '' : ' is-muted'}">${escapeHtml(value || 'Не заполнено')}</div>`;
|
||||
}
|
||||
|
||||
function contactsDetailHtml(card) {
|
||||
const rows = [
|
||||
['Ссылки', card?.web],
|
||||
['Телефон', card?.phone],
|
||||
['Адрес', card?.address],
|
||||
].filter(([, value]) => String(value || '').trim());
|
||||
|
||||
if (!rows.length) {
|
||||
return '<div class="user-profile-detail-copy is-muted">Не заполнено</div>';
|
||||
}
|
||||
return rows.map(([label, value]) => `
|
||||
<div class="user-profile-contact-row">
|
||||
<span>${escapeHtml(label)}</span>
|
||||
<b>${escapeHtml(value)}</b>
|
||||
</div>`).join('');
|
||||
}
|
||||
|
||||
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 topbar = createTopBar({
|
||||
title: login || 'Профиль',
|
||||
className: 'topbar--profile user-profile-header',
|
||||
actions: [
|
||||
{
|
||||
iconNode: createOverflowDots(),
|
||||
title: 'Меню профиля',
|
||||
ariaLabel: 'Меню профиля',
|
||||
className: 'profile-head-menu-btn topbar-overflow-action--raised',
|
||||
menu: {
|
||||
className: 'profile-head-menu',
|
||||
minWidth: 250,
|
||||
items: [
|
||||
{ label: 'Редактировать профиль', iconSrc: '/assets/profile-icon-profile.svg', action: () => navigate('profile-edit-view') },
|
||||
{ label: 'Кошелёк', iconSrc: '/assets/profile-icon-wallet.svg', action: () => navigate('wallet-view') },
|
||||
{ label: 'Настройки', iconSrc: '/assets/profile-icon-settings.svg', action: () => navigate('settings-view') },
|
||||
{ label: 'Подтверждённые аккаунты', action: () => navigate(`SHiNE/${encodeURIComponent(login)}/list/primary_given`) },
|
||||
{ label: 'Подтверждённые сияющие', action: () => navigate(`SHiNE/${encodeURIComponent(login)}/list/shine_given`) },
|
||||
{ label: 'Сменить профиль', action: () => navigate('profiles-view') },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
title: 'Профиль',
|
||||
className: 'topbar--root user-profile-header',
|
||||
});
|
||||
chrome?.setTopbar(topbar);
|
||||
|
||||
@@ -114,57 +30,21 @@ export function render({ navigate, chrome }) {
|
||||
|
||||
function renderProfile() {
|
||||
if (!card) return;
|
||||
const stats = card.stats || {};
|
||||
const official = card.accountRole === 'primary';
|
||||
const shining = card.shineStatus === 'shining';
|
||||
const fullName = [card.firstName, card.lastName]
|
||||
.map((value) => String(value || '').trim())
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
const displayName = fullName || card.login || login || 'Профиль';
|
||||
const about = String(card.about || '').trim();
|
||||
const spiritualPath = String(card.spiritualPath || '').trim();
|
||||
const contactsVisible = hasContacts(card);
|
||||
|
||||
const title = topbar.querySelector('.topbar__title');
|
||||
if (title) title.textContent = card.login || login || 'Профиль';
|
||||
|
||||
body.innerHTML = `
|
||||
<div class="user-profile-hero" aria-label="Профиль ${escapeHtml(card.login)}">
|
||||
${metricHtml({ kind: 'primary_received', label: 'Официальный', value: stats.primaryReceivedCount, glow: official, positionClass: 'is-top-left' })}
|
||||
${metricHtml({ kind: 'shine_received', label: 'Сияющий', value: stats.shineReceivedCount, glow: shining, positionClass: 'is-top-right' })}
|
||||
<div class="user-profile-avatar-slot"></div>
|
||||
</div>
|
||||
|
||||
<div class="user-profile-identity">
|
||||
<div class="user-profile-full-name">${escapeHtml(displayName)}</div>
|
||||
<div class="user-profile-login">@${escapeHtml(card.login || login)}</div>
|
||||
</div>
|
||||
|
||||
<div class="user-profile-social-metrics">
|
||||
${friendsMetricHtml(stats)}
|
||||
${metricHtml({ kind: 'channels_owned', label: 'Каналы', value: stats.ownedPublicChannelsCount, positionClass: 'is-social-metric' })}
|
||||
${metricHtml({ kind: 'channels_following', label: 'Подписки', value: stats.followingChannelsCount, positionClass: 'is-social-metric' })}
|
||||
</div>
|
||||
|
||||
<section class="user-profile-about-card" aria-label="О себе">
|
||||
<div class="user-profile-about-title">О себе</div>
|
||||
<div class="user-profile-about-field${about ? '' : ' is-empty'}">${escapeHtml(about || 'Не заполнено')}</div>
|
||||
</section>
|
||||
|
||||
${(contactsVisible || spiritualPath) ? `
|
||||
<div class="user-profile-detail-links user-profile-detail-links--below-about" aria-label="Дополнительная информация о профиле">
|
||||
${contactsVisible ? `<button type="button" class="ui-button" data-profile-detail="contacts" aria-pressed="false" aria-controls="profile-view-detail-panel"><span class="user-profile-detail-tab-label">Контакты</span></button>` : '<span></span>'}
|
||||
${spiritualPath ? `<button type="button" class="ui-button" data-profile-detail="spiritual-path" aria-pressed="false" aria-controls="profile-view-detail-panel"><span class="user-profile-detail-tab-label">Духовный путь</span></button>` : '<span></span>'}
|
||||
</div>
|
||||
<section class="user-profile-detail-panel" id="profile-view-detail-panel" aria-live="polite" hidden></section>` : ''}
|
||||
|
||||
<div class="user-profile-actions-wrap">
|
||||
<div class="user-profile-actions" aria-label="Действия со своим профилем">
|
||||
<button type="button" class="user-profile-action-btn" data-self-profile-action="edit" aria-label="Редактировать профиль" title="Редактировать профиль"><img src="/assets/profile-icon-profile.svg" alt="" aria-hidden="true"></button>
|
||||
<button type="button" class="user-profile-action-btn" data-self-profile-action="wallet" aria-label="Кошелёк" title="Кошелёк"><img src="/assets/profile-icon-wallet.svg" alt="" aria-hidden="true"></button>
|
||||
<button type="button" class="user-profile-action-btn" data-self-profile-action="settings" aria-label="Настройки" title="Настройки"><img src="/assets/profile-icon-settings.svg" alt="" aria-hidden="true"></button>
|
||||
</div>
|
||||
body.innerHTML = profileCardHtml({
|
||||
card,
|
||||
login,
|
||||
tilesHtml: [
|
||||
profileTileHtml({ icon: 'edit', label: 'Редактировать', attrs: 'data-self-profile-action="edit"' }),
|
||||
profileTileHtml({ icon: 'wallet', label: 'Кошелёк', attrs: 'data-self-profile-action="wallet"' }),
|
||||
profileTileHtml({ icon: 'settings', label: 'Настройки', attrs: 'data-self-profile-action="settings"' }),
|
||||
].join(''),
|
||||
}) + `
|
||||
<div class="nav-list profile-more-list">
|
||||
<button class="nav-row" type="button" data-profile-list="primary_given"><span class="nav-row__label">Подтверждённые мной аккаунты</span><span class="nav-row__hint">Аккаунты, за которые вы поручились</span></button>
|
||||
<button class="nav-row" type="button" data-profile-list="shine_given"><span class="nav-row__label">Отмеченные мной как сияющие</span></button>
|
||||
<button class="nav-row" type="button" data-self-profile-action="profiles"><span class="nav-row__label">Сменить профиль</span><span class="nav-row__hint">Другие аккаунты на этом устройстве</span></button>
|
||||
</div>`;
|
||||
|
||||
const avatarSlot = body.querySelector('.user-profile-avatar-slot');
|
||||
@@ -198,31 +78,10 @@ export function render({ navigate, chrome }) {
|
||||
if (action === 'edit') navigate('profile-edit-view');
|
||||
if (action === 'wallet') navigate('wallet-view');
|
||||
if (action === 'settings') navigate('settings-view');
|
||||
if (action === 'profiles') navigate('profiles-view');
|
||||
return;
|
||||
}
|
||||
|
||||
const detailButton = event.target.closest('[data-profile-detail]');
|
||||
if (!detailButton) return;
|
||||
const detailKind = detailButton.dataset.profileDetail;
|
||||
const detailPanel = body.querySelector('#profile-view-detail-panel');
|
||||
if (!detailPanel) return;
|
||||
|
||||
body.querySelectorAll('[data-profile-detail]').forEach((button) => {
|
||||
const active = button === detailButton;
|
||||
button.classList.toggle('is-active', active);
|
||||
button.setAttribute('aria-pressed', active ? 'true' : 'false');
|
||||
});
|
||||
|
||||
if (detailKind === 'spiritual-path') {
|
||||
detailPanel.innerHTML = spiritualPathDetailHtml(card);
|
||||
} else if (detailKind === 'contacts') {
|
||||
detailPanel.innerHTML = contactsDetailHtml(card);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
detailPanel.hidden = false;
|
||||
detailPanel.dataset.activeDetail = detailKind;
|
||||
});
|
||||
|
||||
async function refresh() {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import {
|
||||
closeAllSavedProfiles,
|
||||
closeSavedProfile,
|
||||
getSavedProfiles,
|
||||
prepareAddProfileLogin,
|
||||
state,
|
||||
switchToSavedProfile,
|
||||
} from '../state.js';
|
||||
|
||||
@@ -58,12 +58,12 @@ export function render({navigate, chrome}) {
|
||||
|
||||
const closeAllButton = document.createElement('button');
|
||||
closeAllButton.type = 'button';
|
||||
closeAllButton.className = 'secondary-btn profiles-close-all';
|
||||
closeAllButton.textContent = 'Закрыть все профили';
|
||||
closeAllButton.className = 'destructive-btn profiles-close-all';
|
||||
closeAllButton.textContent = 'Выйти из всех профилей';
|
||||
closeAllButton.addEventListener('click', async () => {
|
||||
const profiles = getSavedProfiles();
|
||||
if (!profiles.length) return;
|
||||
const confirmed = window.confirm('Закрыть все профили на этом устройстве? После этого откроется экран входа.');
|
||||
const confirmed = await confirmDialog({ title: 'Выйти из всех профилей?', text: 'Все профили на этом устройстве будут закрыты, откроется экран входа.', confirmLabel: 'Выйти', danger: true });
|
||||
if (!confirmed) return;
|
||||
closeAllButton.disabled = true;
|
||||
status.hidden = false;
|
||||
@@ -83,10 +83,8 @@ export function render({navigate, chrome}) {
|
||||
|
||||
const renderList = () => {
|
||||
const profiles = getSavedProfiles();
|
||||
const active = profiles.find((item) => item.isActive);
|
||||
intro.textContent = profiles.length
|
||||
? `Профилей на устройстве: ${profiles.length}. Активен: ${active?.login || state.session.login || '—'}`
|
||||
: 'На устройстве нет сохранённых профилей.';
|
||||
intro.textContent = profiles.length ? '' : 'На устройстве нет сохранённых профилей.';
|
||||
intro.hidden = profiles.length > 0;
|
||||
closeAllButton.disabled = profiles.length === 0;
|
||||
list.innerHTML = '';
|
||||
|
||||
@@ -97,11 +95,11 @@ export function render({navigate, chrome}) {
|
||||
const select = document.createElement('button');
|
||||
select.type = 'button';
|
||||
select.className = 'profiles-select';
|
||||
select.innerHTML = `<span class="profiles-login">${profile.login}</span>${profile.isActive ? '<span class="badge">Активный</span>' : ''}`;
|
||||
select.innerHTML = `<span class="profiles-login">${profile.login}</span>${profile.isActive ? '<span class="profiles-active-badge">Сейчас открыт</span>' : ''}`;
|
||||
select.disabled = profile.isActive;
|
||||
select.addEventListener('click', async () => {
|
||||
if (profile.isActive) return;
|
||||
const confirmed = window.confirm(`Переключиться на профиль «${profile.login}»?`);
|
||||
const confirmed = await confirmDialog({ title: 'Переключить профиль?', text: `Откроется профиль «${profile.login}».`, confirmLabel: 'Переключить' });
|
||||
if (!confirmed) return;
|
||||
status.hidden = false;
|
||||
status.className = 'status-line';
|
||||
@@ -118,16 +116,17 @@ export function render({navigate, chrome}) {
|
||||
const close = document.createElement('button');
|
||||
close.type = 'button';
|
||||
close.className = 'profiles-close';
|
||||
close.setAttribute('aria-label', `Закрыть профиль ${profile.login}`);
|
||||
close.setAttribute('aria-label', `Выйти из профиля ${profile.login}`);
|
||||
close.title = 'Выйти из профиля';
|
||||
close.textContent = '×';
|
||||
close.addEventListener('click', async () => {
|
||||
const others = profiles.filter((item) => item.login.toLowerCase() !== profile.login.toLowerCase());
|
||||
const message = profile.isActive
|
||||
? (others.length
|
||||
? `Закрыть текущий профиль «${profile.login}»? После закрытия приложение переключится на следующий сохранённый профиль.`
|
||||
: `Закрыть текущий профиль «${profile.login}»? После закрытия откроется экран входа.`)
|
||||
: `Закрыть профиль «${profile.login}» на этом устройстве?`;
|
||||
if (!window.confirm(message)) return;
|
||||
? 'Приложение переключится на следующий сохранённый профиль.'
|
||||
: 'После выхода откроется экран входа.')
|
||||
: 'Профиль будет закрыт на этом устройстве.';
|
||||
if (!await confirmDialog({ title: `Выйти из профиля «${profile.login}»?`, text: message, confirmLabel: 'Выйти', danger: true })) return;
|
||||
|
||||
status.hidden = false;
|
||||
status.className = 'status-line';
|
||||
|
||||
@@ -247,10 +247,10 @@ function queueSeedFor(queueId) {
|
||||
|
||||
function styleInputField(field) {
|
||||
if (!field) return;
|
||||
field.style.color = '#111111';
|
||||
field.style.webkitTextFillColor = '#111111';
|
||||
field.style.caretColor = '#111111';
|
||||
field.style.backgroundColor = '#ffffff';
|
||||
field.style.color = 'var(--text-primary)';
|
||||
field.style.webkitTextFillColor = 'var(--text-primary)';
|
||||
field.style.caretColor = 'var(--accent)';
|
||||
field.style.backgroundColor = 'var(--surface)';
|
||||
}
|
||||
|
||||
function readTicketFromUrl() {
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
} from '../services/password-words.js';
|
||||
import { openRegistrationFaq } from './registration-faq-view.js';
|
||||
|
||||
export const pageMeta = { id: 'register-view', title: 'Зарегистрироваться', showAppChrome: false };
|
||||
export const pageMeta = { id: 'register-view', title: 'Регистрация', showAppChrome: false };
|
||||
const MIN_REGISTRATION_LOGIN_LENGTH = 8;
|
||||
|
||||
function normalizeLoginForTemporaryUiGuard(login) {
|
||||
@@ -132,7 +132,7 @@ export function render({ navigate }) {
|
||||
}
|
||||
|
||||
function updatePasswordLength() {
|
||||
passwordLengthText.textContent = `Итоговая длина пароля: ${getCurrentPassword().length} символов.`;
|
||||
passwordLengthText.textContent = `Символов в пароле: ${getCurrentPassword().length}`;
|
||||
}
|
||||
|
||||
function setStatusMessage(message, kind = '') {
|
||||
@@ -333,7 +333,7 @@ export function render({ navigate }) {
|
||||
|
||||
const subtitle = document.createElement('p');
|
||||
subtitle.className = 'meta-muted';
|
||||
subtitle.textContent = 'Процесс запускается сразу: из этого секрета будут вычислены recovery key, root key, blockchain key и client key.';
|
||||
subtitle.textContent = 'Процесс запускается сразу: из этого секрета будут вычислены root/recovery key, blockchain key и client key.';
|
||||
|
||||
const details = document.createElement('p');
|
||||
details.className = 'meta-muted';
|
||||
@@ -425,7 +425,7 @@ export function render({ navigate }) {
|
||||
|
||||
screen.append(
|
||||
createTopBar({
|
||||
title: 'Зарегистрироваться',
|
||||
title: 'Регистрация',
|
||||
back: {
|
||||
label: '←',
|
||||
onClick: () => {
|
||||
|
||||
@@ -109,31 +109,17 @@ export function render({ navigate }) {
|
||||
}
|
||||
card.append(makeSecretField({ label: 'Главный секрет (master secret, base58, 32 байта)', value: secretB58 }));
|
||||
|
||||
// Recovery key
|
||||
const recoverySep = document.createElement('p');
|
||||
recoverySep.className = 'field-label';
|
||||
recoverySep.textContent = 'Recovery key';
|
||||
card.append(recoverySep);
|
||||
card.append(makePublicField({
|
||||
label: 'Recovery — публичный (base58)',
|
||||
value: bytesToBase58(base64ToBytes(keyBundle.recoveryPair.publicKeyB64)),
|
||||
}));
|
||||
card.append(makeSecretField({
|
||||
label: 'Recovery — приватный (seed base58, 32 байта)',
|
||||
value: bytesToBase58(extractSeed32FromPkcs8B64(keyBundle.recoveryPair.privatePkcs8B64)),
|
||||
}));
|
||||
|
||||
// Root key
|
||||
const rootSep = document.createElement('p');
|
||||
rootSep.className = 'field-label';
|
||||
rootSep.textContent = 'Root key';
|
||||
rootSep.textContent = 'Root key (recovery)';
|
||||
card.append(rootSep);
|
||||
card.append(makePublicField({
|
||||
label: 'Root — публичный (base58)',
|
||||
label: 'Root / recovery — публичный (base58)',
|
||||
value: bytesToBase58(base64ToBytes(keyBundle.rootPair.publicKeyB64)),
|
||||
}));
|
||||
card.append(makeSecretField({
|
||||
label: 'Root — приватный (seed base58, 32 байта)',
|
||||
label: 'Root / recovery — приватный (seed base58, 32 байта)',
|
||||
value: bytesToBase58(extractSeed32FromPkcs8B64(keyBundle.rootPair.privatePkcs8B64)),
|
||||
}));
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ export const REGISTRATION_FAQ_TOPICS = [
|
||||
title: 'У кого хранятся ключи?',
|
||||
paragraphs: [
|
||||
'Ключи хранятся только у вас: на вашем устройстве, на доверенных устройствах или на отдельном внешнем устройстве, которое вы контролируете сами.',
|
||||
'SHiNE не хранит ваши приватные ключи на сервере. Сервер помогает с доставкой и синхронизацией, но не владеет вашим секретом.',
|
||||
'Сияние не хранит ваши приватные ключи на сервере. Сервер помогает с доставкой и синхронизацией, но не владеет вашим секретом.',
|
||||
'Если захотите, ключи можно держать на отдельном полностью программируемом устройстве с открытым кодом, например на ESP32-контроллере.',
|
||||
],
|
||||
},
|
||||
@@ -26,11 +26,11 @@ export const REGISTRATION_FAQ_TOPICS = [
|
||||
},
|
||||
{
|
||||
id: 'key-derivation',
|
||||
shortTitle: 'Деривация',
|
||||
shortTitle: 'Как пароль превращается в ключи',
|
||||
title: 'Как генерируются ключи и что делает пароль?',
|
||||
paragraphs: [
|
||||
'Из вашего логина и пароля с помощью Argon2id вычисляется специальный секрет.',
|
||||
'Уже из этого секрета детерминированно строятся четыре основных ключа: recovery key, root key, blockchain key и client key.',
|
||||
'Уже из этого секрета детерминированно строятся три основных ключа: root/recovery key, blockchain key и client key.',
|
||||
'Это значит, что логин и пароль не просто проверяются на сервере, а реально участвуют в создании ваших ключей. У разных логинов даже с одинаковым паролем будут разные ключи.',
|
||||
],
|
||||
},
|
||||
@@ -39,9 +39,9 @@ export const REGISTRATION_FAQ_TOPICS = [
|
||||
shortTitle: 'Три ключа',
|
||||
title: 'Зачем нужны три ключа?',
|
||||
paragraphs: [
|
||||
'Root key нужен для управления вашей основной публичной записью и важными изменениями личности, включая обновление главной публичной части в Solana.',
|
||||
'Blockchain key нужен для подписания действий и записей в блокчейне SHiNE.',
|
||||
'Client key нужен для входов и работы конкретного устройства. Благодаря разделению ключей можно точнее выдавать права одним устройствам и не выдавать другим.',
|
||||
'Главный ключ нужен для управления вашей основной публичной записью и важными изменениями личности, включая обновление главной публичной части в Solana.',
|
||||
'Ключ публикаций нужен для подписания действий и записей в блокчейне Сияния.',
|
||||
'Ключ устройства нужен для входов и работы конкретного устройства. Благодаря разделению ключей можно точнее выдавать права одним устройствам и не выдавать другим.',
|
||||
'Если не хочется в это вникать, обычно можно просто сохранить все ключи на своём устройстве. Для большинства обычных сценариев на iPhone, Android и Linux это вполне практично. Для больших сумм или повышенного риска лучше отдельное внешнее устройство.',
|
||||
],
|
||||
},
|
||||
@@ -78,9 +78,9 @@ export const REGISTRATION_FAQ_TOPICS = [
|
||||
{
|
||||
id: 'first-server',
|
||||
shortTitle: 'Первый сервер',
|
||||
title: 'Что такое первый сервер SHiNE?',
|
||||
title: 'Что такое первый сервер Сияния?',
|
||||
paragraphs: [
|
||||
'Первый сервер SHiNE это тот сервер, на который вам будут писать и звонить в самом начале. При регистрации он записывается как ваш первый сервер доступа.',
|
||||
'Первый сервер Сияния это тот сервер, на который вам будут писать и звонить в самом начале. При регистрации он записывается как ваш первый сервер доступа.',
|
||||
'Позже вы сможете сменить сервер, а ваши данные останутся с вами. В будущем серверов может быть несколько одновременно.',
|
||||
'Если серверов несколько, данные между ними будут синхронизироваться автоматически. Если добавляете новый сервер и убираете старый, просто дождитесь завершения синхронизации перед отключением старого.',
|
||||
'Если у вас не остаётся ни одного сервера, синхронизации, конечно, не будет, пока не появится хотя бы один активный сервер снова.',
|
||||
@@ -93,7 +93,7 @@ export const REGISTRATION_FAQ_TOPICS = [
|
||||
paragraphs: [
|
||||
'На новом устройстве выберите вход через другое устройство и получите код подключения.',
|
||||
'На уже авторизованном устройстве откройте: Профиль → Настройки → Устройства → Подключить по коду. Введите или выберите соответствующий код и подтвердите подключение.',
|
||||
'Client key передаётся новому клиентскому устройству всегда. Если на доверенном устройстве доступны root key и/или blockchain key, перед подтверждением можно отдельно выбрать, какие дополнительные ключи передать.',
|
||||
'Ключ устройства передаётся новому клиентскому устройству всегда. Если на доверенном устройстве доступны главный ключ и/или ключ публикаций, перед подтверждением можно отдельно выбрать, какие дополнительные ключи передать.',
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -118,7 +118,7 @@ export const REGISTRATION_FAQ_TOPICS = [
|
||||
shortTitle: 'Кошелёк',
|
||||
title: 'Можно ли использовать такое устройство как кошелёк?',
|
||||
paragraphs: [
|
||||
'Да. Идея SHiNE в том, что устройство может подписывать не только внутренние действия, но и любые другие данные, если для этого добавлена нужная логика.',
|
||||
'Да. Идея Сияния в том, что устройство может подписывать не только внутренние действия, но и любые другие данные, если для этого добавлена нужная логика.',
|
||||
'То есть это направление совместимо с моделью аппаратного кошелька: вы храните ключи у себя, а устройство подписывает то, что вы разрешили.',
|
||||
'Пока ещё не все валюты и сценарии доведены до готового пользовательского уровня, но архитектурно это именно путь к универсальному подписывающему устройству.',
|
||||
],
|
||||
@@ -142,7 +142,6 @@ export function render({ navigate }) {
|
||||
const heroCard = document.createElement('div');
|
||||
heroCard.className = 'card stack registration-faq-hero';
|
||||
heroCard.innerHTML = `
|
||||
<div class="badge alt">Вопросы о регистрации</div>
|
||||
<p class="auth-copy">Короткие ответы на самые частые вопросы о ключах, пароле, первом сервере и доверенных устройствах.</p>
|
||||
`;
|
||||
|
||||
@@ -174,20 +173,23 @@ export function render({ navigate }) {
|
||||
}
|
||||
|
||||
const topicsCard = document.createElement('div');
|
||||
topicsCard.className = 'card stack';
|
||||
topicsCard.className = 'stack';
|
||||
|
||||
const topicsLabel = document.createElement('p');
|
||||
topicsLabel.className = 'field-label';
|
||||
topicsLabel.className = 'nav-list__title';
|
||||
topicsLabel.textContent = 'Другие вопросы';
|
||||
|
||||
const topicsGrid = document.createElement('div');
|
||||
topicsGrid.className = 'registration-faq-grid';
|
||||
topicsGrid.className = 'nav-list';
|
||||
|
||||
REGISTRATION_FAQ_TOPICS.forEach((topic) => {
|
||||
REGISTRATION_FAQ_TOPICS.filter((topic) => topic.id !== selectedTopic.id).forEach((topic) => {
|
||||
const button = document.createElement('button');
|
||||
button.className = topic.id === selectedTopic.id ? 'secondary-btn' : 'ghost-btn';
|
||||
button.className = 'nav-row';
|
||||
button.type = 'button';
|
||||
button.textContent = topic.shortTitle;
|
||||
const label = document.createElement('span');
|
||||
label.className = 'nav-row__label';
|
||||
label.textContent = topic.title;
|
||||
button.append(label);
|
||||
button.addEventListener('click', () => {
|
||||
state.registrationHelp.selectedTopic = topic.id;
|
||||
navigate('registration-faq-view');
|
||||
|
||||
@@ -83,7 +83,7 @@ export function render({ navigate }) {
|
||||
const blockchainRow = createKeyInfo(
|
||||
blockchainToggle,
|
||||
'Ключ blockchain',
|
||||
'Используется для подписи ваших действий и записей в блокчейне SHiNE.',
|
||||
'Используется для подписи ваших действий и записей в блокчейне Сияния.',
|
||||
);
|
||||
|
||||
const deviceRow = createKeyInfo(
|
||||
|
||||
@@ -6,7 +6,7 @@ export const pageMeta = { id: 'server-settings-view', title: 'Серверы б
|
||||
|
||||
const SERVER_FIELDS = [
|
||||
{ key: 'solanaServer', label: 'Адрес Solana сервера' },
|
||||
{ key: 'shineServerLogin', label: 'Логин сервера Сияние' },
|
||||
{ key: 'shineServerLogin', label: 'Сервер Сияния' },
|
||||
{ key: 'arweaveServer', label: 'Адрес сервера Arweave' },
|
||||
];
|
||||
|
||||
@@ -27,13 +27,9 @@ export function render({navigate, chrome}) {
|
||||
const timers = new Map();
|
||||
|
||||
const introCard = document.createElement('div');
|
||||
introCard.className = 'card stack';
|
||||
introCard.className = 'settings-intro';
|
||||
introCard.innerHTML = `
|
||||
<p class="field-label">Серверы блокчейнов и публичных данных</p>
|
||||
<p class="meta-muted">
|
||||
Здесь настраиваются Solana, SHiNE и Arweave для чтения публичных данных и доступа к блокчейну.
|
||||
Эти настройки не меняют список личных серверов доступа пользователя.
|
||||
</p>
|
||||
<p class="meta-muted">Откуда приложение читает публичные данные: Solana, Сияние и Arweave. Личные серверы доступа здесь не меняются.</p>
|
||||
`;
|
||||
|
||||
const body = document.createElement('div');
|
||||
@@ -138,7 +134,7 @@ export function render({navigate, chrome}) {
|
||||
|
||||
const callTimeoutLabel = document.createElement('label');
|
||||
callTimeoutLabel.className = 'field-label';
|
||||
callTimeoutLabel.textContent = 'Таймаут пред-подключения перед звонком (мс)';
|
||||
callTimeoutLabel.textContent = 'Сколько ждать связи с сервером перед звонком (мс)';
|
||||
|
||||
const callTimeoutInput = document.createElement('input');
|
||||
callTimeoutInput.className = 'input';
|
||||
@@ -155,13 +151,13 @@ export function render({navigate, chrome}) {
|
||||
|
||||
const callTimeoutHint = document.createElement('p');
|
||||
callTimeoutHint.className = 'meta-muted';
|
||||
callTimeoutHint.textContent = 'Перед исходящим звонком клиент проверяет и восстанавливает WS-сессию. Это время ожидания такой проверки перед ошибкой «Сервер временно недоступен».';
|
||||
callTimeoutHint.textContent = 'Перед звонком приложение проверяет и при необходимости восстанавливает соединение с сервером. Это время ожидания такой проверки перед ошибкой «Сервер временно недоступен».';
|
||||
|
||||
callSettings.append(callTimeoutLabel, callTimeoutInput, callTimeoutHint);
|
||||
body.append(callSettings);
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'auth-footer-actions';
|
||||
actions.className = 'action-pair';
|
||||
|
||||
const cancelButton = document.createElement('button');
|
||||
cancelButton.className = 'ghost-btn';
|
||||
@@ -190,7 +186,7 @@ export function render({navigate, chrome}) {
|
||||
help.textContent = '?';
|
||||
help.addEventListener('click', () => {
|
||||
window.alert(
|
||||
'Текст для разработчиков: для SHiNE вводится логин серверного аккаунта. Клиент читает его PDA, берёт server_address, показывает точный https-адрес и проверяет доступность WS-канала автоматически.',
|
||||
'Текст для разработчиков: для Сияния вводится логин серверного аккаунта. Клиент читает его PDA, берёт server_address, показывает точный https-адрес и проверяет доступность WS-канала автоматически.',
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +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 { getThemeMode, resolveThemeMode, setThemeMode } from '../services/theme-service.js';
|
||||
import { openPaletteEditor } from '../components/palette-editor.js';
|
||||
|
||||
export const pageMeta = { id: 'settings-view', title: 'Настройки' };
|
||||
|
||||
@@ -40,7 +42,7 @@ export function render({navigate, chrome}) {
|
||||
const logoButton = document.createElement('button');
|
||||
logoButton.type = 'button';
|
||||
logoButton.className = 'settings-shine-logo-button';
|
||||
logoButton.setAttribute('aria-label', 'Логотип SHiNE');
|
||||
logoButton.setAttribute('aria-label', 'Логотип Сияния');
|
||||
logoButton.title = 'SHiNE';
|
||||
logoButton.innerHTML = '<img class="settings-shine-logo" src="/img/shine-logo-transparent-final_big.png" alt="SHiNE" />';
|
||||
|
||||
@@ -56,44 +58,50 @@ export function render({navigate, chrome}) {
|
||||
});
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack';
|
||||
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>`;
|
||||
card.innerHTML = `
|
||||
<div class="stack">
|
||||
<label for="settings-theme"><strong>Оформление</strong></label>
|
||||
<span class="meta-muted">Тема меняет только цвета и не перезагружает экран.</span>
|
||||
<select class="select" id="settings-theme">
|
||||
<option value="system">Как на устройстве</option>
|
||||
<option value="light">Дневное</option>
|
||||
<option value="dark">Ночное</option>
|
||||
</select>
|
||||
<div class="card stack settings-theme-card">
|
||||
<strong id="settings-theme-label">Оформление</strong>
|
||||
<div class="tabs tabs--auto" id="settings-theme" role="radiogroup" aria-labelledby="settings-theme-label">
|
||||
<button type="button" class="tab-btn" role="radio" data-mode="system">Авто</button>
|
||||
<button type="button" class="tab-btn" role="radio" data-mode="light">День</button>
|
||||
<button type="button" class="tab-btn" role="radio" data-mode="dark">Ночь</button>
|
||||
</div>
|
||||
<span class="meta-muted">«Авто» — как на устройстве.</span>
|
||||
<button type="button" class="secondary-btn settings-theme-editor" id="settings-theme-editor">Настроить цвета</button>
|
||||
</div>
|
||||
<div class="nav-list">
|
||||
${row('settings-device', 'Устройства', 'Сеансы, подключение устройств, ключи')}
|
||||
${row('settings-access-servers', 'Сервер доступа', 'Личная переписка, звонки и зашифрованные данные')}
|
||||
${row('settings-blockchain-servers', 'Серверы блокчейнов', 'Solana, Сияние и Arweave для публичных данных')}
|
||||
${row('settings-arweave-uploads', 'Файлы в блокчейне', 'Заранее загрузить файл и выбрать его потом')}
|
||||
${row('settings-remote-addblock', 'Публикация через домашний сервер', 'Когда ключа публикаций нет на этом устройстве')}
|
||||
${row('settings-language', 'Язык / Language', 'Русский')}
|
||||
</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>
|
||||
<button class="shine-btn shine-btn--settings" type="button" id="settings-device">Устройства</button>
|
||||
<button class="shine-btn shine-btn--settings" type="button" id="settings-remote-addblock">Remote AddBlock через homeserver</button>
|
||||
<button class="shine-btn shine-btn--settings" type="button" id="settings-access-servers">
|
||||
<span style="display:block; text-align:left;">
|
||||
<strong>Сервер доступа</strong>
|
||||
<span class="meta-muted" style="display:block; margin-top:0.2rem;">Личная переписка, звонки и зашифрованные данные</span>
|
||||
</span>
|
||||
</button>
|
||||
<button class="shine-btn shine-btn--settings" type="button" id="settings-blockchain-servers">
|
||||
<span style="display:block; text-align:left;">
|
||||
<strong>Серверы блокчейнов</strong>
|
||||
<span class="meta-muted" style="display:block; margin-top:0.2rem;">Solana, SHiNE и Arweave для публичных данных</span>
|
||||
</span>
|
||||
</button>
|
||||
<button class="shine-btn shine-btn--settings" type="button" id="settings-arweave-uploads">
|
||||
<span style="display:block; text-align:left;">
|
||||
<strong>Загрузить файлы в блокчейн</strong>
|
||||
<span class="meta-muted" style="display:block; margin-top:0.2rem;">Заранее загрузить файл и выбрать его потом из истории</span>
|
||||
</span>
|
||||
</button>
|
||||
<button class="shine-btn shine-btn--settings" type="button" id="settings-language">Язык / Language</button>
|
||||
<button class="shine-btn shine-btn--settings" type="button" id="settings-signout">Завершить текущий сеанс</button>
|
||||
`;
|
||||
|
||||
const themeSelect = card.querySelector('#settings-theme');
|
||||
themeSelect.value = getThemeMode();
|
||||
themeSelect.addEventListener('change', () => setThemeMode(themeSelect.value));
|
||||
const themeSwitch = card.querySelector('#settings-theme');
|
||||
const syncThemeSwitch = () => {
|
||||
const mode = getThemeMode();
|
||||
themeSwitch.querySelectorAll('[data-mode]').forEach((btn) => {
|
||||
btn.setAttribute('aria-checked', String(btn.dataset.mode === mode));
|
||||
});
|
||||
};
|
||||
syncThemeSwitch();
|
||||
|
||||
themeSwitch.addEventListener('click', (event) => {
|
||||
const mode = event.target.closest('[data-mode]')?.dataset.mode;
|
||||
if (!mode) return;
|
||||
setThemeMode(mode);
|
||||
syncThemeSwitch();
|
||||
});
|
||||
card.querySelector('#settings-theme-editor').addEventListener('click', () => {
|
||||
openPaletteEditor({ theme: resolveThemeMode() });
|
||||
});
|
||||
|
||||
card.querySelector('#settings-device').addEventListener('click', () => navigate('device-view'));
|
||||
card.querySelector('#settings-remote-addblock').addEventListener('click', () => navigate('remote-addblock-session-view'));
|
||||
@@ -107,9 +115,12 @@ export function render({navigate, chrome}) {
|
||||
|
||||
const signOutBtn = card.querySelector('#settings-signout');
|
||||
signOutBtn.addEventListener('click', async () => {
|
||||
const confirmed = window.confirm(
|
||||
'Завершить текущий профиль на этом устройстве? Если есть другие сохранённые профили, приложение переключится на следующий.'
|
||||
);
|
||||
const confirmed = await confirmDialog({
|
||||
title: 'Выйти из аккаунта?',
|
||||
text: 'Вы выйдете на этом устройстве. Если сохранены другие профили, приложение переключится на следующий.',
|
||||
confirmLabel: 'Выйти',
|
||||
danger: true,
|
||||
});
|
||||
if (!confirmed) return;
|
||||
|
||||
signOutBtn.disabled = true;
|
||||
|
||||
@@ -4,7 +4,7 @@ import { bytesToBase58 } from '../services/crypto-utils.js';
|
||||
import { extractSeed32FromPkcs8B64 } from '../services/client-key-utils.js';
|
||||
import { loadEncryptedUserSecrets } from '../services/key-vault.js';
|
||||
|
||||
export const pageMeta = { id: 'show-keys-view', title: 'Показать ключи' };
|
||||
export const pageMeta = { id: 'show-keys-view', title: 'Ключи этого устройства' };
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
@@ -23,19 +23,18 @@ export function render({navigate, chrome}) {
|
||||
};
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'Показать ключи',
|
||||
title: 'Ключи этого устройства',
|
||||
back: { label: '←', onClick: () => navigate('device-view') },
|
||||
}));
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack';
|
||||
card.className = 'nav-list key-list';
|
||||
|
||||
const status = document.createElement('p');
|
||||
status.className = 'meta-muted';
|
||||
status.textContent = 'Загружаем сохранённые ключи...';
|
||||
card.append(status);
|
||||
|
||||
const renderField = (id, label) => {
|
||||
const renderField = (id, label, hint = '') => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'key-card stack';
|
||||
const eyeIcon = `
|
||||
@@ -53,8 +52,8 @@ export function render({navigate, chrome}) {
|
||||
`;
|
||||
row.innerHTML = `
|
||||
<div class="row">
|
||||
<span class="field-label">${label}</span>
|
||||
<button class="icon-btn key-toggle-btn" type="button" data-toggle="${id}" aria-label="Показать ключ" title="Показать ключ">${eyeOffIcon}</button>
|
||||
<span class="field-label">${label}${hint ? `<small class="key-card__hint">${hint}</small>` : ''}</span>
|
||||
<button class="icon-btn key-toggle-btn" type="button" data-toggle="${id}" aria-label="Показать ключ" title="Показать ключ">${eyeIcon}</button>
|
||||
</div>
|
||||
<div class="key-value key-value--compact" data-value="${id}">*****</div>
|
||||
`;
|
||||
@@ -64,9 +63,9 @@ export function render({navigate, chrome}) {
|
||||
};
|
||||
|
||||
card.append(
|
||||
renderField('root', 'root key (base58)'),
|
||||
renderField('blockchain', 'blockchain.key (base58)'),
|
||||
renderField('device', 'client key (base58)'),
|
||||
renderField('root', 'Главный ключ', 'Восстановление аккаунта и важные настройки'),
|
||||
renderField('blockchain', 'Ключ публикаций', 'Подпись ваших записей'),
|
||||
renderField('device', 'Ключ устройства', 'Вход с этого устройства'),
|
||||
);
|
||||
|
||||
const setMissingState = (id) => {
|
||||
@@ -91,8 +90,8 @@ export function render({navigate, chrome}) {
|
||||
valueEl.textContent = visible[id] ? keys[id] : '*****';
|
||||
btnEl.disabled = false;
|
||||
btnEl.innerHTML = visible[id]
|
||||
? field?._eyeIcon || ''
|
||||
: field?._eyeOffIcon || '';
|
||||
? field?._eyeOffIcon || ''
|
||||
: field?._eyeIcon || '';
|
||||
btnEl.setAttribute('aria-label', visible[id] ? 'Скрыть ключ' : 'Показать ключ');
|
||||
btnEl.title = visible[id] ? 'Скрыть ключ' : 'Показать ключ';
|
||||
};
|
||||
@@ -108,16 +107,6 @@ export function render({navigate, chrome}) {
|
||||
|
||||
['root', 'blockchain', 'device'].forEach((id) => updateField(id));
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'auth-footer-actions';
|
||||
|
||||
const closeButton = document.createElement('button');
|
||||
closeButton.className = 'ghost-btn';
|
||||
closeButton.type = 'button';
|
||||
closeButton.textContent = 'Назад';
|
||||
closeButton.addEventListener('click', () => navigate('device-view'));
|
||||
actions.append(closeButton);
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
if (!state.session.login || !state.session.storagePwdInMemory) {
|
||||
@@ -149,6 +138,6 @@ export function render({navigate, chrome}) {
|
||||
['root', 'blockchain', 'device'].forEach((id) => updateField(id));
|
||||
})();
|
||||
|
||||
screen.append(card, actions);
|
||||
screen.append(status, card);
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -31,13 +31,13 @@ export function render({ navigate }) {
|
||||
loginButton.addEventListener('click', () => navigate('login-view'));
|
||||
|
||||
const registerButton = document.createElement('button');
|
||||
registerButton.className = 'shine-btn shine-btn--register';
|
||||
registerButton.className = 'secondary-btn shine-btn--register';
|
||||
registerButton.type = 'button';
|
||||
registerButton.textContent = 'Зарегистрироваться';
|
||||
registerButton.addEventListener('click', () => navigate('register-view'));
|
||||
|
||||
const languageButton = document.createElement('button');
|
||||
languageButton.className = 'shine-btn shine-btn--view';
|
||||
languageButton.className = 'text-btn start-language-link';
|
||||
languageButton.type = 'button';
|
||||
languageButton.textContent = 'Язык / Language';
|
||||
languageButton.addEventListener('click', () => {
|
||||
@@ -46,9 +46,9 @@ export function render({ navigate }) {
|
||||
});
|
||||
|
||||
const settingsButton = document.createElement('button');
|
||||
settingsButton.className = 'shine-btn shine-btn--settings';
|
||||
settingsButton.className = 'text-btn start-settings-link';
|
||||
settingsButton.type = 'button';
|
||||
settingsButton.textContent = 'Настройки';
|
||||
settingsButton.textContent = 'Настройки входа';
|
||||
settingsButton.addEventListener('click', () => navigate('entry-settings-view'));
|
||||
|
||||
actions.append(loginButton, registerButton, languageButton, settingsButton);
|
||||
|
||||
@@ -3,7 +3,7 @@ import { authService, setAuthError, setAuthInfo, state } from '../state.js';
|
||||
import { deriveEspPairingPasswordHash } from '../services/device-pairing-service.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'trusted-device-login-settings-view', title: 'Настройки входа через устройство' };
|
||||
export const pageMeta = { id: 'trusted-device-login-settings-view', title: 'Вход с другого устройства' };
|
||||
|
||||
function setStatus(statusEl, message, kind = 'info') {
|
||||
statusEl.classList.toggle('is-unavailable', kind === 'error');
|
||||
@@ -38,15 +38,14 @@ export function render({navigate, chrome}) {
|
||||
status.style.display = 'none';
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'row';
|
||||
actions.style.flexWrap = 'wrap';
|
||||
actions.className = 'stack trusted-login-actions';
|
||||
|
||||
const enableToggleBtn = document.createElement('button');
|
||||
enableToggleBtn.className = 'primary-btn';
|
||||
enableToggleBtn.type = 'button';
|
||||
|
||||
const noPasswordBtn = document.createElement('button');
|
||||
noPasswordBtn.className = 'ghost-btn';
|
||||
noPasswordBtn.className = 'secondary-btn';
|
||||
noPasswordBtn.type = 'button';
|
||||
noPasswordBtn.textContent = 'Сделать вход без пароля';
|
||||
|
||||
@@ -77,6 +76,7 @@ export function render({navigate, chrome}) {
|
||||
busy = flag;
|
||||
enableToggleBtn.disabled = flag;
|
||||
noPasswordBtn.disabled = flag || !settings.enabled || !settings.hasPassword;
|
||||
noPasswordBtn.hidden = !settings.enabled || !settings.hasPassword;
|
||||
savePasswordBtn.disabled = flag;
|
||||
passwordInput.disabled = flag;
|
||||
passwordConfirmInput.disabled = flag;
|
||||
@@ -87,6 +87,7 @@ export function render({navigate, chrome}) {
|
||||
enableToggleBtn.textContent = settings.enabled
|
||||
? 'Запретить вход через другое устройство'
|
||||
: 'Разрешить вход через другое устройство';
|
||||
enableToggleBtn.className = settings.enabled ? 'destructive-btn' : 'primary-btn';
|
||||
|
||||
actions.innerHTML = '';
|
||||
actions.append(enableToggleBtn);
|
||||
@@ -183,7 +184,7 @@ export function render({navigate, chrome}) {
|
||||
});
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'Настройки входа через устройство',
|
||||
title: 'Вход с другого устройства',
|
||||
back: { label: '←', onClick: () => navigate('device-pairing-view') },
|
||||
}));
|
||||
screen.append(
|
||||
|
||||
@@ -5,6 +5,7 @@ import { authService, state } from '../state.js';
|
||||
import { loadRelationsForPair, loadUserProfileCard } from '../services/user-connections.js';
|
||||
import { makeProfileLinksRoute } from '../services/shine-routes.js';
|
||||
import { navigateBack } from '../router.js';
|
||||
import { profileCardHtml, profileTileHtml } from '../components/profile-card.js';
|
||||
|
||||
export const pageMeta = { id: 'user', title: 'Профиль' };
|
||||
|
||||
@@ -24,68 +25,6 @@ function effectiveSocial(flags = {}) {
|
||||
return 'none';
|
||||
}
|
||||
|
||||
function metricHtml({ kind, label, value, glow = false, positionClass = '' }) {
|
||||
const numericValue = Number(value || 0);
|
||||
return `
|
||||
<button
|
||||
type="button"
|
||||
class="user-profile-metric ${positionClass}${glow ? ' is-glowing' : ''}"
|
||||
data-profile-list="${escapeHtml(kind)}"
|
||||
aria-label="${escapeHtml(label)}: ${numericValue}"
|
||||
>
|
||||
<span class="user-profile-metric-circle">${numericValue}</span>
|
||||
<span class="user-profile-metric-label">${escapeHtml(label)}</span>
|
||||
</button>`;
|
||||
}
|
||||
|
||||
function friendsMetricHtml(stats = {}) {
|
||||
const friends = Number(stats.friendsCount || 0);
|
||||
const closeFriends = Number(stats.closeFriendsCount || 0);
|
||||
return `
|
||||
<button
|
||||
type="button"
|
||||
class="user-profile-metric is-social-metric is-friends-combined"
|
||||
data-profile-list="friends"
|
||||
aria-label="Друзья: ${friends}; близкие друзья: ${closeFriends}"
|
||||
>
|
||||
<span class="user-profile-metric-value-combined">${closeFriends} / ${friends}</span>
|
||||
<span class="user-profile-metric-label">Друзья</span>
|
||||
</button>`;
|
||||
}
|
||||
|
||||
function hasContacts(card) {
|
||||
return [card?.web, card?.phone, card?.address].some((value) => String(value || '').trim());
|
||||
}
|
||||
|
||||
function spiritualPathDetailHtml(card) {
|
||||
const value = String(card?.spiritualPath || '').trim();
|
||||
return `<div class="user-profile-detail-copy${value ? '' : ' is-muted'}">${escapeHtml(value || 'Не заполнено')}</div>`;
|
||||
}
|
||||
|
||||
function contactsDetailHtml(card) {
|
||||
const rows = [
|
||||
['Ссылки', card?.web],
|
||||
['Телефон', card?.phone],
|
||||
['Адрес', card?.address],
|
||||
].filter(([, value]) => String(value || '').trim());
|
||||
|
||||
if (!rows.length) {
|
||||
return '<div class="user-profile-detail-copy is-muted">Не заполнено</div>';
|
||||
}
|
||||
return rows.map(([label, value]) => `
|
||||
<div class="user-profile-contact-row">
|
||||
<span>${escapeHtml(label)}</span>
|
||||
<b>${escapeHtml(value)}</b>
|
||||
</div>`).join('');
|
||||
}
|
||||
|
||||
function addIconHtml() {
|
||||
return `
|
||||
<svg class="user-profile-action-svg" viewBox="0 0 40 40" aria-hidden="true">
|
||||
<path d="M10.5 20.5 17 27l13-14" />
|
||||
</svg>`;
|
||||
}
|
||||
|
||||
function relationMenuHtml(flags = {}) {
|
||||
const current = effectiveSocial(flags);
|
||||
const rows = [
|
||||
@@ -107,7 +46,7 @@ export function render({ navigate, route, chrome }) {
|
||||
screen.className = 'stack user-profile-screen';
|
||||
|
||||
const header = createTopBar({
|
||||
title: requestedLogin || 'Профиль',
|
||||
title: 'Профиль',
|
||||
back: { label: '←', onClick: () => navigateBack() },
|
||||
});
|
||||
header.classList.add('user-profile-header');
|
||||
@@ -186,60 +125,20 @@ export function render({ navigate, route, chrome }) {
|
||||
function renderProfile() {
|
||||
if (!card) return;
|
||||
const isSelf = card.login.toLowerCase() === selfLogin.toLowerCase();
|
||||
const stats = card.stats || {};
|
||||
const official = card.accountRole === 'primary';
|
||||
const shining = card.shineStatus === 'shining';
|
||||
const fullName = [card.firstName, card.lastName]
|
||||
.map((value) => String(value || '').trim())
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
const displayName = fullName || card.login || 'Профиль';
|
||||
const about = String(card.about || '').trim();
|
||||
const spiritualPath = String(card.spiritualPath || '').trim();
|
||||
const contactsVisible = hasContacts(card);
|
||||
|
||||
const title = header.querySelector('.topbar__title');
|
||||
if (title) title.textContent = card.login;
|
||||
|
||||
body.innerHTML = `
|
||||
<div class="user-profile-hero" aria-label="Профиль ${escapeHtml(card.login)}">
|
||||
${metricHtml({ kind: 'primary_received', label: 'Официальный', value: stats.primaryReceivedCount, glow: official, positionClass: 'is-top-left' })}
|
||||
${metricHtml({ kind: 'shine_received', label: 'Сияющий', value: stats.shineReceivedCount, glow: shining, positionClass: 'is-top-right' })}
|
||||
<div class="user-profile-avatar-slot"></div>
|
||||
</div>
|
||||
|
||||
<div class="user-profile-identity">
|
||||
<div class="user-profile-full-name">${escapeHtml(displayName)}</div>
|
||||
<div class="user-profile-login">@${escapeHtml(card.login)}</div>
|
||||
</div>
|
||||
|
||||
<div class="user-profile-social-metrics">
|
||||
${friendsMetricHtml(stats)}
|
||||
${metricHtml({ kind: 'channels_owned', label: 'Каналы', value: stats.ownedPublicChannelsCount, positionClass: 'is-social-metric' })}
|
||||
${metricHtml({ kind: 'channels_following', label: 'Подписки', value: stats.followingChannelsCount, positionClass: 'is-social-metric' })}
|
||||
</div>
|
||||
|
||||
<section class="user-profile-about-card" aria-label="О себе">
|
||||
<div class="user-profile-about-title">О себе</div>
|
||||
<div class="user-profile-about-field${about ? '' : ' is-empty'}">${escapeHtml(about || 'Не заполнено')}</div>
|
||||
</section>
|
||||
|
||||
${(contactsVisible || spiritualPath) ? `
|
||||
<div class="user-profile-detail-links user-profile-detail-links--below-about" aria-label="Дополнительная информация о пользователе">
|
||||
${contactsVisible ? `<button type="button" class="ui-button" data-profile-detail="contacts" aria-pressed="false" aria-controls="user-profile-detail-panel"><span class="user-profile-detail-tab-label">Контакты</span></button>` : '<span></span>'}
|
||||
${spiritualPath ? `<button type="button" class="ui-button" data-profile-detail="spiritual-path" aria-pressed="false" aria-controls="user-profile-detail-panel"><span class="user-profile-detail-tab-label">Духовный путь</span></button>` : '<span></span>'}
|
||||
</div>
|
||||
<section class="user-profile-detail-panel" id="user-profile-detail-panel" aria-live="polite" hidden></section>` : ''}
|
||||
|
||||
${!isSelf ? `
|
||||
<div class="user-profile-actions-wrap">
|
||||
<div class="user-profile-add-menu" hidden></div>
|
||||
<div class="user-profile-actions" aria-label="Действия с пользователем">
|
||||
<button type="button" class="user-profile-action-btn" data-profile-action="add" aria-label="Добавить" aria-haspopup="menu" aria-expanded="false">${addIconHtml()}</button>
|
||||
<button type="button" class="user-profile-action-btn is-links" data-profile-action="links" aria-label="Связи" title="Связи"><img src="${SHINE_CONNECTIONS_LOGO_SRC}" alt="" aria-hidden="true"></button>
|
||||
<button type="button" class="user-profile-action-btn" data-profile-action="chat" aria-label="Сообщение" title="Сообщение"><img src="/assets/icon_lichnye.png" alt="" aria-hidden="true"></button>
|
||||
</div>
|
||||
</div>` : ''}`;
|
||||
body.innerHTML = profileCardHtml({
|
||||
card,
|
||||
login: requestedLogin,
|
||||
isSelf,
|
||||
beforeTilesHtml: '<div class="user-profile-add-menu" hidden></div>',
|
||||
tilesHtml: isSelf ? '' : [
|
||||
profileTileHtml({ icon: 'user-plus', label: 'Добавить', attrs: 'data-profile-action="add" aria-haspopup="menu" aria-expanded="false"' }),
|
||||
profileTileHtml({ label: 'Связи', attrs: 'data-profile-action="links"', iconMarkup: `<img class="pf-tile-mandala" src="${SHINE_CONNECTIONS_LOGO_SRC}" alt="" aria-hidden="true">` }),
|
||||
profileTileHtml({ icon: 'message', label: 'Написать', attrs: 'data-profile-action="chat"' }),
|
||||
].join(''),
|
||||
});
|
||||
|
||||
const avatarSlot = body.querySelector('.user-profile-avatar-slot');
|
||||
avatarSlot?.append(renderUserAvatar({
|
||||
@@ -272,31 +171,6 @@ export function render({ navigate, route, chrome }) {
|
||||
return;
|
||||
}
|
||||
|
||||
const detailButton = event.target.closest('[data-profile-detail]');
|
||||
if (detailButton) {
|
||||
const detailKind = detailButton.dataset.profileDetail;
|
||||
const detailPanel = body.querySelector('#user-profile-detail-panel');
|
||||
if (!detailPanel) return;
|
||||
|
||||
body.querySelectorAll('[data-profile-detail]').forEach((button) => {
|
||||
const active = button === detailButton;
|
||||
button.classList.toggle('is-active', active);
|
||||
button.setAttribute('aria-pressed', active ? 'true' : 'false');
|
||||
});
|
||||
|
||||
if (detailKind === 'spiritual-path') {
|
||||
detailPanel.innerHTML = spiritualPathDetailHtml(card);
|
||||
} else if (detailKind === 'contacts') {
|
||||
detailPanel.innerHTML = contactsDetailHtml(card);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
detailPanel.hidden = false;
|
||||
detailPanel.dataset.activeDetail = detailKind;
|
||||
return;
|
||||
}
|
||||
|
||||
const relationButton = event.target.closest('[data-relation-kind]');
|
||||
if (relationButton) {
|
||||
if (!selfLogin) {
|
||||
|
||||
@@ -531,10 +531,10 @@ export function render({navigate, chrome}) {
|
||||
|
||||
function styleSupportInputField(field) {
|
||||
if (!field) return;
|
||||
field.style.color = '#111111';
|
||||
field.style.webkitTextFillColor = '#111111';
|
||||
field.style.caretColor = '#111111';
|
||||
field.style.backgroundColor = '#ffffff';
|
||||
field.style.color = 'var(--text-primary)';
|
||||
field.style.webkitTextFillColor = 'var(--text-primary)';
|
||||
field.style.caretColor = 'var(--accent)';
|
||||
field.style.backgroundColor = 'var(--surface)';
|
||||
}
|
||||
|
||||
function renderSupportHub() {
|
||||
@@ -1283,55 +1283,28 @@ export function render({navigate, chrome}) {
|
||||
content.innerHTML = '';
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack';
|
||||
card.innerHTML = `
|
||||
<h2 style="margin:0 0 6px;">Кошелёк</h2>
|
||||
<p class="meta-muted">Выберите режим кошелька.</p>
|
||||
`;
|
||||
|
||||
const solanaBtn = document.createElement('button');
|
||||
solanaBtn.className = 'primary-btn';
|
||||
solanaBtn.style.width = '100%';
|
||||
solanaBtn.textContent = 'Solana кошелёк';
|
||||
solanaBtn.addEventListener('click', () => {
|
||||
void renderSolanaWallet();
|
||||
card.className = 'nav-list';
|
||||
const items = [
|
||||
['Solana кошелёк', 'Баланс SOL', () => renderSolanaWallet()],
|
||||
['Arweave кошелёк', 'Баланс AR', () => renderArweaveWallet()],
|
||||
['Предоплаченное место Сияния', 'Лимит, израсходовано и остаток', () => renderShineBlockchainWallet()],
|
||||
['Закрепление в Solana', 'Что закреплено в Solana и на сервере', () => renderSolanaPublishWallet()],
|
||||
['Поддержать проект Сияние', 'Билеты и справка', () => renderSupportHub()],
|
||||
];
|
||||
const buttons = items.map(([label, hint, open]) => {
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'nav-row';
|
||||
btn.innerHTML = `<span class="nav-row__label"></span><span class="nav-row__hint"></span>`;
|
||||
btn.querySelector('.nav-row__label').textContent = label;
|
||||
btn.querySelector('.nav-row__hint').textContent = hint;
|
||||
btn.addEventListener('click', () => { void open(); });
|
||||
return btn;
|
||||
});
|
||||
|
||||
const arweaveBtn = document.createElement('button');
|
||||
arweaveBtn.className = 'primary-btn';
|
||||
arweaveBtn.style.width = '100%';
|
||||
arweaveBtn.textContent = 'Arweave кошелёк';
|
||||
arweaveBtn.addEventListener('click', () => {
|
||||
void renderArweaveWallet();
|
||||
});
|
||||
|
||||
const shineBchBtn = document.createElement('button');
|
||||
shineBchBtn.className = 'primary-btn';
|
||||
shineBchBtn.style.width = '100%';
|
||||
shineBchBtn.textContent = 'Предоплаченное место Сияния';
|
||||
shineBchBtn.addEventListener('click', () => {
|
||||
void renderShineBlockchainWallet();
|
||||
});
|
||||
|
||||
const solanaPublishBtn = document.createElement('button');
|
||||
solanaPublishBtn.className = 'primary-btn';
|
||||
solanaPublishBtn.style.width = '100%';
|
||||
solanaPublishBtn.textContent = 'Закрепление в Solana';
|
||||
solanaPublishBtn.addEventListener('click', () => {
|
||||
void renderSolanaPublishWallet();
|
||||
});
|
||||
|
||||
const supportBtn = document.createElement('button');
|
||||
supportBtn.className = 'primary-btn';
|
||||
supportBtn.style.width = '100%';
|
||||
supportBtn.textContent = 'Поддержать проект Сияние';
|
||||
supportBtn.addEventListener('click', () => {
|
||||
void renderSupportHub();
|
||||
});
|
||||
|
||||
const [solanaBtn, arweaveBtn, shineBchBtn, solanaPublishBtn, supportBtn] = buttons;
|
||||
card.append(solanaBtn, arweaveBtn, shineBchBtn, solanaPublishBtn, supportBtn);
|
||||
content.append(card);
|
||||
setStatus('Выберите тип кошелька.');
|
||||
setStatus('');
|
||||
}
|
||||
|
||||
async function renderShineBlockchainWallet() {
|
||||
@@ -2051,7 +2024,7 @@ export function render({navigate, chrome}) {
|
||||
helpCard.innerHTML = `
|
||||
<summary style="cursor:pointer; font-weight:600;">Как получен этот адрес?</summary>
|
||||
<p class="meta-muted" style="margin-top:8px;">
|
||||
SHiNE берёт ваш локальный client.key и по стандарту SAWD-v1 получает из него нативный Arweave-кошелёк.
|
||||
Сияние берёт ваш локальный client.key и по стандарту SAWD-v1 получает из него нативный Arweave-кошелёк.
|
||||
Приватный ключ не отправляется на сервер. После первого расчёта он хранится только в зашифрованном контейнере этого устройства.
|
||||
</p>
|
||||
`;
|
||||
|
||||
+10
-1
@@ -476,7 +476,17 @@ export function navigateBack() {
|
||||
window.history.back();
|
||||
}
|
||||
|
||||
// Чужой профиль открывают из чатов, связей и каналов — подсвечиваем вкладку, откуда пришли.
|
||||
let lastToolbarTab = 'messages-list';
|
||||
|
||||
export function resolveToolbarActive(pageId) {
|
||||
if (pageId === 'user') return lastToolbarTab;
|
||||
const tab = resolveToolbarTab(pageId);
|
||||
lastToolbarTab = tab;
|
||||
return tab;
|
||||
}
|
||||
|
||||
function resolveToolbarTab(pageId) {
|
||||
if (
|
||||
pageId === 'messages-list'
|
||||
|| pageId === 'channels-list'
|
||||
@@ -510,7 +520,6 @@ export function resolveToolbarActive(pageId) {
|
||||
) return 'profile-view';
|
||||
if (pageId === 'chat-view' || pageId === 'contact-search-view') return 'messages-list';
|
||||
if (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';
|
||||
if (pageId === 'user') return 'messages-list';
|
||||
return 'profile-view';
|
||||
}
|
||||
|
||||
|
||||
@@ -177,14 +177,20 @@ function stopVideos(root) {
|
||||
});
|
||||
}
|
||||
|
||||
function createDownloadLink(url, label = 'Скачать') {
|
||||
function createDownloadLink(url, label = 'Скачать', { iconOnly = false } = {}) {
|
||||
const link = document.createElement('a');
|
||||
link.className = 'message-attachment-download';
|
||||
link.className = `message-attachment-download${iconOnly ? ' message-attachment-download--icon' : ''}`;
|
||||
link.href = url;
|
||||
link.target = '_blank';
|
||||
link.rel = 'noopener';
|
||||
link.download = '';
|
||||
link.textContent = label;
|
||||
if (iconOnly) {
|
||||
link.setAttribute('aria-label', label);
|
||||
link.title = label;
|
||||
link.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 4v12M6 10l6 6 6-6M5 20h14"/></svg>';
|
||||
} else {
|
||||
link.textContent = label;
|
||||
}
|
||||
link.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
});
|
||||
@@ -287,6 +293,7 @@ function createMediaSlide({ item, url, kind, messageTimestampMs, slide, previewU
|
||||
|
||||
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;
|
||||
@@ -326,13 +333,14 @@ function createMediaSlide({ item, url, kind, messageTimestampMs, slide, previewU
|
||||
video.muted = true;
|
||||
video.playsInline = true;
|
||||
video.addEventListener('error', () => replaceWithUnavailable(slide, messageTimestampMs), { once: true });
|
||||
video.addEventListener('loadeddata', () => frame.classList.add('is-loaded'), { once: true });
|
||||
const play = document.createElement('span');
|
||||
play.className = 'message-attachment-play';
|
||||
play.textContent = '▶';
|
||||
frame.append(video, play);
|
||||
}
|
||||
|
||||
frame.append(createDownloadLink(url));
|
||||
frame.append(createDownloadLink(url, 'Скачать', { iconOnly: true }));
|
||||
return frame;
|
||||
}
|
||||
|
||||
|
||||
@@ -1133,11 +1133,7 @@ export class AuthService {
|
||||
});
|
||||
if (isCancelled && isCancelled()) throw new Error('DERIVE_CANCELLED');
|
||||
|
||||
if (onProgress) onProgress({ percent: 93, stage: 'derive', message: 'Вычисление recovery key...' });
|
||||
const recoveryPair = await deriveEd25519FromMasterSecret(masterSecret, 'recovery.key');
|
||||
if (isCancelled && isCancelled()) throw new Error('DERIVE_CANCELLED');
|
||||
|
||||
if (onProgress) onProgress({ percent: 95, stage: 'derive', message: 'Вычисление root key...' });
|
||||
if (onProgress) onProgress({ percent: 94, stage: 'derive', message: 'Вычисление root key...' });
|
||||
const rootPair = await deriveEd25519FromMasterSecret(masterSecret, 'root.key');
|
||||
if (isCancelled && isCancelled()) throw new Error('DERIVE_CANCELLED');
|
||||
|
||||
@@ -1149,7 +1145,6 @@ export class AuthService {
|
||||
const clientPair = await deriveEd25519FromMasterSecret(masterSecret, 'client.key');
|
||||
const result = {
|
||||
masterSecretB64: bytesToBase64(masterSecret),
|
||||
recoveryPair,
|
||||
rootPair,
|
||||
blockchainPair,
|
||||
clientPair,
|
||||
|
||||
@@ -28,6 +28,56 @@ function pickUnit(seconds) {
|
||||
return ['year', Math.round(years)];
|
||||
}
|
||||
|
||||
// Время поста внутри дня: «14:32». День показывается отдельной плашкой.
|
||||
export function formatClockTime(timestampMs) {
|
||||
const ts = toNumber(timestampMs);
|
||||
if (!ts) return '';
|
||||
return new Intl.DateTimeFormat('ru-RU', { hour: '2-digit', minute: '2-digit' }).format(new Date(ts));
|
||||
}
|
||||
|
||||
// Плашка дня в ленте: «Сегодня», «Вчера», «24 сентября», «24 сентября 2025».
|
||||
export function formatDayLabel(timestampMs) {
|
||||
const ts = toNumber(timestampMs);
|
||||
if (!ts) return '';
|
||||
const dt = new Date(ts);
|
||||
const today = new Date();
|
||||
const startOf = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
|
||||
const diffDays = Math.round((startOf(today) - startOf(dt)) / 86400000);
|
||||
if (diffDays === 0) return 'Сегодня';
|
||||
if (diffDays === 1) return 'Вчера';
|
||||
const sameYear = dt.getFullYear() === today.getFullYear();
|
||||
return new Intl.DateTimeFormat('ru-RU', { day: 'numeric', month: 'long', ...(sameYear ? {} : { year: 'numeric' }) }).format(dt);
|
||||
}
|
||||
|
||||
export function dayKey(timestampMs) {
|
||||
const ts = toNumber(timestampMs);
|
||||
if (!ts) return '';
|
||||
const dt = new Date(ts);
|
||||
return `${dt.getFullYear()}-${dt.getMonth()}-${dt.getDate()}`;
|
||||
}
|
||||
|
||||
// Время в строках списков (чаты, каналы) — коротко, как в мессенджерах:
|
||||
// сегодня «21:41», вчера «вчера», на этой неделе «пт», в этом году «24.09», раньше «24.09.25».
|
||||
export function formatListTime(timestampMs) {
|
||||
const ts = toNumber(timestampMs);
|
||||
if (!ts) return '';
|
||||
const dt = new Date(ts);
|
||||
const now = new Date();
|
||||
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
|
||||
if (ts >= startOfToday) {
|
||||
return new Intl.DateTimeFormat('ru-RU', { hour: '2-digit', minute: '2-digit' }).format(dt);
|
||||
}
|
||||
const dayMs = 86400000;
|
||||
if (ts >= startOfToday - dayMs) return 'вчера';
|
||||
if (ts >= startOfToday - 6 * dayMs) {
|
||||
return new Intl.DateTimeFormat('ru-RU', { weekday: 'short' }).format(dt);
|
||||
}
|
||||
if (dt.getFullYear() === now.getFullYear()) {
|
||||
return new Intl.DateTimeFormat('ru-RU', { day: '2-digit', month: '2-digit' }).format(dt);
|
||||
}
|
||||
return new Intl.DateTimeFormat('ru-RU', { day: '2-digit', month: '2-digit', year: '2-digit' }).format(dt);
|
||||
}
|
||||
|
||||
export function formatRelativeTime(timestampMs) {
|
||||
const ts = toNumber(timestampMs);
|
||||
if (!ts) return '—';
|
||||
@@ -39,6 +89,8 @@ export function formatRelativeTime(timestampMs) {
|
||||
const ageSeconds = Math.max(0, (now - ts) / 1000);
|
||||
const ageDays = ageSeconds / 86400;
|
||||
|
||||
if (ageSeconds < 60) return 'только что';
|
||||
|
||||
if (ageDays < 7) {
|
||||
const [unit, value] = pickUnit(diffSeconds);
|
||||
if (rtf) return rtf.format(value, unit);
|
||||
|
||||
@@ -43,7 +43,7 @@ function wsUrlToHttpBase(wsUrl = '') {
|
||||
if (parsed.protocol === 'wss:') parsed.protocol = 'https:';
|
||||
else if (parsed.protocol === 'ws:') parsed.protocol = 'http:';
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||||
throw new Error('Не удалось определить HTTP-адрес сервера SHiNE');
|
||||
throw new Error('Не удалось определить HTTP-адрес сервера Сияния');
|
||||
}
|
||||
parsed.pathname = '/';
|
||||
parsed.search = '';
|
||||
@@ -609,7 +609,7 @@ function suggestedPickerTypes(attachment) {
|
||||
const dot = name.lastIndexOf('.');
|
||||
const extension = dot >= 0 ? name.slice(dot) : '';
|
||||
return [{
|
||||
description: 'Файл SHiNE',
|
||||
description: 'Файл Сияния',
|
||||
accept: { [mime]: extension ? [extension] : [] },
|
||||
}];
|
||||
}
|
||||
@@ -692,7 +692,7 @@ export async function downloadAndDecryptDmFile(attachment = {}, { onProgress = n
|
||||
}
|
||||
|
||||
export async function buildDmFileTorrentV2(attachment = {}) {
|
||||
if (Number(attachment?.version || 1) < 2) throw new Error('Torrent-v2 metadata есть только у файлов SHiNE v2');
|
||||
if (Number(attachment?.version || 1) < 2) throw new Error('Torrent-v2 metadata есть только у файлов Сияния v2');
|
||||
const context = await loadV2RootManifest(attachment);
|
||||
const pieceLayer = [];
|
||||
try {
|
||||
|
||||
@@ -55,7 +55,7 @@ export function makeKeyTransferText({ login, keys }) {
|
||||
export function parseKeyTransferText(text) {
|
||||
const raw = String(text || '').trim();
|
||||
if (!raw.startsWith(TRANSFER_PREFIX)) {
|
||||
throw new Error('Это не QR-код переноса ключей SHiNE');
|
||||
throw new Error('Это не QR-код переноса ключей Сияния');
|
||||
}
|
||||
const json = decoder.decode(base64UrlToBytes(raw.slice(TRANSFER_PREFIX.length)));
|
||||
const payload = JSON.parse(json);
|
||||
|
||||
@@ -46,7 +46,7 @@ export async function resolveShineServerByServerLogin({ serverLogin, solanaEndpo
|
||||
solanaEndpoint,
|
||||
});
|
||||
if (!parsed?.isServer) {
|
||||
throw new Error(`Логин @${cleanServerLogin} не опубликован как сервер SHiNE.`);
|
||||
throw new Error(`Логин @${cleanServerLogin} не опубликован как сервер Сияния.`);
|
||||
}
|
||||
const serverAddress = normalizeHostLike(parsed?.serverAddress || '');
|
||||
if (!serverAddress) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,12 +1,248 @@
|
||||
const STORAGE_KEY = 'shine-ui-theme-mode-v1';
|
||||
// Выбранная палитра и личные правки цветов (для дня и ночи отдельно).
|
||||
const PALETTE_KEY = 'shine-ui-palette-v1';
|
||||
// Итоговые значения для каждой темы: их читает скрипт в index.html до первой отрисовки,
|
||||
// чтобы при запуске не мелькала палитра по умолчанию.
|
||||
const APPLIED_KEY = 'shine-ui-palette-applied-v1';
|
||||
const MODES = new Set(['system', 'light', 'dark']);
|
||||
let sessionMode = null;
|
||||
|
||||
// Роли цветов — тот же контракт, что в docs/UI-Design/DESIGN.md (раздел 4.1) и styles/main.css.
|
||||
export const PALETTE_ROLES = [
|
||||
{ id: 'background', label: 'Фон' },
|
||||
{ id: 'surface', label: 'Поверхности: поля, меню, карточки' },
|
||||
{ id: 'surface-selected', label: 'Выбранное и лёгкое выделение' },
|
||||
{ id: 'text-primary', label: 'Основной текст' },
|
||||
{ id: 'text-secondary', label: 'Вторичный текст: время, подсказки' },
|
||||
{ id: 'border-subtle', label: 'Разделители' },
|
||||
{ id: 'border-control', label: 'Рамки полей и кнопок' },
|
||||
{ id: 'accent', label: 'Акцент: главные кнопки, ссылки' },
|
||||
{ id: 'on-accent', label: 'Текст на акцентной кнопке' },
|
||||
{ id: 'reaction-active', label: 'Поставленный лайк' },
|
||||
{ id: 'danger', label: 'Ошибки и удаление' },
|
||||
{ id: 'success', label: 'Успех' },
|
||||
{ id: 'warning', label: 'Предупреждение' },
|
||||
];
|
||||
|
||||
export const PALETTE_PRESETS = {
|
||||
club: {
|
||||
label: 'Индиго',
|
||||
dark: {
|
||||
background: '#12141f', surface: '#1c2031', 'surface-selected': '#272c45',
|
||||
'text-primary': '#eceefa', 'text-secondary': '#a0a6c2',
|
||||
'border-subtle': '#343a55', 'border-control': '#6d7396',
|
||||
accent: '#a9b4ff', 'on-accent': '#151a3d', 'reaction-active': '#ff9bb3',
|
||||
danger: '#ffa7a3', success: '#8fdab4', warning: '#e8c585',
|
||||
},
|
||||
light: {
|
||||
background: '#eef0f5', surface: '#ffffff', 'surface-selected': '#dde3f5',
|
||||
'text-primary': '#1e2233', 'text-secondary': '#5c6279',
|
||||
'border-subtle': '#d5d9e5', 'border-control': '#8a90a8',
|
||||
accent: '#4c5caa', 'on-accent': '#ffffff', 'reaction-active': '#c02a55',
|
||||
danger: '#b3261e', success: '#2c6b4a', warning: '#7d5a10',
|
||||
},
|
||||
},
|
||||
shine: {
|
||||
label: 'Бирюза',
|
||||
dark: {
|
||||
background: '#101b20', surface: '#17272d', 'surface-selected': '#213b3a',
|
||||
'text-primary': '#e8f2f1', 'text-secondary': '#98adaf',
|
||||
'border-subtle': '#2a3b40', 'border-control': '#71888a',
|
||||
accent: '#94e1ce', 'on-accent': '#102c27', 'reaction-active': '#f29aab',
|
||||
danger: '#ffaba8', success: '#94e1ce', warning: '#e6c184',
|
||||
},
|
||||
light: {
|
||||
background: '#faf7f0', surface: '#fffdf8', 'surface-selected': '#efe6d6',
|
||||
'text-primary': '#302c25', 'text-secondary': '#706658',
|
||||
'border-subtle': '#e6dfd1', 'border-control': '#978b79',
|
||||
accent: '#93511e', 'on-accent': '#fffaf3', 'reaction-active': '#a43350',
|
||||
danger: '#b13135', success: '#346a48', warning: '#845b14',
|
||||
},
|
||||
},
|
||||
mono: {
|
||||
label: 'Монохром',
|
||||
dark: {
|
||||
background: '#111212', surface: '#1c1d1d', 'surface-selected': '#2c2d2d',
|
||||
'text-primary': '#f3f3f1', 'text-secondary': '#a3a3a0',
|
||||
'border-subtle': '#2a2b2b', 'border-control': '#6f706e',
|
||||
accent: '#f3f3f1', 'on-accent': '#111212', 'reaction-active': '#ff8a9a',
|
||||
danger: '#ff9d97', success: '#9fd8a8', warning: '#e8c37e',
|
||||
},
|
||||
light: {
|
||||
background: '#ffffff', surface: '#f6f6f5', 'surface-selected': '#ebebea',
|
||||
'text-primary': '#141414', 'text-secondary': '#626262',
|
||||
'border-subtle': '#e4e4e2', 'border-control': '#8c8c8a',
|
||||
accent: '#141414', 'on-accent': '#ffffff', 'reaction-active': '#d0214a',
|
||||
danger: '#b3261e', success: '#2f6b3b', warning: '#7d5a10',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
function mixHex(first, second, amount) {
|
||||
const a = first.match(/[0-9a-f]{2}/gi).map((part) => parseInt(part, 16));
|
||||
const b = second.match(/[0-9a-f]{2}/gi).map((part) => parseInt(part, 16));
|
||||
return `#${a.map((value, index) => Math.round(value * (1 - amount) + b[index] * amount).toString(16).padStart(2, '0')).join('')}`;
|
||||
}
|
||||
|
||||
const EXTRA_PRESETS = [
|
||||
['ocean', 'Океан', '#101c2b', '#182a3d', '#213c55', '#edf5ff', '#a6b9cf', '#75c8f0', '#102b40', '#f9fcff', '#e4f2fb', '#173247', '#536f83', '#087eae', '#ffffff'],
|
||||
['lavender', 'Лаванда', '#211b2b', '#30263d', '#473658', '#f5efff', '#bcb0cf', '#c5a0f5', '#f1ebf7', '#fffaff', '#e9def3', '#31283a', '#6d6076', '#7950a8', '#ffffff'],
|
||||
['graphite', 'Графит', '#17191c', '#222529', '#34383d', '#f2f4f5', '#adb4ba', '#c4cbd1', '#eef0f1', '#ffffff', '#e0e4e6', '#202427', '#5b646a', '#46535b', '#ffffff'],
|
||||
['sakura', 'Сакура', '#291b25', '#382430', '#503140', '#fff0f5', '#c9aab7', '#f39abb', '#fff0f4', '#fffafd', '#f7dce6', '#39232d', '#795967', '#b73565', '#ffffff'],
|
||||
['emerald', 'Изумруд', '#10231e', '#19332b', '#24483a', '#e8f8ef', '#a0c5ae', '#7fe0aa', '#eaf5ed', '#fbfffc', '#d8eddf', '#20372a', '#587363', '#187747', '#ffffff'],
|
||||
['sunrise', 'Рассвет', '#2b2017', '#3b2b1c', '#58402a', '#fff4df', '#d0b894', '#ffc36b', '#fff3df', '#fffaf0', '#f5e4c4', '#3a2b1b', '#78664c', '#a45c12', '#ffffff'],
|
||||
['cyberpunk', 'Киберпанк', '#171329', '#241b3b', '#382657', '#f5f0ff', '#b9a9d8', '#ff70dc', '#f6edfb', '#fffbff', '#eddcf5', '#30233b', '#705b7b', '#a12b91', '#ffffff'],
|
||||
['arctic', 'Арктика', '#14242a', '#1d333a', '#294750', '#edfaff', '#a7c4cc', '#82e2e5', '#e8f7f8', '#fbffff', '#d6eef0', '#20373a', '#587477', '#087f83', '#ffffff'],
|
||||
['coral', 'Коралл', '#2b1d1b', '#3a2925', '#563b34', '#fff1ec', '#d1b2a8', '#ff9d83', '#fff0e9', '#fffaf7', '#f9dfd4', '#3b2923', '#7b6258', '#bc4931', '#ffffff'],
|
||||
['grape', 'Виноград', '#211829', '#302238', '#493151', '#f8efff', '#c1a9cd', '#d39afa', '#f4eafa', '#fffaff', '#e9d8f2', '#35253d', '#725d7a', '#8145a9', '#ffffff'],
|
||||
['forest', 'Лес', '#19231b', '#263328', '#394b39', '#f0f7ed', '#b1c1a7', '#b0d17c', '#f0f4e8', '#fcfff7', '#e4ebd7', '#303828', '#69735d', '#52751f', '#ffffff'],
|
||||
['ruby', 'Рубин', '#28181e', '#382128', '#512e39', '#fff0f2', '#ceabb3', '#fa8095', '#fff0f1', '#fffafb', '#f4dce0', '#3c242b', '#795861', '#b52d4d', '#ffffff'],
|
||||
['lagoon', 'Лагуна', '#102323', '#193333', '#254949', '#e9f8f4', '#a1c4bc', '#67d8c2', '#e7f5ef', '#fbfffc', '#d3eee4', '#1e3932', '#56746b', '#087e70', '#ffffff'],
|
||||
['copper', 'Медь', '#281e19', '#392a22', '#533d30', '#fff2e8', '#ceb5a2', '#e9a879', '#f8eee5', '#fffaf5', '#eddfd1', '#392a21', '#786657', '#a65e2b', '#ffffff'],
|
||||
['neon', 'Неон', '#141f1b', '#1e3028', '#2b4939', '#edfff2', '#a6c6ae', '#a7f36b', '#eff7e9', '#fcfff8', '#dff0d0', '#253923', '#5b7352', '#4c861d', '#ffffff'],
|
||||
['paper', 'Бумага', '#20201e', '#2e2e2b', '#454540', '#f6f5ef', '#bcbcb2', '#d6c49b', '#f3f0e8', '#fffdf7', '#e8e2d3', '#302e28', '#716d61', '#76613b', '#ffffff'],
|
||||
['cosmos', 'Космос', '#171a30', '#222744', '#323b62', '#f0f2ff', '#aeb6d6', '#9eacff', '#edf0fc', '#fbfcff', '#dfe4fa', '#252b46', '#5c6687', '#4f61c5', '#ffffff'],
|
||||
['mint', 'Мята', '#14231f', '#1f332c', '#2e4940', '#ebfbf4', '#a9c6b9', '#8fe2c0', '#eaf5ee', '#fbfffc', '#d7eee1', '#21392f', '#597568', '#16805b', '#ffffff'],
|
||||
['sandstone', 'Песчаник', '#272019', '#382e23', '#514333', '#fff5e8', '#c9b69c', '#f0bd78', '#f6efe3', '#fffdf8', '#e9deca', '#3a3023', '#776b58', '#96601b', '#ffffff'],
|
||||
['dusk', 'Сумерки', '#211b2a', '#30263c', '#493658', '#f5efff', '#b8acc8', '#e0a6c8', '#f2edf4', '#fffaff', '#e8dfe9', '#352a39', '#706174', '#98577d', '#ffffff'],
|
||||
['lemon', 'Лимон', '#202216', '#30331e', '#454a2b', '#f8f9e9', '#bfc39c', '#e2e96d', '#f2f3e3', '#fdfff5', '#e6e9cc', '#353822', '#71755a', '#737c16', '#ffffff'],
|
||||
['obsidian', 'Обсидиан', '#151719', '#202326', '#30363b', '#f2f5f7', '#aab5bc', '#8db7c7', '#e9eef0', '#fbfeff', '#dce5e8', '#252c30', '#5c6a70', '#3b778c', '#ffffff'],
|
||||
];
|
||||
|
||||
function makePreset(label, dark, light) {
|
||||
const toColors = (palette, theme) => {
|
||||
const [background, surface, ...rest] = palette;
|
||||
const [selected, text, secondary, accent, onAccent] = rest.length === 5
|
||||
? rest
|
||||
: [mixHex(surface, rest[0], 0.08), ...rest];
|
||||
return {
|
||||
background,
|
||||
surface,
|
||||
'surface-selected': selected,
|
||||
'text-primary': text,
|
||||
'text-secondary': secondary,
|
||||
'border-subtle': mixHex(surface, text, 0.14),
|
||||
'border-control': mixHex(surface, text, 0.4),
|
||||
accent,
|
||||
'on-accent': onAccent,
|
||||
'reaction-active': theme === 'dark' ? '#ff9bb3' : '#c02a55',
|
||||
danger: theme === 'dark' ? '#ffa7a3' : '#b3261e',
|
||||
success: theme === 'dark' ? '#8fdab4' : '#2c6b4a',
|
||||
warning: theme === 'dark' ? '#e8c585' : '#7d5a10',
|
||||
};
|
||||
};
|
||||
return { label, dark: toColors(dark, 'dark'), light: toColors(light, 'light') };
|
||||
}
|
||||
|
||||
for (const [id, label, ...colors] of EXTRA_PRESETS) {
|
||||
PALETTE_PRESETS[id] = makePreset(label, colors.slice(0, 7), colors.slice(7));
|
||||
}
|
||||
|
||||
const DEFAULT_PRESET = 'club';
|
||||
const HEX_COLOR = /^#[0-9a-f]{6}$/i;
|
||||
|
||||
function normalizeMode(value) {
|
||||
const mode = String(value || '').trim().toLowerCase();
|
||||
return MODES.has(mode) ? mode : 'system';
|
||||
}
|
||||
|
||||
function readJson(key) {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(key) || 'null');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeJson(key, value) {
|
||||
try {
|
||||
if (value === null) localStorage.removeItem(key);
|
||||
else localStorage.setItem(key, JSON.stringify(value));
|
||||
} catch {
|
||||
// В приватном режиме палитра всё равно действует до закрытия страницы.
|
||||
}
|
||||
}
|
||||
|
||||
function cleanOverrides(raw) {
|
||||
const out = {};
|
||||
for (const role of PALETTE_ROLES) {
|
||||
const value = String(raw?.[role.id] || '').trim();
|
||||
if (HEX_COLOR.test(value)) out[role.id] = value.toLowerCase();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
let sessionPalette = null;
|
||||
|
||||
export function getPaletteSettings() {
|
||||
if (sessionPalette) return sessionPalette;
|
||||
const raw = readJson(PALETTE_KEY) || {};
|
||||
const preset = PALETTE_PRESETS[raw.preset] ? raw.preset : DEFAULT_PRESET;
|
||||
return {
|
||||
preset,
|
||||
custom: { dark: cleanOverrides(raw.custom?.dark), light: cleanOverrides(raw.custom?.light) },
|
||||
};
|
||||
}
|
||||
|
||||
export function resolvePalette(resolvedTheme, settings = getPaletteSettings()) {
|
||||
const theme = resolvedTheme === 'light' ? 'light' : 'dark';
|
||||
return { ...PALETTE_PRESETS[settings.preset][theme], ...settings.custom[theme] };
|
||||
}
|
||||
|
||||
function isDefaultPalette(settings) {
|
||||
return settings.preset === DEFAULT_PRESET
|
||||
&& !Object.keys(settings.custom.dark).length
|
||||
&& !Object.keys(settings.custom.light).length;
|
||||
}
|
||||
|
||||
function applyPaletteVars(resolvedTheme) {
|
||||
const root = document.documentElement;
|
||||
const settings = getPaletteSettings();
|
||||
for (const role of PALETTE_ROLES) root.style.removeProperty(`--${role.id}`);
|
||||
root.style.removeProperty('--focus-ring');
|
||||
// Палитра по умолчанию живёт в styles/main.css — inline-переменные не нужны.
|
||||
if (isDefaultPalette(settings)) return;
|
||||
const colors = resolvePalette(resolvedTheme, settings);
|
||||
for (const [role, value] of Object.entries(colors)) root.style.setProperty(`--${role}`, value);
|
||||
root.style.setProperty('--focus-ring', colors.accent);
|
||||
}
|
||||
|
||||
export function setPaletteSettings(next) {
|
||||
const settings = {
|
||||
preset: PALETTE_PRESETS[next?.preset] ? next.preset : DEFAULT_PRESET,
|
||||
custom: { dark: cleanOverrides(next?.custom?.dark), light: cleanOverrides(next?.custom?.light) },
|
||||
};
|
||||
sessionPalette = settings;
|
||||
if (isDefaultPalette(settings)) {
|
||||
writeJson(PALETTE_KEY, null);
|
||||
writeJson(APPLIED_KEY, null);
|
||||
} else {
|
||||
writeJson(PALETTE_KEY, settings);
|
||||
writeJson(APPLIED_KEY, { dark: resolvePalette('dark', settings), light: resolvePalette('light', settings) });
|
||||
}
|
||||
return applyThemeMode();
|
||||
}
|
||||
|
||||
export function exportPalette() {
|
||||
const settings = getPaletteSettings();
|
||||
return JSON.stringify({
|
||||
preset: settings.preset,
|
||||
dark: resolvePalette('dark', settings),
|
||||
light: resolvePalette('light', settings),
|
||||
}, null, 2);
|
||||
}
|
||||
|
||||
export function importPalette(text) {
|
||||
const data = JSON.parse(String(text || ''));
|
||||
const preset = PALETTE_PRESETS[data?.preset] ? data.preset : DEFAULT_PRESET;
|
||||
const base = PALETTE_PRESETS[preset];
|
||||
const diff = (theme) => {
|
||||
const colors = cleanOverrides(data?.[theme]);
|
||||
return Object.fromEntries(Object.entries(colors).filter(([role, value]) => base[theme][role] !== value));
|
||||
};
|
||||
return setPaletteSettings({ preset, custom: { dark: diff('dark'), light: diff('light') } });
|
||||
}
|
||||
|
||||
export function getThemeMode() {
|
||||
if (sessionMode !== null) return sessionMode;
|
||||
try {
|
||||
@@ -16,14 +252,21 @@ export function getThemeMode() {
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveThemeMode(mode = getThemeMode()) {
|
||||
const normalized = normalizeMode(mode);
|
||||
if (normalized !== 'system') return normalized;
|
||||
return window.matchMedia?.('(prefers-color-scheme: light)')?.matches ? 'light' : 'dark';
|
||||
}
|
||||
|
||||
export function applyThemeMode(mode = getThemeMode()) {
|
||||
const normalized = normalizeMode(mode);
|
||||
const resolved = normalized === 'system'
|
||||
? (window.matchMedia?.('(prefers-color-scheme: light)')?.matches ? 'light' : 'dark')
|
||||
: normalized;
|
||||
const resolved = resolveThemeMode(normalized);
|
||||
document.documentElement.dataset.themeMode = normalized;
|
||||
document.documentElement.dataset.theme = resolved;
|
||||
document.documentElement.style.colorScheme = resolved;
|
||||
applyPaletteVars(resolved);
|
||||
const meta = document.querySelector('meta[name="theme-color"]');
|
||||
if (meta) meta.setAttribute('content', resolvePalette(resolved).background);
|
||||
return { mode: normalized, resolved };
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ 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: 'web', readKeys: ['web'], label: 'Links', placeholder: 'Сайт, профиль или другая ссылка' },
|
||||
{ key: 'web', readKeys: ['web'], label: 'Ссылки', placeholder: 'Сайт, профиль или другая ссылка' },
|
||||
{ key: 'phone', readKeys: ['phone'], label: 'Телефон', placeholder: '+7 ...' },
|
||||
{ key: 'about', readKeys: ['about'], label: 'О себе', placeholder: 'Коротко расскажите о себе', maxLength: 160, multiline: true },
|
||||
{ key: 'spiritual_path', readKeys: ['spiritual_path'], label: 'Духовный путь', placeholder: 'Расскажите о своём духовном пути, опыте, практиках и взглядах', maxLength: 5000, multiline: true },
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
</div>
|
||||
|
||||
<h1>Регистрация серверного аккаунта</h1>
|
||||
<p class="subtitle">Создаёт user_pda в Solana с флагом is_server=true</p>
|
||||
<p class="subtitle">Создаёт серверную user_pda в Solana (PDA 1.2)</p>
|
||||
|
||||
<div class="card">
|
||||
<h2>Параметры Solana</h2>
|
||||
@@ -65,12 +65,8 @@
|
||||
<input type="text" id="serverAddress" placeholder="Адрес сервера" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>Логины серверов c которыми будет синхронизировать записи в блокчейн этот сервер (Например shineupme)</label>
|
||||
<textarea id="syncServers" placeholder="По одному логину на строку (можно оставить пустым)"></textarea>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>Серверы доступа (access_servers, опционально)</label>
|
||||
<textarea id="accessServers" placeholder="Обычно пусто для серверного PDA"></textarea>
|
||||
<label>Сервер доступа (access_servers, 0 или 1)</label>
|
||||
<textarea id="accessServers" placeholder="Один логин сервера доступа или пусто"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -99,17 +95,12 @@
|
||||
<div class="sec-lbl">Ключевые пары (base58)</div>
|
||||
|
||||
<div class="kp-block">
|
||||
<div class="kp-title">Recovery Key — восстановление аккаунта</div>
|
||||
<div class="kp-row"><span class="kp-lbl">Публичный</span><input class="kp-inp" type="text" id="recoveryPub" placeholder="base58, ~44 символа" /></div>
|
||||
<div class="kp-row"><span class="kp-lbl">Приватный</span><input class="kp-inp" type="text" id="recoveryPriv" placeholder="seed base58, ~44 символа" /></div>
|
||||
</div>
|
||||
<div class="kp-block">
|
||||
<div class="kp-title">Root Key — подпись PDA-записи</div>
|
||||
<div class="kp-title">Root Key — холодное восстановление / полный контроль PDA</div>
|
||||
<div class="kp-row"><span class="kp-lbl">Публичный</span><input class="kp-inp" type="text" id="rootPub" placeholder="base58, ~44 символа" /></div>
|
||||
<div class="kp-row"><span class="kp-lbl">Приватный</span><input class="kp-inp" type="text" id="rootPriv" placeholder="seed base58, ~44 символа" /></div>
|
||||
</div>
|
||||
<div class="kp-block">
|
||||
<div class="kp-title">Blockchain Key — подпись LastBlockState</div>
|
||||
<div class="kp-title">Blockchain Key — активный ключ блокчейна и обычный authority PDA</div>
|
||||
<div class="kp-row"><span class="kp-lbl">Публичный</span><input class="kp-inp" type="text" id="bchPub" placeholder="base58, ~44 символа" /></div>
|
||||
<div class="kp-row"><span class="kp-lbl">Приватный</span><input class="kp-inp" type="text" id="bchPriv" placeholder="seed base58, ~44 символа" /></div>
|
||||
</div>
|
||||
|
||||
@@ -20,8 +20,6 @@ import { defaultServerAddress, defaultServerLogin, defaultSolanaEndpoint } from
|
||||
|
||||
const fieldMap = {
|
||||
masterSecret: 'masterSecret',
|
||||
recoveryPub: 'recoveryPub',
|
||||
recoveryPriv: 'recoveryPriv',
|
||||
rootPub: 'rootPub',
|
||||
rootPriv: 'rootPriv',
|
||||
bchPub: 'bchPub',
|
||||
@@ -113,7 +111,6 @@ $('btnCreate').addEventListener('click', async () => {
|
||||
login,
|
||||
keyBundle,
|
||||
serverAddress,
|
||||
syncServers: parseLoginList($('syncServers').value),
|
||||
accessServers: parseLoginList($('accessServers').value),
|
||||
solanaEndpoint: endpoint,
|
||||
});
|
||||
|
||||
@@ -112,6 +112,7 @@ function renderParsed(parsed) {
|
||||
|
||||
renderRows([
|
||||
{ label: 'PDA адрес', value: parsed.pdaAddress },
|
||||
{ label: 'Формат', value: `${parsed.formatMajor}.${parsed.formatMinor}` },
|
||||
{ label: 'Логин', value: parsed.login },
|
||||
{ label: 'Статус', value: parsed.isServer ? 'server' : 'not server' },
|
||||
{ label: 'recordNumber', value: String(parsed.recordNumber) },
|
||||
@@ -126,11 +127,10 @@ function renderParsed(parsed) {
|
||||
const badgeLine = $('badgeLine');
|
||||
badgeLine.innerHTML = '';
|
||||
const badges = [
|
||||
{ label: 'format=1.2', kind: 'ok' },
|
||||
{ label: `server=${parsed.isServer ? '1' : '0'}`, kind: parsed.isServer ? 'ok' : 'warn' },
|
||||
{ label: `trusted=${Number(parsed.trustedCount || 0)}`, kind: Number(parsed.trustedCount || 0) > 0 ? 'ok' : 'warn' },
|
||||
{ label: `sessions=${Array.isArray(parsed.sessions) ? parsed.sessions.length : 0}`, kind: 'info' },
|
||||
{ label: `forks=${Array.isArray(parsed.forks) ? parsed.forks.length : 0}`, kind: 'info' },
|
||||
{ label: `access=${Array.isArray(parsed.accessServers) ? parsed.accessServers.length : 0}`, kind: 'info' },
|
||||
{ label: `sync=${Array.isArray(parsed.syncServers) ? parsed.syncServers.length : 0}`, kind: 'info' },
|
||||
];
|
||||
badges.forEach((item) => {
|
||||
const badge = document.createElement('span');
|
||||
@@ -141,84 +141,55 @@ function renderParsed(parsed) {
|
||||
|
||||
const blocks = $('blocksList');
|
||||
blocks.innerHTML = '';
|
||||
blocks.appendChild(renderBlock('RecoveryKeyBlock', 'block_type=0', [
|
||||
{ label: 'recoveryKey32', value: base58(parsed.recoveryKey) },
|
||||
]));
|
||||
blocks.appendChild(renderBlock('RootKeyBlock', 'block_type=1', [
|
||||
blocks.appendChild(renderBlock('RootKeyBlock', 'block_type=1, version=0', [
|
||||
{ label: 'rootKey32', value: base58(parsed.rootKey) },
|
||||
]));
|
||||
blocks.appendChild(renderBlock('ClientKeyBlock', 'block_type=2', [
|
||||
blocks.appendChild(renderBlock('ClientKeyBlock', 'block_type=2, version=0', [
|
||||
{ label: 'clientKey32', value: base58(parsed.clientKey) },
|
||||
]));
|
||||
blocks.appendChild(renderBlock('BlockchainRegistryBlock', 'block_type=3', [
|
||||
{ label: 'blockchainType', value: String(parsed.blockchain?.blockchainType ?? 0) },
|
||||
{ label: 'blockchainName', value: parsed.blockchain?.blockchainName || '—' },
|
||||
{ label: 'blockchainPublicKey32', value: base58(parsed.blockchain?.blockchainPublicKey) },
|
||||
{ label: 'paidLimitBytes', value: formatBigInt(parsed.blockchain?.paidLimitBytes || 0n) },
|
||||
{ label: 'usedBytes', value: formatBigInt(parsed.blockchain?.usedBytes || 0n) },
|
||||
{ label: 'lastBlockNumber', value: String(parsed.blockchain?.lastBlockNumber ?? 0) },
|
||||
{ label: 'lastBlockHash32', value: hex(parsed.blockchain?.lastBlockHash) },
|
||||
{ label: 'lastBlockSignature64', value: base58(parsed.blockchain?.lastBlockSignature) },
|
||||
{ label: 'arweaveTxId', value: parsed.blockchain?.arweaveTxId || '—' },
|
||||
]));
|
||||
blocks.appendChild(renderBlock('ServerProfileBlock', 'block_type=30', [
|
||||
{ label: 'isServer', value: parsed.isServer ? '1' : '0' },
|
||||
{ label: 'addressFormatType', value: String(parsed.addressFormatType ?? 0) },
|
||||
{ label: 'addressFormatVersion', value: String(parsed.addressFormatVersion ?? 0) },
|
||||
{ label: 'serverAddress', value: parsed.serverAddress || '—' },
|
||||
{ label: 'syncServersCount', value: String(parsed.syncServers?.length || 0) },
|
||||
{ label: 'syncServers', value: renderArrayLine(parsed.syncServers) },
|
||||
]));
|
||||
blocks.appendChild(renderBlock('AccessServersBlock', 'block_type=40', [
|
||||
{ label: 'accessServersCount', value: String(parsed.accessServers?.length || 0) },
|
||||
{ label: 'accessServers', value: renderArrayLine(parsed.accessServers) },
|
||||
]));
|
||||
blocks.appendChild(renderBlock('SessionsBlock', 'block_type=50', [
|
||||
{ label: 'sessionsMode', value: String(parsed.sessionsMode ?? 0) },
|
||||
{ label: 'sessionsCount', value: String(parsed.sessions?.length || 0) },
|
||||
{ label: 'sessions', value: parsed.sessions?.length ? 'ниже' : '—' },
|
||||
]));
|
||||
blocks.appendChild(renderBlock('TrustedStateBlock', 'block_type=70', [
|
||||
{ label: 'trustedCount', value: String(parsed.trustedCount ?? 0) },
|
||||
]));
|
||||
blocks.appendChild(renderSessionList(parsed.sessions));
|
||||
|
||||
$('rawJson').textContent = JSON.stringify({
|
||||
const forkLines = (parsed.forks || []).map((fork, idx) =>
|
||||
`#${idx}: ${base58(fork.blockchainKey)} · created=${formatTimestamp(fork.createdAtMs)} · limit=${formatBigInt(fork.paidLimitBytes)}`,
|
||||
);
|
||||
blocks.appendChild(renderBlock('BlockchainRegistryBlock', 'block_type=3, version=0', [
|
||||
{ label: 'forkCount', value: String(parsed.forks?.length || 0) },
|
||||
{ label: 'forks', value: forkLines.length ? forkLines.join('\n') : '—' },
|
||||
]));
|
||||
|
||||
if (parsed.isServer) {
|
||||
const addressLines = (parsed.serverAddresses || []).map((item) =>
|
||||
`type=${item.addressFormatType}, v=${item.addressFormatVersion}: ${item.address}`,
|
||||
);
|
||||
blocks.appendChild(renderBlock('ServerProfileBlock', 'block_type=30, version=0', [
|
||||
{ label: 'addressCount', value: String(parsed.serverAddresses?.length || 0) },
|
||||
{ label: 'address', value: addressLines.length ? addressLines.join('\n') : '—' },
|
||||
]));
|
||||
}
|
||||
if (Array.isArray(parsed.accessServers) && parsed.accessServers.length) {
|
||||
blocks.appendChild(renderBlock('AccessServersBlock', 'block_type=40, version=0', [
|
||||
{ label: 'accessServersCount', value: String(parsed.accessServers.length) },
|
||||
{ label: 'accessServer', value: renderArrayLine(parsed.accessServers) },
|
||||
]));
|
||||
}
|
||||
|
||||
const raw = {
|
||||
pdaAddress: parsed.pdaAddress,
|
||||
format: `${parsed.formatMajor}.${parsed.formatMinor}`,
|
||||
login: parsed.login,
|
||||
isServer: parsed.isServer,
|
||||
recordNumber: parsed.recordNumber,
|
||||
createdAtMs: parsed.createdAtMs.toString(),
|
||||
updatedAtMs: parsed.updatedAtMs.toString(),
|
||||
recordLen: parsed.recordLen,
|
||||
trustedCount: parsed.trustedCount,
|
||||
addressFormatType: parsed.addressFormatType,
|
||||
addressFormatVersion: parsed.addressFormatVersion,
|
||||
serverAddress: parsed.serverAddress,
|
||||
syncServers: parsed.syncServers,
|
||||
accessServers: parsed.accessServers,
|
||||
sessionsMode: parsed.sessionsMode,
|
||||
sessions: parsed.sessions.map((s) => ({
|
||||
sessionType: s.sessionType,
|
||||
sessionVersion: s.sessionVersion,
|
||||
sessionName: s.sessionName,
|
||||
sessionPubKey32: base58(s.sessionPubKey32),
|
||||
})),
|
||||
recoveryKey: base58(parsed.recoveryKey),
|
||||
prevRecordHash: hex(parsed.prevRecordHash),
|
||||
rootKey: base58(parsed.rootKey),
|
||||
clientKey: base58(parsed.clientKey),
|
||||
blockchain: {
|
||||
blockchainType: parsed.blockchain.blockchainType,
|
||||
blockchainName: parsed.blockchain.blockchainName,
|
||||
blockchainPublicKey: base58(parsed.blockchain.blockchainPublicKey),
|
||||
paidLimitBytes: parsed.blockchain.paidLimitBytes.toString(),
|
||||
usedBytes: parsed.blockchain.usedBytes.toString(),
|
||||
lastBlockNumber: parsed.blockchain.lastBlockNumber,
|
||||
lastBlockHash: hex(parsed.blockchain.lastBlockHash),
|
||||
lastBlockSignature: base58(parsed.blockchain.lastBlockSignature),
|
||||
arweaveTxId: parsed.blockchain.arweaveTxId || '',
|
||||
},
|
||||
}, null, 2);
|
||||
serverAddresses: (parsed.serverAddresses || []).map((a) => ({ ...a })),
|
||||
accessServers: parsed.accessServers || [],
|
||||
signature: base58(parsed.signature),
|
||||
};
|
||||
|
||||
$('rawJson').textContent = JSON.stringify(raw, null, 2);
|
||||
}
|
||||
|
||||
$('btnLoad').addEventListener('click', async () => {
|
||||
|
||||
@@ -111,18 +111,6 @@ async function pairFromSeedBase58(seedB58, explicitPubB58) {
|
||||
|
||||
export async function buildKeyBundleFromForm(fieldMap, options = {}) {
|
||||
const requireBlockchain = options.requireBlockchain !== false;
|
||||
let recovery = null;
|
||||
const masterSecretValue = fieldMap.masterSecret ? String($(fieldMap.masterSecret).value || '').trim() : '';
|
||||
if (masterSecretValue) {
|
||||
const masterSecret32 = ensure32Bytes(base58ToBytes(masterSecretValue));
|
||||
const recoveryPair = await deriveEd25519FromMasterSecret(masterSecret32, 'recovery.key');
|
||||
recovery = {
|
||||
publicKeyB64: recoveryPair.publicKeyB64,
|
||||
privatePkcs8B64: recoveryPair.privatePkcs8B64,
|
||||
publicKeyB58: bytesToBase58(base64ToBytes(recoveryPair.publicKeyB64)),
|
||||
privateSeedB58: bytesToBase58(base64ToBytes(recoveryPair.privatePkcs8B64).slice(-32)),
|
||||
};
|
||||
}
|
||||
const root = await pairFromSeedBase58($(fieldMap.rootPriv).value, $(fieldMap.rootPub).value);
|
||||
const device = await pairFromSeedBase58($(fieldMap.devPriv).value, $(fieldMap.devPub).value);
|
||||
const blockchainPriv = String($(fieldMap.bchPriv).value || '').trim();
|
||||
@@ -134,9 +122,6 @@ export async function buildKeyBundleFromForm(fieldMap, options = {}) {
|
||||
}
|
||||
return {
|
||||
keyBundle: {
|
||||
recoveryPair: recovery
|
||||
? { publicKeyB64: recovery.publicKeyB64, privatePkcs8B64: recovery.privatePkcs8B64 }
|
||||
: null,
|
||||
rootPair: { publicKeyB64: root.publicKeyB64, privatePkcs8B64: root.privatePkcs8B64 },
|
||||
blockchainPair: blockchain
|
||||
? { publicKeyB64: blockchain.publicKeyB64, privatePkcs8B64: blockchain.privatePkcs8B64 }
|
||||
@@ -144,8 +129,6 @@ export async function buildKeyBundleFromForm(fieldMap, options = {}) {
|
||||
clientPair: { publicKeyB64: device.publicKeyB64, privatePkcs8B64: device.privatePkcs8B64 },
|
||||
},
|
||||
normalized: {
|
||||
recoveryPubB58: recovery?.publicKeyB58 || '',
|
||||
recoveryPrivB58: recovery?.privateSeedB58 || '',
|
||||
rootPubB58: root.publicKeyB58,
|
||||
rootPrivB58: root.privateSeedB58,
|
||||
bchPubB58: blockchain?.publicKeyB58 || '',
|
||||
@@ -165,20 +148,14 @@ export async function deriveKeyBundleFromPassword({ login, password, onProgress
|
||||
login: cleanLogin,
|
||||
onProgress,
|
||||
});
|
||||
const [recoveryPair, rootPair, blockchainPair, clientPair] = await Promise.all([
|
||||
deriveEd25519FromMasterSecret(masterSecret32, 'recovery.key'),
|
||||
const [rootPair, blockchainPair, clientPair] = await Promise.all([
|
||||
deriveEd25519FromMasterSecret(masterSecret32, 'root.key'),
|
||||
deriveEd25519FromMasterSecret(masterSecret32, 'blockchain.key'),
|
||||
deriveEd25519FromMasterSecret(masterSecret32, 'client.key'),
|
||||
]);
|
||||
return {
|
||||
masterSecret32,
|
||||
keyBundle: {
|
||||
recoveryPair,
|
||||
rootPair,
|
||||
blockchainPair,
|
||||
clientPair,
|
||||
},
|
||||
keyBundle: { rootPair, blockchainPair, clientPair },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -186,10 +163,6 @@ export function fillKeyFields(fieldMap, keyBundle, masterSecret32) {
|
||||
if (masterSecret32) {
|
||||
$(fieldMap.masterSecret).value = bytesToBase58(masterSecret32);
|
||||
}
|
||||
if (fieldMap.recoveryPub && fieldMap.recoveryPriv && keyBundle.recoveryPair) {
|
||||
$(fieldMap.recoveryPub).value = bytesToBase58(base64ToBytes(keyBundle.recoveryPair.publicKeyB64));
|
||||
$(fieldMap.recoveryPriv).value = bytesToBase58(base64ToBytes(keyBundle.recoveryPair.privatePkcs8B64).slice(-32));
|
||||
}
|
||||
$(fieldMap.rootPub).value = bytesToBase58(base64ToBytes(keyBundle.rootPair.publicKeyB64));
|
||||
$(fieldMap.rootPriv).value = bytesToBase58(base64ToBytes(keyBundle.rootPair.privatePkcs8B64).slice(-32));
|
||||
$(fieldMap.bchPub).value = bytesToBase58(base64ToBytes(keyBundle.blockchainPair.publicKeyB64));
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
formatBigInt,
|
||||
formatTimestamp,
|
||||
openDevnetTopup,
|
||||
parseLoginList,
|
||||
publicKeyBytesToBase58,
|
||||
refreshDeviceBalance,
|
||||
setGenMessage,
|
||||
@@ -26,8 +25,6 @@ import { defaultServerAddress, defaultServerLogin, defaultSolanaEndpoint } from
|
||||
|
||||
const fieldMap = {
|
||||
masterSecret: 'masterSecret',
|
||||
recoveryPub: 'recoveryPub',
|
||||
recoveryPriv: 'recoveryPriv',
|
||||
rootPub: 'rootPub',
|
||||
rootPriv: 'rootPriv',
|
||||
bchPub: 'bchPub',
|
||||
@@ -42,7 +39,6 @@ let currentPda = null;
|
||||
|
||||
function resetExpectedKeysUi() {
|
||||
$('expectedKeysBox').style.display = 'none';
|
||||
setText('expectedRecoveryPub', '');
|
||||
setText('expectedRootPub', '');
|
||||
setText('expectedBchPub', '');
|
||||
setText('expectedDevPub', '');
|
||||
@@ -52,7 +48,6 @@ function resetExpectedKeysUi() {
|
||||
|
||||
function renderExpectedKeys(parsed) {
|
||||
$('expectedKeysBox').style.display = 'block';
|
||||
setText('expectedRecoveryPub', publicKeyBytesToBase58(parsed.recoveryKey));
|
||||
setText('expectedRootPub', publicKeyBytesToBase58(parsed.rootKey));
|
||||
setText('expectedBchPub', publicKeyBytesToBase58(parsed.blockchain.blockchainPublicKey));
|
||||
setText('expectedDevPub', publicKeyBytesToBase58(parsed.clientKey));
|
||||
@@ -64,7 +59,6 @@ function compareCurrentFormKeysWithPda() {
|
||||
const blockchainActual = String($('bchPub').value || '').trim();
|
||||
return {
|
||||
resultMap: {
|
||||
recovery: compareExpectedPublicKeys(publicKeyBytesToBase58(currentPda.recoveryKey), $('recoveryPub').value),
|
||||
root: compareExpectedPublicKeys(publicKeyBytesToBase58(currentPda.rootKey), $('rootPub').value),
|
||||
blockchain: blockchainActual
|
||||
? compareExpectedPublicKeys(publicKeyBytesToBase58(currentPda.blockchain.blockchainPublicKey), blockchainActual)
|
||||
@@ -178,17 +172,15 @@ $('btnLoad').addEventListener('click', async () => {
|
||||
$('iCreated').textContent = formatTimestamp(parsed.createdAtMs);
|
||||
$('iUpdated').textContent = formatTimestamp(parsed.updatedAtMs);
|
||||
$('iSrvAddr').textContent = parsed.serverAddress || '—';
|
||||
$('iSync').textContent = parsed.syncServers.length ? parsed.syncServers.join(', ') : '—';
|
||||
$('iBch').textContent = parsed.blockchain.blockchainName;
|
||||
$('iLimit').textContent = formatBigInt(parsed.blockchain.paidLimitBytes);
|
||||
|
||||
$('password').value = '';
|
||||
$('serverAddress').value = parsed.serverAddress || '';
|
||||
$('syncServers').value = parsed.syncServers.join('\n');
|
||||
$('pdaInfo').style.display = 'block';
|
||||
$('updateForm').style.display = 'block';
|
||||
renderExpectedKeys(parsed);
|
||||
setStatus($('status'), 'PDA загружена. Можно менять адрес или sync_servers.', 'success');
|
||||
setStatus($('status'), 'PDA загружена. Можно менять адрес сервера.', 'success');
|
||||
} catch (error) {
|
||||
setStatus($('status'), error?.message || String(error), 'error');
|
||||
} finally {
|
||||
@@ -227,7 +219,6 @@ $('btnUpdate').addEventListener('click', async () => {
|
||||
serverAddress,
|
||||
addressFormatType: currentPda.addressFormatType ?? 1,
|
||||
addressFormatVersion: currentPda.addressFormatVersion ?? 0,
|
||||
syncServers: parseLoginList($('syncServers').value),
|
||||
solanaEndpoint: endpoint,
|
||||
});
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
</div>
|
||||
|
||||
<h1>Обновление PDA сервера</h1>
|
||||
<p class="subtitle">Меняет адрес сервера или список серверов синхронизации</p>
|
||||
<p class="subtitle">Меняет адрес SHiNE-сервера и другие поля PDA 1.2</p>
|
||||
|
||||
<div class="card">
|
||||
<h2>Параметры Solana</h2>
|
||||
@@ -76,7 +76,6 @@
|
||||
<div class="pda-row"><span class="pda-key">Создан</span><span class="pda-value" id="iCreated"></span></div>
|
||||
<div class="pda-row"><span class="pda-key">Обновлён</span><span class="pda-value" id="iUpdated"></span></div>
|
||||
<div class="pda-row"><span class="pda-key">Адрес сервера</span><span class="pda-value" id="iSrvAddr"></span></div>
|
||||
<div class="pda-row"><span class="pda-key">sync_servers</span><span class="pda-value" id="iSync"></span></div>
|
||||
<div class="pda-row"><span class="pda-key">Blockchain</span><span class="pda-value" id="iBch"></span></div>
|
||||
<div class="pda-row"><span class="pda-key">Paid limit</span><span class="pda-value" id="iLimit"></span></div>
|
||||
</div>
|
||||
@@ -89,10 +88,6 @@
|
||||
<label>Арес сервера (URL) например shineup.me</label>
|
||||
<input type="text" id="serverAddress" placeholder="Адрес сервера" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>Логины серверов c которыми будет синхронизировать записи в блокчейн этот сервер (Например shineupme)</label>
|
||||
<textarea id="syncServers" placeholder="По одному логину на строку (можно оставить пустым)"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
@@ -120,12 +115,7 @@
|
||||
<div class="sec-lbl">Ключевые пары (base58)</div>
|
||||
|
||||
<div class="kp-block">
|
||||
<div class="kp-title">Recovery Key — восстановление аккаунта</div>
|
||||
<div class="kp-row"><span class="kp-lbl">Публичный</span><input class="kp-inp" type="text" id="recoveryPub" placeholder="base58, ~44 символа" /></div>
|
||||
<div class="kp-row"><span class="kp-lbl">Приватный</span><input class="kp-inp" type="text" id="recoveryPriv" placeholder="seed base58, ~44 символа" /></div>
|
||||
</div>
|
||||
<div class="kp-block">
|
||||
<div class="kp-title">Root Key — подпись PDA-записи</div>
|
||||
<div class="kp-title">Root Key — холодное восстановление / полный контроль PDA</div>
|
||||
<div class="kp-row"><span class="kp-lbl">Публичный</span><input class="kp-inp" type="text" id="rootPub" placeholder="base58, ~44 символа" /></div>
|
||||
<div class="kp-row"><span class="kp-lbl">Приватный</span><input class="kp-inp" type="text" id="rootPriv" placeholder="seed base58, ~44 символа" /></div>
|
||||
</div>
|
||||
@@ -150,10 +140,6 @@
|
||||
|
||||
<div class="expected-card" id="expectedKeysBox" style="display:none">
|
||||
<div class="expected-ttl">Какие ключи ожидаются по уже загруженной PDA</div>
|
||||
<div class="expected-row">
|
||||
<div class="expected-lbl">Ожидаемый recovery public key</div>
|
||||
<div class="expected-val" id="expectedRecoveryPub"></div>
|
||||
</div>
|
||||
<div class="expected-row">
|
||||
<div class="expected-lbl">Ожидаемый root public key</div>
|
||||
<div class="expected-val" id="expectedRootPub"></div>
|
||||
|
||||
@@ -1032,8 +1032,8 @@ select:focus {
|
||||
/* Viewer v3 */
|
||||
:root{--v3-bg:#f5f5f3;--v3-panel:#fff;--v3-text:#171717;--v3-sub:#747474;--v3-border:#e7e7e3;--v3-hover:#f0f0ed;--v3-shadow:0 18px 60px rgba(0,0,0,.08)}
|
||||
html[data-theme="dark"]{color-scheme:dark;--v3-bg:#101110;--v3-panel:#181918;--v3-text:#f3f3ef;--v3-sub:#9c9d98;--v3-border:#292a28;--v3-hover:#222320;--v3-shadow:0 18px 60px rgba(0,0,0,.28)}
|
||||
html,body{background:var(--v3-bg)!important;color:var(--v3-text)!important}.viewer-app{min-height:100vh;background:var(--v3-bg);padding-bottom:54px}.viewer-toolbar{position:sticky;top:0;z-index:30;height:64px;padding:0 max(18px,calc((100vw - 980px)/2));display:flex;align-items:center;gap:10px;background:color-mix(in srgb,var(--v3-bg) 88%,transparent);backdrop-filter:blur(18px);border-bottom:1px solid var(--v3-border);overflow:visible!important}
|
||||
.v3-brand{font-weight:800;letter-spacing:-.03em;margin-right:auto}.v3-tabs{display:flex;padding:4px;background:var(--v3-hover);border-radius:12px}.v3-tab{border:0;background:transparent;color:var(--v3-sub);padding:8px 13px;border-radius:9px;font-weight:700;cursor:pointer}.v3-tab.is-active{background:var(--v3-panel);color:var(--v3-text);box-shadow:0 1px 5px rgba(0,0,0,.08)}.toolbar-icon{background:var(--v3-panel)!important;color:var(--v3-text)!important;border:1px solid var(--v3-border)!important;border-radius:11px!important;width:40px;height:40px}.v3-menu{position:absolute;right:max(18px,calc((100vw - 980px)/2));top:58px;width:min(340px,calc(100vw - 28px));padding:14px;background:var(--v3-panel);border:1px solid var(--v3-border);border-radius:16px;box-shadow:var(--v3-shadow);z-index:1000}.v3-menu label{color:var(--v3-text)}.v3-menu input{background:var(--v3-bg);color:var(--v3-text);border-color:var(--v3-border)}.v3-switch{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:8px 2px 14px}.viewer-main{width:min(860px,calc(100% - 28px));margin:22px auto!important}.mobile-card,.message-bubble,.channel-row{background:var(--v3-panel)!important;color:var(--v3-text)!important;border-color:var(--v3-border)!important;box-shadow:none!important}.message-bubble__meta,.channel-row__meta,.channel-row__preview,.channel-head p{color:var(--v3-sub)!important}.thread-toggle{border:0;background:transparent;color:var(--v3-sub);padding:8px 0 2px;font-weight:700;cursor:pointer}.thread-toggle:hover{color:var(--v3-text)}.message-thread__replies{border-left:1px solid var(--v3-border)!important;margin-left:18px!important;padding-left:16px!important}.v3-status{position:fixed;z-index:40;left:0;right:0;bottom:0;height:38px;display:flex;align-items:center;padding:0 max(18px,calc((100vw - 980px)/2));background:var(--v3-panel);border-top:1px solid var(--v3-border);font-size:12px;color:var(--v3-sub);cursor:pointer}.v3-status-detail{position:fixed;z-index:39;left:50%;bottom:38px;transform:translateX(-50%);width:min(760px,calc(100% - 28px));max-height:45vh;overflow:auto;background:var(--v3-panel);border:1px solid var(--v3-border);border-bottom:0;border-radius:16px 16px 0 0;padding:16px;box-shadow:var(--v3-shadow);font:12px/1.55 var(--mono);white-space:pre-wrap}.v3-start{max-width:520px;margin:12vh auto;padding:28px;background:var(--v3-panel);border:1px solid var(--v3-border);border-radius:24px;box-shadow:var(--v3-shadow)}.v3-start h1{margin:0 0 8px;font-size:32px;letter-spacing:-.04em}.v3-start p{color:var(--v3-sub);line-height:1.5}.v3-start-grid{display:grid;gap:12px}.v3-start input{background:var(--v3-bg);color:var(--v3-text);border-color:var(--v3-border)}.v3-open{height:48px;border:0;border-radius:12px;background:var(--v3-text);color:var(--v3-bg);font-weight:800;cursor:pointer}.v3-blocks{display:grid;gap:8px}.v3-block{background:var(--v3-panel);border:1px solid var(--v3-border);border-radius:14px;padding:12px 14px}.v3-block summary{cursor:pointer;font-weight:750}.v3-block pre{overflow:auto;color:var(--v3-sub);white-space:pre-wrap}.message-inline-media{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin-top:10px}.message-inline-media:has(>a:only-child){grid-template-columns:minmax(0,1fr)}.message-inline-media a{display:block;overflow:hidden;border-radius:12px;border:1px solid var(--v3-border);background:var(--v3-bg)}.message-inline-media img{display:block;width:100%;max-height:520px;object-fit:contain;background:var(--v3-bg)}@media(max-width:520px){.message-inline-media{grid-template-columns:1fr}.message-inline-media img{max-height:70vh}}
|
||||
html,body{background:var(--v3-bg)!important;color:var(--v3-text)!important}.viewer-app{min-height:100vh;background:var(--v3-bg);padding-bottom:54px}.viewer-toolbar{position:sticky;top:0;z-index:30;height:64px;padding:0 max(18px,calc((100vw - 980px)/2));display:flex;align-items:center;gap:10px;background:color-mix(in srgb,var(--v3-bg) 88%,transparent);backdrop-filter:blur(18px);border-bottom:1px solid var(--v3-border)}
|
||||
.v3-brand{font-weight:800;letter-spacing:-.03em;margin-right:auto}.v3-tabs{display:flex;padding:4px;background:var(--v3-hover);border-radius:12px}.v3-tab{border:0;background:transparent;color:var(--v3-sub);padding:8px 13px;border-radius:9px;font-weight:700;cursor:pointer}.v3-tab.is-active{background:var(--v3-panel);color:var(--v3-text);box-shadow:0 1px 5px rgba(0,0,0,.08)}.toolbar-icon{background:var(--v3-panel)!important;color:var(--v3-text)!important;border:1px solid var(--v3-border)!important;border-radius:11px!important;width:40px;height:40px}.v3-menu{position:absolute;right:max(18px,calc((100vw - 980px)/2));top:58px;width:min(340px,calc(100vw - 28px));padding:14px;background:var(--v3-panel);border:1px solid var(--v3-border);border-radius:16px;box-shadow:var(--v3-shadow);z-index:50}.v3-menu label{color:var(--v3-text)}.v3-menu input{background:var(--v3-bg);color:var(--v3-text);border-color:var(--v3-border)}.v3-switch{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:8px 2px 14px}.viewer-main{width:min(860px,calc(100% - 28px));margin:22px auto!important}.mobile-card,.message-bubble,.channel-row{background:var(--v3-panel)!important;color:var(--v3-text)!important;border-color:var(--v3-border)!important;box-shadow:none!important}.message-bubble__meta,.channel-row__meta,.channel-row__preview,.channel-head p{color:var(--v3-sub)!important}.thread-toggle{border:0;background:transparent;color:var(--v3-sub);padding:8px 0 2px;font-weight:700;cursor:pointer}.thread-toggle:hover{color:var(--v3-text)}.message-thread__replies{border-left:1px solid var(--v3-border)!important;margin-left:18px!important;padding-left:16px!important}.v3-status{position:fixed;z-index:40;left:0;right:0;bottom:0;height:38px;display:flex;align-items:center;padding:0 max(18px,calc((100vw - 980px)/2));background:var(--v3-panel);border-top:1px solid var(--v3-border);font-size:12px;color:var(--v3-sub);cursor:pointer}.v3-status-detail{position:fixed;z-index:39;left:50%;bottom:38px;transform:translateX(-50%);width:min(760px,calc(100% - 28px));max-height:45vh;overflow:auto;background:var(--v3-panel);border:1px solid var(--v3-border);border-bottom:0;border-radius:16px 16px 0 0;padding:16px;box-shadow:var(--v3-shadow);font:12px/1.55 var(--mono);white-space:pre-wrap}.v3-start{max-width:520px;margin:12vh auto;padding:28px;background:var(--v3-panel);border:1px solid var(--v3-border);border-radius:24px;box-shadow:var(--v3-shadow)}.v3-start h1{margin:0 0 8px;font-size:32px;letter-spacing:-.04em}.v3-start p{color:var(--v3-sub);line-height:1.5}.v3-start-grid{display:grid;gap:12px}.v3-start input{background:var(--v3-bg);color:var(--v3-text);border-color:var(--v3-border)}.v3-open{height:48px;border:0;border-radius:12px;background:var(--v3-text);color:var(--v3-bg);font-weight:800;cursor:pointer}.v3-blocks{display:grid;gap:8px}.v3-block{background:var(--v3-panel);border:1px solid var(--v3-border);border-radius:14px;padding:12px 14px}.v3-block summary{cursor:pointer;font-weight:750}.v3-block pre{overflow:auto;color:var(--v3-sub);white-space:pre-wrap}.message-inline-media{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin-top:10px}.message-inline-media:has(>a:only-child){grid-template-columns:minmax(0,1fr)}.message-inline-media a{display:block;overflow:hidden;border-radius:12px;border:1px solid var(--v3-border);background:var(--v3-bg)}.message-inline-media img{display:block;width:100%;max-height:520px;object-fit:contain;background:var(--v3-bg)}@media(max-width:520px){.message-inline-media{grid-template-columns:1fr}.message-inline-media img{max-height:70vh}}
|
||||
.verification-view{position:fixed;inset:0;z-index:80;background:var(--v3-bg);color:var(--v3-text);overflow:auto;padding:0 0 70px}
|
||||
.verification-head{position:sticky;top:0;z-index:2;display:flex;align-items:center;gap:12px;padding:14px max(16px,calc((100vw - 900px)/2));background:var(--v3-panel);border-bottom:1px solid var(--v3-border)}
|
||||
.verification-head h2{margin:0;font-size:18px}.verification-body{width:min(900px,calc(100% - 28px));margin:20px auto;display:grid;gap:14px}
|
||||
@@ -1553,7 +1553,7 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
};
|
||||
}
|
||||
|
||||
function parseShineUserPda(dataBytes) {
|
||||
function parseShineUserPdaLegacy(dataBytes) {
|
||||
const bytes = dataBytes instanceof Uint8Array ? dataBytes : new Uint8Array(dataBytes || []);
|
||||
const reader = makeReader(bytes);
|
||||
const magic = new TextDecoder().decode(reader.readBytes(5));
|
||||
@@ -1717,6 +1717,138 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
};
|
||||
}
|
||||
|
||||
function parseShineUserPdaV12(dataBytes) {
|
||||
const bytes = dataBytes instanceof Uint8Array ? dataBytes : new Uint8Array(dataBytes || []);
|
||||
const reader = makeReader(bytes);
|
||||
const magic = new TextDecoder().decode(reader.readBytes(5));
|
||||
if (magic !== MAGIC) throw new Error('Некорректный формат PDA: magic не совпадает');
|
||||
const formatMajor = reader.readU8();
|
||||
const formatMinor = reader.readU8();
|
||||
const recordLen = reader.readU16();
|
||||
if (formatMajor !== 1 || formatMinor !== 2 || recordLen < 73 || recordLen > bytes.length) {
|
||||
throw new Error('Некорректный формат PDA 1.2');
|
||||
}
|
||||
const createdAtMs = reader.readU64();
|
||||
const updatedAtMs = reader.readU64();
|
||||
const recordNumber = reader.readU32();
|
||||
const prevRecordHash = reader.readBytes(32);
|
||||
const login = reader.readStrU8();
|
||||
const blocksCount = reader.readU8();
|
||||
|
||||
let rootKey = null;
|
||||
let clientKey = null;
|
||||
let forks = null;
|
||||
let serverProfile = null;
|
||||
let accessServers = [];
|
||||
|
||||
for (let index = 0; index < blocksCount; index += 1) {
|
||||
const blockType = reader.readU8();
|
||||
const blockVersion = reader.readU8();
|
||||
if (blockType === BLOCK_TYPE_ROOT_KEY) {
|
||||
if (blockVersion !== 0) throw new Error('Неизвестная версия RootKeyBlock');
|
||||
rootKey = reader.readBytes(32);
|
||||
continue;
|
||||
}
|
||||
if (blockType === BLOCK_TYPE_CLIENT_KEY) {
|
||||
if (blockVersion !== 0) throw new Error('Неизвестная версия ClientKeyBlock');
|
||||
clientKey = reader.readBytes(32);
|
||||
continue;
|
||||
}
|
||||
|
||||
const payloadLen = reader.readU16();
|
||||
const payload = makeReader(reader.readBytes(payloadLen));
|
||||
if (blockVersion !== 0) continue;
|
||||
|
||||
if (blockType === BLOCK_TYPE_BLOCKCHAIN_REGISTRY) {
|
||||
const count = payload.readU16();
|
||||
if (count < 1) throw new Error('BlockchainRegistry 1.2 пуст');
|
||||
forks = [];
|
||||
for (let j = 0; j < count; j += 1) {
|
||||
forks.push({
|
||||
blockchainKey: payload.readBytes(32),
|
||||
paidLimitBytes: BigInt(payload.readU32()),
|
||||
});
|
||||
}
|
||||
} else if (blockType === BLOCK_TYPE_SERVER_PROFILE) {
|
||||
const count = payload.readU8();
|
||||
const addresses = [];
|
||||
for (let j = 0; j < count; j += 1) {
|
||||
addresses.push({
|
||||
addressFormatType: payload.readU8(),
|
||||
addressFormatVersion: payload.readU8(),
|
||||
address: payload.readStrU8(),
|
||||
});
|
||||
}
|
||||
const first = addresses[0] || null;
|
||||
serverProfile = first ? {
|
||||
blockVersion,
|
||||
addressFormatType: first.addressFormatType,
|
||||
addressFormatVersion: first.addressFormatVersion,
|
||||
serverAddress: first.address,
|
||||
addresses,
|
||||
syncServers: [],
|
||||
} : null;
|
||||
} else if (blockType === BLOCK_TYPE_ACCESS_SERVERS) {
|
||||
const count = payload.readU8();
|
||||
if (count > 1) throw new Error('PDA 1.2 допускает максимум один access server');
|
||||
accessServers = [];
|
||||
for (let j = 0; j < count; j += 1) accessServers.push(payload.readStrU8());
|
||||
}
|
||||
}
|
||||
|
||||
if (!rootKey || !clientKey || !forks || forks.length < 1) {
|
||||
throw new Error('В PDA 1.2 отсутствуют обязательные блоки shine_users');
|
||||
}
|
||||
const active = forks[forks.length - 1];
|
||||
const blockchain = {
|
||||
blockchainType: 1,
|
||||
blockchainName: `${String(login).toLowerCase()}-${String(forks.length).padStart(3, '0')}`,
|
||||
blockchainPublicKey: active.blockchainKey,
|
||||
paidLimitBytes: active.paidLimitBytes,
|
||||
usedBytes: 0n,
|
||||
lastBlockNumber: 0,
|
||||
lastBlockHash: new Uint8Array(32),
|
||||
lastBlockSignature: new Uint8Array(64),
|
||||
arweaveTxId: '',
|
||||
};
|
||||
const signature = bytes.slice(recordLen - 64, recordLen);
|
||||
return {
|
||||
formatMajor,
|
||||
formatMinor,
|
||||
recordLen,
|
||||
createdAtMs,
|
||||
updatedAtMs,
|
||||
recordNumber,
|
||||
prevRecordHash,
|
||||
login,
|
||||
blocksCount,
|
||||
recoveryKey: null,
|
||||
rootKey,
|
||||
clientKey,
|
||||
forks,
|
||||
blockchain,
|
||||
serverProfile,
|
||||
accessServers,
|
||||
sessionsMode: DEFAULT_SESSIONS_MODE,
|
||||
sessions: [],
|
||||
trustedCount: 0,
|
||||
signature,
|
||||
};
|
||||
}
|
||||
|
||||
function parseShineUserPda(dataBytes) {
|
||||
const bytes = dataBytes instanceof Uint8Array ? dataBytes : new Uint8Array(dataBytes || []);
|
||||
if (bytes.length < 9) throw new Error('Повреждённый формат PDA');
|
||||
const magic = new TextDecoder().decode(bytes.slice(0, 5));
|
||||
if (magic !== MAGIC) throw new Error('Некорректный формат PDA: magic не совпадает');
|
||||
const formatMajor = bytes[5];
|
||||
const formatMinor = bytes[6];
|
||||
if (formatMajor === 1 && formatMinor === 2) return parseShineUserPdaV12(bytes);
|
||||
if (formatMajor === 1 && formatMinor === 0) return parseShineUserPdaLegacy(bytes);
|
||||
throw new Error(`Неподдерживаемый формат PDA ${formatMajor}.${formatMinor}`);
|
||||
}
|
||||
|
||||
|
||||
async function digestSha256(bytes) {
|
||||
const input = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes || []);
|
||||
const hash = await crypto.subtle.digest('SHA-256', input);
|
||||
@@ -2288,7 +2420,7 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
async function* queryArweaveChannelPages(gatewayBaseUrl, blockchainKey, channelName) {
|
||||
const gateway = baseUrl(gatewayBaseUrl);
|
||||
const ownerAddress = await arweaveOwnerAddressFromBlockchainKey(blockchainKey);
|
||||
// Author-first and transport-agnostic (Turbo/direct Arweave): discover user DataItems by owner + App=test5590; channel/c_test5590 is only a local view filter.
|
||||
// Author-first: channel is a local view filter, never an Arweave query filter.
|
||||
const tags = [{ name: 'App', values: [SHINE_ARWEAVE_APP_TAG] }];
|
||||
const query = `query($owners:[String!],$tags:[TagFilter!],$after:String){transactions(first:100,after:$after,owners:$owners,tags:$tags,sort:HEIGHT_DESC){pageInfo{hasNextPage}edges{cursor node{id owner{address key} block{height timestamp} bundledIn{id} tags{name value}}}}}`;
|
||||
let after = null;
|
||||
@@ -2476,7 +2608,7 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
signatureHex: bytesToHex(parsed.signature),
|
||||
},
|
||||
keys: {
|
||||
recoveryKeyBase58: bytesToBase58(parsed.recoveryKey),
|
||||
recoveryKeyBase58: parsed.recoveryKey ? bytesToBase58(parsed.recoveryKey) : '',
|
||||
rootKeyBase58: bytesToBase58(parsed.rootKey),
|
||||
clientKeyBase58: bytesToBase58(parsed.clientKey),
|
||||
},
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* Feature-specific стили находятся в styles/features/* и network-graph.css.
|
||||
*/
|
||||
.app-shell {
|
||||
width: min(var(--app-viewport-width, 100vw), var(--shell-content-width, 430px));
|
||||
width: min(var(--app-viewport-width, 100vw), var(--shell-content-width, 640px));
|
||||
height: var(--app-viewport-height, 100vh);
|
||||
position: fixed;
|
||||
top: var(--app-viewport-offset-top, 0px);
|
||||
@@ -18,13 +18,17 @@
|
||||
--z-shell-fade: 10;
|
||||
--z-shell-chrome: 20;
|
||||
--z-shell-status: 30;
|
||||
background: transparent;
|
||||
background: var(--background);
|
||||
border-left: 1px solid transparent;
|
||||
border-right: 1px solid transparent;
|
||||
box-shadow: none;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
@media (min-width: 700px) {
|
||||
.app-shell { border-color: var(--border-subtle); }
|
||||
}
|
||||
|
||||
.screen-content {
|
||||
position: absolute;
|
||||
top: calc(var(--call-minimized-bar-height, 0px) + var(--topbar-height, 0px));
|
||||
@@ -65,10 +69,12 @@
|
||||
top: var(--call-minimized-bar-height, 0px);
|
||||
left: 0;
|
||||
right: 0;
|
||||
padding: 0 12px;
|
||||
padding: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.topbar-slot > .topbar { padding-inline: 12px; }
|
||||
|
||||
.topbar-slot > * {
|
||||
pointer-events: auto;
|
||||
}
|
||||
@@ -104,38 +110,23 @@
|
||||
right: 12px;
|
||||
bottom: calc(96px + env(safe-area-inset-bottom));
|
||||
z-index: var(--z-shell-status);
|
||||
border-radius: 11px;
|
||||
border: 1px solid rgba(133, 156, 201, 0.3);
|
||||
background: rgba(10, 19, 37, 0.86);
|
||||
color: #c6d6f7;
|
||||
border-radius: 12px;
|
||||
border: 1px solid var(--border-subtle);
|
||||
background: var(--surface);
|
||||
color: var(--text-primary);
|
||||
box-shadow: var(--shadow);
|
||||
font-size: 12px;
|
||||
line-height: 1.2;
|
||||
text-align: center;
|
||||
padding: 7px 10px;
|
||||
padding: 8px 12px;
|
||||
pointer-events: auto;
|
||||
cursor: pointer;
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.connection-retry-banner.is-connected {
|
||||
border-color: rgba(124, 235, 171, 0.4);
|
||||
color: #d8ffe9;
|
||||
}
|
||||
|
||||
.connection-retry-banner.is-connecting {
|
||||
border-color: transparent;
|
||||
color: #ffe8bb;
|
||||
}
|
||||
|
||||
.connection-retry-banner.is-disconnected {
|
||||
border-color: rgba(228, 127, 145, 0.44);
|
||||
color: #ffdce3;
|
||||
}
|
||||
|
||||
.connection-retry-banner.is-updating {
|
||||
border-color: rgba(144, 201, 255, 0.44);
|
||||
color: #d9eeff;
|
||||
}
|
||||
.connection-retry-banner.is-connected { border-color: var(--success); }
|
||||
.connection-retry-banner.is-connecting { color: var(--text-secondary); }
|
||||
.connection-retry-banner.is-disconnected { border-color: var(--danger); color: var(--danger); }
|
||||
.connection-retry-banner.is-updating { border-color: var(--accent); }
|
||||
|
||||
/* Обычный scroll-container физически продолжается под прозрачным TopBar. */
|
||||
.app-shell--content-under-topbar:not(.app-shell--scroll-nested):not(.app-shell--scroll-locked) .screen-content:not(.no-app-chrome) {
|
||||
@@ -149,10 +140,10 @@
|
||||
top: var(--call-minimized-bar-height, 0px);
|
||||
left: 0;
|
||||
right: 0;
|
||||
width: min(100vw, 430px);
|
||||
width: min(100vw, var(--shell-content-width, 640px));
|
||||
margin: 0 auto;
|
||||
transform: none;
|
||||
padding: 0 12px;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.app-shell--scroll-nested .screen-content {
|
||||
@@ -201,13 +192,13 @@
|
||||
height: calc(var(--topbar-height, 64px) + 48px);
|
||||
background: linear-gradient(
|
||||
to bottom,
|
||||
rgba(5, 7, 10, 1) 0%,
|
||||
rgba(5, 7, 10, 0.98) 16%,
|
||||
rgba(5, 7, 10, 0.88) 32%,
|
||||
rgba(5, 7, 10, 0.66) 52%,
|
||||
rgba(5, 7, 10, 0.38) 70%,
|
||||
rgba(5, 7, 10, 0.15) 84%,
|
||||
rgba(5, 7, 10, 0) 100%
|
||||
color-mix(in srgb, var(--background) 100%, transparent) 0%,
|
||||
color-mix(in srgb, var(--background) 98%, transparent) 16%,
|
||||
color-mix(in srgb, var(--background) 88%, transparent) 32%,
|
||||
color-mix(in srgb, var(--background) 66%, transparent) 52%,
|
||||
color-mix(in srgb, var(--background) 38%, transparent) 70%,
|
||||
color-mix(in srgb, var(--background) 15%, transparent) 84%,
|
||||
color-mix(in srgb, var(--background) 0%, transparent) 100%
|
||||
);
|
||||
}
|
||||
|
||||
@@ -217,13 +208,13 @@
|
||||
height: calc(var(--composer-height, 0px) + 52px);
|
||||
background: linear-gradient(
|
||||
to bottom,
|
||||
rgba(5, 7, 10, 0) 0%,
|
||||
rgba(5, 7, 10, 0.14) 18%,
|
||||
rgba(5, 7, 10, 0.38) 38%,
|
||||
rgba(5, 7, 10, 0.66) 58%,
|
||||
rgba(5, 7, 10, 0.88) 76%,
|
||||
rgba(5, 7, 10, 0.98) 90%,
|
||||
rgba(5, 7, 10, 1) 100%
|
||||
color-mix(in srgb, var(--background) 0%, transparent) 0%,
|
||||
color-mix(in srgb, var(--background) 14%, transparent) 18%,
|
||||
color-mix(in srgb, var(--background) 38%, transparent) 38%,
|
||||
color-mix(in srgb, var(--background) 66%, transparent) 58%,
|
||||
color-mix(in srgb, var(--background) 88%, transparent) 76%,
|
||||
color-mix(in srgb, var(--background) 98%, transparent) 90%,
|
||||
color-mix(in srgb, var(--background) 100%, transparent) 100%
|
||||
);
|
||||
}
|
||||
|
||||
@@ -232,15 +223,15 @@
|
||||
height: var(--topbar-height, 64px);
|
||||
background: linear-gradient(
|
||||
to bottom,
|
||||
rgba(5, 7, 10, 1) 0%,
|
||||
rgba(5, 7, 10, 1) 32%,
|
||||
rgba(5, 7, 10, 0.94) 38%,
|
||||
rgba(5, 7, 10, 0.72) 46%,
|
||||
rgba(5, 7, 10, 0.46) 54%,
|
||||
rgba(5, 7, 10, 0.22) 61%,
|
||||
rgba(5, 7, 10, 0.08) 65%,
|
||||
rgba(5, 7, 10, 0) 68%,
|
||||
rgba(5, 7, 10, 0) 100%
|
||||
color-mix(in srgb, var(--background) 100%, transparent) 0%,
|
||||
color-mix(in srgb, var(--background) 100%, transparent) 32%,
|
||||
color-mix(in srgb, var(--background) 94%, transparent) 38%,
|
||||
color-mix(in srgb, var(--background) 72%, transparent) 46%,
|
||||
color-mix(in srgb, var(--background) 46%, transparent) 54%,
|
||||
color-mix(in srgb, var(--background) 22%, transparent) 61%,
|
||||
color-mix(in srgb, var(--background) 8%, transparent) 65%,
|
||||
color-mix(in srgb, var(--background) 0%, transparent) 68%,
|
||||
color-mix(in srgb, var(--background) 0%, transparent) 100%
|
||||
);
|
||||
}
|
||||
|
||||
@@ -250,15 +241,15 @@
|
||||
height: var(--toolbar-height, 78px);
|
||||
background: linear-gradient(
|
||||
to bottom,
|
||||
rgba(5, 7, 10, 0) 0%,
|
||||
rgba(5, 7, 10, 0) 32%,
|
||||
rgba(5, 7, 10, 0.08) 35%,
|
||||
rgba(5, 7, 10, 0.22) 39%,
|
||||
rgba(5, 7, 10, 0.46) 46%,
|
||||
rgba(5, 7, 10, 0.72) 54%,
|
||||
rgba(5, 7, 10, 0.94) 62%,
|
||||
rgba(5, 7, 10, 1) 68%,
|
||||
rgba(5, 7, 10, 1) 100%
|
||||
color-mix(in srgb, var(--background) 0%, transparent) 0%,
|
||||
color-mix(in srgb, var(--background) 0%, transparent) 32%,
|
||||
color-mix(in srgb, var(--background) 8%, transparent) 35%,
|
||||
color-mix(in srgb, var(--background) 22%, transparent) 39%,
|
||||
color-mix(in srgb, var(--background) 46%, transparent) 46%,
|
||||
color-mix(in srgb, var(--background) 72%, transparent) 54%,
|
||||
color-mix(in srgb, var(--background) 94%, transparent) 62%,
|
||||
color-mix(in srgb, var(--background) 100%, transparent) 68%,
|
||||
color-mix(in srgb, var(--background) 100%, transparent) 100%
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -7,49 +7,73 @@
|
||||
: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; }
|
||||
/* Explicit filled-action variant used by pre-auth/settings/profile screens. */
|
||||
.filled-action-buttons :is(.primary-btn, .secondary-btn, .destructive-btn, .ghost-btn, .text-btn, .shine-btn, .square-btn, .login-panel-inline-back, .registration-faq-link, .profiles-select, .profiles-close) {
|
||||
color: #ffffff;
|
||||
background: var(--shine-action-blue);
|
||||
background-image: linear-gradient(180deg, rgba(255, 255, 255, 0.14), rgba(255, 255, 255, 0));
|
||||
.filled-action-buttons :is(.primary-btn, .shine-btn, .square-btn, .registration-faq-link, .profiles-select) {
|
||||
color: var(--on-accent);
|
||||
background: var(--accent);
|
||||
border: 0;
|
||||
border-radius: 14px;
|
||||
box-shadow:
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.24),
|
||||
0 8px 22px rgba(var(--shine-action-blue-rgb), 0.24);
|
||||
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.18);
|
||||
border-radius: var(--radius-md);
|
||||
box-shadow: none;
|
||||
text-shadow: none;
|
||||
}
|
||||
|
||||
.filled-action-buttons :is(.primary-btn, .secondary-btn, .destructive-btn, .ghost-btn, .text-btn, .shine-btn, .square-btn, .login-panel-inline-back, .registration-faq-link, .profiles-select, .profiles-close):hover {
|
||||
background: var(--shine-action-blue-hover);
|
||||
box-shadow:
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.28),
|
||||
0 10px 26px rgba(var(--shine-action-blue-rgb), 0.32);
|
||||
filter: brightness(1.12);
|
||||
.filled-action-buttons :is(.secondary-btn, .ghost-btn, .text-btn, .login-panel-inline-back, .profiles-close) {
|
||||
color: var(--text-primary);
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border-control);
|
||||
border-radius: var(--radius-md);
|
||||
box-shadow: none;
|
||||
text-shadow: none;
|
||||
}
|
||||
|
||||
.filled-action-buttons .destructive-btn {
|
||||
color: var(--danger);
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border-control);
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
|
||||
.filled-action-buttons :is(.primary-btn, .secondary-btn, .destructive-btn, .ghost-btn, .text-btn, .shine-btn, .square-btn, .login-panel-inline-back, .registration-faq-link, .profiles-select, .profiles-close):active {
|
||||
background: var(--shine-action-blue-pressed);
|
||||
box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.26);
|
||||
transform: translateY(1px) scale(0.97);
|
||||
filter: brightness(0.9);
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
.filled-action-buttons :is(.primary-btn, .secondary-btn, .destructive-btn, .ghost-btn, .text-btn, .shine-btn, .square-btn, .login-panel-inline-back, .registration-faq-link, .profiles-select, .profiles-close):focus-visible {
|
||||
outline: 2px solid rgba(255, 255, 255, 0.62);
|
||||
outline-offset: 2px;
|
||||
.filled-action-buttons :is(.primary-btn, .secondary-btn, .destructive-btn, .ghost-btn, .text-btn, .shine-btn, .square-btn, .login-panel-inline-back, .registration-faq-link, .profiles-select, .profiles-close):disabled {
|
||||
color: var(--text-secondary);
|
||||
background: var(--surface-selected);
|
||||
border-color: transparent;
|
||||
}
|
||||
|
||||
.filled-action-buttons :is(.primary-btn, .secondary-btn, .destructive-btn, .ghost-btn, .text-btn, .shine-btn, .square-btn, .login-panel-inline-back, .registration-faq-link, .profiles-select, .profiles-close)::before,
|
||||
.filled-action-buttons :is(.primary-btn, .secondary-btn, .destructive-btn, .ghost-btn, .text-btn, .shine-btn, .square-btn, .login-panel-inline-back, .registration-faq-link, .profiles-select, .profiles-close)::after {
|
||||
background: transparent;
|
||||
background-image: none;
|
||||
border-color: transparent;
|
||||
box-shadow: none;
|
||||
content: none;
|
||||
}
|
||||
|
||||
.filled-action-buttons :is(.primary-btn, .secondary-btn, .destructive-btn, .ghost-btn, .text-btn, .shine-btn, .square-btn, .login-panel-inline-back, .registration-faq-link, .profiles-select, .profiles-close):disabled {
|
||||
color: rgba(255, 255, 255, 0.58);
|
||||
background: rgba(var(--shine-action-blue-rgb), 0.42);
|
||||
box-shadow: none;
|
||||
.screen-content:is(.filled-action-buttons, .settings-bordered-actions) .shine-btn.shine-btn--settings {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
min-height: 52px;
|
||||
padding: 10px 40px 10px 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
color: var(--text-primary);
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border-subtle);
|
||||
font-size: var(--text-md);
|
||||
font-weight: var(--weight-medium);
|
||||
text-align: left;
|
||||
}
|
||||
.screen-content:is(.filled-action-buttons, .settings-bordered-actions) .shine-btn.shine-btn--settings::after {
|
||||
content: '›';
|
||||
position: absolute;
|
||||
right: 16px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
color: var(--text-secondary);
|
||||
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 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); }
|
||||
.screen-content:is(.filled-action-buttons, .settings-bordered-actions) .shine-btn.shine-btn--settings.shine-btn--danger::after { content: none; }
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
.message-attachment-carousel-viewport {
|
||||
align-items: center;
|
||||
background: var(--surface);
|
||||
background: transparent;
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: 14px;
|
||||
display: grid;
|
||||
@@ -155,11 +155,31 @@
|
||||
|
||||
|
||||
.message-attachment-media-frame > .message-attachment-download {
|
||||
bottom: 0.75rem;
|
||||
bottom: 0.5rem;
|
||||
position: absolute;
|
||||
right: 0.75rem;
|
||||
right: 0.5rem;
|
||||
}
|
||||
|
||||
.message-attachment-download--icon {
|
||||
width: 36px;
|
||||
min-height: 36px;
|
||||
height: 36px;
|
||||
padding: 0;
|
||||
justify-content: center;
|
||||
border-radius: 50%;
|
||||
color: #fff;
|
||||
background: rgba(0, 0, 0, 0.45);
|
||||
backdrop-filter: blur(6px);
|
||||
-webkit-backdrop-filter: blur(6px);
|
||||
}
|
||||
.message-attachment-download--icon svg { width: 18px; height: 18px; }
|
||||
.message-attachment-download--icon:hover { background: rgba(0, 0, 0, 0.6); }
|
||||
|
||||
.message-attachment-media-frame:not(.is-loaded) { background: var(--surface-selected); animation: attachment-loading 1.2s ease-in-out infinite alternate; }
|
||||
.message-attachment-media-frame.is-loaded { background: transparent; }
|
||||
@keyframes attachment-loading { from { opacity: 1; } to { opacity: .55; } }
|
||||
@media (prefers-reduced-motion: reduce) { .message-attachment-media-frame:not(.is-loaded) { animation: none; } }
|
||||
|
||||
|
||||
.message-attachment-file-card {
|
||||
align-items: center;
|
||||
@@ -342,8 +362,48 @@
|
||||
|
||||
.ar-attachment-manager-card {
|
||||
max-width: min(92vw, 34rem);
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.ar-attachment-manager-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.ar-attachment-manager-close { width: 44px; min-width: 44px; padding: 0; font-size: 18px; color: var(--text-secondary); }
|
||||
.ar-attachment-note { margin: 0; font-size: .8125rem; line-height: 1.25rem; color: var(--text-secondary); }
|
||||
.ar-attachment-alt-sources { display: flex; flex-wrap: wrap; gap: 4px 16px; }
|
||||
.ar-attachment-link { min-height: 44px; padding: 0; justify-self: start; color: var(--accent); background: transparent; font-weight: 500; }
|
||||
|
||||
.ar-attachment-file-picker {
|
||||
min-height: 56px;
|
||||
padding: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
border: 1px dashed var(--border-control);
|
||||
border-radius: 12px;
|
||||
background: var(--surface);
|
||||
cursor: pointer;
|
||||
}
|
||||
.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 {
|
||||
flex-shrink: 0;
|
||||
min-height: 40px;
|
||||
padding: 0 14px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
border-radius: 10px;
|
||||
color: var(--on-accent);
|
||||
background: var(--accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
.ar-attachment-file-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-secondary); font-size: .875rem; }
|
||||
|
||||
.ar-attachment-summary { color: var(--text-primary); font-size: .875rem; }
|
||||
.ar-attachment-ok { color: var(--success); font-weight: 600; }
|
||||
.ar-attachment-details { color: var(--text-secondary); font-size: .8125rem; line-height: 1.25rem; }
|
||||
.ar-attachment-details summary { min-height: 36px; display: flex; align-items: center; color: var(--accent); cursor: pointer; }
|
||||
.ar-attachment-details > div { overflow-wrap: anywhere; }
|
||||
|
||||
|
||||
.ar-attachment-manager-card--wide {
|
||||
max-width: min(96vw, 58rem);
|
||||
@@ -359,10 +419,7 @@
|
||||
}
|
||||
|
||||
|
||||
.ar-attachment-wallet-select,
|
||||
.ar-attachment-wallet-select option {
|
||||
color: var(--accent);
|
||||
}
|
||||
.ar-attachment-wallet-select option { color: var(--text-primary); background: var(--surface); }
|
||||
|
||||
|
||||
.ar-attachment-history-table-wrap {
|
||||
@@ -494,7 +551,7 @@
|
||||
border-radius: 999px;
|
||||
bottom: 0.42rem;
|
||||
color: var(--text-primary);
|
||||
font-size: 0.62rem;
|
||||
font-size: 0.6875rem;
|
||||
left: 0.42rem;
|
||||
padding: 0.2rem 0.46rem;
|
||||
position: absolute;
|
||||
@@ -533,7 +590,7 @@
|
||||
color: var(--text-secondary);
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
font-size: 0.6rem;
|
||||
font-size: 0.6875rem;
|
||||
gap: 0.22rem;
|
||||
line-height: 1.05;
|
||||
min-width: 0;
|
||||
@@ -544,7 +601,7 @@
|
||||
background: var(--border-subtle);
|
||||
border-radius: 0.34rem;
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.56rem;
|
||||
font-size: 0.6875rem;
|
||||
line-height: 1.05;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
@@ -558,7 +615,7 @@
|
||||
.ar-attachment-status {
|
||||
border-radius: 999px;
|
||||
flex: 0 0 auto;
|
||||
font-size: 0.58rem;
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 800;
|
||||
line-height: 1;
|
||||
padding: 0.2rem 0.32rem;
|
||||
@@ -588,7 +645,7 @@
|
||||
border-radius: 999px;
|
||||
color: var(--accent);
|
||||
flex: 0 0 auto;
|
||||
font-size: 0.58rem;
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 800;
|
||||
line-height: 1;
|
||||
padding: 0.2rem 0.32rem;
|
||||
|
||||
@@ -6,9 +6,8 @@
|
||||
margin: 0 auto;
|
||||
border-radius: 50%;
|
||||
overflow: hidden;
|
||||
border: 1px solid rgba(155, 182, 233, 0.46);
|
||||
background: rgba(13, 26, 50, 0.86);
|
||||
box-shadow: inset 0 0 0 1px rgba(240, 248, 255, 0.1);
|
||||
border: 1px solid var(--border-control);
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
|
||||
@@ -30,7 +29,7 @@
|
||||
.avatar-wizard-meta {
|
||||
font-size: 13px;
|
||||
line-height: 1.35;
|
||||
color: #d9e7ff;
|
||||
color: var(--text-secondary);
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
@@ -38,7 +37,7 @@
|
||||
.avatar-wizard-error {
|
||||
min-height: 18px;
|
||||
font-size: 13px;
|
||||
color: #f6a8b3;
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
|
||||
@@ -63,11 +62,11 @@
|
||||
flex: 0 0 auto;
|
||||
aspect-ratio: 1 / 1;
|
||||
border-radius: 50%;
|
||||
background: linear-gradient(130deg, #3c4f73, #243352);
|
||||
background: var(--surface-selected);
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-weight: 700;
|
||||
color: #e5ebff;
|
||||
font-weight: 600;
|
||||
color: var(--accent);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
@@ -191,7 +190,7 @@
|
||||
place-items: center;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #ffffff;
|
||||
color: var(--text-primary);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
@@ -211,12 +210,8 @@
|
||||
display: grid;
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
background: #454b55;
|
||||
color: #ffffff;
|
||||
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.42);
|
||||
box-shadow:
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.08),
|
||||
inset 0 -8px 16px rgba(0, 0, 0, 0.16);
|
||||
background: var(--surface-selected);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -28,8 +28,8 @@
|
||||
gap: 10px;
|
||||
min-height: 44px;
|
||||
padding: calc(8px + env(safe-area-inset-top)) 14px 8px;
|
||||
border-bottom: 1px solid rgba(159, 255, 196, 0.28);
|
||||
background: linear-gradient(180deg, rgba(30, 138, 79, 0.98), rgba(18, 106, 60, 0.98));
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--success) 28%, transparent);
|
||||
background: linear-gradient(180deg, var(--success), var(--surface));
|
||||
box-shadow: 0 10px 24px rgba(5, 30, 16, 0.28);
|
||||
pointer-events: auto;
|
||||
}
|
||||
@@ -42,7 +42,7 @@
|
||||
background: transparent;
|
||||
background-image: none;
|
||||
box-shadow: none;
|
||||
color: #ffffff;
|
||||
color: var(--text-primary);
|
||||
text-shadow: none;
|
||||
backdrop-filter: none;
|
||||
-webkit-backdrop-filter: none;
|
||||
@@ -60,22 +60,22 @@
|
||||
|
||||
|
||||
.call-minimized-bar-text:hover {
|
||||
color: #ffffff;
|
||||
color: var(--text-primary);
|
||||
filter: brightness(1.12);
|
||||
}
|
||||
|
||||
.call-minimized-bar-text:active {
|
||||
color: #ffffff;
|
||||
background: rgba(0, 0, 0, 0.12);
|
||||
color: var(--text-primary);
|
||||
background: color-mix(in srgb, var(--surface) 12%, transparent);
|
||||
box-shadow:
|
||||
inset 0 3px 8px rgba(0, 0, 0, 0.58),
|
||||
inset 0 -1px 2px rgba(255, 255, 255, 0.08);
|
||||
inset 0 -1px 2px color-mix(in srgb, var(--text-primary) 8%, transparent);
|
||||
transform: translateY(1px) scale(0.97);
|
||||
filter: brightness(0.9);
|
||||
}
|
||||
|
||||
.call-minimized-bar-text:focus-visible {
|
||||
outline: 2px solid rgba(255, 255, 255, 0.62);
|
||||
outline: 2px solid var(--border-control);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
@@ -109,7 +109,7 @@
|
||||
background: transparent;
|
||||
background-image: none;
|
||||
box-shadow: none;
|
||||
color: #ffffff;
|
||||
color: var(--text-primary);
|
||||
text-shadow: none;
|
||||
backdrop-filter: none;
|
||||
-webkit-backdrop-filter: none;
|
||||
@@ -119,7 +119,7 @@
|
||||
|
||||
|
||||
.call-icon-btn:hover {
|
||||
color: #ffffff;
|
||||
color: var(--text-primary);
|
||||
background: transparent;
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
@@ -129,12 +129,12 @@
|
||||
|
||||
|
||||
.call-icon-btn:active {
|
||||
color: #ffffff;
|
||||
background: rgba(0, 0, 0, 0.12);
|
||||
color: var(--text-primary);
|
||||
background: color-mix(in srgb, var(--surface) 12%, transparent);
|
||||
border: 0;
|
||||
box-shadow:
|
||||
inset 0 3px 8px rgba(0, 0, 0, 0.58),
|
||||
inset 0 -1px 2px rgba(255, 255, 255, 0.08);
|
||||
inset 0 -1px 2px color-mix(in srgb, var(--text-primary) 8%, transparent);
|
||||
transform: translateY(1px) scale(0.97);
|
||||
filter: brightness(0.9);
|
||||
}
|
||||
@@ -142,7 +142,7 @@
|
||||
|
||||
.call-icon-btn:disabled {
|
||||
opacity: 1;
|
||||
color: rgba(255, 255, 255, 0.42);
|
||||
color: var(--text-secondary);
|
||||
background: transparent;
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
@@ -153,7 +153,7 @@
|
||||
|
||||
|
||||
.call-icon-btn:focus-visible {
|
||||
outline: 2px solid rgba(255, 255, 255, 0.62);
|
||||
outline: 2px solid var(--border-control);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
@@ -193,7 +193,7 @@
|
||||
.call-overlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: rgba(4, 8, 16, 0.88);
|
||||
background: var(--surface);
|
||||
backdrop-filter: blur(8px);
|
||||
pointer-events: auto;
|
||||
}
|
||||
@@ -205,13 +205,13 @@
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
background:
|
||||
radial-gradient(circle at 50% 18%, rgba(79, 124, 208, 0.24), transparent 34%),
|
||||
linear-gradient(180deg, rgba(11, 20, 38, 0.98), rgba(3, 7, 15, 1));
|
||||
radial-gradient(circle at 50% 18%, color-mix(in srgb, var(--accent) 24%, transparent), transparent 34%),
|
||||
linear-gradient(180deg, var(--surface), var(--surface));
|
||||
}
|
||||
|
||||
|
||||
.call-overlay-panel--remote-video {
|
||||
background: #010203;
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
|
||||
@@ -234,7 +234,7 @@
|
||||
min-height: 22px;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
color: rgba(236, 242, 255, 0.94);
|
||||
color: var(--text-primary);
|
||||
text-shadow: 0 2px 10px rgba(0, 0, 0, 0.44);
|
||||
}
|
||||
|
||||
@@ -252,7 +252,7 @@
|
||||
bottom: calc(12px + env(safe-area-inset-bottom));
|
||||
z-index: 4;
|
||||
text-align: center;
|
||||
color: rgba(207, 219, 246, 0.84);
|
||||
color: var(--text-primary);
|
||||
font-size: 13px;
|
||||
pointer-events: none;
|
||||
}
|
||||
@@ -263,13 +263,13 @@
|
||||
inset: 0;
|
||||
overflow: hidden;
|
||||
background:
|
||||
radial-gradient(circle at 50% 24%, rgba(54, 88, 151, 0.48), transparent 30%),
|
||||
linear-gradient(180deg, rgba(9, 17, 32, 0.98), rgba(2, 5, 12, 1));
|
||||
radial-gradient(circle at 50% 24%, color-mix(in srgb, var(--accent) 48%, transparent), transparent 30%),
|
||||
linear-gradient(180deg, var(--surface), var(--surface));
|
||||
}
|
||||
|
||||
|
||||
.call-video-stage--remote-video {
|
||||
background: #000;
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
|
||||
@@ -279,7 +279,7 @@
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
background: #02050a;
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
|
||||
@@ -320,8 +320,8 @@
|
||||
min-width: 100%;
|
||||
min-height: 100%;
|
||||
border-radius: 999px;
|
||||
border: 2px solid rgba(221, 233, 255, 0.2);
|
||||
background: linear-gradient(180deg, rgba(18, 31, 58, 0.96), rgba(9, 15, 29, 0.98));
|
||||
border: 2px solid var(--border-subtle);
|
||||
background: linear-gradient(180deg, var(--surface), var(--surface));
|
||||
box-shadow: 0 24px 48px rgba(0, 0, 0, 0.34);
|
||||
}
|
||||
|
||||
@@ -337,7 +337,7 @@
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: #f4f8ff;
|
||||
color: var(--text-primary);
|
||||
font-size: clamp(20px, 5.8vw, 28px);
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.02em;
|
||||
@@ -345,7 +345,7 @@
|
||||
|
||||
|
||||
.call-kind {
|
||||
color: #ffffff;
|
||||
color: var(--text-primary);
|
||||
font-size: clamp(27px, 8vw, 40px);
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.05em;
|
||||
@@ -355,7 +355,7 @@
|
||||
|
||||
.call-hero-status {
|
||||
max-width: 88vw;
|
||||
color: rgba(211, 223, 246, 0.9);
|
||||
color: var(--text-primary);
|
||||
font-size: 14px;
|
||||
line-height: 1.35;
|
||||
}
|
||||
@@ -370,8 +370,8 @@
|
||||
aspect-ratio: 3 / 4;
|
||||
border-radius: 14px;
|
||||
overflow: hidden;
|
||||
border: 1px solid rgba(176, 205, 255, 0.38);
|
||||
background: rgba(7, 12, 22, 0.94);
|
||||
border: 1px solid color-mix(in srgb, var(--accent) 38%, transparent);
|
||||
background: var(--surface);
|
||||
box-shadow: 0 12px 28px rgba(0, 0, 0, 0.32);
|
||||
cursor: grab;
|
||||
touch-action: none;
|
||||
@@ -436,7 +436,7 @@
|
||||
background: transparent;
|
||||
background-image: none;
|
||||
box-shadow: none;
|
||||
color: #ffffff;
|
||||
color: var(--text-primary);
|
||||
text-shadow: none;
|
||||
backdrop-filter: none;
|
||||
-webkit-backdrop-filter: none;
|
||||
@@ -447,7 +447,7 @@
|
||||
|
||||
|
||||
.call-accept-btn:hover {
|
||||
color: #ffffff;
|
||||
color: var(--text-primary);
|
||||
background: transparent;
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
@@ -457,12 +457,12 @@
|
||||
|
||||
|
||||
.call-accept-btn:active {
|
||||
color: #ffffff;
|
||||
background: rgba(0, 0, 0, 0.12);
|
||||
color: var(--text-primary);
|
||||
background: color-mix(in srgb, var(--surface) 12%, transparent);
|
||||
border: 0;
|
||||
box-shadow:
|
||||
inset 0 3px 8px rgba(0, 0, 0, 0.58),
|
||||
inset 0 -1px 2px rgba(255, 255, 255, 0.08);
|
||||
inset 0 -1px 2px color-mix(in srgb, var(--text-primary) 8%, transparent);
|
||||
transform: translateY(1px) scale(0.97);
|
||||
filter: brightness(0.9);
|
||||
}
|
||||
@@ -470,7 +470,7 @@
|
||||
|
||||
.call-accept-btn:disabled {
|
||||
opacity: 1;
|
||||
color: rgba(255, 255, 255, 0.42);
|
||||
color: var(--text-secondary);
|
||||
background: transparent;
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
@@ -481,7 +481,7 @@
|
||||
|
||||
|
||||
.call-accept-btn:focus-visible {
|
||||
outline: 2px solid rgba(255, 255, 255, 0.62);
|
||||
outline: 2px solid var(--border-control);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
|
||||
@@ -92,19 +92,21 @@
|
||||
overflow-y: hidden;
|
||||
width: 100%;
|
||||
min-height: 160px;
|
||||
padding: 0;
|
||||
padding: 12px 14px;
|
||||
resize: none;
|
||||
border: 0;
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: 14px;
|
||||
outline: 0;
|
||||
color: var(--text-primary);
|
||||
background: transparent;
|
||||
background: var(--surface);
|
||||
transition: border-color 160ms ease;
|
||||
font: inherit;
|
||||
font-size: 16px;
|
||||
line-height: 24px;
|
||||
caret-color: var(--accent);
|
||||
}
|
||||
|
||||
.channel-editor__input::placeholder { color: var(--text-secondary); }
|
||||
.channel-editor__input::placeholder { color: color-mix(in srgb, var(--text-secondary) 62%, var(--background)); opacity: 1; }
|
||||
|
||||
.channel-editor__type {
|
||||
display: grid;
|
||||
@@ -113,17 +115,7 @@
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.channel-editor__type .select {
|
||||
color: var(--text-primary);
|
||||
background: var(--surface);
|
||||
border-color: var(--border-control);
|
||||
}
|
||||
|
||||
.channel-editor__input:focus-visible {
|
||||
border-radius: 4px;
|
||||
outline: 2px solid var(--focus-ring);
|
||||
outline-offset: 4px;
|
||||
}
|
||||
.channel-editor__input:focus-visible { outline: 0; border-color: var(--accent); }
|
||||
|
||||
.channel-editor__attachments { display: grid; gap: 8px; }
|
||||
.channel-editor__author { display: flex; align-items: center; gap: 12px; font-size: .875rem; }
|
||||
@@ -178,16 +170,31 @@
|
||||
}
|
||||
|
||||
.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);
|
||||
}
|
||||
|
||||
.channel-editor__submit:disabled {
|
||||
opacity: 1;
|
||||
color: var(--text-secondary);
|
||||
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; }
|
||||
|
||||
.channel-editor__counter {
|
||||
min-width: 0;
|
||||
color: var(--text-secondary);
|
||||
@@ -207,11 +214,12 @@
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 370px) {
|
||||
.channel-editor__footer { grid-template-columns: auto minmax(0, 1fr); }
|
||||
.channel-editor__counter { grid-column: 1 / -1; grid-row: 1; }
|
||||
.channel-editor__attach { grid-column: 1; }
|
||||
.channel-editor__submit { grid-column: 2; }
|
||||
@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) {
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/* Чипы-фильтры: ряд над списком («Все / Близкие / …»), как папки в мессенджерах.
|
||||
* Выбранный чип выглядит так же, как выбранная вкладка (.tab-btn[aria-checked]). */
|
||||
.chip-row {
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
overflow-x: auto;
|
||||
padding: var(--space-1) 0;
|
||||
scrollbar-width: none;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
.chip-row::-webkit-scrollbar { display: none; }
|
||||
|
||||
.chip,
|
||||
.fg-filter-chip {
|
||||
flex-shrink: 0;
|
||||
min-height: 36px;
|
||||
padding: 0 14px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: var(--radius-pill);
|
||||
color: var(--text-secondary);
|
||||
background: var(--surface);
|
||||
font: inherit;
|
||||
font-size: var(--text-sm);
|
||||
font-weight: var(--weight-medium);
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
box-shadow: none;
|
||||
backdrop-filter: none;
|
||||
-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[aria-pressed='true'],
|
||||
.chip.is-active,
|
||||
.fg-filter-chip.is-active {
|
||||
color: var(--text-primary);
|
||||
background: var(--surface-selected);
|
||||
border-color: color-mix(in srgb, var(--accent) 55%, var(--border-control));
|
||||
font-weight: var(--weight-bold);
|
||||
box-shadow: none;
|
||||
}
|
||||
.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);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user