SHA256
Отключить мультиаккаунтность и уточнить статусы профиля
This commit is contained in:
+7
-44
@@ -40,9 +40,6 @@ import {
|
||||
addAppLogEntry,
|
||||
authorizeSession,
|
||||
hydrateMessagesFromStore,
|
||||
getSavedProfiles,
|
||||
closeSavedProfile,
|
||||
switchToSavedProfile,
|
||||
isSessionInvalidError,
|
||||
refreshSessions,
|
||||
setSessionAuthorizedHandler,
|
||||
@@ -125,7 +122,6 @@ import * as chatMediaView from './pages/chat-media-view.js';
|
||||
import { isDmChatMuted } from './services/dm-chat-prefs.js';
|
||||
import { getDevicePref } from './services/device-prefs.js';
|
||||
import { isDeveloperToolsEnabled } from './services/feature-settings.js';
|
||||
import { confirmDialog } from './components/confirm-dialog.js';
|
||||
import * as userProfileView from './pages/user-profile-view.js?v=20261110-pwa-avatar';
|
||||
import * as userProfileListView from './pages/user-profile-list-view.js';
|
||||
import * as userRelationManageView from './pages/user-relation-manage-view.js';
|
||||
@@ -967,41 +963,13 @@ function pushTargetPath(payload = {}) {
|
||||
return '/profile';
|
||||
}
|
||||
|
||||
function savedProfileExists(login) {
|
||||
const normalized = String(login || '').trim().toLowerCase();
|
||||
if (!normalized) return false;
|
||||
return getSavedProfiles().some((item) => String(item.login || '').trim().toLowerCase() === normalized);
|
||||
}
|
||||
|
||||
async function ensurePushTargetProfile(payload = {}, { action = '' } = {}) {
|
||||
// Multi-profile switching is disabled; never open a notification for another login.
|
||||
async function ensurePushTargetProfile(payload = {}) {
|
||||
const targetLogin = pushTargetLogin(payload);
|
||||
const currentLogin = String(state.session.login || '').trim();
|
||||
if (!targetLogin || targetLogin.toLowerCase() === currentLogin.toLowerCase()) return true;
|
||||
if (!savedProfileExists(targetLogin)) {
|
||||
showToast(t('remaining.app.a_notification_was_sent_to_profile_login_which_is_not_sav', { login: targetLogin }), { kind: 'info' });
|
||||
return false;
|
||||
}
|
||||
|
||||
const kind = String(payload?.kind || '').trim();
|
||||
const question = kind === 'incoming_call'
|
||||
? t('remaining.app.incoming_call_for_profile_login_switch_to_this_profile', { login: targetLogin })
|
||||
: t('remaining.app.this_message_was_sent_to_profile_login_switch_profiles_to', { login: targetLogin });
|
||||
const confirmed = await confirmDialog({ title: t('remaining.app.switch_profile'), text: question, confirmLabel: t('remaining.app.switch') });
|
||||
if (!confirmed) return false;
|
||||
|
||||
try {
|
||||
await switchToSavedProfile(targetLogin);
|
||||
if (action === 'accept' || action === 'decline') {
|
||||
savePendingCallPushAction(action, payload);
|
||||
window.location.assign(pushTargetPath(payload));
|
||||
} else {
|
||||
window.location.assign(pushTargetPath(payload));
|
||||
}
|
||||
return false;
|
||||
} catch (error) {
|
||||
showToast(toUserMessage(error, t('remaining.app.could_not_switch_profile')), { kind: 'error' });
|
||||
return false;
|
||||
}
|
||||
showToast(t('screens.registration_identity.other_profile_notification'), { kind: 'info' });
|
||||
return false;
|
||||
}
|
||||
|
||||
async function handleNotificationClick(payload = {}) {
|
||||
@@ -1544,7 +1512,7 @@ function renderApp() {
|
||||
return;
|
||||
}
|
||||
|
||||
const addingProfile = state.session.isAuthorized && String(state.authReturnHash || '').trim() === '/profiles';
|
||||
const addingProfile = false; // Multi-profile mode temporarily disabled.
|
||||
if (state.session.isAuthorized && PRE_AUTH_PAGES.includes(pageId) && !addingProfile) {
|
||||
navigate('messages-list');
|
||||
return;
|
||||
@@ -1638,11 +1606,6 @@ async function tryAutoLogin() {
|
||||
} catch {}
|
||||
} catch (error) {
|
||||
if (isSessionInvalidError(error)) {
|
||||
const result = await closeSavedProfile(state.session.login);
|
||||
if (result?.nextProfile) {
|
||||
window.location.assign('/profile');
|
||||
return;
|
||||
}
|
||||
await terminateCurrentSession({
|
||||
infoMessage: t('remaining.app.this_session_has_ended_on_this_device_please_sign_in_agai'),
|
||||
});
|
||||
@@ -1794,8 +1757,8 @@ async function init() {
|
||||
}
|
||||
|
||||
authService.onEvent('SessionRevoked', async () => {
|
||||
const result = await closeSavedProfile(state.session.login);
|
||||
window.location.assign(result?.nextProfile ? '/profile' : '/start');
|
||||
await terminateCurrentSession({ notifySessionReset: false });
|
||||
window.location.assign('/start');
|
||||
});
|
||||
|
||||
authService.onEvent('ForceUiReload', async (evt) => {
|
||||
|
||||
@@ -8,6 +8,7 @@ export function confirmDialog({
|
||||
danger = false,
|
||||
aboveEditor = false,
|
||||
rememberChoice = null,
|
||||
infoOnly = false,
|
||||
} = {}) {
|
||||
return new Promise((resolve) => {
|
||||
const opener = document.activeElement;
|
||||
@@ -40,6 +41,10 @@ export function confirmDialog({
|
||||
}
|
||||
modal.querySelector('[data-answer="no"]').textContent = cancelLabel;
|
||||
modal.querySelector('[data-answer="yes"]').textContent = confirmLabel;
|
||||
if (infoOnly) {
|
||||
modal.querySelector('[data-answer="no"]').remove();
|
||||
modal.querySelector('.form-actions-grid').classList.add('form-actions-grid--single');
|
||||
}
|
||||
|
||||
const finish = (answer) => {
|
||||
document.removeEventListener('keydown', onKeydown, true);
|
||||
@@ -58,6 +63,6 @@ export function confirmDialog({
|
||||
});
|
||||
document.addEventListener('keydown', onKeydown, true);
|
||||
document.body.append(modal);
|
||||
modal.querySelector('[data-answer="no"]').focus();
|
||||
modal.querySelector(infoOnly ? '[data-answer="yes"]' : '[data-answer="no"]').focus();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ export function escapeProfileHtml(text) {
|
||||
const esc = escapeProfileHtml;
|
||||
|
||||
// Карточка статуса у аватара: кто подтвердил этот аккаунт и кого подтвердил он сам.
|
||||
function statusSideHtml({ kind, title, active, received, given, verb }) {
|
||||
function statusSideHtml({ kind, title, active, received, given, verb, showGiven = true }) {
|
||||
const isOfficial = kind === 'primary';
|
||||
const receivedKind = isOfficial ? 'primary_received' : 'shine_received';
|
||||
const givenKind = isOfficial ? 'primary_given' : 'shine_given';
|
||||
@@ -25,9 +25,9 @@ function statusSideHtml({ kind, title, active, received, given, verb }) {
|
||||
<button type="button" class="pf-sc__row" data-profile-list="${receivedKind}" aria-label="${esc(title)}${th('remaining.html_profile_card.confirmed_by')}${Number(received || 0)}">
|
||||
<strong>${Number(received || 0)}</strong><span>${th('screens.profile_card.text_017')}</span>
|
||||
</button>
|
||||
<button type="button" class="pf-sc__row" data-profile-list="${givenKind}" aria-label="${esc(title)}: ${esc(verb)} ${Number(given || 0)}">
|
||||
${showGiven ? `<button type="button" class="pf-sc__row" data-profile-list="${givenKind}" aria-label="${esc(title)}: ${esc(verb)} ${Number(given || 0)}">
|
||||
<strong>${Number(given || 0)}</strong><span>${esc(verb)}</span>
|
||||
</button>
|
||||
</button>` : ''}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
@@ -92,15 +92,11 @@ export function profileCardHtml({ card, login = '', tilesHtml = '', tilesWrapCla
|
||||
const shineGiven = Number(stats.shineGivenCount || 0);
|
||||
const primaryReceived = Number(stats.primaryReceivedCount || 0);
|
||||
const primaryGiven = Number(stats.primaryGivenCount || 0);
|
||||
// Статусы по бокам аватара: слева «Официальный», справа «Сияние». На своём профиле – всегда
|
||||
// (пустая сторона бледнее), на чужом – если статус есть или уже есть подтверждения.
|
||||
const verb = card?.gender === 'female' ? t('screens.profile_card.text_009') : card?.gender === 'male' ? t('screens.profile_card.text_010') : t('screens.profile_card.text_011');
|
||||
const officialSide = (isSelf || official || primaryReceived || primaryGiven)
|
||||
? statusSideHtml({ kind: 'primary', title: t('screens.profile_card.text_001'), active: official, received: primaryReceived, given: primaryGiven, verb })
|
||||
: '';
|
||||
const shineSide = (isSelf || shining || shineReceived || shineGiven)
|
||||
? statusSideHtml({ kind: 'shine', title: t('screens.profile_card.text_002'), active: shining, received: shineReceived, given: shineGiven, verb })
|
||||
: '';
|
||||
const verb = t('screens.registration_identity.given');
|
||||
const officialSide = official
|
||||
? statusSideHtml({ kind: 'primary', title: t('screens.profile_card.text_001'), active: true, received: primaryReceived, given: primaryGiven, verb }) : '';
|
||||
const shineSide = shining
|
||||
? statusSideHtml({ kind: 'shine', title: t('screens.profile_card.text_002'), active: true, received: shineReceived, given: shineGiven, verb, showGiven: official }) : '';
|
||||
|
||||
return `
|
||||
<div class="pf-hero" aria-label="${th('remaining.html_profile_card.profile')}${esc(cardLogin)}">
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
/** В выборе тарифа счётчик не показываем: он начинается с логина. */
|
||||
export function createRegistrationStepper(step) {
|
||||
const current = Math.max(1, Math.min(4, Number(step) || 1));
|
||||
export function createRegistrationStepper(step, total = 4) {
|
||||
const current = Math.max(1, Math.min(total, Number(step) || 1));
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.className = 'signup-stepper';
|
||||
wrapper.setAttribute('aria-label', t('screens.registration_stepper.text_001', { value1: current }));
|
||||
wrapper.setAttribute('aria-label', t('screens.registration_stepper.text_001', { value1: current, value2: total }));
|
||||
const dots = document.createElement('div');
|
||||
dots.className = 'signup-stepper__dots';
|
||||
for (let i = 1; i <= 4; i += 1) {
|
||||
for (let i = 1; i <= total; i += 1) {
|
||||
const dot = document.createElement('span');
|
||||
dot.className = `signup-stepper__dot${i === current ? ' is-active' : ''}${i < current ? ' is-complete' : ''}`;
|
||||
dots.append(dot);
|
||||
}
|
||||
const label = document.createElement('span');
|
||||
label.className = 'signup-stepper__label';
|
||||
label.textContent = t('screens.registration_stepper.text_002', { value1: current });
|
||||
label.textContent = t('screens.registration_stepper.text_002', { value1: current, value2: total });
|
||||
wrapper.append(dots, label);
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
@@ -928,7 +928,7 @@
|
||||
"vzaimnye_znakomstva_i_podtverzhdeniya_drugih_lyude": "Mutual connections and other people’s confirmations can help evaluate claims. The social graph matters, but the number of connections alone proves nothing; exceptions do exist. Independent analysis tools may consider all available public signals together.",
|
||||
"ponimayu_chto_set_otsenivaet_ne_tolko_moyu_galochk": "I understand the network considers more than my own declaration.",
|
||||
"podtverzhdeniya_drugih": "Confirmations of others",
|
||||
"tolko_ofitsialnyy_siyayuschiy_mozhet_podtverzhdat": "Only an official Shining member can confirm another person’s Shining status. False confirmations and artificial relationships can remain in public history and be detected by analysis tools. Confirm only what you genuinely believe.",
|
||||
"tolko_ofitsialnyy_siyayuschiy_mozhet_podtverzhdat": "Only an official Shining member can confirm others who have already declared themselves Shining. False confirmations and artificial relationships can remain in public history and be detected by analysis tools. Confirm only what you genuinely believe.",
|
||||
"budu_podtverzhdat_drugih_dobrosovestno": "I will confirm others in good faith.",
|
||||
"otkrytoe_zayavlenie": "Open statement",
|
||||
"otmetka_siyayuschiy_sozdayot_publichnuyu_zapis_eyo": "Marking yourself as Shining creates a public record. Other services may read and analyze it, and removing your status later will not erase the history. The app may limit what it displays, but deleting the record from distributed copies may be impossible.",
|
||||
@@ -1012,7 +1012,7 @@
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
"secret_generation_overlay": {"title": "Generating your digital keys…", "description": "Generating them from your login and password directly on this device."}
|
||||
"secret_generation_overlay": {"title": "Generating your digital keys…", "description": "Generating keys from your login and password directly on this device. Your private keys are never sent to the server and will be stored only on your device."}
|
||||
},
|
||||
"screens": {
|
||||
"dm_attachments": {
|
||||
@@ -3192,7 +3192,7 @@
|
||||
"text_016": "Confirm if you consider this person a Shining member",
|
||||
"text_017": "<div class=\"relation-manage-confirmation\">✓ You confirmed this person as a Shining member</div>",
|
||||
"text_007": "Could not update connection",
|
||||
"text_009": "This is marked as the primary account",
|
||||
"text_009": "This account is declared official",
|
||||
"text_021": "Connection removed",
|
||||
"text_022": "Added to contacts",
|
||||
"text_023": "Added as a friend",
|
||||
@@ -4229,11 +4229,11 @@
|
||||
"registration_identity": {
|
||||
"title": "Choose your account type",
|
||||
"immutable": "The account type is chosen once at registration and cannot be changed later.",
|
||||
"primary": "Primary account",
|
||||
"primary_detail": "SHiNE counts votes from real people. Each person is entitled to only one primary account.",
|
||||
"alternative": "Alternative account",
|
||||
"alternative_detail": "You may have any number of alternative accounts. Likes and ratings from alternative accounts are counted separately from votes of real people using primary accounts.",
|
||||
"previous_detail": "If you previously had primary accounts, list them. Analysis systems can trace your identity history through social connections, for example when friends move from an old account to your new one. This is only your declaration; previous accounts are not blocked and their votes do not change for now.",
|
||||
"primary": "Official account",
|
||||
"primary_detail": "SHiNE counts the votes of real people separately. Each person may have only one official account. If you had other official accounts, mark them as no longer in use at the next registration step. In the future, a social graph analysis system can assess your declared official status.",
|
||||
"alternative": "Unofficial account",
|
||||
"alternative_detail": "You may have any number of unofficial accounts for communication, creativity and publishing. Their likes and ratings are counted separately from the votes of real people with official accounts.",
|
||||
"previous_detail": "If you lost the password and access to any previous official accounts, list them here. Future analysis can avoid counting their votes as those of separate people and trace changes in your social connections, such as friends moving to your new account. For now, previous accounts are not blocked and their votes are unchanged.",
|
||||
"disclosure": "Your declaration will be publicly recorded in the blockchain and preserved in the public blockchain archive. Analysis systems may check the account status in the future. If you provide false information, it will remain in the public blockchain history. Proof of ownership of previous accounts is not required.",
|
||||
"add": "+ Add account",
|
||||
"remove": "Remove from list",
|
||||
@@ -4241,11 +4241,19 @@
|
||||
"find": "Search",
|
||||
"not_found": "No matching accounts found.",
|
||||
"search_error": "Search failed.",
|
||||
"next": "Continue"
|
||||
"next": "Continue",
|
||||
"previous_title": "Your previous official accounts",
|
||||
"official_help": "Your account is official. Your likes count toward official votes and public SHiNE rankings.",
|
||||
"alternative_help": "Your account is unofficial. You can like posts, but those likes are counted separately in overall statistics and do not count as official votes.",
|
||||
"official_button": "Official account",
|
||||
"alternative_button": "Unofficial account",
|
||||
"ok": "OK",
|
||||
"given": "Confirmed",
|
||||
"other_profile_notification": "This notification is for another account."
|
||||
},
|
||||
"registration_stepper": {
|
||||
"text_001": "Registration: step {value1} out of 4",
|
||||
"text_002": "Step {value1} of 4"
|
||||
"text_001": "Registration: step {value1} out of {value2}",
|
||||
"text_002": "Step {value1} of {value2}"
|
||||
},
|
||||
"network_version_switcher": {
|
||||
"text_001": "<span>Version:</span>",
|
||||
|
||||
@@ -961,7 +961,7 @@
|
||||
"vzaimnye_znakomstva_i_podtverzhdeniya_drugih_lyude": "Взаимные знакомства и подтверждения других людей помогают оценивать заявления. Социальный граф важен, но количество связей само по себе ничего не доказывает: бывают и редкие исключения. Независимые анализаторы могут учитывать всю совокупность открытых сигналов.",
|
||||
"ponimayu_chto_set_otsenivaet_ne_tolko_moyu_galochk": "Понимаю, что сеть оценивает не только мою галочку.",
|
||||
"podtverzhdeniya_drugih": "Подтверждения других",
|
||||
"tolko_ofitsialnyy_siyayuschiy_mozhet_podtverzhdat": "Только официальный сияющий может подтверждать, что другой человек сияющий. Ложные голоса и искусственные связи могут остаться в истории и быть обнаружены анализаторами. Отмечайте только то, в чём действительно уверены.",
|
||||
"tolko_ofitsialnyy_siyayuschiy_mozhet_podtverzhdat": "Только официальный сияющий может подтверждать сияние других людей, уже отметивших себя сияющими. Ложные голоса и искусственные связи могут остаться в истории и быть обнаружены анализаторами. Отмечайте только то, в чём действительно уверены.",
|
||||
"budu_podtverzhdat_drugih_dobrosovestno": "Буду подтверждать других добросовестно.",
|
||||
"otkrytoe_zayavlenie": "Открытое заявление",
|
||||
"otmetka_siyayuschiy_sozdayot_publichnuyu_zapis_eyo": "Отметка «Сияющий» создаёт публичную запись. Её могут прочитать и анализировать другие сервисы; последующая отмена не стирает историю. В приложении возможны меры ограничения отображения, но удалить запись из распределённых копий может быть невозможно.",
|
||||
@@ -1012,7 +1012,7 @@
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
"secret_generation_overlay": {"title": "Генерируем ваши цифровые ключи…", "description": "Генерируем их из вашего логина и пароля непосредственно на этом устройстве."}
|
||||
"secret_generation_overlay": {"title": "Генерируем ваши цифровые ключи…", "description": "Генерируем ключи из вашего логина и пароля непосредственно на этом устройстве. Ваши приватные ключи никогда не передаются на сервер и будут храниться только на вашем устройстве."}
|
||||
},
|
||||
"screens": {
|
||||
"dm_attachments": {
|
||||
@@ -3435,7 +3435,7 @@
|
||||
"text_006": "Не удалось загрузить связь",
|
||||
"text_007": "Не удалось изменить связь",
|
||||
"text_008": "Проверьте соединение и попробуйте ещё раз.",
|
||||
"text_009": "Этот аккаунт отмечен как основной",
|
||||
"text_009": "Этот аккаунт отмечен как официальный",
|
||||
"text_010": "Подтвердите, если это официальный аккаунт этого человека",
|
||||
"text_011": "<div class=\"relation-manage-confirmation\">✓ Вы подтвердили его официальный аккаунт</div>",
|
||||
"text_012": "<div class=\"relation-manage-confirmation\">✓ Этот пользователь подтвердил ваш официальный аккаунт</div>",
|
||||
@@ -4232,11 +4232,11 @@
|
||||
"registration_identity": {
|
||||
"title": "Выберите тип аккаунта",
|
||||
"immutable": "Тип аккаунта выбирается один раз при регистрации и впоследствии не может быть изменён.",
|
||||
"primary": "Основной аккаунт (Primary)",
|
||||
"primary_detail": "В SHiNE учитываются голоса реальных людей. Каждый человек имеет право иметь только один основной аккаунт.",
|
||||
"alternative": "Альтернативный аккаунт (Alternative)",
|
||||
"alternative_detail": "Вы можете иметь любое количество альтернативных аккаунтов. Лайки и рейтинги альтернативных аккаунтов учитываются отдельно от голосов реальных людей с основных аккаунтов.",
|
||||
"previous_detail": "Если у вас ранее были основные аккаунты, укажите их. Система анализа сможет проследить историю вашей личности по социальным связям, например когда друзья переходят от прежнего аккаунта к новому. Это только ваше заявление: прежние аккаунты не блокируются и их голоса пока не меняются.",
|
||||
"primary": "Официальный аккаунт",
|
||||
"primary_detail": "В SHiNE отдельно учитываются голоса реальных людей. Каждый человек имеет право иметь только один официальный аккаунт. Если у вас ранее были другие официальные аккаунты, вам необходимо отметить их как больше неиспользуемые на следующем этапе регистрации. Достоверность официального статуса в будущем будет проверяться системой анализа социального графа.",
|
||||
"alternative": "Неофициальный аккаунт",
|
||||
"alternative_detail": "Вы можете иметь любое количество неофициальных аккаунтов для общения, творчества, публикаций и других целей. Лайки и рейтинги неофициальных аккаунтов учитываются отдельно от голосов реальных людей с официальных аккаунтов.",
|
||||
"previous_detail": "Если у вас ранее были другие официальные аккаунты, от которых вы потеряли пароль и доступ, укажите их. В будущем система анализа сможет не учитывать их голоса как голоса отдельных людей и проследить историю вашей личности по социальным связям, например когда друзья переходят от прежнего аккаунта к новому. Сейчас прежние аккаунты не блокируются и их голоса не меняются.",
|
||||
"disclosure": "Ваше заявление будет публично записано в блокчейн и сохранено в публичном блокчейн-архиве. Статус аккаунта в будущем сможет проверять система анализа. Если вы предоставите ложную информацию, она останется в публичной истории блокчейна. Подтверждать владение прежними аккаунтами не требуется.",
|
||||
"add": "+ Добавить аккаунт",
|
||||
"remove": "Удалить из списка",
|
||||
@@ -4244,11 +4244,19 @@
|
||||
"find": "Найти",
|
||||
"not_found": "Подходящие аккаунты не найдены.",
|
||||
"search_error": "Не удалось выполнить поиск.",
|
||||
"next": "Продолжить"
|
||||
"next": "Продолжить",
|
||||
"previous_title": "Ваши предыдущие официальные аккаунты",
|
||||
"official_help": "Ваш аккаунт является официальным. Ваши лайки учитываются при подсчёте официальных голосов и формировании публичных рейтингов SHiNE.",
|
||||
"alternative_help": "Ваш аккаунт является неофициальным. Вы можете ставить лайки, но они учитываются в общей статистике отдельно и не входят в подсчёт официальных голосов.",
|
||||
"official_button": "Аккаунт официальный",
|
||||
"alternative_button": "Аккаунт неофициальный",
|
||||
"ok": "Понятно",
|
||||
"given": "Подтверждено",
|
||||
"other_profile_notification": "Уведомление предназначено для другого аккаунта."
|
||||
},
|
||||
"registration_stepper": {
|
||||
"text_001": "Регистрация: шаг {value1} из 4",
|
||||
"text_002": "Шаг {value1} из 4"
|
||||
"text_001": "Регистрация: шаг {value1} из {value2}",
|
||||
"text_002": "Шаг {value1} из {value2}"
|
||||
},
|
||||
"topbar_filter_title": {
|
||||
"text_001": "Выбрать раздел «{value1}»",
|
||||
|
||||
@@ -2,7 +2,6 @@ import { t } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import {
|
||||
authService,
|
||||
cancelAddProfileLogin,
|
||||
clearAuthMessages,
|
||||
setAuthBusy,
|
||||
setAuthError,
|
||||
@@ -160,11 +159,6 @@ export function render({ navigate }) {
|
||||
back: {
|
||||
label: '←',
|
||||
onClick: async () => {
|
||||
if (state.authReturnHash === '/profiles') {
|
||||
await cancelAddProfileLogin();
|
||||
navigate('profiles-view');
|
||||
return;
|
||||
}
|
||||
navigate('start-view');
|
||||
},
|
||||
},
|
||||
|
||||
@@ -22,9 +22,6 @@ export const pageMeta = {
|
||||
},
|
||||
};
|
||||
|
||||
const GENDER_MALE = 'male';
|
||||
const GENDER_FEMALE = 'female';
|
||||
const GENDER_UNKNOWN = 'unknown';
|
||||
|
||||
function normalizeLogin(value) {
|
||||
return String(value || '').trim();
|
||||
@@ -64,13 +61,6 @@ function escapeHtml(text) {
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
|
||||
function normalizeGender(value) {
|
||||
const clean = String(value || '').trim().toLowerCase();
|
||||
if (clean === GENDER_MALE) return GENDER_MALE;
|
||||
if (clean === GENDER_FEMALE) return GENDER_FEMALE;
|
||||
return GENDER_UNKNOWN;
|
||||
}
|
||||
|
||||
function toSet(list) {
|
||||
return new Set(uniqueLogins(list).map((value) => normKey(value)));
|
||||
}
|
||||
@@ -117,24 +107,6 @@ function normalizeAvatar(row) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function applyRelativeGender(map, rows) {
|
||||
(Array.isArray(rows) ? rows : []).forEach((row) => {
|
||||
const login = normalizeLogin(row?.login);
|
||||
if (!login) return;
|
||||
const key = normKey(login);
|
||||
const gender = normalizeGender(row?.gender);
|
||||
const prev = map.get(key) || GENDER_UNKNOWN;
|
||||
if (prev === GENDER_UNKNOWN || gender !== GENDER_UNKNOWN) map.set(key, gender);
|
||||
});
|
||||
}
|
||||
|
||||
function getRelativeGenderMap(graph) {
|
||||
const map = new Map();
|
||||
// Родственные связи пока скрыты из UI, хотя сервер продолжает хранить их коды.
|
||||
void graph;
|
||||
return map;
|
||||
}
|
||||
|
||||
function buildGraphModel(graph, centerLogin) {
|
||||
const login = normalizeLogin(graph?.login || centerLogin || state.session.login);
|
||||
const outFriends = toSet(graph?.outFriends);
|
||||
@@ -156,7 +128,6 @@ function buildGraphModel(graph, centerLogin) {
|
||||
role: 'friend',
|
||||
relationType: hasLogin(outCloseFriends, targetLogin) ? 'close_friend' : 'friend',
|
||||
isRelative: false,
|
||||
gender: GENDER_UNKNOWN,
|
||||
forward: true,
|
||||
backward: hasLogin(inCloseFriends, targetLogin) || hasLogin(inFriends, targetLogin),
|
||||
mark: allMarks.get(normKey(targetLogin)) || null,
|
||||
|
||||
@@ -22,16 +22,8 @@ const CONNECTION_OFFICIAL_UNCONFIRMED = 81;
|
||||
const profileSnapshotCache = new Map();
|
||||
const profileSnapshotPending = new Map();
|
||||
|
||||
// Глагол по полу из профиля автора («Добавила вас в друзья»); пока профиль не пришёл или пол
|
||||
// не указан – нейтральное «Добавил(а)».
|
||||
function byGender(gender, male, female, neutral) {
|
||||
if (gender === 'male') return male;
|
||||
if (gender === 'female') return female;
|
||||
return neutral;
|
||||
}
|
||||
|
||||
function connectionActionLabel(typeCode, gender = '') {
|
||||
const verb = (male, female) => byGender(gender, male, female, t('screens.notifications_view.text_032', { value1: male }));
|
||||
function connectionActionLabel(typeCode) {
|
||||
const verb = (male, female) => t('screens.notifications_view.text_032', { value1: male });
|
||||
switch (Number(typeCode)) {
|
||||
case CONNECTION_CLOSE_FRIEND: return t('screens.notifications_view.text_033', { value1: verb(t('screens.notifications_view.text_047'), t('screens.notifications_view.text_048')) });
|
||||
case CONNECTION_UNCLOSE_FRIEND: return t('screens.notifications_view.text_034', { value1: verb(t('screens.notifications_view.text_049'), t('screens.notifications_view.text_050')) });
|
||||
@@ -45,16 +37,15 @@ function connectionActionLabel(typeCode, gender = '') {
|
||||
}
|
||||
}
|
||||
|
||||
function eventActionLabel(typeCode, gender = '') {
|
||||
if (Number(typeCode) === CONNECTION_UNFOLLOW) return t('screens.notifications_view.text_042', { value1: byGender(gender, t('screens.notifications_view.text_065'), t('screens.notifications_view.text_066'), t('screens.notifications_view.text_067')) });
|
||||
return t('screens.notifications_view.text_043', { value1: byGender(gender, t('screens.notifications_view.text_068'), t('screens.notifications_view.text_069'), t('screens.notifications_view.text_070')) });
|
||||
function eventActionLabel(typeCode) {
|
||||
if (Number(typeCode) === CONNECTION_UNFOLLOW) return t('screens.notifications_view.text_042', { value1: t('screens.notifications_view.text_067') });
|
||||
return t('screens.notifications_view.text_043', { value1: t('screens.notifications_view.text_070') });
|
||||
}
|
||||
|
||||
function actionLabel(item, activeTab) {
|
||||
const gender = String(item.profile?.gender || '');
|
||||
return activeTab === 'connections'
|
||||
? connectionActionLabel(item.connectionTypeCode ?? item.sourceMsgSubType, gender)
|
||||
: eventActionLabel(item.sourceMsgSubType, gender);
|
||||
? connectionActionLabel(item.connectionTypeCode ?? item.sourceMsgSubType)
|
||||
: eventActionLabel(item.sourceMsgSubType);
|
||||
}
|
||||
|
||||
function reciprocalRelationKind(item) {
|
||||
|
||||
@@ -8,14 +8,10 @@ import { showToast } from '../services/channels-ux.js';
|
||||
import { profile } from '../mock-data.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import {
|
||||
PROFILE_GENDER_FEMALE,
|
||||
PROFILE_GENDER_MALE,
|
||||
PROFILE_GENDER_UNKNOWN,
|
||||
PROFILE_ACCOUNT_ROLE_PRIMARY,
|
||||
PROFILE_SHINE_SHINING,
|
||||
PROFILE_SHINE_UNKNOWN,
|
||||
loadProfileSnapshot,
|
||||
saveProfileGender,
|
||||
saveProfileParamBlock,
|
||||
saveProfileStatus,
|
||||
} from '../services/user-profile-params.js';
|
||||
@@ -25,10 +21,6 @@ import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
|
||||
export const pageMeta = { id: 'profile-edit-view', get title() { return t('screens.profile_edit_view.text_001'); } };
|
||||
|
||||
function accountRoleLabel(value) {
|
||||
return value === PROFILE_ACCOUNT_ROLE_PRIMARY ? t('screens.profile_edit_view.text_009') : t('screens.profile_edit_view.text_010');
|
||||
}
|
||||
|
||||
function shineStatusLabel(value) {
|
||||
return value === PROFILE_SHINE_SHINING ? t('screens.profile_edit_view.text_011') : t('screens.profile_edit_view.text_012');
|
||||
}
|
||||
@@ -53,18 +45,6 @@ function showLocalErrorAlert(prefix, error) {
|
||||
showToast(`${prefix}. ${toUserMessage(error, t('screens.profile_edit_view.text_006'))}`, { kind: 'error' });
|
||||
}
|
||||
|
||||
function genderLabel(value) {
|
||||
if (value === PROFILE_GENDER_MALE) return t('screens.profile_edit_view.text_013');
|
||||
if (value === PROFILE_GENDER_FEMALE) return t('screens.profile_edit_view.text_014');
|
||||
return t('screens.profile_edit_view.text_015');
|
||||
}
|
||||
|
||||
const GENDER_OPTIONS = Object.freeze([
|
||||
{ value: PROFILE_GENDER_MALE, get label() { return t('screens.profile_edit_view.text_002'); } },
|
||||
{ value: PROFILE_GENDER_FEMALE, get label() { return t('screens.profile_edit_view.text_003'); } },
|
||||
{ value: PROFILE_GENDER_UNKNOWN, get label() { return t('screens.profile_edit_view.text_004'); } },
|
||||
]);
|
||||
|
||||
function escapeHtml(text) {
|
||||
return String(text || '')
|
||||
.replaceAll('&', '&')
|
||||
@@ -107,7 +87,7 @@ export function render({ navigate, chrome }) {
|
||||
const badgesRow = document.createElement('div');
|
||||
badgesRow.className = 'chip-row profile-edit-statuses';
|
||||
badgesRow.innerHTML = `
|
||||
<span class="badge is-no" data-status="account_role">${th('screens.profile_edit_view.text_029')}</span>
|
||||
<button type="button" class="badge profile-account-info is-no" data-status="account_role">${th('screens.registration_identity.alternative_button')}</button>
|
||||
<button class="chip profile-toggle-btn is-no" type="button" data-status="shine">${th('screens.profile_edit_view.text_030')}</button>
|
||||
`;
|
||||
|
||||
@@ -125,66 +105,12 @@ export function render({ navigate, chrome }) {
|
||||
|
||||
let currentFields = [];
|
||||
let currentAccountRole = '';
|
||||
let currentAccountType = null;
|
||||
let currentShineStatus = '';
|
||||
let currentGender = PROFILE_GENDER_UNKNOWN;
|
||||
let statusFlowOpen = false;
|
||||
let currentAvatar = { value: '', source: '', txId: '', pr: '', timeMs: 0 };
|
||||
const identityEl = topRow.querySelector('[data-profile-identity="true"]');
|
||||
const avatarSlotEl = topRow.querySelector('[data-profile-avatar-slot="true"]');
|
||||
|
||||
function openGenderPickerModal(initialGender) {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!root) return Promise.resolve(null);
|
||||
root.innerHTML = '';
|
||||
|
||||
const selected = GENDER_OPTIONS.some((item) => item.value === initialGender)
|
||||
? initialGender
|
||||
: PROFILE_GENDER_UNKNOWN;
|
||||
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="profile-gender-modal">
|
||||
<div class="modal-card stack">
|
||||
<h3 class="modal-title">${t('dialogs.modals.profile_edit_view.label_001')}</h3>
|
||||
<p class="meta-muted">${t('dialogs.modals.profile_edit_view.label_002')}</p>
|
||||
<select class="input profile-gender-select" id="profile-gender-select">
|
||||
${GENDER_OPTIONS.map((item) => (
|
||||
`<option value="${item.value}" ${item.value === selected ? 'selected' : ''}>${item.label}</option>`
|
||||
)).join('')}
|
||||
</select>
|
||||
<div class="form-actions-grid">
|
||||
<button class="secondary-btn" id="profile-gender-cancel" type="button">${t('dialogs.remaining.pages.profile_edit_view.markup.otmena')}</button>
|
||||
<button class="primary-btn" id="profile-gender-save" type="button">${t('dialogs.remaining.pages.profile_edit_view.markup.sohranit')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const modal = root.querySelector('#profile-gender-modal');
|
||||
const selectEl = root.querySelector('#profile-gender-select');
|
||||
const saveEl = root.querySelector('#profile-gender-save');
|
||||
const cancelEl = root.querySelector('#profile-gender-cancel');
|
||||
if (!(modal instanceof HTMLElement) || !(selectEl instanceof HTMLSelectElement)) {
|
||||
root.innerHTML = '';
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const close = (value = null) => {
|
||||
root.innerHTML = '';
|
||||
resolve(value);
|
||||
};
|
||||
|
||||
modal.addEventListener('click', (event) => {
|
||||
if (event.target === modal) close(null);
|
||||
});
|
||||
cancelEl?.addEventListener('click', () => close(null));
|
||||
saveEl?.addEventListener('click', () => close(selectEl.value || PROFILE_GENDER_UNKNOWN));
|
||||
window.setTimeout(() => selectEl.focus(), 0);
|
||||
});
|
||||
}
|
||||
|
||||
function syncIdentity() {
|
||||
if (!identityEl) return;
|
||||
const firstName = currentFields.find((field) => field.key === 'first_name')?.value || '';
|
||||
@@ -217,9 +143,7 @@ export function render({ navigate, chrome }) {
|
||||
|
||||
function updateStatusesUi() {
|
||||
if (accountRoleBtn) {
|
||||
accountRoleBtn.textContent = currentAccountType === 1 ? t('screens.profile_edit_view.text_009')
|
||||
: currentAccountType === 0 ? t('screens.registration_identity.alternative')
|
||||
: t('screens.profile_edit_view.text_020', { value1: accountRoleLabel(currentAccountRole) });
|
||||
accountRoleBtn.textContent = t(currentAccountRole === PROFILE_ACCOUNT_ROLE_PRIMARY ? 'screens.registration_identity.official_button' : 'screens.registration_identity.alternative_button');
|
||||
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');
|
||||
}
|
||||
@@ -231,12 +155,6 @@ export function render({ navigate, chrome }) {
|
||||
}
|
||||
}
|
||||
|
||||
function updateGenderUi() {
|
||||
const genderValueEl = listWrap.querySelector('[data-gender-value]');
|
||||
if (!genderValueEl) return;
|
||||
genderValueEl.textContent = genderLabel(currentGender);
|
||||
}
|
||||
|
||||
function openFieldEditModal({ label, value, placeholder = '', maxLength = 300, multiline = false, suggestions = null }) {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!root) return Promise.resolve(null);
|
||||
@@ -314,16 +232,6 @@ export function render({ navigate, chrome }) {
|
||||
row.innerHTML = `<span class="nav-row__hint">${escapeHtml(field.label)}</span><span class="nav-row__label${value ? '' : ' is-empty'}">${escapeHtml(value || t('screens.profile_edit_view.text_019'))}</span>`;
|
||||
listWrap.append(row);
|
||||
|
||||
if (field.key === 'last_name') {
|
||||
const genderRow = document.createElement('button');
|
||||
genderRow.type = 'button';
|
||||
genderRow.className = 'nav-row profile-param-item';
|
||||
genderRow.dataset.editGender = 'true';
|
||||
const genderText = genderLabel(currentGender);
|
||||
const genderEmpty = currentGender !== PROFILE_GENDER_MALE && currentGender !== PROFILE_GENDER_FEMALE;
|
||||
genderRow.innerHTML = `<span class="nav-row__hint">${th('screens.profile_edit_view.text_031')}</span><span class="nav-row__label${genderEmpty ? ' is-empty' : ''}" data-gender-value>${escapeHtml(genderEmpty ? t('screens.profile_edit_view.text_016') : genderText)}</span>`;
|
||||
listWrap.append(genderRow);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -337,15 +245,12 @@ export function render({ navigate, chrome }) {
|
||||
const snapshot = await loadProfileSnapshot(login);
|
||||
currentFields = snapshot.fields;
|
||||
currentAccountRole = snapshot.accountRole || '';
|
||||
currentAccountType = snapshot.accountType;
|
||||
currentShineStatus = snapshot.shineStatus || '';
|
||||
currentGender = snapshot.gender || PROFILE_GENDER_UNKNOWN;
|
||||
currentAvatar = snapshot.avatar || { value: '', source: '', txId: '', pr: '', timeMs: 0 };
|
||||
|
||||
syncIdentity();
|
||||
renderFields(currentFields);
|
||||
updateStatusesUi();
|
||||
updateGenderUi();
|
||||
updateAvatarUi();
|
||||
|
||||
status.className = 'status-line';
|
||||
@@ -462,38 +367,9 @@ export function render({ navigate, chrome }) {
|
||||
}
|
||||
}
|
||||
|
||||
async function onGenderClick() {
|
||||
const nextGender = await openGenderPickerModal(currentGender);
|
||||
if (!nextGender || nextGender === currentGender) return;
|
||||
const accepted = await confirmPublicHistoryAction({
|
||||
title: t('dialogs.final.consent.gender_publish_title'),
|
||||
text: t('dialogs.final.consent.public_history_warning'),
|
||||
confirmLabel: t('dialogs.final.consent.record_yes'),
|
||||
cancelLabel: t('dialogs.final.consent.record_no'),
|
||||
});
|
||||
if (!accepted || !screen.isConnected) return;
|
||||
|
||||
status.className = 'status-line';
|
||||
status.textContent = t('dialogs.modals.profile_edit_view.label_009');
|
||||
|
||||
try {
|
||||
await saveProfileGender(login, nextGender);
|
||||
await refreshProfileSnapshot();
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = t('screens.profile_edit_view.text_027', { value1: toUserMessage(error, t('dialogs.modals.profile_edit_view.label_010')) });
|
||||
showLocalErrorAlert(t('screens.profile_edit_view.text_008'), error);
|
||||
}
|
||||
}
|
||||
|
||||
listWrap.addEventListener('click', (event) => {
|
||||
const target = event.target;
|
||||
if (!(target instanceof HTMLElement)) return;
|
||||
const genderRow = target.closest('[data-edit-gender="true"]');
|
||||
if (genderRow) {
|
||||
onGenderClick();
|
||||
return;
|
||||
}
|
||||
const fieldRow = target.closest('[data-edit-field]');
|
||||
const fieldKey = String(fieldRow?.getAttribute('data-edit-field') || '');
|
||||
if (!fieldKey) return;
|
||||
@@ -501,7 +377,10 @@ export function render({ navigate, chrome }) {
|
||||
});
|
||||
|
||||
reloadBtn.addEventListener('click', refreshProfileSnapshot);
|
||||
accountRoleBtn.title = t('screens.registration_identity.immutable');
|
||||
accountRoleBtn.addEventListener('click', () => {
|
||||
const official = currentAccountRole === PROFILE_ACCOUNT_ROLE_PRIMARY;
|
||||
void confirmDialog({ title: accountRoleBtn.textContent, text: t(official ? 'screens.registration_identity.official_help' : 'screens.registration_identity.alternative_help') + '\n\n' + t('screens.registration_identity.immutable'), confirmLabel: t('screens.registration_identity.ok'), infoOnly: true });
|
||||
});
|
||||
shineBtn.addEventListener('click', () => onStatusClick('shine'));
|
||||
avatarActionEl?.addEventListener('click', () => { void onChangeAvatarClick(); });
|
||||
|
||||
|
||||
@@ -62,10 +62,7 @@ export function render({ navigate, chrome }) {
|
||||
profileTileHtml({ icon: 'wallet', label: t('screens.profile_view.text_008'), attrs: 'data-self-profile-action="wallet"' }),
|
||||
profileTileHtml({ icon: 'settings', label: t('screens.profile_view.text_009'), attrs: 'data-self-profile-action="settings"' }),
|
||||
].join(''),
|
||||
}) + `
|
||||
<div class="nav-list profile-more-list">
|
||||
<button class="nav-row" type="button" data-self-profile-action="profiles"><span class="nav-row__label">${th('screens.profile_view.text_015')}</span><span class="nav-row__hint">${th('screens.profile_view.text_016')}</span></button>
|
||||
</div>`;
|
||||
});
|
||||
|
||||
attachSupportStats(body, { login: card.login || login, isActive: () => !disposed });
|
||||
avatarPreview = attachProfileAvatarPreview(body.querySelector('.user-profile-avatar-slot'), card);
|
||||
@@ -89,7 +86,6 @@ 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;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { t } from '../i18n/index.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import {
|
||||
MULTI_PROFILE_ENABLED,
|
||||
closeAllSavedProfiles,
|
||||
closeSavedProfile,
|
||||
getSavedProfiles,
|
||||
@@ -18,6 +19,10 @@ function reloadTo(path) {
|
||||
}
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
if (!MULTI_PROFILE_ENABLED) {
|
||||
queueMicrotask(() => navigate('profile-view'));
|
||||
return document.createElement('section');
|
||||
}
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack profiles-screen';
|
||||
|
||||
|
||||
@@ -37,6 +37,10 @@ export function render({ navigate }) {
|
||||
return window.confirm(t('screens.register_view.text_039'));
|
||||
}
|
||||
function goBack() {
|
||||
if (Number(draft.uiStep) === 4) {
|
||||
showAccountType();
|
||||
return;
|
||||
}
|
||||
if (Number(draft.uiStep) === 3) {
|
||||
showPassword();
|
||||
return;
|
||||
@@ -70,7 +74,7 @@ export function render({ navigate }) {
|
||||
}
|
||||
function showLogin() {
|
||||
draft.uiStep = 1;
|
||||
body.replaceChildren(createRegistrationStepper(1));
|
||||
body.replaceChildren(createRegistrationStepper(1, draft.accountType === 1 ? 5 : 4));
|
||||
const [heading, description] = title(t('screens.register_view.text_014'), t('screens.register_view.text_015'));
|
||||
const label = document.createElement('label');
|
||||
label.className = 'stack';
|
||||
@@ -143,7 +147,7 @@ export function render({ navigate }) {
|
||||
}
|
||||
function showPassword() {
|
||||
draft.uiStep = 2;
|
||||
body.replaceChildren(createRegistrationStepper(2));
|
||||
body.replaceChildren(createRegistrationStepper(2, draft.accountType === 1 ? 5 : 4));
|
||||
const [heading, description] = title(t('screens.register_view.text_016'), t('screens.register_view.text_017'));
|
||||
const label = document.createElement('label');
|
||||
label.className = 'stack';
|
||||
@@ -238,7 +242,7 @@ export function render({ navigate }) {
|
||||
|
||||
function showAccountType() {
|
||||
draft.uiStep = 3;
|
||||
body.replaceChildren(createRegistrationStepper(3));
|
||||
body.replaceChildren(createRegistrationStepper(3, draft.accountType === 1 ? 5 : 4));
|
||||
const tr = key => t(`screens.registration_identity.${key}`);
|
||||
const [heading, description] = title(tr('title'), tr('immutable'));
|
||||
const choices = document.createElement('div'); choices.className = 'stack';
|
||||
@@ -249,12 +253,33 @@ export function render({ navigate }) {
|
||||
const titleRow = document.createElement('strong'); titleRow.append(radio, ' ' + tr(name));
|
||||
const p = document.createElement('p'); p.textContent = tr(detail);
|
||||
label.append(titleRow, p); choices.append(label);
|
||||
radio.addEventListener('change', () => { draft.accountType = type; refresh(); });
|
||||
radio.addEventListener('change', () => { draft.accountType = type; next.disabled = false; body.firstElementChild.replaceWith(createRegistrationStepper(3, type === 1 ? 5 : 4)); });
|
||||
};
|
||||
option(1, 'primary', 'primary_detail');
|
||||
option(0, 'alternative', 'alternative_detail');
|
||||
const status = statusLine();
|
||||
const next = document.createElement('button'); next.type = 'button'; next.className = 'primary-btn signup-next'; next.textContent = tr('next');
|
||||
next.disabled = ![0, 1].includes(draft.accountType);
|
||||
next.addEventListener('click', () => {
|
||||
if (draft.accountType === 1) showPreviousAccounts();
|
||||
else if (draft.accountType === 0) { draft.previousAccounts = []; finishIdentity(status); }
|
||||
});
|
||||
body.append(heading, description, choices, status, next);
|
||||
}
|
||||
|
||||
function finishIdentity(status) {
|
||||
try {
|
||||
savePendingHeaderIdentity(draft.login, draft.preGeneratedKeyBundle?.blockchainPair?.publicKeyB64, draft);
|
||||
navigate(flowType === 'free' ? 'registration-email-view' : 'registration-payment-view');
|
||||
} catch (error) { status.textContent = error.message; }
|
||||
}
|
||||
|
||||
function showPreviousAccounts() {
|
||||
draft.uiStep = 4;
|
||||
body.replaceChildren(createRegistrationStepper(4, 5));
|
||||
const tr = key => t(`screens.registration_identity.${key}`);
|
||||
const [heading, description] = title(tr('previous_title'), tr('previous_detail'));
|
||||
const previous = document.createElement('div'); previous.className = 'stack';
|
||||
const explanation = document.createElement('p'); explanation.textContent = tr('previous_detail');
|
||||
const disclosure = document.createElement('p'); disclosure.className = 'signup-guidance'; disclosure.textContent = tr('disclosure');
|
||||
const list = document.createElement('div'); list.className = 'stack';
|
||||
const add = document.createElement('button'); add.type = 'button'; add.className = 'secondary-btn'; add.textContent = tr('add');
|
||||
@@ -264,12 +289,10 @@ export function render({ navigate }) {
|
||||
const results = document.createElement('div'); results.className = 'stack';
|
||||
const status = statusLine();
|
||||
searchBox.append(input, search, results);
|
||||
previous.append(explanation, list, add, searchBox, disclosure);
|
||||
previous.append(list, add, searchBox, disclosure);
|
||||
const next = document.createElement('button'); next.type = 'button'; next.className = 'primary-btn signup-next'; next.textContent = tr('next');
|
||||
let queryRevision = 0;
|
||||
function refresh() {
|
||||
previous.hidden = draft.accountType !== 1;
|
||||
next.disabled = draft.accountType === null;
|
||||
list.replaceChildren();
|
||||
for (const login of draft.previousAccounts) {
|
||||
const row = document.createElement('div'); row.className = 'signup-full-login';
|
||||
@@ -289,7 +312,7 @@ export function render({ navigate }) {
|
||||
const revision = ++queryRevision; results.replaceChildren(); status.textContent = '';
|
||||
try {
|
||||
const users = await authService.searchPeople(query, { limit: 20 });
|
||||
if (!screen.isConnected || draft.uiStep !== 3 || revision !== queryRevision || draft.accountType !== 1) return;
|
||||
if (!screen.isConnected || draft.uiStep !== 4 || revision !== queryRevision || draft.accountType !== 1) return;
|
||||
const seen = new Set([draft.login, ...draft.previousAccounts].map(v => v.toLowerCase()));
|
||||
for (const user of users) {
|
||||
const login = String(user?.login || '');
|
||||
@@ -306,22 +329,16 @@ export function render({ navigate }) {
|
||||
if (!results.childElementCount) status.textContent = tr('not_found');
|
||||
} catch (error) { if (screen.isConnected && revision === queryRevision) status.textContent = error.message || tr('search_error'); }
|
||||
});
|
||||
next.addEventListener('click', () => {
|
||||
if (![0, 1].includes(draft.accountType)) return;
|
||||
try {
|
||||
if (draft.accountType === 0) draft.previousAccounts = [];
|
||||
savePendingHeaderIdentity(draft.login, draft.preGeneratedKeyBundle?.blockchainPair?.publicKeyB64, draft);
|
||||
navigate(flowType === 'free' ? 'registration-email-view' : 'registration-payment-view');
|
||||
} catch (error) { status.textContent = error.message; }
|
||||
});
|
||||
body.append(heading, description, choices, previous, status, next); refresh();
|
||||
next.addEventListener('click', () => finishIdentity(status));
|
||||
body.append(heading, description, previous, status, next); refresh();
|
||||
}
|
||||
|
||||
if (flowType !== 'free' && flowType !== 'paid') {
|
||||
queueMicrotask(() => navigate('registration-choice-view'));
|
||||
return screen;
|
||||
}
|
||||
if (Number(draft.uiStep) === 3 && draft.login && draft.preGeneratedKeyBundle) showAccountType();
|
||||
if (Number(draft.uiStep) === 4 && draft.accountType === 1 && draft.login && draft.preGeneratedKeyBundle) showPreviousAccounts();
|
||||
else if (Number(draft.uiStep) === 3 && draft.login && draft.preGeneratedKeyBundle) showAccountType();
|
||||
else if (Number(draft.uiStep) === 2 && draft.login) showPassword();
|
||||
else showLogin();
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ export function render({ navigate }) {
|
||||
edit.className = 'ghost-btn';
|
||||
edit.textContent = t('screens.registration_email_view.text_011');
|
||||
|
||||
form.append(createRegistrationStepper(4), title, lead, inputLabel, info, status, next, codeLabel, codeInfo, confirm, resend, edit);
|
||||
form.append(createRegistrationStepper(state.registrationDraft.accountType === 1 ? 5 : 4, state.registrationDraft.accountType === 1 ? 5 : 4), title, lead, inputLabel, info, status, next, codeLabel, codeInfo, confirm, resend, edit);
|
||||
let disposed = false;
|
||||
let emailRequestId = 0;
|
||||
let confirming = false;
|
||||
@@ -207,6 +207,6 @@ export function render({ navigate }) {
|
||||
} else {
|
||||
showEmail();
|
||||
}
|
||||
screen.append(createTopBar({ title: t('screens.registration_email_view.text_025'), back: { label: '←', onClick: () => { draft.uiStep = 3; navigate('register-view'); } } }), form);
|
||||
screen.append(createTopBar({ title: t('screens.registration_email_view.text_025'), back: { label: '←', onClick: () => { draft.uiStep = draft.accountType === 1 ? 4 : 3; navigate('register-view'); } } }), form);
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -446,14 +446,14 @@ export function render({ navigate }) {
|
||||
card.append(testHint);
|
||||
}
|
||||
card.append(submitButton, status);
|
||||
card.prepend(createRegistrationStepper(4));
|
||||
card.prepend(createRegistrationStepper(state.registrationDraft.accountType === 1 ? 5 : 4, state.registrationDraft.accountType === 1 ? 5 : 4));
|
||||
|
||||
screen.append(
|
||||
createTopBar({
|
||||
title: t('screens.registration_payment_view.text_022'),
|
||||
back: { label: '←', onClick: () => {
|
||||
if (parseBalanceSol(state.registrationPayment.balanceSOL) > 0 && !window.confirm(t('screens.registration_payment_view.text_071'))) return;
|
||||
state.registrationDraft.uiStep = 3; navigate('register-view');
|
||||
state.registrationDraft.uiStep = state.registrationDraft.accountType === 1 ? 4 : 3; navigate('register-view');
|
||||
} },
|
||||
}),
|
||||
card,
|
||||
|
||||
@@ -91,7 +91,7 @@ export function render({ navigate, route, chrome }) {
|
||||
else if (theyFriend) { label = t('screens.user_profile_view.text_016'); hint = t('screens.user_profile_view.text_017'); }
|
||||
else if (r.inContact) {
|
||||
label = t('screens.user_profile_view.text_018');
|
||||
hint = t('screens.user_profile_view.text_019', { value1: card.gender === 'female' ? t('screens.user_profile_view.text_010') : card.gender === 'male' ? t('screens.user_profile_view.text_011') : t('screens.user_profile_view.text_012') });
|
||||
hint = t('screens.user_profile_view.text_019', { value1: t('screens.user_profile_view.text_012') });
|
||||
}
|
||||
tile.innerHTML = `${iconHtml(icon)}<span></span>`;
|
||||
tile.querySelector('span').textContent = label;
|
||||
|
||||
@@ -285,7 +285,7 @@ export function parseRouteFromPath(pathname = '') {
|
||||
}
|
||||
|
||||
if (pageId === 'profiles') {
|
||||
return { pageId: 'profiles-view', params: {} };
|
||||
return { pageId: 'profile-view', params: {} }; // Multi-profile mode temporarily disabled.
|
||||
}
|
||||
|
||||
if (pageId === 'messages') {
|
||||
|
||||
@@ -7,5 +7,5 @@ export function confirmationRights(actor, target) {
|
||||
const a = String(actor?.login || '').trim().toLowerCase();
|
||||
const b = String(target?.login || '').trim().toLowerCase();
|
||||
const primary = Boolean(a && b && a !== b && actor?.accountRole === 'primary' && target?.accountRole === 'primary');
|
||||
return { primary, shine: primary && actor?.shineStatus === 'shining' && target?.shineStatus !== 'not_interested' };
|
||||
return { primary, shine: Boolean(a && b && a !== b && actor?.accountRole === 'primary' && actor?.shineStatus === 'shining' && target?.shineStatus === 'shining') };
|
||||
}
|
||||
|
||||
@@ -260,7 +260,6 @@ export async function loadUserProfileCard(login) {
|
||||
spiritualPath: fields.spiritual_path || '',
|
||||
accountRole: String(snapshot?.accountRole || '').trim().toLowerCase(),
|
||||
shineStatus: String(snapshot?.shineStatus || '').trim().toLowerCase(),
|
||||
gender: String(snapshot?.gender || 'unknown').trim().toLowerCase() || 'unknown',
|
||||
// Compatibility aliases for older graph/card consumers; values come only from the new profile schema.
|
||||
official: String(snapshot?.accountRole || '').trim().toLowerCase() === 'primary',
|
||||
shine: String(snapshot?.shineStatus || '').trim().toLowerCase() === 'shining',
|
||||
|
||||
@@ -26,15 +26,6 @@ export const PROFILE_SHINE_SHINING = 'shining';
|
||||
export const PROFILE_SHINE_UNKNOWN = 'unknown';
|
||||
export const PROFILE_SHINE_NOT_INTERESTED = 'not_interested';
|
||||
|
||||
export const PROFILE_GENDER_MALE = 'male';
|
||||
export const PROFILE_GENDER_FEMALE = 'female';
|
||||
export const PROFILE_GENDER_UNKNOWN = 'unknown';
|
||||
export const PROFILE_GENDER_VALUES = Object.freeze([
|
||||
PROFILE_GENDER_MALE,
|
||||
PROFILE_GENDER_FEMALE,
|
||||
PROFILE_GENDER_UNKNOWN,
|
||||
]);
|
||||
|
||||
function normalizeItem(param, payload) {
|
||||
if (!param) return null;
|
||||
|
||||
@@ -53,13 +44,6 @@ function parseToggleValue(value) {
|
||||
return normalized === 'true' || normalized === 'yes' || normalized === '1';
|
||||
}
|
||||
|
||||
function normalizeGenderValue(value) {
|
||||
const normalized = String(value || '').trim().toLowerCase();
|
||||
if (normalized === PROFILE_GENDER_MALE) return PROFILE_GENDER_MALE;
|
||||
if (normalized === PROFILE_GENDER_FEMALE) return PROFILE_GENDER_FEMALE;
|
||||
return PROFILE_GENDER_UNKNOWN;
|
||||
}
|
||||
|
||||
async function getStoragePwd() {
|
||||
const storagePwd = state.session.storagePwdInMemory;
|
||||
if (!storagePwd) {
|
||||
@@ -75,7 +59,7 @@ function normalizeListItems(payload) {
|
||||
const row = rows[i];
|
||||
if (!row || typeof row !== 'object') continue;
|
||||
const param = String(row.param || '').trim();
|
||||
if (!param) continue;
|
||||
if (!param || param.toLowerCase() === 'gender') continue;
|
||||
const item = normalizeItem(param, row);
|
||||
if (item) normalized.push(item);
|
||||
}
|
||||
@@ -135,8 +119,6 @@ export async function loadProfileSnapshot(login) {
|
||||
{ key: 'shine', get label() { return t('remaining.profile_fields.shine'); }, enabled: shineStatus === PROFILE_SHINE_SHINING, rawValue: shineStatus, timeMs: latestShine?.timeMs || 0 },
|
||||
];
|
||||
|
||||
const latestGender = loadLatestByAliasesFromItems(items, ['gender']);
|
||||
const gender = normalizeGenderValue(latestGender?.value || PROFILE_GENDER_UNKNOWN);
|
||||
const latestAvatar = loadLatestByAliasesFromItems(items, ['ava']);
|
||||
const parsedAvatar = parseAvatarReference(latestAvatar?.value || '');
|
||||
const avatar = parsedAvatar.ok
|
||||
@@ -168,8 +150,6 @@ export async function loadProfileSnapshot(login) {
|
||||
accountRoleTimeMs: latestAccountRole?.timeMs || 0,
|
||||
shineStatus,
|
||||
shineTimeMs: latestShine?.timeMs || 0,
|
||||
gender,
|
||||
genderTimeMs: latestGender?.timeMs || 0,
|
||||
avatar,
|
||||
};
|
||||
}
|
||||
@@ -181,6 +161,7 @@ export function profileDisplayName(snapshot, fallback = '') {
|
||||
}
|
||||
|
||||
export async function saveProfileParamBlock(login, key, value) {
|
||||
if (String(key).trim().toLowerCase() === 'gender') throw new Error('gender_disabled');
|
||||
const storagePwd = await getStoragePwd();
|
||||
await authService.addBlockUserParam({
|
||||
login,
|
||||
@@ -210,17 +191,6 @@ export async function saveProfileToggle(login, key, enabled) {
|
||||
throw new Error(`Неизвестный legacy toggle: ${key}`);
|
||||
}
|
||||
|
||||
export async function saveProfileGender(login, gender) {
|
||||
const normalized = normalizeGenderValue(gender);
|
||||
const storagePwd = await getStoragePwd();
|
||||
await authService.addBlockUserParam({
|
||||
login,
|
||||
param: 'gender',
|
||||
value: normalized,
|
||||
storagePwd,
|
||||
});
|
||||
}
|
||||
|
||||
export async function saveProfileAvatar(login, avatar) {
|
||||
const ar = String(avatar?.ar || '').trim();
|
||||
const pr = String(avatar?.pr || '').trim();
|
||||
|
||||
+18
-3
@@ -218,6 +218,9 @@ function persistProfileStoreRaw(items) {
|
||||
}
|
||||
}
|
||||
|
||||
// MULTI-PROFILE MODE: temporarily disabled. Preserve dormant implementation.
|
||||
export const MULTI_PROFILE_ENABLED = false;
|
||||
|
||||
function getActiveProfileLoginRaw() {
|
||||
try {
|
||||
return normalizeProfileLogin(localStorage.getItem(ACTIVE_PROFILE_STORAGE_KEY));
|
||||
@@ -297,7 +300,7 @@ function loadStoredSession() {
|
||||
const profiles = loadProfileStoreRaw();
|
||||
if (profiles.length) {
|
||||
const activeLogin = getActiveProfileLoginRaw();
|
||||
const active = profiles.find((item) => normalizeProfileLogin(item.login) === activeLogin) || profiles[0];
|
||||
const active = profiles.find((item) => normalizeProfileLogin(item.login) === activeLogin) || (MULTI_PROFILE_ENABLED ? profiles[0] : null);
|
||||
if (active) {
|
||||
setActiveProfileLoginRaw(active.login);
|
||||
return {
|
||||
@@ -358,7 +361,7 @@ function loadStoredEntrySettings() {
|
||||
const profiles = loadProfileStoreRaw();
|
||||
if (profiles.length) {
|
||||
const activeLogin = getActiveProfileLoginRaw();
|
||||
const active = profiles.find((item) => normalizeProfileLogin(item.login) === activeLogin) || profiles[0];
|
||||
const active = profiles.find((item) => normalizeProfileLogin(item.login) === activeLogin) || (MULTI_PROFILE_ENABLED ? profiles[0] : null);
|
||||
if (active?.entrySettings && typeof active.entrySettings === 'object') {
|
||||
return active.entrySettings;
|
||||
}
|
||||
@@ -1282,6 +1285,10 @@ export async function terminateCurrentSession({ infoMessage = '', closeServerSes
|
||||
await tryCloseCurrentSessionOnServer();
|
||||
}
|
||||
|
||||
if (!MULTI_PROFILE_ENABLED) {
|
||||
persistProfileStoreRaw(loadProfileStoreRaw().filter(item => normalizeProfileLogin(item.login) !== normalizeProfileLogin(signedOutLogin)));
|
||||
setActiveProfileLoginRaw('');
|
||||
}
|
||||
clearStoredSession();
|
||||
resetStateForSignedOut();
|
||||
await clearStoredMessages(signedOutLogin).catch(() => {});
|
||||
@@ -1318,6 +1325,7 @@ export function getSavedProfiles() {
|
||||
}
|
||||
|
||||
export async function switchToSavedProfile(login) {
|
||||
if (!MULTI_PROFILE_ENABLED) throw new Error('Multi-profile mode is disabled');
|
||||
const targetLogin = normalizeProfileLogin(login);
|
||||
const target = loadProfileStoreRaw().find((item) => normalizeProfileLogin(item.login) === targetLogin);
|
||||
if (!target) throw new Error('Профиль не найден на этом устройстве');
|
||||
@@ -1412,6 +1420,11 @@ async function closeSavedProfileSessionBestEffort(profile) {
|
||||
}
|
||||
|
||||
export async function closeSavedProfile(login) {
|
||||
if (!MULTI_PROFILE_ENABLED) {
|
||||
if (!login || normalizeProfileLogin(login) !== normalizeProfileLogin(state.session.login)) return { closed: false, nextProfile: null };
|
||||
await terminateCurrentSession({ closeServerSession: true, notifySessionReset: false });
|
||||
return { closed: true, nextProfile: null };
|
||||
}
|
||||
const normalized = normalizeProfileLogin(login);
|
||||
const items = loadProfileStoreRaw();
|
||||
const index = items.findIndex((item) => normalizeProfileLogin(item.login) === normalized);
|
||||
@@ -1441,6 +1454,7 @@ export async function closeSavedProfile(login) {
|
||||
}
|
||||
|
||||
export async function closeAllSavedProfiles() {
|
||||
if (!MULTI_PROFILE_ENABLED) throw new Error('Multi-profile mode is disabled');
|
||||
const items = loadProfileStoreRaw();
|
||||
for (const item of items) {
|
||||
await clearStoredMessages(item.login).catch(() => {});
|
||||
@@ -1462,10 +1476,11 @@ export async function closeAllSavedProfiles() {
|
||||
}
|
||||
|
||||
export function isAddingProfileLogin() {
|
||||
return state.session.isAuthorized && String(state.authReturnHash || '').trim() === '/profiles';
|
||||
return MULTI_PROFILE_ENABLED && state.session.isAuthorized && String(state.authReturnHash || '').trim() === '/profiles';
|
||||
}
|
||||
|
||||
export async function prepareAddProfileLogin() {
|
||||
if (!MULTI_PROFILE_ENABLED) throw new Error('Multi-profile mode is disabled');
|
||||
state.loginDraft.login = '';
|
||||
state.loginDraft.password = '';
|
||||
clearAuthMessages();
|
||||
|
||||
Reference in New Issue
Block a user