Настройки: «Оформление», «Уведомления» и «О приложении»

- «Оформление»: тема Авто / Светлая / Тёмная и все 26 палитр образцами – применяются сразу;
  «Настроить цвета вручную» – прежний редактор. Раньше тема переключалась пилюлей
  с эмодзи в шапке, а палитры были спрятаны в настройках разработчика;
- «Уведомления»: звук нового сообщения в открытом приложении (вкл/выкл), состояние
  разрешения системных уведомлений с кнопкой «Разрешить», список чатов «без звука»
  с «Включить звук»;
- «О приложении»: версии приложения, сборки (датой), сервера и сервер доступа,
  «Скопировать сведения» – для обращения в поддержку;
- разделы сгруппированы: внешний вид и уведомления – сверху, устройства и ключи – ниже;
- device-prefs.js – настройки этого устройства (не аккаунта);
- hidden снова скрывает .nav-list.
This commit is contained in:
q
2026-10-13 03:48:00 +03:00
parent 26db18e250
commit 96d23b16fc
12 changed files with 474 additions and 94 deletions
+133
View File
@@ -0,0 +1,133 @@
// «Оформление»: тема (Авто / Светлая / Тёмная) и палитра – образцами, применяются сразу.
// Тонкая ручная настройка цветов – прежний редактор палитры.
import { createTopBar } from '../components/topbar.js';
import { iconHtml } from '../components/ui-icon.js';
import { openPaletteEditor } from '../components/palette-editor.js';
import {
PALETTE_PRESETS, getPaletteSettings, getThemeMode, resolvePalette, resolveThemeMode, setPaletteSettings, setThemeMode,
} from '../services/theme-service.js';
export const pageMeta = { id: 'appearance-view', title: 'Оформление' };
const THEME_MODES = [
['system', 'Авто'],
['light', 'Светлая'],
['dark', 'Тёмная'],
];
export function render({ navigate, chrome } = {}) {
const screen = document.createElement('section');
screen.className = 'stack appearance-screen';
let closeEditor = null; // openPaletteEditor возвращает функцию закрытия
chrome?.setTopbar(createTopBar({
title: 'Оформление',
back: { onClick: () => navigate('settings-view') },
}));
// --- тема ---
const themeTitle = document.createElement('p');
themeTitle.className = 'nav-list__title';
themeTitle.textContent = 'Тема';
const themeTabs = document.createElement('div');
themeTabs.className = 'tabs tabs--three appearance-theme';
themeTabs.setAttribute('role', 'radiogroup');
themeTabs.setAttribute('aria-label', 'Тема оформления');
const themeHint = document.createElement('p');
themeHint.className = 'meta-muted appearance-hint';
for (const [mode, label] of THEME_MODES) {
const button = document.createElement('button');
button.type = 'button';
button.className = 'tab-btn';
button.dataset.mode = mode;
button.setAttribute('role', 'radio');
button.textContent = label;
button.addEventListener('click', () => {
setThemeMode(mode);
sync();
});
themeTabs.append(button);
}
// --- палитра ---
const paletteTitle = document.createElement('p');
paletteTitle.className = 'nav-list__title';
paletteTitle.textContent = 'Цвета';
const grid = document.createElement('div');
grid.className = 'palette-grid';
grid.setAttribute('role', 'radiogroup');
grid.setAttribute('aria-label', 'Палитра');
const swatches = new Map();
for (const [id, preset] of Object.entries(PALETTE_PRESETS)) {
const button = document.createElement('button');
button.type = 'button';
button.className = 'palette-swatch';
button.setAttribute('role', 'radio');
button.setAttribute('aria-label', preset.label);
button.innerHTML = `
<span class="palette-swatch__sample" aria-hidden="true">
<span class="palette-swatch__bar"></span>
<span class="palette-swatch__bubble"></span>
<span class="palette-swatch__dot"></span>
<span class="palette-swatch__check">${iconHtml('check')}</span>
</span>
<span class="palette-swatch__label"></span>
`;
button.querySelector('.palette-swatch__label').textContent = preset.label;
button.addEventListener('click', () => {
// Выбор готовой палитры сбрасывает ручные правки – иначе выбор выглядел бы «не тем».
setPaletteSettings({ preset: id, custom: { dark: {}, light: {} } });
sync();
});
swatches.set(id, button);
grid.append(button);
}
const more = document.createElement('div');
more.className = 'nav-list';
const customRow = document.createElement('button');
customRow.type = 'button';
customRow.className = 'nav-row';
customRow.innerHTML = '<span class="nav-row__label">Настроить цвета вручную</span><span class="nav-row__hint"></span>';
customRow.addEventListener('click', () => {
closeEditor?.();
closeEditor = openPaletteEditor({ onClose: () => { closeEditor = null; sync(); } });
});
more.append(customRow);
function sync() {
const mode = getThemeMode();
const resolved = resolveThemeMode(mode);
themeTabs.querySelectorAll('.tab-btn').forEach((button) => {
button.setAttribute('aria-checked', String(button.dataset.mode === mode));
});
themeHint.textContent = mode === 'system'
? `Как в системе устройства: сейчас ${resolved === 'light' ? 'светлая' : 'тёмная'}.`
: 'Не зависит от настроек устройства.';
const settings = getPaletteSettings();
const customized = Object.keys(settings.custom.dark).length + Object.keys(settings.custom.light).length > 0;
swatches.forEach((button, id) => {
// Образцы показывают ту тему, что сейчас на экране.
const colors = resolvePalette(resolved, { preset: id, custom: { dark: {}, light: {} } });
const sample = button.querySelector('.palette-swatch__sample');
sample.style.setProperty('--swatch-bg', colors.background);
sample.style.setProperty('--swatch-surface', colors.surface);
sample.style.setProperty('--swatch-accent', colors.accent);
sample.style.setProperty('--swatch-bubble', colors['bubble-out']);
sample.style.setProperty('--swatch-on-accent', colors['on-accent']);
button.setAttribute('aria-checked', String(settings.preset === id && !customized));
});
customRow.querySelector('.nav-row__hint').textContent = customized
? `Свои правки поверх «${PALETTE_PRESETS[settings.preset]?.label || settings.preset}»`
: 'Каждый цвет отдельно, для светлой и тёмной темы';
}
sync();
screen.append(themeTitle, themeTabs, themeHint, paletteTitle, grid, more);
screen.cleanup = () => {
const close = closeEditor;
closeEditor = null;
close?.();
};
return screen;
}
+1 -1
View File
@@ -783,7 +783,7 @@ export function render({ navigate, route, chrome } = {}) {
['line', 'contact', 'Контакт'],
['dash', 'friend', 'Пунктир – связь только с одной стороны'],
['aura', '', 'Свечение вокруг – сияющий'],
['badge', '', 'Синяя галочка – основной аккаунт'],
['badge', '', 'Синяя галочка – официальный аккаунт'],
['mark', '', 'Цветная точка – ваша заметка или метка'],
];
for (const [kind, type, text] of rows) {
@@ -0,0 +1,139 @@
// «Уведомления» в настройках: звук сообщений, разрешение системных уведомлений и чаты
// «без звука». Всё – настройки этого устройства, сервер про них не знает.
import { createTopBar } from '../components/topbar.js';
import { normalizeDmChatId } from '../state.js';
import { DM_CHAT_PREFS_EVENT, getMutedDmChats, setDmChatMuted } from '../services/dm-chat-prefs.js';
import { DEVICE_PREFS_EVENT, getDevicePref, setDevicePref } from '../services/device-prefs.js';
import { showToast } from '../services/channels-ux.js';
export const pageMeta = { id: 'notification-settings-view', title: 'Уведомления' };
function permissionState() {
if (typeof Notification === 'undefined') return 'unsupported';
return Notification.permission; // granted | denied | default
}
export function render({ navigate, chrome } = {}) {
const screen = document.createElement('section');
screen.className = 'stack notification-settings-screen';
let disposed = false;
chrome?.setTopbar(createTopBar({
title: 'Уведомления',
back: { onClick: () => navigate('settings-view') },
}));
const soundTitle = document.createElement('p');
soundTitle.className = 'nav-list__title';
soundTitle.textContent = 'Сообщения';
const soundList = document.createElement('div');
soundList.className = 'nav-list';
const soundRow = document.createElement('label');
soundRow.className = 'nav-row nav-row--switch';
soundRow.innerHTML = `
<span class="nav-row__text">
<span class="nav-row__label">Звук в открытом приложении</span>
<span class="nav-row__hint">Короткий сигнал о новом сообщении</span>
</span>
<input class="switch" type="checkbox" />
`;
const soundSwitch = soundRow.querySelector('input');
soundSwitch.checked = getDevicePref('dmSound', true) !== false;
soundSwitch.addEventListener('change', () => setDevicePref('dmSound', soundSwitch.checked));
soundList.append(soundRow);
// Системные уведомления – когда приложение свёрнуто или закрыто.
const systemList = document.createElement('div');
systemList.className = 'nav-list';
const systemRow = document.createElement('div');
systemRow.className = 'nav-row nav-row--action';
systemList.append(systemRow);
function renderSystemRow() {
const permission = permissionState();
const texts = {
granted: ['Уведомления на устройстве', 'Разрешены: придут, даже когда приложение свёрнуто'],
denied: ['Уведомления на устройстве', 'Запрещены. Разрешите их для этого сайта в настройках браузера'],
default: ['Уведомления на устройстве', 'Пока не разрешены – без них не узнать о сообщении, когда приложение свёрнуто'],
unsupported: ['Уведомления на устройстве', 'Этот браузер их не поддерживает'],
};
const [label, hint] = texts[permission] || texts.unsupported;
systemRow.innerHTML = `
<span class="nav-row__text">
<span class="nav-row__label"></span>
<span class="nav-row__hint"></span>
</span>
`;
systemRow.querySelector('.nav-row__label').textContent = label;
systemRow.querySelector('.nav-row__hint').textContent = hint;
if (permission === 'default') {
const allow = document.createElement('button');
allow.type = 'button';
allow.className = 'primary-btn nav-row__button';
allow.textContent = 'Разрешить';
allow.addEventListener('click', async () => {
allow.disabled = true;
try {
const result = await Notification.requestPermission();
if (result === 'granted') showToast('Уведомления разрешены');
} catch {
showToast('Не удалось запросить разрешение', { kind: 'error' });
}
if (!disposed) renderSystemRow();
});
systemRow.append(allow);
}
}
renderSystemRow();
// Чаты «без звука»: здесь их видно списком и можно вернуть звук.
const mutedTitle = document.createElement('p');
mutedTitle.className = 'nav-list__title';
const mutedList = document.createElement('div');
mutedList.className = 'nav-list';
const mutedEmpty = document.createElement('p');
mutedEmpty.className = 'meta-muted appearance-hint';
function renderMuted() {
const muted = getMutedDmChats();
mutedTitle.textContent = muted.length ? `Чаты без звука · ${muted.length}` : 'Чаты без звука';
mutedList.replaceChildren();
mutedList.hidden = !muted.length;
mutedEmpty.hidden = Boolean(muted.length);
mutedEmpty.textContent = 'Нет. Выключить звук чата можно в его меню «•••» или долгим нажатием в списке чатов.';
for (const chatId of muted) {
const row = document.createElement('div');
row.className = 'nav-row nav-row--action';
const text = document.createElement('span');
text.className = 'nav-row__text';
const label = document.createElement('button');
label.type = 'button';
label.className = 'nav-row__label text-btn notification-settings-chat';
label.textContent = `@${chatId}`;
label.addEventListener('click', () => navigate(`chat/${encodeURIComponent(normalizeDmChatId(chatId))}`));
text.append(label);
const unmute = document.createElement('button');
unmute.type = 'button';
unmute.className = 'secondary-btn nav-row__button';
unmute.textContent = 'Включить звук';
unmute.addEventListener('click', () => setDmChatMuted(chatId, false));
row.append(text, unmute);
mutedList.append(row);
}
}
renderMuted();
const onPrefs = () => { if (!disposed) renderMuted(); };
const onDevicePrefs = () => { if (!disposed) soundSwitch.checked = getDevicePref('dmSound', true) !== false; };
window.addEventListener(DM_CHAT_PREFS_EVENT, onPrefs);
window.addEventListener(DEVICE_PREFS_EVENT, onDevicePrefs);
screen.append(soundTitle, soundList, systemList, mutedTitle, mutedList, mutedEmpty);
screen.cleanup = () => {
if (disposed) return;
disposed = true;
window.removeEventListener(DM_CHAT_PREFS_EVENT, onPrefs);
window.removeEventListener(DEVICE_PREFS_EVENT, onDevicePrefs);
};
return screen;
}
+88 -81
View File
@@ -1,8 +1,9 @@
import { confirmDialog } from '../components/confirm-dialog.js';
import { createTopBar } from '../components/topbar.js';
import { addAppLogEntry, authService, closeSavedProfile, state } from '../state.js';
import { isDeveloperToolsEnabled } from '../services/feature-settings.js';
import { getThemeMode, setThemeMode } from '../services/theme-service.js';
import { openSheet } from '../components/sheet.js';
import { showToast } from '../services/channels-ux.js';
import { PALETTE_PRESETS, getPaletteSettings, getThemeMode } from '../services/theme-service.js';
import {
canInstallPwa,
isStandalonePwaMode,
@@ -12,56 +13,95 @@ import {
export const pageMeta = { id: 'settings-view', title: 'Настройки' };
// Номер сборки вида 20261013040000 – это дата и время: показываем «13.10.2026, 04:00».
function formatBuildStamp(rawValue) {
const value = String(rawValue || '').trim();
if (!/^\d{14}$/.test(value)) return value;
const yyyy = value.slice(0, 4);
const mm = value.slice(4, 6);
const dd = value.slice(6, 8);
const hh = value.slice(8, 10);
const min = value.slice(10, 12);
const ss = value.slice(12, 14);
return `${yyyy}-${mm}-${dd}/${hh}:${min}__${ss}`;
return `${value.slice(6, 8)}.${value.slice(4, 6)}.${value.slice(0, 4)}, ${value.slice(8, 10)}:${value.slice(10, 12)}`;
}
function formatVersionForUi(rawValue) {
const value = String(rawValue || '').trim();
if (!value) return 'n/a';
const formatted = formatBuildStamp(value);
if (formatted && formatted !== value) {
return `${formatted} (${value})`;
}
if (formatted && formatted !== value) return formatted;
return value;
}
// Сервер отвечает версией на Ping (или GetServerInfo у старых серверов).
async function loadServerVersion() {
try {
const pingResp = await authService.ws.request('Ping', { ts: Date.now() }, 7000);
const value = String(pingResp?.payload?.serverVersion || pingResp?.serverVersion || '').trim();
if (value) return value;
} catch {
// ниже – запасной запрос
}
const infoResp = await authService.ws.request('GetServerInfo', {});
return String(infoResp?.payload?.version || '').trim();
}
// «О приложении»: версии клиента, сборки и сервера – и кнопка скопировать их для поддержки.
function openAboutSheet() {
let disposed = false;
return openSheet({
title: 'О приложении',
className: 'about-sheet',
onClose: () => { disposed = true; },
content: () => {
const list = document.createElement('div');
list.className = 'nav-list';
const rows = [
['Версия приложения', formatVersionForUi(window.__SHINE_CLIENT_VERSION__)],
['Сборка', formatVersionForUi(window.__SHINE_BUILD_HASH__)],
['Сервер', 'Узнаю…'],
['Сервер доступа', String(state.entrySettings?.shineServerLogin || '').trim() || '—'],
];
const values = rows.map(([label, value]) => {
const row = document.createElement('div');
row.className = 'nav-row nav-row--static';
row.innerHTML = '<span class="nav-row__hint"></span><span class="nav-row__label"></span>';
row.querySelector('.nav-row__hint').textContent = label;
row.querySelector('.nav-row__label').textContent = value;
list.append(row);
return row.querySelector('.nav-row__label');
});
void loadServerVersion()
.then((value) => { if (!disposed) values[2].textContent = formatVersionForUi(value) || '—'; })
.catch(() => { if (!disposed) values[2].textContent = 'Нет связи с сервером'; });
const copy = document.createElement('button');
copy.type = 'button';
copy.className = 'secondary-btn about-sheet__copy';
copy.textContent = 'Скопировать сведения';
copy.addEventListener('click', async () => {
const text = rows.map(([label], index) => `${label}: ${values[index].textContent}`).join('\n');
try {
await navigator.clipboard.writeText(text);
showToast('Сведения скопированы');
} catch {
showToast('Не удалось скопировать', { kind: 'error' });
}
});
const box = document.createElement('div');
box.className = 'stack';
box.append(list, copy);
return box;
},
});
}
const THEME_LABELS = { system: 'авто', light: 'светлая', dark: 'тёмная' };
export function render({navigate, chrome}) {
const screen = document.createElement('section');
screen.className = 'stack';
let isDisposed = false;
let aboutSheet = null;
const topbar = createTopBar({
title: 'Настройки',
back: { label: '←', onClick: () => navigate('profile-view') },
});
const themeButton = document.createElement('button');
themeButton.type = 'button';
themeButton.className = 'settings-theme-cycle';
themeButton.title = 'Переключить тему оформления';
themeButton.setAttribute('aria-label', 'Переключить тему оформления');
const modes = ['light', 'dark', 'system'];
const themeNames = { light: '☀️ Светлая', dark: '🌙 Тёмная', system: '◐ Авто' };
const updateThemeButton = () => {
const mode = getThemeMode();
themeButton.textContent = themeNames[mode] || themeNames.system;
themeButton.setAttribute('aria-label', `Тема: ${themeButton.textContent}. Нажмите для переключения`);
};
themeButton.addEventListener('click', () => {
const index = modes.indexOf(getThemeMode());
setThemeMode(modes[(index + 1) % modes.length]);
updateThemeButton();
});
updateThemeButton();
topbar.querySelector('.topbar__right')?.append(themeButton);
chrome?.setTopbar(topbar);
// Скрытый вход в «Дополнительные настройки»: пять быстрых нажатий на заголовок.
@@ -79,23 +119,36 @@ export function render({navigate, chrome}) {
const card = document.createElement('div');
card.className = 'stack settings-sections';
const row = (id, label, hint) => `<button class="nav-row" type="button" id="${id}"><span class="nav-row__label">${label}</span>${hint ? `<span class="nav-row__hint">${hint}</span>` : ''}</button>`;
const palette = PALETTE_PRESETS[getPaletteSettings().preset]?.label || '';
const appearanceHint = `Тема: ${THEME_LABELS[getThemeMode()] || 'авто'}${palette ? ` · цвета «${palette}»` : ''}`;
card.innerHTML = `
<div class="nav-list">
${row('settings-appearance', 'Оформление', appearanceHint)}
${row('settings-notifications', 'Уведомления', 'Звук, разрешение, чаты без звука')}
${row('settings-language', 'Язык / Language', 'Русский')}
</div>
<div class="nav-list">
${row('settings-device', 'Устройства', 'Сеансы и подключение устройств')}
${row('settings-my-blockchain', 'Мой блокчейн', 'История записей, файлы и внешнее устройство')}
${row('settings-servers', 'Настройки серверов', 'Сервер доступа и серверы блокчейнов')}
${row('settings-access-keys', 'Ключи и пароли', 'Просмотр ключей и смена пароля')}
${row('settings-language', 'Язык / Language', 'Русский')}
</div>
<div class="nav-list" id="settings-install-list" hidden></div>
<div class="nav-list">
${row('settings-developer', 'Настройки разработчика', 'Цветовая схема и инструменты разработчика')}
${row('settings-about', 'О приложении', `Версия ${window.__SHINE_CLIENT_VERSION__ || '—'}`)}
${row('settings-developer', 'Настройки разработчика', 'Инструменты и журнал приложения')}
</div>
<div class="nav-list">
<button class="nav-row nav-row--danger" type="button" id="settings-signout"><span class="nav-row__label">Выйти из аккаунта</span></button>
</div>
`;
card.querySelector('#settings-appearance').addEventListener('click', () => navigate('appearance-view'));
card.querySelector('#settings-notifications').addEventListener('click', () => navigate('notification-settings-view'));
card.querySelector('#settings-about').addEventListener('click', () => {
aboutSheet?.close();
aboutSheet = openAboutSheet();
});
card.querySelector('#settings-device').addEventListener('click', () => navigate('device-view'));
card.querySelector('#settings-my-blockchain').addEventListener('click', () => navigate('my-blockchain-view'));
card.querySelector('#settings-servers').addEventListener('click', () => navigate('settings-servers-view'));
@@ -160,56 +213,10 @@ export function render({navigate, chrome}) {
screen.append(card);
if (isDeveloperToolsEnabled()) {
const versionCard = document.createElement('div');
versionCard.className = 'card stack';
const title = document.createElement('p');
title.className = 'field-label';
title.textContent = 'Версии';
const clientVersion = document.createElement('p');
clientVersion.className = 'meta-muted';
clientVersion.textContent = `Клиент: ${formatVersionForUi(window.__SHINE_CLIENT_VERSION__)}`;
const uiBuild = document.createElement('p');
uiBuild.className = 'meta-muted';
uiBuild.textContent = `Сборка UI: ${formatVersionForUi(window.__SHINE_BUILD_HASH__)}`;
const serverVersion = document.createElement('p');
serverVersion.className = 'meta-muted';
serverVersion.textContent = 'Сервер: загружается...';
versionCard.append(title, clientVersion, uiBuild, serverVersion);
void (async () => {
try {
let value = '';
try {
const pingResp = await authService.ws.request('Ping', { ts: Date.now() }, 7000);
value = String(pingResp?.payload?.serverVersion || pingResp?.serverVersion || '').trim();
} catch {
// fallback below
}
if (!value) {
const infoResp = await authService.ws.request('GetServerInfo', {});
value = String(infoResp?.payload?.version || '').trim();
}
if (!isDisposed) serverVersion.textContent = `Сервер: ${formatVersionForUi(value)}`;
} catch {
if (!isDisposed) {
serverVersion.textContent = 'Сервер: недоступно';
}
}
})();
screen.append(versionCard);
}
screen.cleanup = () => {
if (isDisposed) return;
isDisposed = true;
aboutSheet?.close();
unsubscribeInstallAvailability();
};
return screen;