Files
scrabble-game/ui/src/screens/Profile.svelte
T
Ilia Denisov cabcd94d92 feat(profile): account-deletion flow + terminal deleted screen
Profile gains a Delete-account control (durable accounts) opening a step-up dialog: a
mailed code for an email account, or the typed DELETE phrase for a platform-only one.
On success the app swaps to a terminal AccountDeleted screen ('Учётная запись удалена')
with a Close that closes the host Mini App (telegramClose / vkClose; web = no close).
Wires deleteRequest/deleteConfirm through client/transport/mock/codec; ru/en i18n;
codec wire test + Chromium/WebKit e2e.
2026-07-03 13:18:37 +02:00

700 lines
22 KiB
Svelte

<script lang="ts">
import { onMount } from 'svelte';
import Modal from '../components/Modal.svelte';
import {
app,
applyLinkResult,
confirmDeleteAccount,
handleError,
logout,
requestDeleteAccount,
showToast,
} from '../lib/app.svelte';
import { GatewayError } from '../lib/client';
import { connection } from '../lib/connection.svelte';
import { gateway } from '../lib/gateway';
import { loginWidgetAvailable, requestTelegramLogin } from '../lib/telegram';
import { t } from '../lib/i18n/index.svelte';
import {
awayDurationOk,
awayHours,
awayMinutes,
browserOffset,
isOffsetZone,
timezoneOffsets,
validDisplayName,
validEmail,
} from '../lib/profileValidation';
import { ALL_VARIANTS, VARIANT_RULES } from '../lib/variants';
import type { Variant } from '../lib/model';
let dn = $state('');
let tz = $state('+00:00');
// Away start/end as hour + 10-minute parts, so the picker is a <select> like every
// other profile control (consistent native control across iOS / desktop).
let startH = $state('00');
let startM = $state('00');
let endH = $state('07');
let endM = $state('00');
let blockChat = $state(false);
let blockFriendRequests = $state(false);
let notificationsInAppOnly = $state(true);
let variantPrefs = $state<Variant[]>([]);
let emailInput = $state('');
let codeInput = $state('');
let emailSent = $state(false);
// A pending irreversible merge surfaced after the code/widget was verified; the
// dialog confirms it. tgData holds the Telegram widget payload for the merge step.
let pendingMerge = $state<null | { kind: 'email' | 'telegram'; name: string; games: number; friends: number }>(null);
let tgData = '';
// The change-email sub-form is open (a new address is being entered/confirmed).
let changingEmail = $state(false);
// A pending unlink awaiting the confirmation dialog (email is never unlinked).
let confirmUnlink = $state<null | { kind: 'telegram' | 'vk'; label: string }>(null);
// The account-deletion step-up dialog: null when closed, else the required proof method.
let deleting = $state<null | { method: 'email' | 'phrase' }>(null);
let deleteCode = $state('');
let deletePhrase = $state('');
const telegramLinkable = loginWidgetAvailable();
function defaultTz(): string {
const b = browserOffset();
return timezoneOffsets.includes(b) ? b : '+00:00';
}
function splitTime(hhmm: string): [string, string] {
const m = /^(\d{2}):(\d{2})$/.exec(hhmm);
if (!m) return ['00', '00'];
return [m[1], awayMinutes.includes(m[2]) ? m[2] : '00'];
}
// populate loads the editable form from the current profile. The profile screen is
// edited inline (no edit/cancel toggle), so this runs on mount and after a
// link/merge swaps the active account.
function populate() {
const p = app.profile;
if (!p) return;
dn = p.displayName;
tz = isOffsetZone(p.timeZone) && timezoneOffsets.includes(p.timeZone) ? p.timeZone : defaultTz();
[startH, startM] = splitTime(p.awayStart);
[endH, endM] = splitTime(p.awayEnd);
blockChat = p.blockChat;
blockFriendRequests = p.blockFriendRequests;
notificationsInAppOnly = p.notificationsInAppOnly;
variantPrefs = [...p.variantPreferences];
}
onMount(populate);
const awayStart = $derived(`${startH}:${startM}`);
const awayEnd = $derived(`${endH}:${endM}`);
const nameOk = $derived(validDisplayName(dn));
const awayOk = $derived(awayDurationOk(awayStart, awayEnd));
const formValid = $derived(nameOk && awayOk && variantPrefs.length >= 1);
const emailOk = $derived(validEmail(emailInput));
// Count the account's confirmed sign-in methods, to hide an Unlink that would remove the
// last identity (the backend also refuses it — this is a UX guard, not the enforcement).
const linkedCount = $derived(
app.profile
? (app.profile.email ? 1 : 0) + (app.profile.telegramLinked ? 1 : 0) + (app.profile.vkLinked ? 1 : 0)
: 0,
);
const canUnlink = $derived(linkedCount >= 2);
// toggleVariant flips a variant in the preference set, refusing to remove the last one —
// the player must allow themselves at least one variant.
function toggleVariant(id: Variant) {
if (variantPrefs.includes(id)) {
if (variantPrefs.length > 1) variantPrefs = variantPrefs.filter((v) => v !== id);
} else {
variantPrefs = [...variantPrefs, id];
}
}
async function save() {
if (!formValid) return;
try {
app.profile = await gateway.profileUpdate({
displayName: dn.trim(),
preferredLanguage: app.profile!.preferredLanguage, // language lives in Settings
timeZone: tz,
awayStart,
awayEnd,
blockChat,
blockFriendRequests,
notificationsInAppOnly,
variantPreferences: variantPrefs,
});
showToast(t('profile.saved'));
} catch (e) {
handleError(e);
}
}
function resetEmail() {
emailSent = false;
emailInput = '';
codeInput = '';
}
async function requestEmail() {
if (!emailOk) return;
try {
await gateway.linkEmailRequest(emailInput.trim());
emailSent = true;
showToast(t('profile.emailSent', { email: emailInput.trim() }));
} catch (e) {
handleError(e);
}
}
async function confirmEmail() {
try {
const r = await gateway.linkEmailConfirm(emailInput.trim(), codeInput.trim());
if (r.status === 'merge_required') {
pendingMerge = { kind: 'email', name: r.secondaryDisplayName, games: r.secondaryGames, friends: r.secondaryFriends };
return;
}
await applyLinkResult(r);
populate();
resetEmail();
showToast(t('profile.linked'));
} catch (e) {
handleError(e);
}
}
async function linkTelegram() {
try {
const data = await requestTelegramLogin();
if (!data) return;
const r = await gateway.linkTelegram(data);
if (r.status === 'merge_required') {
tgData = data;
pendingMerge = { kind: 'telegram', name: r.secondaryDisplayName, games: r.secondaryGames, friends: r.secondaryFriends };
return;
}
await applyLinkResult(r);
populate();
showToast(t('profile.linked'));
} catch (e) {
handleError(e);
}
}
async function confirmMerge() {
if (!pendingMerge) return;
try {
const r =
pendingMerge.kind === 'email'
? await gateway.linkEmailMerge(emailInput.trim(), codeInput.trim())
: await gateway.linkTelegramMerge(tgData);
await applyLinkResult(r);
populate();
pendingMerge = null;
tgData = '';
resetEmail();
showToast(t('profile.merged'));
} catch (e) {
handleError(e);
}
}
// startChangeEmail opens the change-email sub-form on a clean slate (a new address then a
// code), independent of any half-finished add-email attempt.
function startChangeEmail() {
changingEmail = true;
emailSent = false;
emailInput = '';
codeInput = '';
}
async function requestChangeEmail() {
if (!emailOk) return;
try {
await gateway.changeEmailRequest(emailInput.trim());
emailSent = true;
showToast(t('profile.emailSent', { email: emailInput.trim() }));
} catch (e) {
handleError(e);
}
}
async function confirmChangeEmail() {
try {
const r = await gateway.changeEmailConfirm(emailInput.trim(), codeInput.trim());
await applyLinkResult(r);
populate();
changingEmail = false;
resetEmail();
showToast(t('profile.emailChanged'));
} catch (e) {
// A new address confirmed by another account is refused without disclosing it.
if (e instanceof GatewayError && e.code === 'email_taken') {
showToast(t('profile.emailChangeTaken'), 'error');
return;
}
handleError(e);
}
}
async function unlink(kind: 'telegram' | 'vk') {
confirmUnlink = null;
try {
const r = await gateway.linkUnlink(kind);
await applyLinkResult(r);
populate();
showToast(t('profile.unlinked'));
} catch (e) {
handleError(e);
}
}
// startDelete opens the deletion dialog, asking the backend which step-up the account uses
// (a mailed code for an email account, or a typed phrase for a platform-only one).
async function startDelete() {
try {
const method = await requestDeleteAccount();
deleteCode = '';
deletePhrase = '';
deleting = { method };
} catch (e) {
handleError(e);
}
}
async function doDelete() {
if (!deleting) return;
try {
// On success the app swaps to the terminal "account deleted" screen (app.accountDeleted).
await confirmDeleteAccount(deleteCode.trim(), deletePhrase.trim());
} catch (e) {
handleError(e);
}
}
</script>
<div class="page">
{#if app.profile}
{@const p = app.profile}
<div class="name">{p.displayName}</div>
{#if p.isGuest}<span class="badge">{t('profile.guest')}</span>{/if}
{#if p.isGuest}
<p class="muted">{t('profile.guestLocked')}</p>
{:else}
<form class="edit" onsubmit={(e) => { e.preventDefault(); void save(); }}>
<label>
<span>{t('profile.displayName')}</span>
<input class:invalid={!nameOk} bind:value={dn} maxlength="40" />
</label>
<label>
<span>{t('profile.timezone')}</span>
<select bind:value={tz}>
{#each timezoneOffsets as o (o)}<option value={o}>{o}</option>{/each}
</select>
</label>
<fieldset class="away" class:invalid={!awayOk}>
<legend>{t('profile.awayWindow')}</legend>
<div class="times">
<span class="tlabel">{t('profile.from')}</span>
<select bind:value={startH}>{#each awayHours as h (h)}<option>{h}</option>{/each}</select>
<span class="colon">:</span>
<select bind:value={startM}>{#each awayMinutes as m (m)}<option>{m}</option>{/each}</select>
</div>
<div class="times">
<span class="tlabel">{t('profile.to')}</span>
<select bind:value={endH}>{#each awayHours as h (h)}<option>{h}</option>{/each}</select>
<span class="colon">:</span>
<select bind:value={endM}>{#each awayMinutes as m (m)}<option>{m}</option>{/each}</select>
</div>
<p class="muted">{t('profile.awayHint')}</p>
</fieldset>
<label class="check">
<input type="checkbox" bind:checked={blockChat} />
<span>{t('profile.blockChat')}</span>
</label>
<label class="check">
<input type="checkbox" bind:checked={blockFriendRequests} />
<span>{t('profile.blockFriendRequests')}</span>
</label>
<label class="check">
<input type="checkbox" bind:checked={notificationsInAppOnly} />
<span>{t('profile.notificationsInAppOnly')}</span>
</label>
<fieldset class="prefs">
<legend>{t('profile.preferences')}</legend>
<p class="muted">{t('profile.preferencesHint')}</p>
{#each ALL_VARIANTS as v (v.id)}
<label class="check pref">
<input
type="checkbox"
checked={variantPrefs.includes(v.id)}
disabled={variantPrefs.length === 1 && variantPrefs.includes(v.id)}
onchange={() => toggleVariant(v.id)}
/>
<span class="pname">{t(v.label)}</span>
<span class="prule">{t(VARIANT_RULES[v.id])}</span>
</label>
{/each}
</fieldset>
<div class="formacts">
<button type="submit" class="btn" disabled={!formValid || !connection.online}>{t('common.save')}</button>
</div>
</form>
{/if}
<!-- Sign-in methods: bind/change an email and link/unlink providers. A returning email
(add) triggers the merge dialog below. On the web an account can add Telegram via the
login widget; adding VK on the web is deferred (no VK OAuth) and inside a Mini App the
host provider is already linked. Email is never unlinked — it is changed. Unlink is
offered only when another identity remains (the backend also refuses the last one). -->
<section class="accounts">
<h3>{t('profile.accountsTitle')}</h3>
{#if p.email}
<div class="acctrow">
<span class="prov"><span class="ic">✉️</span>{p.email}</span>
{#if !changingEmail}
<button class="ghost" onclick={startChangeEmail} disabled={!connection.online}>{t('profile.changeEmail')}</button>
{/if}
</div>
{#if changingEmail}
{#if !emailSent}
<div class="addrow">
<input
class:invalid={emailInput.length > 0 && !emailOk}
bind:value={emailInput}
placeholder={t('profile.newEmailPlaceholder')}
type="email"
/>
<button class="ghost" onclick={requestChangeEmail} disabled={!emailOk || !connection.online}>{t('login.sendCode')}</button>
</div>
{:else}
<div class="addrow">
<input class="codein" bind:value={codeInput} placeholder={t('profile.emailCode')} inputmode="numeric" maxlength="6" />
<button class="btn" onclick={confirmChangeEmail} disabled={!connection.online}>{t('common.ok')}</button>
</div>
{/if}
<button class="linklike" onclick={() => { changingEmail = false; resetEmail(); }}>{t('common.cancel')}</button>
{/if}
{:else if !emailSent}
<div class="addrow">
<input
class:invalid={emailInput.length > 0 && !emailOk}
bind:value={emailInput}
placeholder={t('login.emailPlaceholder')}
type="email"
/>
<button class="ghost" onclick={requestEmail} disabled={!emailOk || !connection.online}>{t('login.sendCode')}</button>
</div>
{:else}
<div class="addrow">
<input class="codein" bind:value={codeInput} placeholder={t('profile.emailCode')} inputmode="numeric" maxlength="6" />
<button class="btn" onclick={confirmEmail} disabled={!connection.online}>{t('common.ok')}</button>
</div>
{/if}
{#if p.telegramLinked}
<div class="acctrow">
<span class="prov"><img src="telegram-logo.svg" alt="" width="18" height="18" />Telegram</span>
{#if canUnlink}
<button class="ghost danger" onclick={() => (confirmUnlink = { kind: 'telegram', label: 'Telegram' })} disabled={!connection.online}>{t('profile.unlink')}</button>
{/if}
</div>
{:else if telegramLinkable}
<button class="ghost tg" onclick={linkTelegram} disabled={!connection.online}>
<img src="telegram-logo.svg" alt="" width="18" height="18" />{t('profile.linkTelegram')}
</button>
{/if}
{#if p.vkLinked}
<div class="acctrow">
<span class="prov"><img src="vk-logo.svg" alt="" width="18" height="18" />VK</span>
{#if canUnlink}
<button class="ghost danger" onclick={() => (confirmUnlink = { kind: 'vk', label: 'VK' })} disabled={!connection.online}>{t('profile.unlink')}</button>
{/if}
</div>
{/if}
</section>
{#if !p.isGuest}
<button class="deletebtn" onclick={startDelete} disabled={!connection.online}>{t('profile.deleteAccount')}</button>
{/if}
<!-- Logout is hidden for now but kept wired — drop `hidden` to re-enable
once its entry point is decided; logout() also still runs on an invalid session. -->
<button class="logout" hidden onclick={() => logout()}>{t('login.title')} / logout</button>
{/if}
</div>
{#if pendingMerge}
<Modal title={t('profile.mergeTitle')} onclose={() => (pendingMerge = null)}>
<p>{t('profile.mergeBody', { name: pendingMerge.name, games: pendingMerge.games, friends: pendingMerge.friends })}</p>
<p class="warn">{t('profile.mergeIrreversible')}</p>
<div class="addrow end">
<button class="ghost" onclick={() => (pendingMerge = null)}>{t('common.cancel')}</button>
<button class="btn" onclick={confirmMerge} disabled={!connection.online}>{t('profile.mergeConfirm')}</button>
</div>
</Modal>
{/if}
{#if confirmUnlink}
{@const cu = confirmUnlink}
<Modal title={t('profile.unlinkTitle')} onclose={() => (confirmUnlink = null)}>
<p>{t('profile.unlinkBody', { provider: cu.label })}</p>
<div class="addrow end">
<button class="ghost" onclick={() => (confirmUnlink = null)}>{t('common.cancel')}</button>
<button class="btn danger" onclick={() => unlink(cu.kind)} disabled={!connection.online}>{t('profile.unlink')}</button>
</div>
</Modal>
{/if}
{#if deleting}
{@const d = deleting}
<Modal title={t('profile.deleteTitle')} onclose={() => (deleting = null)}>
<p class="warn">{t('profile.deleteWarn')}</p>
{#if d.method === 'email'}
<p class="muted">{t('profile.deleteEmailPrompt')}</p>
<div class="addrow">
<input class="codein" bind:value={deleteCode} placeholder={t('profile.emailCode')} inputmode="numeric" maxlength="6" />
</div>
{:else}
<p class="muted">{t('profile.deletePhrasePrompt')}</p>
<div class="addrow">
<input bind:value={deletePhrase} placeholder={t('profile.deletePhrasePlaceholder')} autocapitalize="characters" />
</div>
{/if}
<div class="addrow end">
<button class="ghost" onclick={() => (deleting = null)}>{t('common.cancel')}</button>
<button class="btn danger" onclick={doDelete} disabled={!connection.online}>{t('profile.deleteConfirm')}</button>
</div>
</Modal>
{/if}
<style>
.page {
padding: var(--pad);
display: flex;
flex-direction: column;
gap: 16px;
}
.name {
font-size: 1.4rem;
font-weight: 700;
}
.badge {
align-self: flex-start;
padding: 2px 8px;
border-radius: 999px;
background: var(--surface-2);
color: var(--text-muted);
font-size: 0.8rem;
}
.muted {
color: var(--text-muted);
font-size: 0.9rem;
margin: 0;
}
.edit {
display: flex;
flex-direction: column;
gap: 14px;
}
.edit > label {
display: flex;
flex-direction: column;
gap: 4px;
font-size: 0.9rem;
color: var(--text-muted);
}
.edit input:not([type='checkbox']),
.edit select {
min-width: 0;
padding: 9px 11px;
border: 1px solid var(--border);
background: var(--surface);
color: var(--text);
border-radius: var(--radius-sm);
}
.invalid {
border-color: var(--danger, #c0392b) !important;
}
.away {
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 10px 12px;
margin: 0;
display: flex;
flex-direction: column;
gap: 8px;
}
.away legend {
color: var(--text-muted);
font-size: 0.9rem;
padding: 0 4px;
}
.times {
display: flex;
align-items: center;
gap: 8px;
}
.tlabel {
min-width: 2.5em;
color: var(--text-muted);
font-size: 0.85rem;
}
.colon {
font-weight: 700;
}
.check {
flex-direction: row !important;
align-items: center;
gap: 10px !important;
color: var(--text) !important;
}
.prefs {
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 10px 12px;
margin: 0;
display: flex;
flex-direction: column;
gap: 8px;
}
.prefs legend {
color: var(--text-muted);
font-size: 0.9rem;
padding: 0 4px;
}
.pref {
align-items: baseline;
}
.pname {
font-weight: 600;
}
.prule {
color: var(--text-muted);
font-size: 0.8rem;
}
.formacts {
display: flex;
gap: 10px;
}
.btn:disabled {
opacity: 0.5;
}
.accounts {
display: flex;
flex-direction: column;
gap: 10px;
}
.accounts h3 {
margin: 0 0 2px;
font-size: 0.95rem;
color: var(--text-muted);
}
.acctrow {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 8px 10px;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--surface);
}
.prov {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.prov .ic {
width: 18px;
text-align: center;
}
.tg {
display: inline-flex;
align-items: center;
gap: 8px;
align-self: flex-start;
}
.ghost.danger {
border-color: var(--danger, #c0392b);
color: var(--danger, #c0392b);
}
.btn.danger {
background: var(--danger, #c0392b);
border-color: var(--danger, #c0392b);
color: #fff;
}
.linklike {
align-self: flex-start;
background: none;
border: none;
padding: 2px 0;
color: var(--text-muted);
text-decoration: underline;
font-size: 0.85rem;
cursor: pointer;
}
.addrow {
display: flex;
gap: 8px;
}
.addrow input {
flex: 1;
min-width: 0;
padding: 9px 11px;
border: 1px solid var(--border);
background: var(--surface);
color: var(--text);
border-radius: var(--radius-sm);
}
.addrow input.codein {
letter-spacing: 0.3em;
font-size: 1.1rem;
}
.btn {
align-self: flex-start;
padding: 9px 14px;
border: 1px solid var(--accent);
background: var(--accent);
color: var(--accent-text);
border-radius: var(--radius-sm);
}
.ghost {
padding: 9px 14px;
border: 1px solid var(--border);
background: var(--surface);
color: var(--text);
border-radius: var(--radius-sm);
}
.ghost:disabled {
opacity: 0.5;
}
.deletebtn {
margin-top: 8px;
align-self: flex-start;
padding: 8px 14px;
border: 1px solid var(--danger, #c0392b);
background: transparent;
color: var(--danger, #c0392b);
border-radius: var(--radius-sm);
}
.deletebtn:disabled {
opacity: 0.5;
}
.logout {
margin-top: 8px;
align-self: flex-start;
padding: 8px 14px;
border: 1px solid var(--border);
background: var(--surface);
color: var(--text);
border-radius: var(--radius-sm);
}
</style>