refactor: code review

This commit is contained in:
Amiram_se 2026-10-10 18:28:58 +04:00
parent 27ef8fe5b0
commit aec09a0ecd
78 changed files with 1037 additions and 316 deletions

View File

@ -8,7 +8,11 @@ import {
import type { NextConfig } from 'next';
import path from 'node:path';
import { API_PROXY_PATH, API_PROXY_TIMEOUT_MS } from './src/constants';
import {
API_PROXY_MAX_BODY,
API_PROXY_PATH,
API_PROXY_TIMEOUT_MS,
} from './src/constants';
import { apiInternalUrl } from './src/env/env.config';
// Fonts and the icon sprite keep fixed names; a changed font gets a new name, and the sprite a new
@ -17,12 +21,25 @@ const immutable = [
{ key: 'Cache-Control', value: 'public, max-age=31536000, immutable' },
];
// No page may be framed by another site (checkout, finance and account pages act on a click), and
// the browser never guesses a type or sends full URLs to other sites.
const security = [
{ key: 'Content-Security-Policy', value: "frame-ancestors 'none'" },
{ key: 'X-Frame-Options', value: 'DENY' },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
];
const nextConfig: NextConfig = {
// Every visitor gets the metadata in <head>, where Chrome looks for the manifest and Safari for
// its home-screen tags; Next.js would otherwise stream it to the end of <body> (0054).
htmlLimitedBots: /.*/,
// The `/api` proxy's wait for the gateway (0018); uploads outlast Next.js's 30-second default.
experimental: { proxyTimeout: API_PROXY_TIMEOUT_MS },
// The `/api` proxy's wait for the gateway (0018); uploads outlast Next.js's 30-second default
// and two ID images come close to its 10 MB body limit.
experimental: {
proxyTimeout: API_PROXY_TIMEOUT_MS,
proxyClientMaxBodySize: API_PROXY_MAX_BODY,
},
// Workspace packages export TypeScript source, so Next.js compiles them.
transpilePackages: [
'@lumina/market',
@ -55,6 +72,7 @@ const nextConfig: NextConfig = {
// island's plugins write theirs. Next runs from the app's folder, as every Nx target does.
writeServiceWorker({ publicDir: path.join(process.cwd(), 'public') });
return [
{ source: '/:path*', headers: security },
{ source: '/fonts/:path*', headers: immutable },
{ source: '/icons/:path*', headers: immutable },
// Revalidated on every update check, so a new worker reaches visitors at their next

View File

@ -1,4 +1,4 @@
import { ROUTES } from '@lumina/market/app/navigation';
import { ROUTES, withSearchParams } from '@lumina/market/app/navigation';
import { getChannel, readOnServer } from '@lumina/market/server';
import { toChannelUsername } from '@lumina/market/shared/utils';
import type { Metadata } from 'next';
@ -7,7 +7,10 @@ import { notFound, permanentRedirect, redirect } from 'next/navigation';
import { i18n } from '../../../../i18n';
import { CheckoutTemplate } from './templates/checkout-template';
type CheckoutPageProps = { params: Promise<{ username: string }> };
type CheckoutPageProps = {
params: Promise<{ username: string }>;
searchParams: Promise<Record<string, string | string[] | undefined>>;
};
export const metadata: Metadata = {
title: i18n.t('payment:checkout.title'),
@ -20,11 +23,19 @@ export const metadata: Metadata = {
* browser. Another spelling of the username redirects to the stored one; a suspended channel
* sends the visitor to the channel, which says it is unavailable.
*/
export default async function CheckoutPage({ params }: CheckoutPageProps) {
export default async function CheckoutPage({
params,
searchParams,
}: CheckoutPageProps) {
const segment = (await params).username;
const username = toChannelUsername(segment);
if (!username) notFound();
if (username !== segment) permanentRedirect(ROUTES.checkout(username));
// The invite link's `?code=` goes along (0059).
if (username !== segment) {
permanentRedirect(
withSearchParams(ROUTES.checkout(username), await searchParams),
);
}
const channel = await readOnServer(() => getChannel(username));
if (channel.status !== 'ok') notFound();
if (channel.data.suspended) redirect(ROUTES.channel(username));

View File

@ -1,4 +1,4 @@
import { ROUTES } from '@lumina/market/app/navigation';
import { ROUTES, withSearchParams } from '@lumina/market/app/navigation';
import {
channelMetadata,
getChannel,
@ -13,7 +13,10 @@ import { displayUrl } from '../../../../configs';
import { i18n } from '../../../../i18n';
import { ChannelTemplate } from './templates/channel-template';
type ChannelPageProps = { params: Promise<{ username: string }> };
type ChannelPageProps = {
params: Promise<{ username: string }>;
searchParams: Promise<Record<string, string | string[] | undefined>>;
};
// The one kind of route whose metadata names its data (0055): it reads through the same per-request
// cache as the page, so the first byte, held for the metadata in <head> (0054), waits for that
@ -43,11 +46,19 @@ export async function generateMetadata({
* track record and the first posts; subscribe, follow and the locked posts' gates load in the
* browser. Any other spelling of the username redirects to the one the API stores.
*/
export default async function ChannelPage({ params }: ChannelPageProps) {
export default async function ChannelPage({
params,
searchParams,
}: ChannelPageProps) {
const segment = (await params).username;
const username = toChannelUsername(segment);
if (!username) notFound();
if (username !== segment) permanentRedirect(ROUTES.channel(username));
// An invite link's `?code=` goes along (0059).
if (username !== segment) {
permanentRedirect(
withSearchParams(ROUTES.channel(username), await searchParams),
);
}
const channel = await readOnServer(() => getChannel(username));
if (channel.status !== 'ok') notFound();

View File

@ -14,3 +14,9 @@ export const API_PROXY_PATH = '/api';
* sets no timeout for uploads.
*/
export const API_PROXY_TIMEOUT_MS = 120_000;
/**
* The largest request body the `/api` proxy passes on (Next.js cuts at 10 MB by default). Creator
* registration and verification send two 5 MB ID images plus the form in one request.
*/
export const API_PROXY_MAX_BODY = '12mb';

View File

@ -1,2 +1,7 @@
export { API_PROXY_PATH, API_PROXY_TIMEOUT_MS, API_VERSION_PATH } from './api';
export {
API_PROXY_MAX_BODY,
API_PROXY_PATH,
API_PROXY_TIMEOUT_MS,
API_VERSION_PATH,
} from './api';
export { FORWARDED_COOKIES } from './cookies';

View File

@ -8,7 +8,11 @@ import {
import type { NextConfig } from 'next';
import path from 'node:path';
import { API_PROXY_PATH, API_PROXY_TIMEOUT_MS } from './src/constants';
import {
API_PROXY_MAX_BODY,
API_PROXY_PATH,
API_PROXY_TIMEOUT_MS,
} from './src/constants';
import { apiInternalUrl } from './src/env/env.config';
// Fonts and the icon sprite keep fixed names; a changed font gets a new name, and the sprite a new
@ -17,12 +21,25 @@ const immutable = [
{ key: 'Cache-Control', value: 'public, max-age=31536000, immutable' },
];
// No page may be framed by another site (checkout, finance and account pages act on a click), and
// the browser never guesses a type or sends full URLs to other sites.
const security = [
{ key: 'Content-Security-Policy', value: "frame-ancestors 'none'" },
{ key: 'X-Frame-Options', value: 'DENY' },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
];
const nextConfig: NextConfig = {
// Every visitor gets the metadata in <head>, where Chrome looks for the manifest and Safari for
// its home-screen tags; Next.js would otherwise stream it to the end of <body> (0054).
htmlLimitedBots: /.*/,
// The `/api` proxy's wait for the gateway (0018); uploads outlast Next.js's 30-second default.
experimental: { proxyTimeout: API_PROXY_TIMEOUT_MS },
// The `/api` proxy's wait for the gateway (0018); uploads outlast Next.js's 30-second default
// and two ID images come close to its 10 MB body limit.
experimental: {
proxyTimeout: API_PROXY_TIMEOUT_MS,
proxyClientMaxBodySize: API_PROXY_MAX_BODY,
},
// Workspace packages export TypeScript source, so Next.js compiles them.
transpilePackages: [
'@lumina/market',
@ -55,6 +72,7 @@ const nextConfig: NextConfig = {
// island's plugins write theirs. Next runs from the app's folder, as every Nx target does.
writeServiceWorker({ publicDir: path.join(process.cwd(), 'public') });
return [
{ source: '/:path*', headers: security },
{ source: '/fonts/:path*', headers: immutable },
{ source: '/icons/:path*', headers: immutable },
// Revalidated on every update check, so a new worker reaches visitors at their next

View File

@ -1,4 +1,4 @@
import { ROUTES } from '@lumina/market/app/navigation';
import { ROUTES, withSearchParams } from '@lumina/market/app/navigation';
import { getChannel, readOnServer } from '@lumina/market/server';
import { toChannelUsername } from '@lumina/market/shared/utils';
import type { Metadata } from 'next';
@ -7,7 +7,10 @@ import { notFound, permanentRedirect, redirect } from 'next/navigation';
import { i18n } from '../../../../i18n';
import { CheckoutTemplate } from './templates/checkout-template';
type CheckoutPageProps = { params: Promise<{ username: string }> };
type CheckoutPageProps = {
params: Promise<{ username: string }>;
searchParams: Promise<Record<string, string | string[] | undefined>>;
};
export const metadata: Metadata = {
title: i18n.t('payment:checkout.title'),
@ -20,11 +23,19 @@ export const metadata: Metadata = {
* browser. Another spelling of the username redirects to the stored one; a suspended channel
* sends the visitor to the channel, which says it is unavailable.
*/
export default async function CheckoutPage({ params }: CheckoutPageProps) {
export default async function CheckoutPage({
params,
searchParams,
}: CheckoutPageProps) {
const segment = (await params).username;
const username = toChannelUsername(segment);
if (!username) notFound();
if (username !== segment) permanentRedirect(ROUTES.checkout(username));
// The invite link's `?code=` goes along (0059).
if (username !== segment) {
permanentRedirect(
withSearchParams(ROUTES.checkout(username), await searchParams),
);
}
const channel = await readOnServer(() => getChannel(username));
if (channel.status !== 'ok') notFound();
if (channel.data.suspended) redirect(ROUTES.channel(username));

View File

@ -1,4 +1,4 @@
import { ROUTES } from '@lumina/market/app/navigation';
import { ROUTES, withSearchParams } from '@lumina/market/app/navigation';
import {
channelMetadata,
getChannel,
@ -13,7 +13,10 @@ import { displayUrl } from '../../../../configs';
import { i18n } from '../../../../i18n';
import { ChannelTemplate } from './templates/channel-template';
type ChannelPageProps = { params: Promise<{ username: string }> };
type ChannelPageProps = {
params: Promise<{ username: string }>;
searchParams: Promise<Record<string, string | string[] | undefined>>;
};
// The one kind of route whose metadata names its data (0055): it reads through the same per-request
// cache as the page, so the first byte, held for the metadata in <head> (0054), waits for that
@ -43,11 +46,19 @@ export async function generateMetadata({
* track record and the first posts; subscribe, follow and the locked posts' gates load in the
* browser. Any other spelling of the username redirects to the one the API stores.
*/
export default async function ChannelPage({ params }: ChannelPageProps) {
export default async function ChannelPage({
params,
searchParams,
}: ChannelPageProps) {
const segment = (await params).username;
const username = toChannelUsername(segment);
if (!username) notFound();
if (username !== segment) permanentRedirect(ROUTES.channel(username));
// An invite link's `?code=` goes along (0059).
if (username !== segment) {
permanentRedirect(
withSearchParams(ROUTES.channel(username), await searchParams),
);
}
const channel = await readOnServer(() => getChannel(username));
if (channel.status !== 'ok') notFound();

View File

@ -14,3 +14,9 @@ export const API_PROXY_PATH = '/api';
* sets no timeout for uploads.
*/
export const API_PROXY_TIMEOUT_MS = 120_000;
/**
* The largest request body the `/api` proxy passes on (Next.js cuts at 10 MB by default). Creator
* registration and verification send two 5 MB ID images plus the form in one request.
*/
export const API_PROXY_MAX_BODY = '12mb';

View File

@ -1,2 +1,7 @@
export { API_PROXY_PATH, API_PROXY_TIMEOUT_MS, API_VERSION_PATH } from './api';
export {
API_PROXY_MAX_BODY,
API_PROXY_PATH,
API_PROXY_TIMEOUT_MS,
API_VERSION_PATH,
} from './api';
export { FORWARDED_COOKIES } from './cookies';

View File

@ -1,6 +1,6 @@
import { number } from '@lumina/tools/format';
import { Element } from '../../primitives/element';
import { GridBox } from '../grid-box';
import { cn } from '../../tools/cn';
import type { CountBadgeProps } from './types';
@ -18,16 +18,19 @@ export function CountBadge({
if (count <= 0) return null;
return (
<Element
<GridBox
tag="span"
aria-hidden
display="inline-grid"
justifyItems="justify-items-center"
alignItems="items-center"
className={cn(
'inline-grid h-4.5 min-w-4.5 place-items-center rounded-full bg-danger-solid px-1 text-micro font-bold text-text-on-action tabular-nums',
'h-4.5 min-w-4.5 rounded-full bg-danger-solid px-1 text-micro font-bold text-text-on-action tabular-nums',
className,
)}
{...props}
>
{count > cap ? `${number(cap)}+` : number(count)}
</Element>
</GridBox>
);
}

View File

@ -14,6 +14,13 @@ import {
} from './constants';
import type { DialogProps } from './types';
/** The modal dialogs in the top layer now, other than `dialog`. */
function otherModals(dialog: HTMLDialogElement): Element[] {
return Array.from(document.querySelectorAll('dialog[open]')).filter(
(other) => other !== dialog && other.matches(':modal'),
);
}
function announce(type: string, dialog: HTMLDialogElement): void {
document.dispatchEvent(new CustomEvent(type, { detail: dialog }));
}
@ -76,12 +83,34 @@ export function Dialog({
if (open && !isPresent) setIsPresent(true);
// Where the last press started, so a drag out of the panel (selecting text) never closes it.
const pressedLayer = useRef(false);
// Whether this dialog announced itself open to the toasts and hasn't announced its close yet, so
// each open is matched by exactly one close, however the dialog leaves.
const announced = useRef(false);
// Whether it was shown and hasn't left yet, so `onExited` runs once however it leaves.
const shown = useRef(false);
// `open` as last rendered, for the browser's own close to check after the parent answered.
const openRef = useRef(open);
useEffect(() => {
openRef.current = open;
});
const show = useEffectEvent((dialog: HTMLDialogElement) =>
showDialog(dialog, raiseToasts),
);
const show = (dialog: HTMLDialogElement) => {
showDialog(dialog, raiseToasts && !announced.current);
if (raiseToasts) announced.current = true;
shown.current = true;
};
const showOnOpen = useEffectEvent(show);
// Stops a re-show still waiting after the browser closed the dialog (handleNativeClose).
const stopReshow = useRef<(() => void) | null>(null);
const cancelReshow = () => {
stopReshow.current?.();
stopReshow.current = null;
};
const cancelReshowOnClose = useEffectEvent(cancelReshow);
const left = useEffectEvent((dialog: HTMLDialogElement) => {
if (raiseToasts) announce(DIALOG_CLOSE_EVENT, dialog);
if (announced.current) announce(DIALOG_CLOSE_EVENT, dialog);
announced.current = false;
shown.current = false;
onExited?.();
});
@ -91,10 +120,17 @@ export function Dialog({
if (open) {
// Reopened mid-close: the exit transitions run back from where they are.
dialog.removeAttribute('data-closing');
if (!dialog.open) show(dialog);
if (!dialog.open) showOnOpen(dialog);
return undefined;
}
cancelReshowOnClose();
// The browser already closed it (see handleNativeClose) and the parent agreed: nothing to
// animate, only the close to announce.
if (!dialog.open) {
if (shown.current) left(dialog);
setIsPresent(false);
return undefined;
}
if (!dialog.open) return undefined;
dialog.setAttribute('data-closing', '');
let cancelled = false;
@ -114,7 +150,8 @@ export function Dialog({
useEffect(() => {
const dialog = ref.current;
return () => {
if (dialog?.open) left(dialog);
cancelReshowOnClose();
if (dialog && shown.current) left(dialog);
};
}, []);
@ -128,12 +165,41 @@ export function Dialog({
// The browser can close the dialog without asking: Chrome makes a repeated Escape uncancelable
// when the page has had no user activation (right after the ZarinPal return), and a
// `<form method="dialog">` closes it too. Our own close() runs only once `open` is false.
// `<form method="dialog">` closes it too. Our own close() runs only once `open` is false. The
// parent may keep it open (a guarded close that asks first): then it is shown again, but only
// once no other modal covers it, so it never lands above the confirm that close opened.
const handleNativeClose = (event: SyntheticEvent<HTMLDialogElement>) => {
const dialog = event.currentTarget;
if (event.target !== dialog || !open || dialog.open) return;
if (dismissible && onClose) onClose();
else showDialog(dialog, raiseToasts);
if (!dismissible || !onClose) {
show(dialog);
return;
}
// Dialogs already open beneath this one never count as covering it.
const beneath = new Set(otherModals(dialog));
onClose();
cancelReshow();
const attempt = () => {
if (!openRef.current || !dialog.isConnected || dialog.open) {
cancelReshow();
return;
}
// Covered by a dialog the close opened: wait for it to close.
if (otherModals(dialog).some((other) => !beneath.has(other))) return;
cancelReshow();
show(dialog);
};
// After the parent's answer has rendered, and again after each dialog's close.
const timers = new Set<ReturnType<typeof setTimeout>>();
const later = () => {
timers.add(setTimeout(attempt));
};
later();
document.addEventListener('close', later, true);
stopReshow.current = () => {
timers.forEach(clearTimeout);
document.removeEventListener('close', later, true);
};
};
// The layer fills the screen, so a press that starts and ends on it, not on the panel, hit the

View File

@ -30,10 +30,14 @@ export function Switch({
const hasText = children != null || description != null;
return (
<Element
<FlexBox
tag="button"
type="button"
role="switch"
display="inline-flex"
alignItems="items-center"
justifyContent={hasText ? 'justify-between' : 'justify-center'}
gap="gap-3"
aria-checked={checked}
aria-disabled={locked || undefined}
// The label alone names it; the description is announced after it, not inside the name.
@ -46,9 +50,9 @@ export function Switch({
if (!locked && !event.defaultPrevented) onCheckedChange?.(!checked);
}}
className={cn(
'inline-flex min-h-touch-target min-w-touch-target items-center justify-center gap-3 rounded-md outline-none focus-visible:focus-ring',
'min-h-touch-target min-w-touch-target rounded-md outline-none focus-visible:focus-ring',
locked ? 'cursor-not-allowed' : 'cursor-pointer',
hasText && 'justify-between text-start',
hasText && 'text-start',
className,
)}
{...props}
@ -81,13 +85,15 @@ export function Switch({
)}
</FlexBox>
)}
<Element
<FlexBox
tag="span"
aria-hidden
display="inline-flex"
alignItems="items-center"
className={switchTrackVariants({ checked, locked })}
>
<Element tag="span" className={switchKnobVariants({ checked })} />
</Element>
</Element>
</FlexBox>
</FlexBox>
);
}

View File

@ -2,7 +2,7 @@ import { cva } from 'class-variance-authority';
/** The 44×24 track; the knob slides to the end when on, mirrored in RTL. */
export const switchTrackVariants = cva(
'relative inline-flex h-6 w-11 flex-none items-center rounded-full border-[1.5px] p-0.5 transition-colors duration-120 ease-standard',
'relative h-6 w-11 flex-none rounded-full border-[1.5px] p-0.5 transition-colors duration-120 ease-standard',
{
variants: {
checked: {

View File

@ -35,6 +35,12 @@ export function AvatarField({
className,
}: AvatarFieldProps) {
const inputRef = useRef<HTMLInputElement>(null);
// Remove and retry leave with the state they change: focus stays on the picker beside them.
const pickRef = useRef<HTMLButtonElement>(null);
const thenFocusPick = (action: () => void) => () => {
action();
pickRef.current?.focus();
};
const messageId = useId();
const isUploading = status === 'uploading';
const isFailed = status === 'failed';
@ -63,6 +69,7 @@ export function AvatarField({
/>
<FlexBox direction="flex-col" alignItems="items-start" gap="gap-1">
<Button
ref={pickRef}
variant="secondary"
icon="image"
isLoading={isUploading}
@ -90,12 +97,16 @@ export function AvatarField({
variant="ghost"
size="sm"
disabled={disabled}
onClick={onRemove}
onClick={thenFocusPick(onRemove)}
>
{labels.remove}
</Button>
) : (
<LinkButton standalone disabled={disabled} onClick={onRemove}>
<LinkButton
standalone
disabled={disabled}
onClick={thenFocusPick(onRemove)}
>
{labels.remove}
</LinkButton>
))}
@ -109,7 +120,7 @@ export function AvatarField({
standalone
iconStart="refresh"
disabled={disabled}
onClick={onRetry}
onClick={thenFocusPick(onRetry)}
>
{labels.retry}
</LinkButton>

View File

@ -151,7 +151,11 @@ export function FileField({
icon="trash"
label={labels.remove}
disabled={disabled}
onClick={() => onChange(null)}
onClick={() => {
onChange(null);
// The button leaves with the file: focus goes to the picker in its place.
inputRef.current?.focus();
}}
className="flex-none"
/>
)}

View File

@ -2,9 +2,9 @@
import { useEffect, useId, useRef, useState } from 'react';
import { FlexBox } from '../../atoms/flex-box';
import { Icon } from '../../atoms/icon';
import { Typography } from '../../atoms/typography';
import { Element } from '../../primitives/element';
import { cn } from '../../tools/cn';
import type { InfoTipProps } from './types';
import { infoTipVariants } from './variants';
@ -44,23 +44,27 @@ export function InfoTip({
}, [isOpen]);
return (
<Element
<FlexBox
tag="span"
ref={rootRef}
className={cn('group relative -my-3 inline-flex', className)}
display="inline-flex"
className={cn('group relative -my-3', className)}
onMouseLeave={() => setIsOpen(false)}
>
<Element
<FlexBox
tag="button"
type="button"
display="inline-flex"
alignItems="items-center"
justifyContent="justify-center"
aria-label={label}
aria-describedby={tipId}
aria-expanded={isOpen}
onClick={() => setIsOpen((open) => !open)}
className="inline-flex size-touch-target cursor-pointer items-center justify-center rounded-full text-text-secondary outline-none hover:text-text-primary focus-visible:focus-ring"
className="size-touch-target cursor-pointer rounded-full text-text-secondary outline-none hover:text-text-primary focus-visible:focus-ring"
>
<Icon name="info" size={16} />
</Element>
</FlexBox>
<Typography
tag="span"
id={tipId}
@ -71,6 +75,6 @@ export function InfoTip({
>
{children}
</Typography>
</Element>
</FlexBox>
);
}

View File

@ -1,3 +1,5 @@
import { useRef } from 'react';
import { FlexBox } from '../../atoms/flex-box';
import { GridBox } from '../../atoms/grid-box';
import { Icon } from '../../atoms/icon';
@ -14,7 +16,8 @@ const IMAGE_CLASS = 'block size-full object-cover';
* A form's picked images (DS MediaStrip), such as the post composer's: thumbnails in the order
* they were added, each with a 28px ✕; one uploading sits under a light veil with a spinner, a
* failed one has a danger frame and, with `onRetry`, sends again on tap. A dashed «افزودن» tile
* ends the strip until `max`. It wraps; 76px thumbnails, 96px at `lg`.
* ends the strip until `max`. It wraps; 76px thumbnails, 96px at `lg`. A ✕ or retry that leaves
* with its tile or state hands focus on: the ✕ now in that place, else «افزودن».
*/
export function MediaStrip({
items,
@ -28,6 +31,18 @@ export function MediaStrip({
disabled = false,
className,
}: MediaStripProps) {
const listRef = useRef<HTMLUListElement>(null);
// After the parent's update has rendered.
const focusRemoveAt = (index: number) =>
setTimeout(() => {
const list = listRef.current;
if (!list) return;
const removes = list.querySelectorAll<HTMLElement>('[data-remove]');
const target =
removes[Math.min(index, removes.length - 1)] ??
list.querySelector<HTMLElement>('[data-add]');
target?.focus();
});
const canAdd =
onAdd != null && addLabel != null && !disabled && items.length < max;
if (items.length === 0 && !canAdd) return null;
@ -44,12 +59,13 @@ export function MediaStrip({
return (
<FlexBox
tag="ul"
ref={listRef}
aria-label={label}
wrap="flex-wrap"
gap="gap-2"
className={className}
>
{items.map((item) => {
{items.map((item, index) => {
const status = item.status ?? 'ready';
const retry =
status === 'error' && onRetry && item.retryLabel ? onRetry : null;
@ -64,7 +80,10 @@ export function MediaStrip({
<Element
tag="button"
type="button"
onClick={() => retry(item.key)}
onClick={() => {
retry(item.key);
focusRemoveAt(index);
}}
disabled={disabled}
aria-label={item.retryLabel}
className="block size-full cursor-pointer focus-visible:focus-ring disabled:cursor-not-allowed"
@ -86,9 +105,13 @@ export function MediaStrip({
<GridBox
tag="button"
type="button"
onClick={() => onRemove(item.key)}
onClick={() => {
onRemove(item.key);
focusRemoveAt(index);
}}
disabled={disabled}
aria-label={item.removeLabel}
data-remove
justifyItems="justify-items-center"
alignItems="items-center"
className="absolute end-1 top-1 z-1 size-7 cursor-pointer rounded-full bg-scrim-chip text-text-inverse focus-visible:focus-ring disabled:frozen"
@ -104,6 +127,7 @@ export function MediaStrip({
tag="button"
type="button"
onClick={onAdd}
data-add
justifyItems="justify-items-center"
alignContent="content-center"
className={cn(mediaStripAddVariants({ size }), 'gap-0.5')}

View File

@ -1,6 +1,6 @@
'use client';
import { useId, useRef } from 'react';
import { useEffect, useId, useRef } from 'react';
import { FlexBox } from '../../../atoms/flex-box';
import { Typography } from '../../../atoms/typography';
@ -16,7 +16,8 @@ import { SheetHead } from './SheetHead';
* A desktop popover, 320px (360px `wide`, the DS SharePopover), anchored by its caller in a positioned container next to the
* trigger. It hangs under the trigger at the inline end, and flips above or to the inline start
* when it would run off the screen. No scrim and not modal: Escape, the ✕ or a press outside
* closes it.
* closes it. Escape and the ✕ return focus to the trigger (`[aria-haspopup]` beside it); a press
* outside leaves focus where the press put it.
*/
export function SheetPopover({
open,
@ -31,7 +32,32 @@ export function SheetPopover({
}: SheetPopoverProps) {
const ref = useRef<HTMLDialogElement>(null);
const titleId = useId();
useDismiss(ref, open, onClose);
// Where focus was as it opened: the trigger when the press focused it.
const opener = useRef<HTMLElement | null>(null);
useEffect(() => {
if (open && document.activeElement instanceof HTMLElement)
opener.current = document.activeElement;
}, [open]);
// The popover's own trigger beside it (never a menu trigger inside the popover), else whatever
// held focus as it opened, such as a link elsewhere in the card.
const closeToTrigger = () => {
const popover = ref.current;
const beside = Array.from(
popover?.parentElement?.querySelectorAll<HTMLElement>(
'[aria-haspopup]',
) ?? [],
).find((element) => !popover?.contains(element));
const previous = opener.current;
const trigger =
beside ??
(previous?.isConnected && previous !== document.body
? previous
: undefined);
onClose?.();
trigger?.focus();
};
const close = onClose && closeToTrigger;
useDismiss(ref, open, onClose, close);
useFlip(ref, open);
if (!open) return null;
@ -50,7 +76,7 @@ export function SheetPopover({
<SheetHead
title={title}
titleId={titleId}
onClose={onClose}
onClose={close}
closeLabel={closeLabel}
compact
/>

View File

@ -4,20 +4,23 @@ import { useEffect, useEffectEvent } from 'react';
import type { RefObject } from 'react';
/**
* Closes a non-modal layer on Escape or a press outside it. "Outside" also excludes the layer's
* positioned parent, which holds its trigger, so a press on the trigger doesn't close and reopen.
* Closes a non-modal layer on Escape (`onEscape`, by default `onDismiss`) or a press outside it.
* "Outside" also excludes the layer's positioned parent, which holds its trigger, so a press on
* the trigger doesn't close and reopen.
*/
export function useDismiss(
ref: RefObject<HTMLElement | null>,
isOpen: boolean,
onDismiss?: () => void,
onEscape: (() => void) | undefined = onDismiss,
): void {
const dismiss = useEffectEvent(() => onDismiss?.());
const escape = useEffectEvent(() => onEscape?.());
useEffect(() => {
if (!isOpen) return undefined;
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') dismiss();
if (event.key === 'Escape') escape();
};
const handlePointerDown = (event: PointerEvent) => {
const area = ref.current?.parentElement ?? ref.current;

View File

@ -1,6 +1,6 @@
'use client';
import { useState } from 'react';
import { useRef, useState } from 'react';
import { Button } from '../../../atoms/button';
import { FlexBox } from '../../../atoms/flex-box';
@ -23,10 +23,12 @@ export function PostSharePopover({
url,
}: PostSharePopoverProps) {
const [isOpen, setIsOpen] = useState(false);
const triggerRef = useRef<HTMLButtonElement>(null);
return (
<FlexBox display="inline-flex" className="relative">
<Button
ref={triggerRef}
variant="ghost"
icon="share"
label={label}
@ -60,6 +62,8 @@ export function PostSharePopover({
block
onClick={() => {
setIsOpen(false);
// The copy button leaves with the popover: focus returns to share.
triggerRef.current?.focus();
onCopyLink();
}}
>

View File

@ -1,22 +1,24 @@
import { GridBox } from '../../../atoms/grid-box';
import { Typography } from '../../../atoms/typography';
import { Element } from '../../../primitives/element';
import type { LevelGlyphProps } from '../types';
import { glyphVariants } from '../variants';
/** The level's mark beside its name: stop square, entry ring, numbered target, close arrowhead. */
export function LevelGlyph({ kind, n, hit }: LevelGlyphProps) {
if (kind === 'target') {
return (
<Typography
tag="span"
aria-hidden
variant="inherit"
color="inherit"
className={glyphVariants({ kind, hit })}
>
{n}
</Typography>
);
}
return <Element tag="span" aria-hidden className={glyphVariants({ kind })} />;
return (
<GridBox
tag="span"
aria-hidden
display="inline-grid"
justifyItems="justify-items-center"
alignItems="items-center"
className={glyphVariants(kind === 'target' ? { kind, hit } : { kind })}
>
{kind === 'target' && (
<Typography tag="span" variant="inherit" color="inherit">
{n}
</Typography>
)}
</GridBox>
);
}

View File

@ -1,6 +1,7 @@
import { number, price } from '@lumina/tools/format';
import { FlexBox } from '../../../atoms/flex-box';
import { GridBox } from '../../../atoms/grid-box';
import { Typography } from '../../../atoms/typography';
import { Element } from '../../../primitives/element';
import { OUTCOME_TRENDS } from '../constants';
@ -73,28 +74,30 @@ export function PredictionRange({
/>
)}
{hasStop && (
<Element
<GridBox
tag="span"
className={markerVariants({ kind: 'stop' })}
style={atPosition(position(risk))}
/>
)}
<Element
<GridBox
tag="span"
className={markerVariants({ kind: 'entry' })}
style={atPosition(entry)}
/>
{targetsFav.map((target, index) => (
<Typography
<GridBox
key={index}
tag="span"
variant="inherit"
color="inherit"
justifyItems="justify-items-center"
alignItems="items-center"
className={markerVariants({ kind: 'target', hit: hits[index] })}
style={atPosition(position(target))}
>
{number(index + 1)}
</Typography>
<Typography tag="span" variant="inherit" color="inherit">
{number(index + 1)}
</Typography>
</GridBox>
))}
{close != null && (
<ClosePin x={close} tone={closeTrend}>

View File

@ -42,7 +42,7 @@ export const rangeBandVariants = cva(
/** A level on the track, centred on its place from the inline start. */
export const markerVariants = cva(
'absolute top-1/2 box-border grid -translate-x-1/2 -translate-y-1/2 place-items-center rtl:translate-x-1/2',
'absolute top-1/2 box-border -translate-x-1/2 -translate-y-1/2 rtl:translate-x-1/2',
{
variants: {
kind: {
@ -96,26 +96,23 @@ export const pinStemVariants = cva('h-2.5 w-0.5', {
});
/** The small level glyphs in the levels grid and the ladder, matching the track's markers. */
export const glyphVariants = cva(
'box-border inline-grid flex-none place-items-center',
{
variants: {
kind: {
stop: 'size-2.25 rounded-[2px] bg-danger',
entry: 'size-2.5 rounded-full border-[2.5px] border-text-primary',
target:
'size-3.5 rounded-full border-[1.5px] border-success text-[0.5625rem] leading-none font-bold text-success-text',
close:
'size-0 border-x-5 border-t-7 border-x-transparent border-t-text-secondary',
},
hit: {
true: 'border-success-solid bg-success-solid text-text-on-action',
false: '',
},
export const glyphVariants = cva('box-border flex-none', {
variants: {
kind: {
stop: 'size-2.25 rounded-[2px] bg-danger',
entry: 'size-2.5 rounded-full border-[2.5px] border-text-primary',
target:
'size-3.5 rounded-full border-[1.5px] border-success text-[0.5625rem] leading-none font-bold text-success-text',
close:
'size-0 border-x-5 border-t-7 border-x-transparent border-t-text-secondary',
},
hit: {
true: 'border-success-solid bg-success-solid text-text-on-action',
false: '',
},
defaultVariants: { hit: false },
},
);
defaultVariants: { hit: false },
});
/** Tiles fit as many per row as they can; long prices get wider ones so they never truncate. */
export const levelsVariants = cva('m-0', {

View File

@ -18,10 +18,12 @@ import {
SERVER_TIMEOUT,
} from './constants';
import {
asRequestError,
asUnauthorized,
createHttpError,
defaultMapErrorBody,
errorFromResponse,
isHttpError,
notConfiguredError,
toHttpError,
} from './http-error';
@ -380,15 +382,28 @@ export class HttpClient {
if (wantsRefresh) {
if (replayed) throw asUnauthorized(error);
replayed = true;
// A request sent before the latest refresh replays without another one.
if (coordinator.generation !== generation) continue;
const refreshed = await abortable(
coordinator.refresh(
() => this.sendRefresh(refresh),
refresh.onFailure,
),
signal,
);
// A request sent before the latest refresh replays, or fails when that refresh ended
// the session, without another one.
if (coordinator.generation !== generation) {
if (coordinator.renewed) continue;
throw asUnauthorized(error);
}
let refreshed: boolean;
try {
refreshed = await abortable(
coordinator.refresh(
() => this.sendRefresh(refresh),
refresh.onFailure,
),
signal,
);
} catch (failure) {
// The refresh failed for a reason that may pass (offline, timeout, 5xx): this request
// fails with that cause, reported as itself.
if (isHttpError(failure) && !signal.aborted)
throw asRequestError(failure, context);
throw failure;
}
if (refreshed) continue;
throw asUnauthorized(error);
}

View File

@ -130,6 +130,22 @@ export function toHttpError(
);
}
// Another request's failure (the shared refresh) told as this request's own: its cause and status,
// this request's id, method and URL, and none of the other request's field errors.
export function asRequestError(
error: HttpError,
context: RequestContext,
): HttpError {
return new HttpError({
...error.toJSON(),
requestId: context.requestId,
method: context.method,
url: context.url,
fieldErrors: undefined,
cause: error,
});
}
export function asUnauthorized(error: HttpError): HttpError {
if (error.code === 'UNAUTHORIZED') return error;
return new HttpError({

View File

@ -1,13 +1,21 @@
import { REFRESH_LOCK_NAME } from './constants';
import { isHttpError } from './http-error';
// Statuses that say "try again later" rather than "no".
const RETRY_LATER_STATUSES = [408, 429];
// One refresh at a time for the root client and every feature client.
export class RefreshCoordinator {
// Incremented on each successful refresh, so a stale 401 replays without refreshing again.
// Incremented each time a refresh settles the session (renewed or ended), so a stale 401 sent
// before it replays or fails without another refresh.
generation = 0;
// Whether the latest settled refresh renewed the session.
renewed = true;
private pending?: Promise<boolean>;
// Resolves true when the refresh succeeded. Joins the refresh in flight, if any.
// Resolves true when the refresh succeeded, false when the session ended. Rejects with the
// refresh's own error when it failed for another reason (offline, timeout, 5xx, aborted), so the
// session stays and the caller's request fails with that cause. Joins the refresh in flight.
refresh(
send: () => Promise<unknown>,
onFailure?: () => void,
@ -24,19 +32,35 @@ export class RefreshCoordinator {
): Promise<boolean> {
try {
await withLock(send);
this.generation += 1;
return true;
} catch (error) {
if (!(isHttpError(error) && error.code === 'ABORTED')) {
try {
onFailure?.();
} catch {
// A failing callback must not break the waiting requests.
}
if (!isSessionEnded(error)) throw error;
this.settle(false);
try {
onFailure?.();
} catch {
// A failing callback must not break the waiting requests.
}
return false;
}
this.settle(true);
return true;
}
private settle(renewed: boolean): void {
this.generation += 1;
this.renewed = renewed;
}
}
function isSessionEnded(error: unknown): boolean {
// The refresh endpoint refused it (any 4xx but a "later"): the session is over. A network blip,
// a timeout or a 5xx may pass.
return (
isHttpError(error) &&
error.status >= 400 &&
error.status < 500 &&
!RETRY_LATER_STATUSES.includes(error.status)
);
}
// Two tabs never send the same refresh cookie at once.

View File

@ -51,7 +51,7 @@ export interface RefreshConfig {
endpoint: string; // relative to baseUrl or absolute, e.g. '/auth/refresh'
method?: 'POST' | 'GET'; // default 'POST'
shouldRefresh?: (error: HttpError) => boolean; // default: error.status === 401
onFailure?: () => void; // called once per failed refresh, e.g. emit the logout event
onFailure?: () => void; // called once per refresh the server refused (a 4xx but 408/429), e.g. emit the logout event
}
export interface HttpClientConfig {

View File

@ -166,9 +166,10 @@ async function staleWhileRevalidate(event: FetchEvent): Promise<Response> {
const stored = await lookup(event.request);
if (!stored) return fromNetwork(event);
// The check finishes after the response: a changed file replaces the copy, an unchanged one
// counts as used, and a failed check keeps the copy.
// counts as used, and a failed check keeps the copy. It asks the server, past the HTTP cache,
// which holds fonts and the sprite as immutable and would only hand the same copy back.
event.waitUntil(
fetch(event.request).then(
fetch(event.request, { cache: 'no-cache' }).then(
(fresh) =>
isStorable(fresh) && !isSameFile(stored, fresh)
? store(event.request, fresh)
@ -253,23 +254,26 @@ worker.addEventListener('install', (event) => {
);
});
// Activation in progress, if this worker is activating. A page's message can arrive before it
// ends (`serviceWorker.ready` resolves while activating), and the cache exists only after it.
let activation: Promise<void> | undefined;
worker.addEventListener('activate', (event) => {
event.waitUntil(
(async () => {
await worker.registration.navigationPreload
?.enable()
.catch(() => undefined);
// The only place the cache is created (openCache).
await caches.open(cacheName).catch(() => undefined);
const names = await caches.keys();
await Promise.all(
names
.filter((name) => name.startsWith(cachePrefix) && name !== cacheName)
.map((name) => caches.delete(name)),
);
await worker.clients.claim();
})(),
);
activation = (async () => {
await worker.registration.navigationPreload
?.enable()
.catch(() => undefined);
// The only place the cache is created (openCache).
await caches.open(cacheName).catch(() => undefined);
const names = await caches.keys();
await Promise.all(
names
.filter((name) => name.startsWith(cachePrefix) && name !== cacheName)
.map((name) => caches.delete(name)),
);
await worker.clients.claim();
})();
event.waitUntil(activation);
});
worker.addEventListener('fetch', (event) => {
@ -296,6 +300,11 @@ worker.addEventListener('message', (event) => {
import('./types').CacheLoadedMessage
> | null;
if (message?.type === cacheLoadedMessage && Array.isArray(message.urls)) {
event.waitUntil(storeLoaded(message.urls));
const { urls } = message;
event.waitUntil(
Promise.resolve(activation)
.catch(() => undefined)
.then(() => storeLoaded(urls)),
);
}
});

View File

@ -22,3 +22,6 @@ export const NETWORK_COPY = {
NetworkState,
{ title: string; description: string | undefined }
>;
/** Waits before reading the session again after a read that may pass failed; the last repeats. */
export const SESSION_RESTORE_RETRY_MS = [2000, 5000, 10_000, 30_000];

View File

@ -8,21 +8,48 @@ import { AUTH_EVENTS, restoreSession } from '../../../features/auth';
import { useAuthStore } from '../../../stores/auth';
import { useCheckoutDraftStore } from '../../../stores/checkout-draft';
import { usePostDraftStore } from '../../../stores/post-draft';
import { SESSION_RESTORE_RETRY_MS } from '../constants';
/**
* The browser learns who the viewer is once per page load; auth-dependent parts wait in their
* skeleton until then. A read that failed offline or on a gateway error leaves the viewer unknown,
* so it runs again when the connection comes back. When the session ends (sign-out, or a refresh
* so it runs again after a growing wait, and at once when the connection comes back. When the session ends (sign-out, or a refresh
* that failed), the store goes back to guest and every cached query is dropped: it belonged to the
* old account. A sign-out, or a suspension mid-session (J01-3d), also drops what the account kept
* on the device (`session.` keys); a session that ran out keeps its drafts for the next sign-in.
*/
export function useSession(queryClient: QueryClient): void {
useEffect(() => {
const restore = () =>
restoreSession().catch((error: unknown) =>
handleError(error, { where: 'app', name: 'restore-session' }),
);
let disposed = false;
let inFlight = false;
let retryTimer: number | undefined;
let failures = 0;
const restore = async () => {
window.clearTimeout(retryTimer);
// One read at a time: the connection coming back during a read waits for its answer.
if (disposed || inFlight) return;
inFlight = true;
try {
await restoreSession();
failures = 0;
} catch (error) {
// A long outage reports once per chain, not on every retry.
if (failures === 0) {
handleError(error, { where: 'app', name: 'restore-session' });
}
if (disposed || useAuthStore.getState().status !== 'unknown') return;
// Offline, the `online` listener restores as the connection comes back.
if (!navigator.onLine) return;
const delay =
SESSION_RESTORE_RETRY_MS[
Math.min(failures, SESSION_RESTORE_RETRY_MS.length - 1)
];
failures += 1;
retryTimer = window.setTimeout(() => void restore(), delay);
} finally {
inFlight = false;
}
};
const restoreIfUnknown = () => {
if (useAuthStore.getState().status === 'unknown') void restore();
};
@ -40,6 +67,8 @@ export function useSession(queryClient: QueryClient): void {
storage.clearByPrefix('session.');
});
return () => {
disposed = true;
window.clearTimeout(retryTimer);
window.removeEventListener('online', restoreIfUnknown);
offLogout();
};

View File

@ -12,23 +12,39 @@ export const backTargetStore = createStore<{ target: BackTarget | null }>()(
() => ({ target: null }),
);
/**
* Sign-in and onboarding steps a finished flow left in history: their guards send a signed-in
* visitor straight back, so for a member returning to one looks like back did nothing. A guest
* still goes back to them (a sign-in step that opened the rules).
*/
const FLOW_PREFIXES = ['/auth/', '/onboarding/'];
const isFlowPath = (pathname: string) =>
FLOW_PREFIXES.some((prefix) => pathname.startsWith(prefix));
/**
* The key of the previous history entry when back should return to it (0057): `parentHref` itself,
* or, with `toPrevious`, any page of this site. The Navigation API lists only this site's entries,
* or, with `toPrevious`, any page of this site; for a signed-in viewer (`isMember`) not a sign-in
* or onboarding step the current page isn't part of. The Navigation API lists only this site's entries,
* so a page opened from a link, a notification, another site or the bank has none; without the
* API there is none either, and back opens `parentHref`.
*/
export function previousEntryKey(
parentHref: string,
toPrevious: boolean,
isMember: boolean,
): string | undefined {
if (!('navigation' in window)) return undefined;
const current = navigation.currentEntry;
if (!current || current.index < 1) return undefined;
const previous = navigation.entries()[current.index - 1];
if (!previous?.url) return undefined;
if (toPrevious) return previous.key;
const from = new URL(previous.url).pathname;
if (toPrevious) {
const leftFlow =
isMember && isFlowPath(from) && !isFlowPath(window.location.pathname);
return leftFlow ? undefined : previous.key;
}
const to = new URL(parentHref, window.location.href).pathname;
return from === to ? previous.key : undefined;
}

View File

@ -2,6 +2,7 @@
import { useRouter } from 'next/navigation';
import { useViewerStatus } from '../../../stores/auth';
import { previousEntryKey, traverseTo } from '../back-target';
import type { BackAction, BackOptions } from '../types';
import { useDeclaredBackTarget } from './use-back-target';
@ -12,10 +13,14 @@ type ParentOptions = Pick<BackOptions, 'parentHref' | 'backToPrevious'>;
/** The page's parent, and whether any page of this site behind it counts as the way back. */
function useParent({ parentHref, backToPrevious = false }: ParentOptions) {
const homeHref = useHomeHref();
// A viewer not known yet (right after a load) counts as a member, so a member never bounces off
// a sign-in step; only a known guest goes back to one.
const isMember = useViewerStatus() !== 'guest';
return {
href: parentHref ?? homeHref,
// Home is a fallback, not a parent the page names.
toPrevious: backToPrevious || parentHref === undefined,
isMember,
};
}
@ -36,7 +41,11 @@ export function useBack({ href, onBack, ...options }: BackOptions): BackAction {
return {
href: parent.href,
onNavigate: (event) => {
const key = previousEntryKey(parent.href, parent.toPrevious);
const key = previousEntryKey(
parent.href,
parent.toPrevious,
parent.isMember,
);
if (key === undefined) return;
event.preventDefault();
traverseTo(key);
@ -49,7 +58,11 @@ export function useGoBack(options: ParentOptions): () => void {
const router = useRouter();
const parent = useParent(options);
return () => {
const key = previousEntryKey(parent.href, parent.toPrevious);
const key = previousEntryKey(
parent.href,
parent.toPrevious,
parent.isMember,
);
if (key === undefined) router.push(parent.href);
else traverseTo(key);
};

View File

@ -28,6 +28,7 @@ export {
ROUTES,
subscribeLoginRoute,
withReturnPath,
withSearchParams,
} from './navigation';
export { safeReturnPath } from './return-path';
export type { AuthRoutes, BackOptions, DialogRoute } from './types';

View File

@ -124,3 +124,21 @@ export function withReturnPath(
): string {
return returnTo ? `${path}?redirect=${encodeURIComponent(returnTo)}` : path;
}
/**
* `href` with a page's query string kept, as a page's `searchParams` give it: a redirect to another
* spelling of the same page keeps `?code=` (0059) and the rest.
*/
export function withSearchParams(
href: string,
searchParams: Record<string, string | string[] | undefined>,
): string {
const query = new URLSearchParams();
for (const [key, value] of Object.entries(searchParams)) {
for (const item of Array.isArray(value) ? value : [value]) {
if (item !== undefined) query.append(key, item);
}
}
const search = query.toString();
return search ? `${href}?${search}` : href;
}

View File

@ -2,6 +2,7 @@
import { useTranslation } from 'react-i18next';
import { useInviteLink } from '../../../../../../../features/checkout';
import { AuthGuard } from '../../../../../../guards/auth-guard';
import { CheckoutForm } from './components/CheckoutForm';
import { CheckoutSkeleton } from './CheckoutSkeleton';
@ -10,10 +11,13 @@ import type { CheckoutPanelProps } from './types';
/**
* Checkout below the page's bar (U9). The creator row comes from the server; the rest is the
* investor's own (their standing, the code, the payment), so it renders in the browser behind a
* same-size skeleton. A guest goes to login and comes back here; a creator gets no access.
* same-size skeleton. A guest goes to login and comes back here; a creator gets no access. A
* `?code=` is kept for this creator on arrival, before the guard knows the viewer (0059), so a
* guest who leaves the sign-in still has it; the form drops it from the address once it opens.
*/
export function CheckoutPanel(props: CheckoutPanelProps) {
const { t } = useTranslation('payment');
useInviteLink(props.creatorId);
return (
<AuthGuard

View File

@ -20,11 +20,7 @@ export function CheckoutSkeleton({
const padding = layout === 'desktop' ? 'lg' : 'md';
return (
<SkeletonRegion
label={label}
delayed={delayed}
className="flex flex-1 flex-col"
>
<SkeletonRegion label={label} delayed={delayed} className="flex-1">
<CheckoutFrame
layout={layout}
creator={creator}

View File

@ -3,6 +3,7 @@ import { Button } from '@lumina/island/atoms/button';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { StateArt } from '@lumina/island/atoms/state-art';
import { Typography } from '@lumina/island/atoms/typography';
import { useOfflineFreeze } from '@lumina/island/hooks/use-online';
import { useTranslation } from 'react-i18next';
import { ROUTES } from '../../../../../../../navigation/navigation';
@ -18,7 +19,9 @@ import { HaltDialog } from './HaltDialog';
* (۶.۱); already on it, one way back (۶.۲).
*/
export function CheckoutHalts({ model, layout }: CheckoutPartProps) {
const { t } = useTranslation('payment');
const { t } = useTranslation(['payment', 'common']);
// Paying the new price and joining the waitlist need the network: frozen offline, saying why.
const offline = useOfflineFreeze(t('common:network.frozen'));
const { halt, phase } = model;
const size = layout === 'mobile' ? 'lg' : 'md';
const currency = t('tier.currency');
@ -37,6 +40,7 @@ export function CheckoutHalts({ model, layout }: CheckoutPartProps) {
variant="primary"
size={size}
block
{...offline}
onClick={model.confirmPriceChange}
>
{t('checkout.price-changed.confirm')}
@ -104,6 +108,7 @@ export function CheckoutHalts({ model, layout }: CheckoutPartProps) {
size={size}
block
isLoading={phase === 'joining'}
{...offline}
onClick={model.joinWaitlist}
>
{t('checkout.waitlist.join')}

View File

@ -10,7 +10,7 @@ import { useTranslation } from 'react-i18next';
import {
displaySocialUrl,
fromSocialUrl,
toSocialLink,
} from '../../../../../../../../shared/utils';
import { SupportDialog } from '../../../../../../organisms/support-entry';
import type { NoCodeSheetProps } from '../types';
@ -46,16 +46,16 @@ export function NoCodeSheet({
{hasLinks ? (
<List tone="soft" aria-label={t('checkout.no-code.links')}>
{creatorLinks.map(({ label, url }) => {
const { platform } = fromSocialUrl(label, url);
const { platform, href } = toSocialLink(label, url);
const address = (
<Element tag="bdi" dir="ltr">
{displaySocialUrl(url)}
{displaySocialUrl(href)}
</Element>
);
return (
<ListRow
key={url}
href={url}
key={href}
href={href}
external
icon={platform === 'telegram' ? 'telegram' : 'link'}
title={

View File

@ -2,6 +2,7 @@ import { Button } from '@lumina/island/atoms/button';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Icon } from '@lumina/island/atoms/icon';
import { Typography } from '@lumina/island/atoms/typography';
import { useOfflineFreeze } from '@lumina/island/hooks/use-online';
import { Banner } from '@lumina/island/molecules/banner';
import { SegmentedChoice } from '@lumina/island/molecules/segmented-choice';
import { TextInput } from '@lumina/island/molecules/text-input';
@ -22,7 +23,8 @@ import { ComposerLimit } from './ComposerLimit';
* field (۳.۲). Mobile: twelve rows, eight once there are images; desktop: six.
*/
export function ComposerBody({ model, layout, picker }: ComposerBodyProps) {
const { t } = useTranslation('content');
const { t } = useTranslation(['content', 'common']);
const offline = useOfflineFreeze(t('common:network.frozen'));
const { form, images, phase, mode } = model;
const isSaving = phase === 'saving';
const rows = layout === 'desktop' ? 6 : images.images.length > 0 ? 8 : 12;
@ -52,6 +54,7 @@ export function ComposerBody({ model, layout, picker }: ComposerBodyProps) {
<Button
variant="secondary"
icon="refresh"
{...offline}
onClick={model.submit}
disabled={isSaving || model.isEditExpired}
>

View File

@ -9,6 +9,7 @@ import { useTranslation } from 'react-i18next';
import { usePostComposerPage } from '../../../../../../../../features/post';
import { MobileTopBar } from '../../../../../../../navigation/components/mobile-top-bar';
import { useGoBack } from '../../../../../../../navigation/hooks/use-back';
import { ROUTES } from '../../../../../../../navigation/navigation';
import type { ComposerFormProps } from '../types';
import { ComposerAddImage } from './ComposerAddImage';
@ -35,10 +36,17 @@ export function ComposerForm({
const { t } = useTranslation('content');
const router = useRouter();
const picker = useRef<HTMLInputElement>(null);
// Back as the bar's back (0057): to any page of this site behind it, else the post or channel.
const goBack = useGoBack({
parentHref: post
? ROUTES.post(username, post.id)
: ROUTES.channel(username),
backToPrevious: true,
});
const model = usePostComposerPage({
creatorId,
post,
onDone: (saved) => {
onDone: () => {
// Replaced, so back never reopens an empty composer.
if (!post) {
router.replace(ROUTES.channel(username));
@ -47,13 +55,9 @@ export function ComposerForm({
// Back restores the page as the router kept it, from before the edit. The refresh drops
// those copies at once (the navigation then takes over from it), so that page is read again.
router.refresh();
if (window.history.length > 1) router.back();
else router.replace(ROUTES.post(username, saved.id));
},
onLeave: () => {
if (window.history.length > 1) router.back();
else router.push(ROUTES.channel(username));
goBack();
},
onLeave: goBack,
});
const title = t(post ? 'composer.edit-title' : 'composer.new-title');

View File

@ -5,6 +5,7 @@ import { useRef } from 'react';
import type { ChangeEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { translateMessage } from '../../../../../../../../shared/utils';
import { CHART_ACCEPT } from '../constants';
import type { ComposerPartProps } from '../types';
import { FieldGroup } from './FieldGroup';
@ -20,6 +21,8 @@ export function ChartField({ model, layout }: ComposerPartProps) {
const { image } = chart;
const n = number(1);
const busy = model.phase === 'publishing';
// The API's refusal of the uploaded chart; a new pick or ✕ clears it.
const serverError = model.form.formState.errors.root?.chart?.message;
const onPick = (event: ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
@ -32,7 +35,9 @@ export function ChartField({ model, layout }: ComposerPartProps) {
<FieldGroup
label={t('composer.chart')}
error={
chart.error ? t(`content:composer.images.${chart.error}`) : undefined
chart.error
? t(`content:composer.images.${chart.error}`)
: translateMessage(t, serverError)
}
caption={t('content:composer.images.hint')}
>

View File

@ -10,6 +10,7 @@ import { useTranslation } from 'react-i18next';
import { usePredictionComposerPage } from '../../../../../../../../features/prediction';
import { MobileTopBar } from '../../../../../../../navigation/components/mobile-top-bar';
import { useGoBack } from '../../../../../../../navigation/hooks/use-back';
import { ROUTES } from '../../../../../../../navigation/navigation';
import type { ComposerPageProps } from '../types';
import { ComposerFields } from './ComposerFields';
@ -33,14 +34,16 @@ export function ComposerPage({
}: ComposerPageProps) {
const { t } = useTranslation('predictions');
const router = useRouter();
// Back as the bar's back (0057): to any page of this site behind it, else the channel.
const goBack = useGoBack({
parentHref: ROUTES.channel(username),
backToPrevious: true,
});
const model = usePredictionComposerPage({
creatorId,
// Replaced, so back never reopens an empty composer.
onDone: () => router.replace(ROUTES.channel(username)),
onLeave: () => {
if (window.history.length > 1) router.back();
else router.push(ROUTES.channel(username));
},
onLeave: goBack,
});
const cancel = (
<Button

View File

@ -3,6 +3,7 @@ import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Icon } from '@lumina/island/atoms/icon';
import { Separator } from '@lumina/island/atoms/separator';
import { Typography } from '@lumina/island/atoms/typography';
import { useOfflineFreeze } from '@lumina/island/hooks/use-online';
import { DetailRow } from '@lumina/island/molecules/detail-row';
import { KeyValue } from '@lumina/island/molecules/key-value';
import { Modal } from '@lumina/island/molecules/modal';
@ -19,7 +20,8 @@ import type { ComposerPartProps } from '../types';
* dismisses it. A bottom sheet on mobile, a 420px modal on desktop.
*/
export function ConfirmPublish({ model, layout }: ComposerPartProps) {
const { t } = useTranslation(['predictions', 'content']);
const { t } = useTranslation(['predictions', 'content', 'common']);
const offline = useOfflineFreeze(t('common:network.frozen'));
const summary = model.confirmSummary;
const isPublishing = model.phase === 'publishing';
const size = layout === 'mobile' ? 'lg' : undefined;
@ -102,6 +104,7 @@ export function ConfirmPublish({ model, layout }: ComposerPartProps) {
size={size}
block
isLoading={isPublishing}
{...offline}
onClick={model.publish}
>
{t('composer.confirm.submit')}

View File

@ -1,14 +1,16 @@
import { Button } from '@lumina/island/atoms/button';
import { useOfflineFreeze } from '@lumina/island/hooks/use-online';
import { useTranslation } from 'react-i18next';
import type { ComposerPartProps } from '../types';
/**
* «انتشار پیش‌بینی»: frozen until the form can publish, saying why (J09-1b, J09-2, J09-2c); a
* press checks the form, then asks to confirm (J09-3).
* press checks the form, then asks to confirm (J09-3). Offline it freezes and says why (0043).
*/
export function PublishButton({ model, layout }: ComposerPartProps) {
const { t } = useTranslation('predictions');
const { t } = useTranslation(['predictions', 'common']);
const offline = useOfflineFreeze(t('common:network.frozen'));
const isMobile = layout === 'mobile';
return (
@ -16,8 +18,8 @@ export function PublishButton({ model, layout }: ComposerPartProps) {
variant="primary"
size={isMobile ? 'lg' : undefined}
block={isMobile}
frozen={model.publishBlock.frozen}
frozenReason={model.publishBlock.reason}
frozen={offline.frozen || model.publishBlock.frozen}
frozenReason={offline.frozenReason ?? model.publishBlock.reason}
frozenAlign={isMobile ? undefined : 'end'}
isLoading={model.phase === 'publishing'}
onClick={model.requestPublish}

View File

@ -14,11 +14,7 @@ export function PaymentResultSkeleton({
delayed,
}: PaymentResultSkeletonProps) {
return (
<SkeletonRegion
label={label}
delayed={delayed}
className="flex flex-1 flex-col"
>
<SkeletonRegion label={label} delayed={delayed} className="flex-1">
<ResultFrame
layout={layout}
body={

View File

@ -3,6 +3,8 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Icon } from '@lumina/island/atoms/icon';
import { Typography } from '@lumina/island/atoms/typography';
import { useOfflineFreeze } from '@lumina/island/hooks/use-online';
import { Banner } from '@lumina/island/molecules/banner';
import { useTranslation } from 'react-i18next';
import { useNotificationSettingsPage } from '../../../../../../../features/notification-settings';
@ -12,22 +14,26 @@ import type { NotificationSettingsProps } from './types';
/**
* تنظیمات اعلان‌ها (J12-3, J12-3b): «اعلان در لومینا» and «پیامک», each a card of switches for
* the member's role, then the lock line naming the SMS that always go. No save button: each switch
* saves as it flips, and «تنظیمات ذخیره شد.» confirms it.
* saves as it flips, and «تنظیمات ذخیره شد.» confirms it. Offline every switch freezes and one
* banner says why (0043).
*/
export function NotificationSettings({ layout }: NotificationSettingsProps) {
const { t } = useTranslation('account');
const { t } = useTranslation(['account', 'common']);
const model = useNotificationSettingsPage();
const offline = useOfflineFreeze(t('common:network.frozen'));
return (
<FlexBox
direction="flex-col"
gap={layout === 'desktop' ? 'gap-4' : 'gap-3'}
>
{offline.frozen && <Banner tone="warning" title={offline.frozenReason} />}
{model.sections.map((section) => (
<SettingsSection
key={section.channel}
section={section}
model={model}
frozen={offline.frozen === true}
/>
))}
<FlexBox

View File

@ -12,8 +12,13 @@ import type { SettingsSectionProps } from '../types';
/**
* One channel (اعلان در لومینا, پیامک): its title, then a card of switches with a hairline between
* them. Each row's name and line under it are front copy per role; a locked one is on and frozen.
* `frozen` (offline) holds every switch as it is.
*/
export function SettingsSection({ section, model }: SettingsSectionProps) {
export function SettingsSection({
section,
model,
frozen,
}: SettingsSectionProps) {
const { t, i18n } = useTranslation('account');
const titleId = useId();
// The row keys come from the API, so their copy is looked up by a built key.
@ -44,7 +49,7 @@ export function SettingsSection({ section, model }: SettingsSectionProps) {
)}
<Switch
checked={row.enabled}
locked={row.locked}
locked={row.locked || frozen}
description={
i18n.exists(`${copy}.description`)
? translate(`${copy}.description`)

View File

@ -18,4 +18,6 @@ export type NotificationSettingsSkeletonProps = NotificationSettingsProps & {
export type SettingsSectionProps = {
section: NotificationSettingsSection;
model: NotificationSettingsPageModel;
/** Offline: every switch is held, the page's banner says why. */
frozen: boolean;
};

View File

@ -69,7 +69,8 @@ export function GuestActions({
)}
</FlexBox>
{!saleOpen && <SaleClosedNote />}
{saleOpen && inviteNoteName !== undefined && (
{/* A guest who came with the code is told so instead of where to get one. */}
{saleOpen && !hasInviteCode && inviteNoteName !== undefined && (
<InviteOnlyNote name={inviteNoteName} />
)}
{followsToSubscribe && <InviteLinkNote />}

View File

@ -131,8 +131,11 @@ export function InvestorActions({
onCancel={standing.saleNotice ? cancelSaleNotice : undefined}
/>
)}
{/* Only when nothing else is said under the row: not with the link's code or a failed payment. */}
{subscribeLive &&
!standing.waitlisted &&
!hasInviteCode &&
!standing.paymentFailed &&
inviteNoteName !== undefined && (
<InviteOnlyNote name={inviteNoteName} />
)}

View File

@ -5,7 +5,7 @@ import { Element } from '@lumina/island/primitives/element';
import {
displaySocialUrl,
fromSocialUrl,
toSocialLink,
} from '../../../../../../../../shared/utils';
import type { ChannelLinksProps } from '../types';
@ -17,12 +17,12 @@ export function ChannelLinks({ links, labels }: ChannelLinksProps) {
return (
<FlexBox tag="ul" aria-label={labels.links} wrap="flex-wrap" xGap="gap-x-5">
{links.map(({ label, url }) => {
const { platform } = fromSocialUrl(label, url);
const { platform, href } = toSocialLink(label, url);
return (
<Element tag="li" key={url}>
<Element tag="li" key={href}>
<FlexBox
tag="a"
href={url}
href={href}
target="_blank"
rel="noopener noreferrer"
alignItems="items-center"
@ -38,7 +38,7 @@ export function ChannelLinks({ links, labels }: ChannelLinksProps) {
>
{platform === 'website' ? (
<Element tag="bdi" dir="ltr">
{displaySocialUrl(url)}
{displaySocialUrl(href)}
</Element>
) : (
labels.platforms[platform]

View File

@ -2,7 +2,7 @@
import { Modal } from '@lumina/island/molecules/modal';
import { Sheet } from '@lumina/island/molecules/sheet';
import { Suspense } from 'react';
import { Suspense, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { PartBoundary } from '../../../../../../error-boundaries';
@ -12,7 +12,8 @@ import type { RenewalSheetProps } from './types';
/**
* «تمدید» and «فعال‌سازی مجدد» (U3): a bottom sheet on mobile, a centred modal on desktop (U2
* ۴.۳). ✕, Escape and the scrim close it. The periods load inside it, with their own skeleton and
* ۴.۳). ✕, Escape and the scrim close it, except while a payment is starting: the request would
* still send the investor to the bank after they dismissed it. The periods load inside it, with their own skeleton and
* error, so a failure never touches the list behind it.
*/
export function RenewalSheet({
@ -22,6 +23,7 @@ export function RenewalSheet({
onClose,
}: RenewalSheetProps) {
const { t } = useTranslation('dashboard');
const [isBusy, setIsBusy] = useState(false);
const title =
target.status === 'expired'
? t('subscriptions.renewal.reactivate-title')
@ -40,6 +42,7 @@ export function RenewalSheet({
key={target.id}
subscriptionId={target.id}
layout={layout}
onBusyChange={setIsBusy}
/>
</Suspense>
</PartBoundary>
@ -47,11 +50,23 @@ export function RenewalSheet({
const closeLabel = t('subscriptions.renewal.close');
return layout === 'mobile' ? (
<Sheet open={open} title={title} onClose={onClose} closeLabel={closeLabel}>
<Sheet
open={open}
title={title}
onClose={onClose}
closeLabel={closeLabel}
dismissible={!isBusy}
>
{body}
</Sheet>
) : (
<Modal open={open} title={title} onClose={onClose} closeLabel={closeLabel}>
<Modal
open={open}
title={title}
onClose={onClose}
closeLabel={closeLabel}
dismissible={!isBusy}
>
{body}
</Modal>
);

View File

@ -10,7 +10,7 @@ import { Banner } from '@lumina/island/molecules/banner';
import { TierOption } from '@lumina/island/organisms/tier-option';
import { Element } from '@lumina/island/primitives/element';
import { date } from '@lumina/tools/format';
import { useId } from 'react';
import { useEffect, useId } from 'react';
import { useTranslation } from 'react-i18next';
import { useRenewalSheet } from '../../../../../../../../features/subscription';
@ -29,7 +29,11 @@ import type { RenewalFormProps } from '../types';
* button. Renew starts on the current period; reactivate starts with none, so its button stays
* frozen and says why until one is picked (R3 05). Dates and total follow the choice.
*/
export function RenewalForm({ subscriptionId, layout }: RenewalFormProps) {
export function RenewalForm({
subscriptionId,
layout,
onBusyChange,
}: RenewalFormProps) {
const { t } = useTranslation('dashboard');
const { t: tPayment } = useTranslation('payment');
const { t: tCommon } = useTranslation('common');
@ -43,6 +47,11 @@ export function RenewalForm({ subscriptionId, layout }: RenewalFormProps) {
const countdownLabels = promotionCountdownLabels(tPayment);
const from = selectedTier?.periodFrom ?? tiers[0]?.periodFrom;
const isBusy = phase !== 'idle';
// Unmounted (a boundary took over), it never holds the sheet open.
useEffect(() => {
onBusyChange(isBusy);
return () => onBusyChange(false);
}, [isBusy, onBusyChange]);
const payLabel = isBusy
? t('subscriptions.renewal.paying')
: model.isOffline

View File

@ -13,4 +13,6 @@ export type RenewalSheetProps = {
export type RenewalFormProps = {
subscriptionId: string;
layout: DashboardLayout;
/** True from «پرداخت» until the bank or a failure: the sheet can't be closed meanwhile. */
onBusyChange: (busy: boolean) => void;
};

View File

@ -1,8 +1,10 @@
'use client';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
import { Sheet } from '@lumina/island/molecules/sheet';
import { Suspense } from 'react';
import type { MouseEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { PartBoundary } from '../../../../../error-boundaries';
@ -11,10 +13,18 @@ import type { NotificationPanelProps } from './types';
/**
* The centre on desktop (U5 ۴.۱): a 400px side panel from the header's bell, over whatever page is
* open. ✕, Escape and the scrim close it. The list loads inside it with its own skeleton and error.
* open. ✕, Escape and the scrim close it, and so does following any of its links, also one to the
* page already open with a new query (a ledger entry, a renewal). The list loads inside it with its
* own skeleton and error.
*/
export function NotificationPanel({ open, onClose }: NotificationPanelProps) {
const { t } = useTranslation('notifications');
const closeOnLink = (event: MouseEvent<HTMLDivElement>) => {
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey)
return;
const target = event.target instanceof Element ? event.target : null;
if (target?.closest('a[href]')) onClose();
};
const skeleton = (
<SkeletonPreset preset="list" avatar={false} label={t('loading')} />
);
@ -27,11 +37,13 @@ export function NotificationPanel({ open, onClose }: NotificationPanelProps) {
onClose={onClose}
closeLabel={t('close')}
>
<PartBoundary name="notification-centre" description={t('error')}>
<Suspense fallback={skeleton}>
<NotificationCentre layout="panel" supportPlacement="popover" />
</Suspense>
</PartBoundary>
<FlexBox direction="flex-col" onClick={closeOnLink}>
<PartBoundary name="notification-centre" description={t('error')}>
<Suspense fallback={skeleton}>
<NotificationCentre layout="panel" supportPlacement="popover" />
</Suspense>
</PartBoundary>
</FlexBox>
</Sheet>
);
}

View File

@ -4,6 +4,7 @@ import { Button } from '@lumina/island/atoms/button';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Icon } from '@lumina/island/atoms/icon';
import { Typography } from '@lumina/island/atoms/typography';
import { useOfflineFreeze } from '@lumina/island/hooks/use-online';
import { Banner } from '@lumina/island/molecules/banner';
import { Modal } from '@lumina/island/molecules/modal';
import { Sheet } from '@lumina/island/molecules/sheet';
@ -38,6 +39,7 @@ export function ClosePredictionSheet({
const { t } = useTranslation('predictions');
const { t: tContent } = useTranslation('content');
const { t: tCommon } = useTranslation('common');
const offline = useOfflineFreeze(tCommon('network.frozen'));
const cardLabels = useMemo(() => predictionCardLabels(tContent), [tContent]);
const model = useClosePredictionPart({ post, onDone: onClose });
const size = layout === 'mobile' ? 'lg' : undefined;
@ -102,8 +104,8 @@ export function ClosePredictionSheet({
variant="primary"
size={size}
block
frozen={model.view !== 'quote'}
frozenReason={blockedReason}
frozen={offline.frozen || model.view !== 'quote'}
frozenReason={offline.frozenReason ?? blockedReason}
isLoading={model.isClosing}
onClick={model.close}
>

View File

@ -1,6 +1,7 @@
'use client';
import { Button } from '@lumina/island/atoms/button';
import { useOfflineFreeze } from '@lumina/island/hooks/use-online';
import { Modal } from '@lumina/island/molecules/modal';
import { Sheet } from '@lumina/island/molecules/sheet';
import { useTranslation } from 'react-i18next';
@ -19,7 +20,8 @@ export function DeletePostConfirm({
onCancel,
layout,
}: DeletePostConfirmProps) {
const { t } = useTranslation('content');
const { t } = useTranslation(['content', 'common']);
const offline = useOfflineFreeze(t('common:network.frozen'));
const size = layout === 'mobile' ? 'lg' : undefined;
const title = t('post.delete.title');
const buttons = (
@ -29,6 +31,7 @@ export function DeletePostConfirm({
size={size}
block
isLoading={isDeleting}
{...offline}
onClick={onConfirm}
>
{t('post.delete.confirm')}

View File

@ -12,9 +12,9 @@ import type {
/** Creates an investor account and signs it in (cookies and auth store); the flow's number and token are dropped. Emits `auth.register`. */
export async function registerInvestor(
args: RegisterInvestorArgs,
{ emit = true }: { emit?: boolean } = {},
{ emit = true, signal }: { emit?: boolean; signal?: AbortSignal } = {},
): Promise<SessionPayload> {
const session = await authRepository.registerInvestor(args);
const session = await authRepository.registerInvestor(args, { signal });
useAuthFlowStore.getState().reset();
useAuthFlowStore.getState().markRegistered(session.account.role);
useAuthStore.getState().setSession(session);

View File

@ -29,6 +29,7 @@ import type {
} from './types';
import { useRegisterLeave } from './use-register-leave';
import { useRegistrationAutosave } from './use-registration-autosave';
import { useRegistrationRequest } from './use-registration-request';
import { useUsernameAvailability } from './use-username-availability';
/** `RegisterCreatorArgs` names → this form's fields, so server errors land under their field. */
@ -82,7 +83,9 @@ export function useCreatorIdentityPart({
const username = useUsernameAvailability(form);
const { errors, isSubmitting } = form.formState;
const saveDraft = useRegistrationAutosave(form);
const request = useRegistrationRequest();
const leave = useRegisterLeave(submission.phase !== 'done', () => {
request.cancel();
useAuthFlowStore.getState().keepDraft(form.getValues());
saveDraft();
});
@ -115,6 +118,7 @@ export function useCreatorIdentityPart({
return;
}
setSubmission({ phase: 'uploading', progress: 0 });
const signal = request.start();
try {
await registerCreator(
{
@ -129,6 +133,7 @@ export function useCreatorIdentityPart({
nationalIdBackImage: values.idCardBack,
},
{
signal,
onProgress: ({ percent }) =>
setSubmission({ phase: 'uploading', progress: percent }),
},
@ -137,6 +142,8 @@ export function useCreatorIdentityPart({
showToast({ tone: 'success', message: t('register.identity.success') });
router.replace(profileHref);
} catch (error) {
// Cancelled because the person left: nothing to show.
if (signal.aborted) return;
setSubmission({ phase: 'idle' });
if (authErrorCode(error) === AUTH_ERROR_CODES.registrationExpired) {
onExpired();

View File

@ -21,6 +21,7 @@ import {
import type { InvestorDetailsPartModel, UseDetailsPartOptions } from './types';
import { useRegisterLeave } from './use-register-leave';
import { useRegistrationAutosave } from './use-registration-autosave';
import { useRegistrationRequest } from './use-registration-request';
import { useUsernameAvailability } from './use-username-availability';
/**
@ -56,7 +57,9 @@ export function useInvestorDetailsPart({
const [isDone, setIsDone] = useState(false);
const { errors, isSubmitting } = form.formState;
const saveDraft = useRegistrationAutosave(form);
const request = useRegistrationRequest();
const leave = useRegisterLeave(!isDone, () => {
request.cancel();
useAuthFlowStore.getState().keepDraft(form.getValues());
saveDraft();
});
@ -75,16 +78,18 @@ export function useInvestorDetailsPart({
);
return;
}
const signal = request.start();
try {
await registerInvestor({
phone,
registrationToken: registration.token,
...values,
});
await registerInvestor(
{ phone, registrationToken: registration.token, ...values },
{ signal },
);
setIsDone(true);
showToast({ tone: 'success', message: t('register.details.success') });
router.replace(profileHref);
} catch (error) {
// Cancelled because the person left: nothing to show.
if (signal.aborted) return;
if (authErrorCode(error) === AUTH_ERROR_CODES.registrationExpired) {
onExpired();
return;

View File

@ -14,7 +14,8 @@ type DraftFields = { firstName: string; lastName: string; username: string };
* token, so logging in with the number later resumes them; the ID images are never kept. A pause
* in typing saves, and so does leaving the step (the returned `flush`, and unmounting). Unchanged
* values aren't sent again. Nothing is saved without a token (after registering, or a reload). A
* failed save is left alone: it is a convenience, and the next pause tries again.
* failed save is left alone: it is a convenience, and the next pause tries again. Saves go one
* after another, so a slow older one never lands after a newer one.
*/
export function useRegistrationAutosave<T extends FieldValues & DraftFields>(
form: UseFormReturn<T, unknown, unknown>,
@ -22,6 +23,7 @@ export function useRegistrationAutosave<T extends FieldValues & DraftFields>(
const pending = useRef<DraftFields | null>(null);
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const lastSaved = useRef<string | null>(null);
const queue = useRef<Promise<void>>(Promise.resolve());
const flush = useCallback(() => {
clearTimeout(timer.current);
@ -32,16 +34,20 @@ export function useRegistrationAutosave<T extends FieldValues & DraftFields>(
const key = JSON.stringify(fields);
if (key === lastSaved.current) return;
lastSaved.current = key;
authRepository
.saveRegistrationDraft({
phone,
registrationToken: registration.token,
role: role ?? undefined,
...fields,
})
.catch(() => {
lastSaved.current = null;
});
const draft = {
phone,
registrationToken: registration.token,
role: role ?? undefined,
...fields,
};
queue.current = queue.current
.then(() => authRepository.saveRegistrationDraft(draft))
.then(
() => undefined,
() => {
if (lastSaved.current === key) lastSaved.current = null;
},
);
}, []);
useEffect(

View File

@ -0,0 +1,25 @@
import { useEffect, useMemo, useRef } from 'react';
/**
* The register request in flight. Leaving the step or unmounting cancels the browser's side, so
* the page never signs in and navigates after the person chose to go. A request the API already
* finished stays done: the account exists and the next session read signs the person in.
*/
export function useRegistrationRequest(): {
start: () => AbortSignal;
cancel: () => void;
} {
const controller = useRef<AbortController | null>(null);
useEffect(() => () => controller.current?.abort(), []);
return useMemo(
() => ({
start: () => {
controller.current?.abort();
controller.current = new AbortController();
return controller.current.signal;
},
cancel: () => controller.current?.abort(),
}),
[],
);
}

View File

@ -139,12 +139,15 @@ export const authRepository = {
return toOtpSentPayload(response);
},
async registerInvestor(args: RegisterInvestorArgs): Promise<SessionPayload> {
async registerInvestor(
args: RegisterInvestorArgs,
{ signal }: { signal?: AbortSignal } = {},
): Promise<SessionPayload> {
const response = await send(() =>
authHttp.post<SessionResponseDto>(
AUTH_ENDPOINTS.registerInvestor,
toRegisterInvestorDto(args),
{ skipRefresh: true },
{ skipRefresh: true, signal },
),
);
return toSessionPayload(response);

View File

@ -324,9 +324,12 @@ export function useCheckoutPage({
showActionError(error, options);
};
// `confirmedPriceToman` is the new price the investor accepted in the price-change halt: it is
// sent as the expected price, so a price that moves again halts again instead of charging an
// amount they never saw.
const submit = async (
{ tierId: chosen, referralCode: code }: CheckoutFormOutput,
confirmPriceChange = false,
confirmedPriceToman?: number,
) => {
const tier = tiers.find((item) => item.id === chosen);
setPhase('paying');
@ -337,8 +340,8 @@ export function useCheckoutPage({
creatorId,
tierId: chosen,
referralCode: code,
expectedPriceToman: tier?.priceToman ?? undefined,
confirmPriceChange: confirmPriceChange || undefined,
expectedPriceToman:
confirmedPriceToman ?? tier?.priceToman ?? undefined,
}),
);
} catch (error) {
@ -440,13 +443,18 @@ export function useCheckoutPage({
isOffline,
halt,
confirmPriceChange: () => {
const confirmed = halt?.kind === 'price-changed' ? halt : null;
setHalt(null);
// The tiers show the price the investor just accepted.
refreshScreen();
// Reactivation pays the live price with no confirmation to send, so it simply goes again.
if (reactivation && selectedTier) {
void reactivate(selectedTier.id, reactivation.id);
return;
}
void form.handleSubmit((values) => submit(values, true))();
void form.handleSubmit((values) =>
submit(values, confirmed?.newAmountToman),
)();
},
cancelPriceChange: () => {
setHalt(null);

View File

@ -1,3 +1,4 @@
import { isHttpError } from '@lumina/libs/http';
import { useQuery } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';
@ -9,6 +10,17 @@ import { transactionKeys, transactionRepository } from '../../../transaction';
import { PAYMENT_CONFIRM_TIMEOUT_MS, PAYMENT_POLL_MS } from '../../constants';
import type { UsePaymentReturnPageOptions } from './types';
/** A refusal no later read changes (an unknown payment, another account's): no point polling. */
function isFinal(error: unknown): boolean {
return (
isHttpError(error) &&
error.status >= 400 &&
error.status < 500 &&
error.status !== 408 &&
error.status !== 429
);
}
/**
* U10 ۱.۱: where the API sends the browser back from the bank, once it has verified the payment.
* It reads the payment until it is settled, then replaces itself with the result page, so refresh
@ -26,22 +38,30 @@ export function usePaymentReturnPage({
queryFn: ({ signal }) =>
transactionRepository.getDetail(paymentId ?? '', { signal }),
enabled: paymentId !== null && status === 'member',
refetchInterval: (query) =>
query.state.data?.confirmation.phase === 'processing'
? PAYMENT_POLL_MS
: false,
// A failed read (a 502 right after the bank) never throws to the boundary: the page keeps
// polling, and the timeout still takes the investor to the result page (0029).
throwOnError: false,
refetchInterval: (query) => {
const data = query.state.data;
if (data === undefined) {
return isFinal(query.state.error) ? false : PAYMENT_POLL_MS;
}
return data.confirmation.phase === 'processing' ? PAYMENT_POLL_MS : false;
},
});
const phase = payment.data?.confirmation.phase;
const refused = payment.data === undefined && isFinal(payment.error);
useEffect(() => {
if (paymentId === null) {
router.replace(ROUTES.dashboard.transactions);
return;
}
if (phase && phase !== 'processing') {
// Settled, or refused for good: the result page says which.
if ((phase && phase !== 'processing') || refused) {
router.replace(ROUTES.paymentResult(paymentId));
}
}, [paymentId, phase, router]);
}, [paymentId, phase, refused, router]);
// The bank's callback brought the browser here: nothing is left at the gateway to settle. The
// AppShell loads the draft after this page's first effects, so this waits for it.

View File

@ -111,7 +111,6 @@ export function toSubscribeDto(args: SubscribeArgs): SubscribeDto {
tierId: args.tierId,
referralCode: args.referralCode.trim(),
expectedPriceToman: args.expectedPriceToman,
confirmPriceChange: args.confirmPriceChange,
};
}

View File

@ -243,20 +243,17 @@ export type SubscribeArgs = {
referralCode: string;
/** The `priceToman` the investor saw; a different live price answers `price-changed`. */
expectedPriceToman?: number;
/** The investor accepted the new price; skips the price check. */
confirmPriceChange?: boolean;
};
export type SubscribeDto = {
tierId: string;
referralCode: string;
expectedPriceToman?: number;
confirmPriceChange?: boolean;
};
export type SubscribeResponseDto = CheckoutResultEntity;
/** The live price moved since checkout loaded; subscribe again with `confirmPriceChange`. */
/** The live price moved since checkout loaded; subscribe again expecting `newAmountToman`. */
export type PriceChangedPayload = {
outcome: 'price-changed';
oldAmountToman: number;

View File

@ -135,14 +135,28 @@ export function useLedgerPart(): LedgerPartModel {
}, [router, pathname]);
// The linked row isn't among the rows read yet: read on, a few pages at most, then let it go.
// A page that failed to load lets it go too, so the effect never re-requests it in a loop.
const pageCount = list.data.pages.length;
const { hasNextPage, isFetching, fetchNextPage } = list;
const { hasNextPage, isFetching, isFetchNextPageError, fetchNextPage } = list;
const isLooking = linked !== null && linkedRow === null;
useEffect(() => {
if (!isLooking || isFetching) return;
if (hasNextPage && pageCount < LINKED_ROW_MAX_PAGES) void fetchNextPage();
if (
hasNextPage &&
!isFetchNextPageError &&
pageCount < LINKED_ROW_MAX_PAGES
)
void fetchNextPage();
else dropLink();
}, [isLooking, isFetching, hasNextPage, pageCount, fetchNextPage, dropLink]);
}, [
isLooking,
isFetching,
isFetchNextPageError,
hasNextPage,
pageCount,
fetchNextPage,
dropLink,
]);
const openDetail = (row: LedgerItemPayload) => {
setDetail(row);

View File

@ -5,6 +5,7 @@ import {
useQueryClient,
useSuspenseQuery,
} from '@tanstack/react-query';
import { useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { showActionError } from '../../../../shared/utils';
@ -45,8 +46,9 @@ const withSwitch = (
* تنظیمات اعلان‌ها (J12-3, J12-3b): the member's switches, in the bell and by SMS, in the browser
* only. There is no save button: each switch flips at once and saves on its own (optimistic), and
* «تنظیمات ذخیره شد.» confirms it; a failure flips it back with an error toast. Locked switches
* are always on and never saved. While several saves are on their way, only the last answer
* replaces the screen's view, so a quick second flip is never undone by the first one's answer.
* are always on and never saved. Saves go one at a time in tap order, and only the last answer
* (the server's settings after every flip) replaces the screen's view, so a quick second flip is
* never undone by the first one's answer. A failure while others wait is settled by the last one.
*/
export function useNotificationSettingsPage(): NotificationSettingsPageModel {
const { t } = useTranslation('account');
@ -55,6 +57,9 @@ export function useNotificationSettingsPage(): NotificationSettingsPageModel {
const role = useCurrentAccount()?.role ?? 'investor';
const queryKey = notificationSettingsKeys.mine();
const mutationKey = notificationSettingsKeys.update();
// A save failed while later ones were still waiting: the last one settles the view.
const failedEarlier = useRef(false);
const isLast = () => queryClient.isMutating({ mutationKey }) <= 1;
const { data } = useSuspenseQuery({
queryKey,
@ -63,6 +68,7 @@ export function useNotificationSettingsPage(): NotificationSettingsPageModel {
const save = useMutation({
mutationKey,
scope: { id: mutationKey.join(':') },
mutationFn: (args: UpdateNotificationSettingArgs) =>
updateNotificationSetting(args),
onMutate: async (args) => {
@ -73,17 +79,26 @@ export function useNotificationSettingsPage(): NotificationSettingsPageModel {
);
},
onSuccess: (settings) => {
if (queryClient.isMutating({ mutationKey }) <= 1) {
if (isLast()) {
failedEarlier.current = false;
queryClient.setQueryData(queryKey, settings);
}
showToast({ tone: 'success', message: t('notifications.saved') });
},
onError: (error, args) => {
queryClient.setQueryData<NotificationSettingsPayload>(
queryKey,
(current) =>
current && withSwitch(current, { ...args, enabled: !args.enabled }),
);
if (!isLast()) {
failedEarlier.current = true;
} else if (failedEarlier.current) {
// Earlier flips failed too: the screen reads what the server holds.
failedEarlier.current = false;
void queryClient.invalidateQueries({ queryKey });
} else {
queryClient.setQueryData<NotificationSettingsPayload>(
queryKey,
(current) =>
current && withSwitch(current, { ...args, enabled: !args.enabled }),
);
}
if (isHttpError(error) && STALE_CODES.has(error.code)) {
void queryClient.invalidateQueries({ queryKey });
}

View File

@ -3,10 +3,18 @@ import { useCountdown } from '@lumina/island/hooks/use-countdown';
import { showToast } from '@lumina/island/molecules/toast';
import { isHttpError } from '@lumina/libs/http';
import { useQueryClient } from '@tanstack/react-query';
import { useEffect, useEffectEvent, useState } from 'react';
import { useRouter } from 'next/navigation';
import {
useCallback,
useEffect,
useEffectEvent,
useRef,
useState,
} from 'react';
import { useForm, useWatch } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useLeaveGuard } from '../../../../app/navigation/hooks/use-leave-guard';
import { applyServerErrors, showActionError } from '../../../../shared/utils';
import { profileKeys } from '../../../profile';
import { postComposerSchema } from '../../../../shared/validations';
@ -74,12 +82,14 @@ export function usePostComposerPage({
const isEmpty = !hasText && images.images.length === 0;
const [phase, setPhase] = useState<ComposerPhase>('idle');
const [isConfirmingLeave, setIsConfirmingLeave] = useState(false);
// A link elsewhere in the app followed during an edit with changes: asked first.
const [leaveTo, setLeaveTo] = useState<string | null>(null);
const router = useRouter();
// The last post sent and its key: sending it again unchanged reuses the key, so a retry after a
// lost answer never posts twice; any change gets a new one.
const [lastSend, setLastSend] = useState<{
body: string;
key: string;
} | null>(null);
// lost answer never posts twice; any change gets a new one. Refs, so two quick submits before a
// render share one send.
const lastSend = useRef<{ body: string; key: string } | null>(null);
const isSending = useRef(false);
const editEndsAt = post?.publishedAt
? new Date(post.publishedAt).getTime() + POST_LIMITS.editWindowMs
@ -89,6 +99,13 @@ export function usePostComposerPage({
});
const isEditExpired = mode === 'edit' && secondsLeft === 0;
// Drops the stored draft only when it is this creator's: another account's waits for its next
// sign-in on this device (0042).
const clearOwnDraft = () => {
const store = usePostDraftStore.getState();
if (store.draft?.creatorId === creatorId) store.clearDraft();
};
// A new post's draft follows every change; an empty composer keeps none.
const keepDraft = useEffectEvent(() => {
if (post) return;
@ -97,12 +114,11 @@ export function usePostComposerPage({
(image): image is ComposerImage & { fileId: string; url: string } =>
image.status === 'ready' && image.fileId !== null && image.url !== null,
);
const store = usePostDraftStore.getState();
if (!caption.trim() && ready.length === 0) {
store.clearDraft();
clearOwnDraft();
return;
}
store.saveDraft({
usePostDraftStore.getState().saveDraft({
creatorId,
caption,
accessLevel,
@ -150,8 +166,8 @@ export function usePostComposerPage({
return changes;
};
const submit = form.handleSubmit(async ({ caption, accessLevel }) => {
if (blocker || phase === 'saving' || isEditExpired) return;
const send = async ({ caption, accessLevel }: PostComposerFormValues) => {
if (blocker || isSending.current || isEditExpired) return;
const text = caption.trim();
const media = images.images
.filter((image) => image.status === 'ready' && image.fileId !== null)
@ -165,6 +181,7 @@ export function usePostComposerPage({
return;
}
isSending.current = true;
setPhase('saving');
let saved: PostPayload;
try {
@ -183,10 +200,10 @@ export function usePostComposerPage({
};
const body = JSON.stringify(args);
const send =
lastSend?.body === body
? lastSend
lastSend.current?.body === body
? lastSend.current
: { body, key: crypto.randomUUID() };
setLastSend(send);
lastSend.current = send;
saved = await publishPost(args, { idempotencyKey: send.key });
}
} catch (error) {
@ -210,11 +227,12 @@ export function usePostComposerPage({
}
// The key went with another post (it never should): the retry sends a new one.
if (isHttpError(error) && error.code === 'IDEMPOTENCY_KEY_REUSED') {
setLastSend(null);
lastSend.current = null;
}
}
// Only a failed request frees the CTA. Saved, it stays held until `onDone`'s navigation
// takes the composer away: a second tap would publish again, or save again and go back twice.
isSending.current = false;
setPhase('idle');
return;
}
@ -227,7 +245,9 @@ export function usePostComposerPage({
showToast({ tone: 'success', message: t('composer.published') });
}
onDone(saved);
});
};
// Validated inside the press, so the send guard's refs are read only then.
const submit = () => form.handleSubmit(send)();
const hasSomethingToLose = () => {
const { caption, accessLevel } = form.getValues();
@ -245,10 +265,31 @@ export function usePostComposerPage({
const leave = () => {
images.abortAll();
if (!post) usePostDraftStore.getState().clearDraft();
if (!post) clearOwnDraft();
onLeave();
};
const requestLink = useCallback((href: string) => {
setLeaveTo(href);
setIsConfirmingLeave(true);
}, []);
// An edit's changes live only here, so a header link, a reload or closing the tab asks too; a
// new post keeps its draft on the device. The same check as back's; the watch renders again
// whenever the caption or access starts or stops differing from the post (images are state).
const textChanged = useWatch({
control: form.control,
compute: ({ caption, accessLevel }) =>
post !== undefined &&
((caption ?? '').trim() !== (post.caption ?? '') ||
accessLevel !== post.accessLevel),
});
useLeaveGuard(
post !== undefined &&
phase !== 'saving' &&
(textChanged || hasSomethingToLose()),
requestLink,
);
return {
mode,
form,
@ -268,9 +309,18 @@ export function usePostComposerPage({
isConfirmingLeave,
confirmLeave: () => {
setIsConfirmingLeave(false);
leave();
if (leaveTo === null) {
leave();
return;
}
setLeaveTo(null);
images.abortAll();
router.push(leaveTo);
},
cancelLeave: () => {
setIsConfirmingLeave(false);
setLeaveTo(null);
},
cancelLeave: () => setIsConfirmingLeave(false),
minutesLeft:
secondsLeft === null ? null : Math.ceil(secondsLeft / SECONDS_PER_MINUTE),
isEditExpired,

View File

@ -34,19 +34,21 @@ export function useOwnerPostPart({
: undefined;
const secondsLeft = useCountdown(editEndsAt, { intervalMs: MINUTE_MS });
const deleted = () => {
setIsConfirmingDelete(false);
removeCachedPost(queryClient, post);
showToast({ tone: 'success', message: t('post.delete.deleted') });
// The channel's first page and track record are rendered on the server: the page it goes
// to is read fresh, and one it stays on renders again. Refreshed before leaving, the post
// page would flash its «deleted» state first.
if (onDeleted) onDeleted();
else router.refresh();
};
const remove = useMutation({
mutationFn: () =>
deletePost({ postId: post.id, creatorId: post.creatorId }),
onSuccess: () => {
setIsConfirmingDelete(false);
removeCachedPost(queryClient, post);
showToast({ tone: 'success', message: t('post.delete.deleted') });
// The channel's first page and track record are rendered on the server: the page it goes
// to is read fresh, and one it stays on renders again. Refreshed before leaving, the post
// page would flash its «deleted» state first.
if (onDeleted) onDeleted();
else router.refresh();
},
onSuccess: deleted,
onError: (error) => {
// A published prediction stays as it is (409 PREDICTION_LOCKED); its card offers no delete,
// so only a stale one gets here.
@ -59,7 +61,13 @@ export function useOwnerPostPart({
});
return;
}
// Deleting twice is harmless, so the toast may offer to try again.
// Already gone (an earlier delete whose answer was lost, or another tab): the API answers
// 404, which is the outcome asked for.
if (isHttpError(error) && error.status === 404) {
deleted();
return;
}
// A retry after a lost answer ends in that 404, so the toast may offer to try again.
showActionError(error, {
t,
failedMessage: t('post.delete.failed'),

View File

@ -4,6 +4,7 @@ import { useRouter } from 'next/navigation';
import { useTranslation } from 'react-i18next';
import { showActionError } from '../../../../shared/utils';
import { postKeys, resetCachedChannel } from '../../../post';
import { closePrediction } from '../../actions/close-prediction';
import { QUOTE_REFRESH_MS } from '../../repositories/market-data';
import {
@ -41,7 +42,12 @@ export function useClosePredictionPart({
const settled = (error: unknown): CloseQuoteState | null => {
const code = predictionErrorCode(error);
if (code === PREDICTION_ERROR_CODES.closePending) {
// Every card of it reads again to say so: the dashboard's, the channel's and the post page's.
void queryClient.invalidateQueries({ queryKey: predictionKeys.own() });
void queryClient.invalidateQueries({
queryKey: postKeys.detail(post.id),
});
resetCachedChannel(queryClient, post.creatorId);
return { kind: 'pending' };
}
if (code === PREDICTION_ERROR_CODES.quoteUnavailable) {

View File

@ -3,11 +3,19 @@ import { showToast } from '@lumina/island/molecules/toast';
import { isHttpError } from '@lumina/libs/http';
import { list, number } from '@lumina/tools/format';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect, useEffectEvent, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import {
useCallback,
useEffect,
useEffectEvent,
useRef,
useState,
} from 'react';
import { useFieldArray, useForm, useWatch } from 'react-hook-form';
import type { FieldPath } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useLeaveGuard } from '../../../../app/navigation/hooks/use-leave-guard';
import {
levelPrice,
PREDICTION_FORM_LIMITS,
@ -126,9 +134,12 @@ export function usePredictionComposerPage({
}: UsePredictionComposerPageOptions): PredictionComposerPageModel {
const { t } = useTranslation(['predictions', 'content']);
const queryClient = useQueryClient();
const router = useRouter();
const chart = useChartImage();
const [phase, setPhase] = useState<ComposerPhase>('idle');
const [isConfirmingLeave, setIsConfirmingLeave] = useState(false);
// A link elsewhere in the app the creator followed with something typed: asked first.
const [leaveTo, setLeaveTo] = useState<string | null>(null);
// What the confirm step opened with, should the price drop out while it is open.
const [confirmed, setConfirmed] = useState<ComposerSummary | null>(null);
// When the API last said there was no price at publish: a newer price clears it.
@ -406,6 +417,20 @@ export function usePredictionComposerPage({
onLeave();
};
// The API refused the chart: a new pick or ✕ answers it, so the publish is free again.
const chartKey = chart.image?.key ?? null;
useEffect(() => {
form.clearErrors('root.chart');
}, [chartKey, form]);
const requestLink = useCallback((href: string) => {
setLeaveTo(href);
setIsConfirmingLeave(true);
}, []);
// A header link, a reload or closing the tab asks too; back and «انصراف» ask through
// `requestLeave`. A publish in flight navigates by itself.
useLeaveGuard(phase !== 'publishing' && hasSomethingToLose(), requestLink);
return {
form,
markets,
@ -492,8 +517,17 @@ export function usePredictionComposerPage({
isConfirmingLeave,
confirmLeave: () => {
setIsConfirmingLeave(false);
leave();
if (leaveTo === null) {
leave();
return;
}
setLeaveTo(null);
chart.abort();
router.push(leaveTo);
},
cancelLeave: () => {
setIsConfirmingLeave(false);
setLeaveTo(null);
},
cancelLeave: () => setIsConfirmingLeave(false),
};
}

View File

@ -110,6 +110,9 @@ export function usePricingPage(): PricingPageModel {
const [serverErrors, setServerErrors] = useState<Record<string, string>>({});
// What «ذخیره و خروج» does once this save went through (J10-4n).
const onSavedRef = useRef<(() => void) | null>(null);
// The draft the API checked and the dialog shows: «تأیید و ذخیره» saves exactly this, even if a
// field changed while the check ran.
const checkedArgs = useRef<ReturnType<typeof toSavePricingArgs> | null>(null);
// A start set on this page is never earlier than the minute it opened (۴.۳).
const [openedAt] = useState(() => {
const now = new Date();
@ -272,6 +275,7 @@ export function usePricingPage(): PricingPageModel {
const failed = (error: unknown) => {
onSavedRef.current = null;
checkedArgs.current = null;
setConfirmation(null);
setPhase('idle');
if (
@ -285,7 +289,26 @@ export function usePricingPage(): PricingPageModel {
}
if (isHttpError(error) && error.status === 409) {
// The lock started since the page was read (a first purchase): show the form as it is now.
void queryClient.invalidateQueries({ queryKey: pricingKeys.all });
// The standing prices and periods go back to the saved ones, since they are read-only
// under the lock and would fail every later save; the promotion edits stay.
void queryClient
.invalidateQueries({ queryKey: pricingKeys.all })
.then(() => {
const fresh = queryClient.getQueryData<PricingFormPayload>(
pricingKeys.form(),
);
if (!fresh?.cooldown.locked) return;
const saved = toFormValues(fresh);
for (const tier of fresh.tiers) {
const period = tier.billingPeriod;
form.resetField(`tiers.${period}.enabled`, {
defaultValue: saved.tiers[period].enabled,
});
form.resetField(`tiers.${period}.priceToman`, {
defaultValue: saved.tiers[period].priceToman,
});
}
});
}
if (isConnectionError(error)) {
// The banner with «تلاش دوباره» says it (۵.۴); a toast too would say it twice.
@ -306,10 +329,10 @@ export function usePricingPage(): PricingPageModel {
return;
}
setPhase('checking');
const args = toSavePricingArgs(values);
checkedArgs.current = args;
try {
const result = await pricingRepository.validate(
toSavePricingArgs(values),
);
const result = await pricingRepository.validate(args);
if (!result.valid) {
onSavedRef.current = null;
setServerErrors(result.fieldErrors);
@ -325,9 +348,11 @@ export function usePricingPage(): PricingPageModel {
};
const confirm = async () => {
const args = checkedArgs.current;
if (!args) return;
setPhase('saving');
try {
const saved = await savePricing(toSavePricingArgs(values));
const saved = await savePricing(args);
queryClient.setQueryData(pricingKeys.form(), saved);
// The dashboard's figures carry the tiers too, and a first priced plan wakes the invite code.
void queryClient.invalidateQueries({ queryKey: overviewKeys.all });
@ -398,6 +423,7 @@ export function usePricingPage(): PricingPageModel {
confirmation,
closeConfirmation: () => {
onSavedRef.current = null;
checkedArgs.current = null;
setConfirmation(null);
setPhase('idle');
},

View File

@ -25,6 +25,7 @@ export {
displaySocialUrl,
fromSocialUrl,
toSocialHandle,
toSocialLink,
toSocialUrl,
toTypedHandle,
} from './social-links';

View File

@ -69,8 +69,9 @@ export function toSocialUrl(platform: SocialPlatform, handle: string): string {
}
/**
* A stored link back into a row. The label names the platform for links this form saved; older
* links fall back to their host, and anything else is a website. A platform link whose path is no
* A stored link back into a row. The platform is the one its host belongs to; the label only picks
* between platforms sharing a host, so a link labelled «تلگرام» that leads elsewhere is a website
* showing its real address. Anything else is a website. A platform link whose path is no
* handle (`t.me/s/channel`, `youtube.com/channel/UC…`) stays a website row with its whole address:
* a row that can't be saved would be dropped from the draft, and the server would lose the link.
*/
@ -79,16 +80,16 @@ export function fromSocialUrl(
url: string,
): { platform: SocialPlatform; handle: string } {
const address = parseAddress(url);
const byLabel = isHandlePlatform(label) ? label : null;
const byHost = address
? (Object.keys(SOCIAL_HANDLE_ADDRESSES) as HandlePlatform[]).find(
(platform) =>
(
SOCIAL_HANDLE_ADDRESSES[platform].hosts as readonly string[]
).includes(address.host),
)
: undefined;
const platform = byLabel ?? byHost;
const servesHost = (platform: HandlePlatform) =>
address !== null &&
(SOCIAL_HANDLE_ADDRESSES[platform].hosts as readonly string[]).includes(
address.host,
);
const byHost = (
Object.keys(SOCIAL_HANDLE_ADDRESSES) as HandlePlatform[]
).find(servesHost);
const platform =
isHandlePlatform(label) && servesHost(label) ? label : byHost;
if (platform && address) {
const handle = handleFromPath(platform, address.path).toLowerCase();
if (SOCIAL_HANDLE_PATTERN.test(handle)) return { platform, handle };
@ -102,6 +103,18 @@ export function fromSocialUrl(
};
}
/**
* A stored link as the channel shows it: its platform and an `https://` address to open, rebuilt
* from the row, so an older link stored without its scheme never becomes a link inside the site.
*/
export function toSocialLink(
label: string,
url: string,
): { platform: SocialPlatform; href: string } {
const { platform, handle } = fromSocialUrl(label, url);
return { platform, href: toSocialUrl(platform, handle) };
}
/** The address as the profile shows it, without the scheme: `t.me/ali_gold`. */
export function displaySocialUrl(url: string): string {
return url.replace(/^https?:\/\//i, '').replace(/\/$/, '');

View File

@ -33,22 +33,26 @@ export const useAuthFlowStore = create<AuthFlowState>()(
}),
carryPhone: (phone) =>
set((state) => {
// A different number starts clean: the sent code, the block and the misses belong to the
// old one.
// A different number starts clean: the sent code, the block, the misses, the registration
// token and the step-4 draft belong to the old one. The role was chosen for this visit.
if (state.phone !== phone) {
state.codeSentAt = null;
state.blockedUntil = null;
state.limitedUntil = null;
state.misses = 0;
state.registration = null;
state.draft = null;
}
state.phone = phone;
}),
codeSent: (purpose, phone, sentAt) =>
set((state) => {
// A different number starts clean: the block and the limit belong to the old one.
// A different number starts clean: the block, the limit and the step-4 draft belong to the
// old one.
if (state.phone !== phone) {
state.blockedUntil = null;
state.limitedUntil = null;
state.draft = null;
}
state.purpose = purpose;
state.phone = phone;