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 type { NextConfig } from 'next';
import path from 'node:path'; 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'; 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 // 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' }, { 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 = { const nextConfig: NextConfig = {
// Every visitor gets the metadata in <head>, where Chrome looks for the manifest and Safari for // 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). // its home-screen tags; Next.js would otherwise stream it to the end of <body> (0054).
htmlLimitedBots: /.*/, htmlLimitedBots: /.*/,
// The `/api` proxy's wait for the gateway (0018); uploads outlast Next.js's 30-second default. // The `/api` proxy's wait for the gateway (0018); uploads outlast Next.js's 30-second default
experimental: { proxyTimeout: API_PROXY_TIMEOUT_MS }, // 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. // Workspace packages export TypeScript source, so Next.js compiles them.
transpilePackages: [ transpilePackages: [
'@lumina/market', '@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. // island's plugins write theirs. Next runs from the app's folder, as every Nx target does.
writeServiceWorker({ publicDir: path.join(process.cwd(), 'public') }); writeServiceWorker({ publicDir: path.join(process.cwd(), 'public') });
return [ return [
{ source: '/:path*', headers: security },
{ source: '/fonts/:path*', headers: immutable }, { source: '/fonts/:path*', headers: immutable },
{ source: '/icons/:path*', headers: immutable }, { source: '/icons/:path*', headers: immutable },
// Revalidated on every update check, so a new worker reaches visitors at their next // 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 { getChannel, readOnServer } from '@lumina/market/server';
import { toChannelUsername } from '@lumina/market/shared/utils'; import { toChannelUsername } from '@lumina/market/shared/utils';
import type { Metadata } from 'next'; import type { Metadata } from 'next';
@ -7,7 +7,10 @@ import { notFound, permanentRedirect, redirect } from 'next/navigation';
import { i18n } from '../../../../i18n'; import { i18n } from '../../../../i18n';
import { CheckoutTemplate } from './templates/checkout-template'; 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 = { export const metadata: Metadata = {
title: i18n.t('payment:checkout.title'), 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 * 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. * 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 segment = (await params).username;
const username = toChannelUsername(segment); const username = toChannelUsername(segment);
if (!username) notFound(); 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)); const channel = await readOnServer(() => getChannel(username));
if (channel.status !== 'ok') notFound(); if (channel.status !== 'ok') notFound();
if (channel.data.suspended) redirect(ROUTES.channel(username)); 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 { import {
channelMetadata, channelMetadata,
getChannel, getChannel,
@ -13,7 +13,10 @@ import { displayUrl } from '../../../../configs';
import { i18n } from '../../../../i18n'; import { i18n } from '../../../../i18n';
import { ChannelTemplate } from './templates/channel-template'; 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 // 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 // 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 * 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. * 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 segment = (await params).username;
const username = toChannelUsername(segment); const username = toChannelUsername(segment);
if (!username) notFound(); 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)); const channel = await readOnServer(() => getChannel(username));
if (channel.status !== 'ok') notFound(); if (channel.status !== 'ok') notFound();

View File

@ -14,3 +14,9 @@ export const API_PROXY_PATH = '/api';
* sets no timeout for uploads. * sets no timeout for uploads.
*/ */
export const API_PROXY_TIMEOUT_MS = 120_000; 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'; export { FORWARDED_COOKIES } from './cookies';

View File

@ -8,7 +8,11 @@ import {
import type { NextConfig } from 'next'; import type { NextConfig } from 'next';
import path from 'node:path'; 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'; 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 // 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' }, { 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 = { const nextConfig: NextConfig = {
// Every visitor gets the metadata in <head>, where Chrome looks for the manifest and Safari for // 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). // its home-screen tags; Next.js would otherwise stream it to the end of <body> (0054).
htmlLimitedBots: /.*/, htmlLimitedBots: /.*/,
// The `/api` proxy's wait for the gateway (0018); uploads outlast Next.js's 30-second default. // The `/api` proxy's wait for the gateway (0018); uploads outlast Next.js's 30-second default
experimental: { proxyTimeout: API_PROXY_TIMEOUT_MS }, // 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. // Workspace packages export TypeScript source, so Next.js compiles them.
transpilePackages: [ transpilePackages: [
'@lumina/market', '@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. // island's plugins write theirs. Next runs from the app's folder, as every Nx target does.
writeServiceWorker({ publicDir: path.join(process.cwd(), 'public') }); writeServiceWorker({ publicDir: path.join(process.cwd(), 'public') });
return [ return [
{ source: '/:path*', headers: security },
{ source: '/fonts/:path*', headers: immutable }, { source: '/fonts/:path*', headers: immutable },
{ source: '/icons/:path*', headers: immutable }, { source: '/icons/:path*', headers: immutable },
// Revalidated on every update check, so a new worker reaches visitors at their next // 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 { getChannel, readOnServer } from '@lumina/market/server';
import { toChannelUsername } from '@lumina/market/shared/utils'; import { toChannelUsername } from '@lumina/market/shared/utils';
import type { Metadata } from 'next'; import type { Metadata } from 'next';
@ -7,7 +7,10 @@ import { notFound, permanentRedirect, redirect } from 'next/navigation';
import { i18n } from '../../../../i18n'; import { i18n } from '../../../../i18n';
import { CheckoutTemplate } from './templates/checkout-template'; 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 = { export const metadata: Metadata = {
title: i18n.t('payment:checkout.title'), 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 * 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. * 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 segment = (await params).username;
const username = toChannelUsername(segment); const username = toChannelUsername(segment);
if (!username) notFound(); 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)); const channel = await readOnServer(() => getChannel(username));
if (channel.status !== 'ok') notFound(); if (channel.status !== 'ok') notFound();
if (channel.data.suspended) redirect(ROUTES.channel(username)); 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 { import {
channelMetadata, channelMetadata,
getChannel, getChannel,
@ -13,7 +13,10 @@ import { displayUrl } from '../../../../configs';
import { i18n } from '../../../../i18n'; import { i18n } from '../../../../i18n';
import { ChannelTemplate } from './templates/channel-template'; 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 // 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 // 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 * 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. * 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 segment = (await params).username;
const username = toChannelUsername(segment); const username = toChannelUsername(segment);
if (!username) notFound(); 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)); const channel = await readOnServer(() => getChannel(username));
if (channel.status !== 'ok') notFound(); if (channel.status !== 'ok') notFound();

View File

@ -14,3 +14,9 @@ export const API_PROXY_PATH = '/api';
* sets no timeout for uploads. * sets no timeout for uploads.
*/ */
export const API_PROXY_TIMEOUT_MS = 120_000; 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'; export { FORWARDED_COOKIES } from './cookies';

View File

@ -1,6 +1,6 @@
import { number } from '@lumina/tools/format'; import { number } from '@lumina/tools/format';
import { Element } from '../../primitives/element'; import { GridBox } from '../grid-box';
import { cn } from '../../tools/cn'; import { cn } from '../../tools/cn';
import type { CountBadgeProps } from './types'; import type { CountBadgeProps } from './types';
@ -18,16 +18,19 @@ export function CountBadge({
if (count <= 0) return null; if (count <= 0) return null;
return ( return (
<Element <GridBox
tag="span" tag="span"
aria-hidden aria-hidden
display="inline-grid"
justifyItems="justify-items-center"
alignItems="items-center"
className={cn( 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, className,
)} )}
{...props} {...props}
> >
{count > cap ? `${number(cap)}+` : number(count)} {count > cap ? `${number(cap)}+` : number(count)}
</Element> </GridBox>
); );
} }

View File

@ -14,6 +14,13 @@ import {
} from './constants'; } from './constants';
import type { DialogProps } from './types'; 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 { function announce(type: string, dialog: HTMLDialogElement): void {
document.dispatchEvent(new CustomEvent(type, { detail: dialog })); document.dispatchEvent(new CustomEvent(type, { detail: dialog }));
} }
@ -76,12 +83,34 @@ export function Dialog({
if (open && !isPresent) setIsPresent(true); if (open && !isPresent) setIsPresent(true);
// Where the last press started, so a drag out of the panel (selecting text) never closes it. // Where the last press started, so a drag out of the panel (selecting text) never closes it.
const pressedLayer = useRef(false); 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) => const show = (dialog: HTMLDialogElement) => {
showDialog(dialog, raiseToasts), 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) => { 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?.(); onExited?.();
}); });
@ -91,10 +120,17 @@ export function Dialog({
if (open) { if (open) {
// Reopened mid-close: the exit transitions run back from where they are. // Reopened mid-close: the exit transitions run back from where they are.
dialog.removeAttribute('data-closing'); 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; return undefined;
} }
if (!dialog.open) return undefined;
dialog.setAttribute('data-closing', ''); dialog.setAttribute('data-closing', '');
let cancelled = false; let cancelled = false;
@ -114,7 +150,8 @@ export function Dialog({
useEffect(() => { useEffect(() => {
const dialog = ref.current; const dialog = ref.current;
return () => { 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 // 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 // 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 handleNativeClose = (event: SyntheticEvent<HTMLDialogElement>) => {
const dialog = event.currentTarget; const dialog = event.currentTarget;
if (event.target !== dialog || !open || dialog.open) return; if (event.target !== dialog || !open || dialog.open) return;
if (dismissible && onClose) onClose(); if (!dismissible || !onClose) {
else showDialog(dialog, raiseToasts); 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 // 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; const hasText = children != null || description != null;
return ( return (
<Element <FlexBox
tag="button" tag="button"
type="button" type="button"
role="switch" role="switch"
display="inline-flex"
alignItems="items-center"
justifyContent={hasText ? 'justify-between' : 'justify-center'}
gap="gap-3"
aria-checked={checked} aria-checked={checked}
aria-disabled={locked || undefined} aria-disabled={locked || undefined}
// The label alone names it; the description is announced after it, not inside the name. // 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); if (!locked && !event.defaultPrevented) onCheckedChange?.(!checked);
}} }}
className={cn( 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', locked ? 'cursor-not-allowed' : 'cursor-pointer',
hasText && 'justify-between text-start', hasText && 'text-start',
className, className,
)} )}
{...props} {...props}
@ -81,13 +85,15 @@ export function Switch({
)} )}
</FlexBox> </FlexBox>
)} )}
<Element <FlexBox
tag="span" tag="span"
aria-hidden aria-hidden
display="inline-flex"
alignItems="items-center"
className={switchTrackVariants({ checked, locked })} className={switchTrackVariants({ checked, locked })}
> >
<Element tag="span" className={switchKnobVariants({ checked })} /> <Element tag="span" className={switchKnobVariants({ checked })} />
</Element> </FlexBox>
</Element> </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. */ /** The 44×24 track; the knob slides to the end when on, mirrored in RTL. */
export const switchTrackVariants = cva( 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: { variants: {
checked: { checked: {

View File

@ -35,6 +35,12 @@ export function AvatarField({
className, className,
}: AvatarFieldProps) { }: AvatarFieldProps) {
const inputRef = useRef<HTMLInputElement>(null); 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 messageId = useId();
const isUploading = status === 'uploading'; const isUploading = status === 'uploading';
const isFailed = status === 'failed'; const isFailed = status === 'failed';
@ -63,6 +69,7 @@ export function AvatarField({
/> />
<FlexBox direction="flex-col" alignItems="items-start" gap="gap-1"> <FlexBox direction="flex-col" alignItems="items-start" gap="gap-1">
<Button <Button
ref={pickRef}
variant="secondary" variant="secondary"
icon="image" icon="image"
isLoading={isUploading} isLoading={isUploading}
@ -90,12 +97,16 @@ export function AvatarField({
variant="ghost" variant="ghost"
size="sm" size="sm"
disabled={disabled} disabled={disabled}
onClick={onRemove} onClick={thenFocusPick(onRemove)}
> >
{labels.remove} {labels.remove}
</Button> </Button>
) : ( ) : (
<LinkButton standalone disabled={disabled} onClick={onRemove}> <LinkButton
standalone
disabled={disabled}
onClick={thenFocusPick(onRemove)}
>
{labels.remove} {labels.remove}
</LinkButton> </LinkButton>
))} ))}
@ -109,7 +120,7 @@ export function AvatarField({
standalone standalone
iconStart="refresh" iconStart="refresh"
disabled={disabled} disabled={disabled}
onClick={onRetry} onClick={thenFocusPick(onRetry)}
> >
{labels.retry} {labels.retry}
</LinkButton> </LinkButton>

View File

@ -151,7 +151,11 @@ export function FileField({
icon="trash" icon="trash"
label={labels.remove} label={labels.remove}
disabled={disabled} 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" className="flex-none"
/> />
)} )}

View File

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

View File

@ -1,3 +1,5 @@
import { useRef } from 'react';
import { FlexBox } from '../../atoms/flex-box'; import { FlexBox } from '../../atoms/flex-box';
import { GridBox } from '../../atoms/grid-box'; import { GridBox } from '../../atoms/grid-box';
import { Icon } from '../../atoms/icon'; 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 * 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 * 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 * 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({ export function MediaStrip({
items, items,
@ -28,6 +31,18 @@ export function MediaStrip({
disabled = false, disabled = false,
className, className,
}: MediaStripProps) { }: 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 = const canAdd =
onAdd != null && addLabel != null && !disabled && items.length < max; onAdd != null && addLabel != null && !disabled && items.length < max;
if (items.length === 0 && !canAdd) return null; if (items.length === 0 && !canAdd) return null;
@ -44,12 +59,13 @@ export function MediaStrip({
return ( return (
<FlexBox <FlexBox
tag="ul" tag="ul"
ref={listRef}
aria-label={label} aria-label={label}
wrap="flex-wrap" wrap="flex-wrap"
gap="gap-2" gap="gap-2"
className={className} className={className}
> >
{items.map((item) => { {items.map((item, index) => {
const status = item.status ?? 'ready'; const status = item.status ?? 'ready';
const retry = const retry =
status === 'error' && onRetry && item.retryLabel ? onRetry : null; status === 'error' && onRetry && item.retryLabel ? onRetry : null;
@ -64,7 +80,10 @@ export function MediaStrip({
<Element <Element
tag="button" tag="button"
type="button" type="button"
onClick={() => retry(item.key)} onClick={() => {
retry(item.key);
focusRemoveAt(index);
}}
disabled={disabled} disabled={disabled}
aria-label={item.retryLabel} aria-label={item.retryLabel}
className="block size-full cursor-pointer focus-visible:focus-ring disabled:cursor-not-allowed" className="block size-full cursor-pointer focus-visible:focus-ring disabled:cursor-not-allowed"
@ -86,9 +105,13 @@ export function MediaStrip({
<GridBox <GridBox
tag="button" tag="button"
type="button" type="button"
onClick={() => onRemove(item.key)} onClick={() => {
onRemove(item.key);
focusRemoveAt(index);
}}
disabled={disabled} disabled={disabled}
aria-label={item.removeLabel} aria-label={item.removeLabel}
data-remove
justifyItems="justify-items-center" justifyItems="justify-items-center"
alignItems="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" 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" tag="button"
type="button" type="button"
onClick={onAdd} onClick={onAdd}
data-add
justifyItems="justify-items-center" justifyItems="justify-items-center"
alignContent="content-center" alignContent="content-center"
className={cn(mediaStripAddVariants({ size }), 'gap-0.5')} className={cn(mediaStripAddVariants({ size }), 'gap-0.5')}

View File

@ -1,6 +1,6 @@
'use client'; 'use client';
import { useId, useRef } from 'react'; import { useEffect, useId, useRef } from 'react';
import { FlexBox } from '../../../atoms/flex-box'; import { FlexBox } from '../../../atoms/flex-box';
import { Typography } from '../../../atoms/typography'; 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 * 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 * 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 * 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({ export function SheetPopover({
open, open,
@ -31,7 +32,32 @@ export function SheetPopover({
}: SheetPopoverProps) { }: SheetPopoverProps) {
const ref = useRef<HTMLDialogElement>(null); const ref = useRef<HTMLDialogElement>(null);
const titleId = useId(); 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); useFlip(ref, open);
if (!open) return null; if (!open) return null;
@ -50,7 +76,7 @@ export function SheetPopover({
<SheetHead <SheetHead
title={title} title={title}
titleId={titleId} titleId={titleId}
onClose={onClose} onClose={close}
closeLabel={closeLabel} closeLabel={closeLabel}
compact compact
/> />

View File

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

View File

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

View File

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

View File

@ -1,6 +1,7 @@
import { number, price } from '@lumina/tools/format'; import { number, price } from '@lumina/tools/format';
import { FlexBox } from '../../../atoms/flex-box'; import { FlexBox } from '../../../atoms/flex-box';
import { GridBox } from '../../../atoms/grid-box';
import { Typography } from '../../../atoms/typography'; import { Typography } from '../../../atoms/typography';
import { Element } from '../../../primitives/element'; import { Element } from '../../../primitives/element';
import { OUTCOME_TRENDS } from '../constants'; import { OUTCOME_TRENDS } from '../constants';
@ -73,28 +74,30 @@ export function PredictionRange({
/> />
)} )}
{hasStop && ( {hasStop && (
<Element <GridBox
tag="span" tag="span"
className={markerVariants({ kind: 'stop' })} className={markerVariants({ kind: 'stop' })}
style={atPosition(position(risk))} style={atPosition(position(risk))}
/> />
)} )}
<Element <GridBox
tag="span" tag="span"
className={markerVariants({ kind: 'entry' })} className={markerVariants({ kind: 'entry' })}
style={atPosition(entry)} style={atPosition(entry)}
/> />
{targetsFav.map((target, index) => ( {targetsFav.map((target, index) => (
<Typography <GridBox
key={index} key={index}
tag="span" tag="span"
variant="inherit" justifyItems="justify-items-center"
color="inherit" alignItems="items-center"
className={markerVariants({ kind: 'target', hit: hits[index] })} className={markerVariants({ kind: 'target', hit: hits[index] })}
style={atPosition(position(target))} style={atPosition(position(target))}
> >
{number(index + 1)} <Typography tag="span" variant="inherit" color="inherit">
</Typography> {number(index + 1)}
</Typography>
</GridBox>
))} ))}
{close != null && ( {close != null && (
<ClosePin x={close} tone={closeTrend}> <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. */ /** A level on the track, centred on its place from the inline start. */
export const markerVariants = cva( 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: { variants: {
kind: { 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. */ /** The small level glyphs in the levels grid and the ladder, matching the track's markers. */
export const glyphVariants = cva( export const glyphVariants = cva('box-border flex-none', {
'box-border inline-grid flex-none place-items-center', variants: {
{ kind: {
variants: { stop: 'size-2.25 rounded-[2px] bg-danger',
kind: { entry: 'size-2.5 rounded-full border-[2.5px] border-text-primary',
stop: 'size-2.25 rounded-[2px] bg-danger', target:
entry: 'size-2.5 rounded-full border-[2.5px] border-text-primary', 'size-3.5 rounded-full border-[1.5px] border-success text-[0.5625rem] leading-none font-bold text-success-text',
target: close:
'size-3.5 rounded-full border-[1.5px] border-success text-[0.5625rem] leading-none font-bold text-success-text', 'size-0 border-x-5 border-t-7 border-x-transparent border-t-text-secondary',
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',
hit: { false: '',
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. */ /** Tiles fit as many per row as they can; long prices get wider ones so they never truncate. */
export const levelsVariants = cva('m-0', { export const levelsVariants = cva('m-0', {

View File

@ -18,10 +18,12 @@ import {
SERVER_TIMEOUT, SERVER_TIMEOUT,
} from './constants'; } from './constants';
import { import {
asRequestError,
asUnauthorized, asUnauthorized,
createHttpError, createHttpError,
defaultMapErrorBody, defaultMapErrorBody,
errorFromResponse, errorFromResponse,
isHttpError,
notConfiguredError, notConfiguredError,
toHttpError, toHttpError,
} from './http-error'; } from './http-error';
@ -380,15 +382,28 @@ export class HttpClient {
if (wantsRefresh) { if (wantsRefresh) {
if (replayed) throw asUnauthorized(error); if (replayed) throw asUnauthorized(error);
replayed = true; replayed = true;
// A request sent before the latest refresh replays without another one. // A request sent before the latest refresh replays, or fails when that refresh ended
if (coordinator.generation !== generation) continue; // the session, without another one.
const refreshed = await abortable( if (coordinator.generation !== generation) {
coordinator.refresh( if (coordinator.renewed) continue;
() => this.sendRefresh(refresh), throw asUnauthorized(error);
refresh.onFailure, }
), let refreshed: boolean;
signal, 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; if (refreshed) continue;
throw asUnauthorized(error); 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 { export function asUnauthorized(error: HttpError): HttpError {
if (error.code === 'UNAUTHORIZED') return error; if (error.code === 'UNAUTHORIZED') return error;
return new HttpError({ return new HttpError({

View File

@ -1,13 +1,21 @@
import { REFRESH_LOCK_NAME } from './constants'; import { REFRESH_LOCK_NAME } from './constants';
import { isHttpError } from './http-error'; 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. // One refresh at a time for the root client and every feature client.
export class RefreshCoordinator { 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; generation = 0;
// Whether the latest settled refresh renewed the session.
renewed = true;
private pending?: Promise<boolean>; 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( refresh(
send: () => Promise<unknown>, send: () => Promise<unknown>,
onFailure?: () => void, onFailure?: () => void,
@ -24,19 +32,35 @@ export class RefreshCoordinator {
): Promise<boolean> { ): Promise<boolean> {
try { try {
await withLock(send); await withLock(send);
this.generation += 1;
return true;
} catch (error) { } catch (error) {
if (!(isHttpError(error) && error.code === 'ABORTED')) { if (!isSessionEnded(error)) throw error;
try { this.settle(false);
onFailure?.(); try {
} catch { onFailure?.();
// A failing callback must not break the waiting requests. } catch {
} // A failing callback must not break the waiting requests.
} }
return false; 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. // 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' endpoint: string; // relative to baseUrl or absolute, e.g. '/auth/refresh'
method?: 'POST' | 'GET'; // default 'POST' method?: 'POST' | 'GET'; // default 'POST'
shouldRefresh?: (error: HttpError) => boolean; // default: error.status === 401 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 { export interface HttpClientConfig {

View File

@ -166,9 +166,10 @@ async function staleWhileRevalidate(event: FetchEvent): Promise<Response> {
const stored = await lookup(event.request); const stored = await lookup(event.request);
if (!stored) return fromNetwork(event); if (!stored) return fromNetwork(event);
// The check finishes after the response: a changed file replaces the copy, an unchanged one // 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( event.waitUntil(
fetch(event.request).then( fetch(event.request, { cache: 'no-cache' }).then(
(fresh) => (fresh) =>
isStorable(fresh) && !isSameFile(stored, fresh) isStorable(fresh) && !isSameFile(stored, fresh)
? store(event.request, 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) => { worker.addEventListener('activate', (event) => {
event.waitUntil( activation = (async () => {
(async () => { await worker.registration.navigationPreload
await worker.registration.navigationPreload ?.enable()
?.enable() .catch(() => undefined);
.catch(() => undefined); // The only place the cache is created (openCache).
// The only place the cache is created (openCache). await caches.open(cacheName).catch(() => undefined);
await caches.open(cacheName).catch(() => undefined); const names = await caches.keys();
const names = await caches.keys(); await Promise.all(
await Promise.all( names
names .filter((name) => name.startsWith(cachePrefix) && name !== cacheName)
.filter((name) => name.startsWith(cachePrefix) && name !== cacheName) .map((name) => caches.delete(name)),
.map((name) => caches.delete(name)), );
); await worker.clients.claim();
await worker.clients.claim(); })();
})(), event.waitUntil(activation);
);
}); });
worker.addEventListener('fetch', (event) => { worker.addEventListener('fetch', (event) => {
@ -296,6 +300,11 @@ worker.addEventListener('message', (event) => {
import('./types').CacheLoadedMessage import('./types').CacheLoadedMessage
> | null; > | null;
if (message?.type === cacheLoadedMessage && Array.isArray(message.urls)) { 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, NetworkState,
{ title: string; description: string | undefined } { 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 { useAuthStore } from '../../../stores/auth';
import { useCheckoutDraftStore } from '../../../stores/checkout-draft'; import { useCheckoutDraftStore } from '../../../stores/checkout-draft';
import { usePostDraftStore } from '../../../stores/post-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 * 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, * 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 * 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 * 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. * on the device (`session.` keys); a session that ran out keeps its drafts for the next sign-in.
*/ */
export function useSession(queryClient: QueryClient): void { export function useSession(queryClient: QueryClient): void {
useEffect(() => { useEffect(() => {
const restore = () => let disposed = false;
restoreSession().catch((error: unknown) => let inFlight = false;
handleError(error, { where: 'app', name: 'restore-session' }), 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 = () => { const restoreIfUnknown = () => {
if (useAuthStore.getState().status === 'unknown') void restore(); if (useAuthStore.getState().status === 'unknown') void restore();
}; };
@ -40,6 +67,8 @@ export function useSession(queryClient: QueryClient): void {
storage.clearByPrefix('session.'); storage.clearByPrefix('session.');
}); });
return () => { return () => {
disposed = true;
window.clearTimeout(retryTimer);
window.removeEventListener('online', restoreIfUnknown); window.removeEventListener('online', restoreIfUnknown);
offLogout(); offLogout();
}; };

View File

@ -12,23 +12,39 @@ export const backTargetStore = createStore<{ target: BackTarget | null }>()(
() => ({ target: 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, * 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 * 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`. * API there is none either, and back opens `parentHref`.
*/ */
export function previousEntryKey( export function previousEntryKey(
parentHref: string, parentHref: string,
toPrevious: boolean, toPrevious: boolean,
isMember: boolean,
): string | undefined { ): string | undefined {
if (!('navigation' in window)) return undefined; if (!('navigation' in window)) return undefined;
const current = navigation.currentEntry; const current = navigation.currentEntry;
if (!current || current.index < 1) return undefined; if (!current || current.index < 1) return undefined;
const previous = navigation.entries()[current.index - 1]; const previous = navigation.entries()[current.index - 1];
if (!previous?.url) return undefined; if (!previous?.url) return undefined;
if (toPrevious) return previous.key;
const from = new URL(previous.url).pathname; 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; const to = new URL(parentHref, window.location.href).pathname;
return from === to ? previous.key : undefined; return from === to ? previous.key : undefined;
} }

View File

@ -2,6 +2,7 @@
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { useViewerStatus } from '../../../stores/auth';
import { previousEntryKey, traverseTo } from '../back-target'; import { previousEntryKey, traverseTo } from '../back-target';
import type { BackAction, BackOptions } from '../types'; import type { BackAction, BackOptions } from '../types';
import { useDeclaredBackTarget } from './use-back-target'; 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. */ /** The page's parent, and whether any page of this site behind it counts as the way back. */
function useParent({ parentHref, backToPrevious = false }: ParentOptions) { function useParent({ parentHref, backToPrevious = false }: ParentOptions) {
const homeHref = useHomeHref(); 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 { return {
href: parentHref ?? homeHref, href: parentHref ?? homeHref,
// Home is a fallback, not a parent the page names. // Home is a fallback, not a parent the page names.
toPrevious: backToPrevious || parentHref === undefined, toPrevious: backToPrevious || parentHref === undefined,
isMember,
}; };
} }
@ -36,7 +41,11 @@ export function useBack({ href, onBack, ...options }: BackOptions): BackAction {
return { return {
href: parent.href, href: parent.href,
onNavigate: (event) => { onNavigate: (event) => {
const key = previousEntryKey(parent.href, parent.toPrevious); const key = previousEntryKey(
parent.href,
parent.toPrevious,
parent.isMember,
);
if (key === undefined) return; if (key === undefined) return;
event.preventDefault(); event.preventDefault();
traverseTo(key); traverseTo(key);
@ -49,7 +58,11 @@ export function useGoBack(options: ParentOptions): () => void {
const router = useRouter(); const router = useRouter();
const parent = useParent(options); const parent = useParent(options);
return () => { return () => {
const key = previousEntryKey(parent.href, parent.toPrevious); const key = previousEntryKey(
parent.href,
parent.toPrevious,
parent.isMember,
);
if (key === undefined) router.push(parent.href); if (key === undefined) router.push(parent.href);
else traverseTo(key); else traverseTo(key);
}; };

View File

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

View File

@ -124,3 +124,21 @@ export function withReturnPath(
): string { ): string {
return returnTo ? `${path}?redirect=${encodeURIComponent(returnTo)}` : path; 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 { useTranslation } from 'react-i18next';
import { useInviteLink } from '../../../../../../../features/checkout';
import { AuthGuard } from '../../../../../../guards/auth-guard'; import { AuthGuard } from '../../../../../../guards/auth-guard';
import { CheckoutForm } from './components/CheckoutForm'; import { CheckoutForm } from './components/CheckoutForm';
import { CheckoutSkeleton } from './CheckoutSkeleton'; 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 * 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 * 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) { export function CheckoutPanel(props: CheckoutPanelProps) {
const { t } = useTranslation('payment'); const { t } = useTranslation('payment');
useInviteLink(props.creatorId);
return ( return (
<AuthGuard <AuthGuard

View File

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

View File

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

View File

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

View File

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

View File

@ -9,6 +9,7 @@ import { useTranslation } from 'react-i18next';
import { usePostComposerPage } from '../../../../../../../../features/post'; import { usePostComposerPage } from '../../../../../../../../features/post';
import { MobileTopBar } from '../../../../../../../navigation/components/mobile-top-bar'; import { MobileTopBar } from '../../../../../../../navigation/components/mobile-top-bar';
import { useGoBack } from '../../../../../../../navigation/hooks/use-back';
import { ROUTES } from '../../../../../../../navigation/navigation'; import { ROUTES } from '../../../../../../../navigation/navigation';
import type { ComposerFormProps } from '../types'; import type { ComposerFormProps } from '../types';
import { ComposerAddImage } from './ComposerAddImage'; import { ComposerAddImage } from './ComposerAddImage';
@ -35,10 +36,17 @@ export function ComposerForm({
const { t } = useTranslation('content'); const { t } = useTranslation('content');
const router = useRouter(); const router = useRouter();
const picker = useRef<HTMLInputElement>(null); 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({ const model = usePostComposerPage({
creatorId, creatorId,
post, post,
onDone: (saved) => { onDone: () => {
// Replaced, so back never reopens an empty composer. // Replaced, so back never reopens an empty composer.
if (!post) { if (!post) {
router.replace(ROUTES.channel(username)); 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 // 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. // those copies at once (the navigation then takes over from it), so that page is read again.
router.refresh(); router.refresh();
if (window.history.length > 1) router.back(); goBack();
else router.replace(ROUTES.post(username, saved.id));
},
onLeave: () => {
if (window.history.length > 1) router.back();
else router.push(ROUTES.channel(username));
}, },
onLeave: goBack,
}); });
const title = t(post ? 'composer.edit-title' : 'composer.new-title'); 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 type { ChangeEvent } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { translateMessage } from '../../../../../../../../shared/utils';
import { CHART_ACCEPT } from '../constants'; import { CHART_ACCEPT } from '../constants';
import type { ComposerPartProps } from '../types'; import type { ComposerPartProps } from '../types';
import { FieldGroup } from './FieldGroup'; import { FieldGroup } from './FieldGroup';
@ -20,6 +21,8 @@ export function ChartField({ model, layout }: ComposerPartProps) {
const { image } = chart; const { image } = chart;
const n = number(1); const n = number(1);
const busy = model.phase === 'publishing'; 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 onPick = (event: ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0]; const file = event.target.files?.[0];
@ -32,7 +35,9 @@ export function ChartField({ model, layout }: ComposerPartProps) {
<FieldGroup <FieldGroup
label={t('composer.chart')} label={t('composer.chart')}
error={ 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')} caption={t('content:composer.images.hint')}
> >

View File

@ -10,6 +10,7 @@ import { useTranslation } from 'react-i18next';
import { usePredictionComposerPage } from '../../../../../../../../features/prediction'; import { usePredictionComposerPage } from '../../../../../../../../features/prediction';
import { MobileTopBar } from '../../../../../../../navigation/components/mobile-top-bar'; import { MobileTopBar } from '../../../../../../../navigation/components/mobile-top-bar';
import { useGoBack } from '../../../../../../../navigation/hooks/use-back';
import { ROUTES } from '../../../../../../../navigation/navigation'; import { ROUTES } from '../../../../../../../navigation/navigation';
import type { ComposerPageProps } from '../types'; import type { ComposerPageProps } from '../types';
import { ComposerFields } from './ComposerFields'; import { ComposerFields } from './ComposerFields';
@ -33,14 +34,16 @@ export function ComposerPage({
}: ComposerPageProps) { }: ComposerPageProps) {
const { t } = useTranslation('predictions'); const { t } = useTranslation('predictions');
const router = useRouter(); 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({ const model = usePredictionComposerPage({
creatorId, creatorId,
// Replaced, so back never reopens an empty composer. // Replaced, so back never reopens an empty composer.
onDone: () => router.replace(ROUTES.channel(username)), onDone: () => router.replace(ROUTES.channel(username)),
onLeave: () => { onLeave: goBack,
if (window.history.length > 1) router.back();
else router.push(ROUTES.channel(username));
},
}); });
const cancel = ( const cancel = (
<Button <Button

View File

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

View File

@ -1,14 +1,16 @@
import { Button } from '@lumina/island/atoms/button'; import { Button } from '@lumina/island/atoms/button';
import { useOfflineFreeze } from '@lumina/island/hooks/use-online';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import type { ComposerPartProps } from '../types'; import type { ComposerPartProps } from '../types';
/** /**
* «انتشار پیش‌بینی»: frozen until the form can publish, saying why (J09-1b, J09-2, J09-2c); a * «انتشار پیش‌بینی»: 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) { 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'; const isMobile = layout === 'mobile';
return ( return (
@ -16,8 +18,8 @@ export function PublishButton({ model, layout }: ComposerPartProps) {
variant="primary" variant="primary"
size={isMobile ? 'lg' : undefined} size={isMobile ? 'lg' : undefined}
block={isMobile} block={isMobile}
frozen={model.publishBlock.frozen} frozen={offline.frozen || model.publishBlock.frozen}
frozenReason={model.publishBlock.reason} frozenReason={offline.frozenReason ?? model.publishBlock.reason}
frozenAlign={isMobile ? undefined : 'end'} frozenAlign={isMobile ? undefined : 'end'}
isLoading={model.phase === 'publishing'} isLoading={model.phase === 'publishing'}
onClick={model.requestPublish} onClick={model.requestPublish}

View File

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

View File

@ -3,6 +3,8 @@
import { FlexBox } from '@lumina/island/atoms/flex-box'; import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Icon } from '@lumina/island/atoms/icon'; import { Icon } from '@lumina/island/atoms/icon';
import { Typography } from '@lumina/island/atoms/typography'; 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 { useTranslation } from 'react-i18next';
import { useNotificationSettingsPage } from '../../../../../../../features/notification-settings'; 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 * تنظیمات اعلان‌ها (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 * 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) { export function NotificationSettings({ layout }: NotificationSettingsProps) {
const { t } = useTranslation('account'); const { t } = useTranslation(['account', 'common']);
const model = useNotificationSettingsPage(); const model = useNotificationSettingsPage();
const offline = useOfflineFreeze(t('common:network.frozen'));
return ( return (
<FlexBox <FlexBox
direction="flex-col" direction="flex-col"
gap={layout === 'desktop' ? 'gap-4' : 'gap-3'} gap={layout === 'desktop' ? 'gap-4' : 'gap-3'}
> >
{offline.frozen && <Banner tone="warning" title={offline.frozenReason} />}
{model.sections.map((section) => ( {model.sections.map((section) => (
<SettingsSection <SettingsSection
key={section.channel} key={section.channel}
section={section} section={section}
model={model} model={model}
frozen={offline.frozen === true}
/> />
))} ))}
<FlexBox <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 * 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. * 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 { t, i18n } = useTranslation('account');
const titleId = useId(); const titleId = useId();
// The row keys come from the API, so their copy is looked up by a built key. // 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 <Switch
checked={row.enabled} checked={row.enabled}
locked={row.locked} locked={row.locked || frozen}
description={ description={
i18n.exists(`${copy}.description`) i18n.exists(`${copy}.description`)
? translate(`${copy}.description`) ? translate(`${copy}.description`)

View File

@ -18,4 +18,6 @@ export type NotificationSettingsSkeletonProps = NotificationSettingsProps & {
export type SettingsSectionProps = { export type SettingsSectionProps = {
section: NotificationSettingsSection; section: NotificationSettingsSection;
model: NotificationSettingsPageModel; 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> </FlexBox>
{!saleOpen && <SaleClosedNote />} {!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} /> <InviteOnlyNote name={inviteNoteName} />
)} )}
{followsToSubscribe && <InviteLinkNote />} {followsToSubscribe && <InviteLinkNote />}

View File

@ -131,8 +131,11 @@ export function InvestorActions({
onCancel={standing.saleNotice ? cancelSaleNotice : undefined} 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 && {subscribeLive &&
!standing.waitlisted && !standing.waitlisted &&
!hasInviteCode &&
!standing.paymentFailed &&
inviteNoteName !== undefined && ( inviteNoteName !== undefined && (
<InviteOnlyNote name={inviteNoteName} /> <InviteOnlyNote name={inviteNoteName} />
)} )}

View File

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

View File

@ -2,7 +2,7 @@
import { Modal } from '@lumina/island/molecules/modal'; import { Modal } from '@lumina/island/molecules/modal';
import { Sheet } from '@lumina/island/molecules/sheet'; import { Sheet } from '@lumina/island/molecules/sheet';
import { Suspense } from 'react'; import { Suspense, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { PartBoundary } from '../../../../../../error-boundaries'; 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 * «تمدید» 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. * error, so a failure never touches the list behind it.
*/ */
export function RenewalSheet({ export function RenewalSheet({
@ -22,6 +23,7 @@ export function RenewalSheet({
onClose, onClose,
}: RenewalSheetProps) { }: RenewalSheetProps) {
const { t } = useTranslation('dashboard'); const { t } = useTranslation('dashboard');
const [isBusy, setIsBusy] = useState(false);
const title = const title =
target.status === 'expired' target.status === 'expired'
? t('subscriptions.renewal.reactivate-title') ? t('subscriptions.renewal.reactivate-title')
@ -40,6 +42,7 @@ export function RenewalSheet({
key={target.id} key={target.id}
subscriptionId={target.id} subscriptionId={target.id}
layout={layout} layout={layout}
onBusyChange={setIsBusy}
/> />
</Suspense> </Suspense>
</PartBoundary> </PartBoundary>
@ -47,11 +50,23 @@ export function RenewalSheet({
const closeLabel = t('subscriptions.renewal.close'); const closeLabel = t('subscriptions.renewal.close');
return layout === 'mobile' ? ( return layout === 'mobile' ? (
<Sheet open={open} title={title} onClose={onClose} closeLabel={closeLabel}> <Sheet
open={open}
title={title}
onClose={onClose}
closeLabel={closeLabel}
dismissible={!isBusy}
>
{body} {body}
</Sheet> </Sheet>
) : ( ) : (
<Modal open={open} title={title} onClose={onClose} closeLabel={closeLabel}> <Modal
open={open}
title={title}
onClose={onClose}
closeLabel={closeLabel}
dismissible={!isBusy}
>
{body} {body}
</Modal> </Modal>
); );

View File

@ -10,7 +10,7 @@ import { Banner } from '@lumina/island/molecules/banner';
import { TierOption } from '@lumina/island/organisms/tier-option'; import { TierOption } from '@lumina/island/organisms/tier-option';
import { Element } from '@lumina/island/primitives/element'; import { Element } from '@lumina/island/primitives/element';
import { date } from '@lumina/tools/format'; import { date } from '@lumina/tools/format';
import { useId } from 'react'; import { useEffect, useId } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useRenewalSheet } from '../../../../../../../../features/subscription'; 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 * 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. * 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 } = useTranslation('dashboard');
const { t: tPayment } = useTranslation('payment'); const { t: tPayment } = useTranslation('payment');
const { t: tCommon } = useTranslation('common'); const { t: tCommon } = useTranslation('common');
@ -43,6 +47,11 @@ export function RenewalForm({ subscriptionId, layout }: RenewalFormProps) {
const countdownLabels = promotionCountdownLabels(tPayment); const countdownLabels = promotionCountdownLabels(tPayment);
const from = selectedTier?.periodFrom ?? tiers[0]?.periodFrom; const from = selectedTier?.periodFrom ?? tiers[0]?.periodFrom;
const isBusy = phase !== 'idle'; 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 const payLabel = isBusy
? t('subscriptions.renewal.paying') ? t('subscriptions.renewal.paying')
: model.isOffline : model.isOffline

View File

@ -13,4 +13,6 @@ export type RenewalSheetProps = {
export type RenewalFormProps = { export type RenewalFormProps = {
subscriptionId: string; subscriptionId: string;
layout: DashboardLayout; 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'; 'use client';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
import { Sheet } from '@lumina/island/molecules/sheet'; import { Sheet } from '@lumina/island/molecules/sheet';
import { Suspense } from 'react'; import { Suspense } from 'react';
import type { MouseEvent } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { PartBoundary } from '../../../../../error-boundaries'; 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 * 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) { export function NotificationPanel({ open, onClose }: NotificationPanelProps) {
const { t } = useTranslation('notifications'); 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 = ( const skeleton = (
<SkeletonPreset preset="list" avatar={false} label={t('loading')} /> <SkeletonPreset preset="list" avatar={false} label={t('loading')} />
); );
@ -27,11 +37,13 @@ export function NotificationPanel({ open, onClose }: NotificationPanelProps) {
onClose={onClose} onClose={onClose}
closeLabel={t('close')} closeLabel={t('close')}
> >
<PartBoundary name="notification-centre" description={t('error')}> <FlexBox direction="flex-col" onClick={closeOnLink}>
<Suspense fallback={skeleton}> <PartBoundary name="notification-centre" description={t('error')}>
<NotificationCentre layout="panel" supportPlacement="popover" /> <Suspense fallback={skeleton}>
</Suspense> <NotificationCentre layout="panel" supportPlacement="popover" />
</PartBoundary> </Suspense>
</PartBoundary>
</FlexBox>
</Sheet> </Sheet>
); );
} }

View File

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

View File

@ -1,6 +1,7 @@
'use client'; 'use client';
import { Button } from '@lumina/island/atoms/button'; import { Button } from '@lumina/island/atoms/button';
import { useOfflineFreeze } from '@lumina/island/hooks/use-online';
import { Modal } from '@lumina/island/molecules/modal'; import { Modal } from '@lumina/island/molecules/modal';
import { Sheet } from '@lumina/island/molecules/sheet'; import { Sheet } from '@lumina/island/molecules/sheet';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
@ -19,7 +20,8 @@ export function DeletePostConfirm({
onCancel, onCancel,
layout, layout,
}: DeletePostConfirmProps) { }: DeletePostConfirmProps) {
const { t } = useTranslation('content'); const { t } = useTranslation(['content', 'common']);
const offline = useOfflineFreeze(t('common:network.frozen'));
const size = layout === 'mobile' ? 'lg' : undefined; const size = layout === 'mobile' ? 'lg' : undefined;
const title = t('post.delete.title'); const title = t('post.delete.title');
const buttons = ( const buttons = (
@ -29,6 +31,7 @@ export function DeletePostConfirm({
size={size} size={size}
block block
isLoading={isDeleting} isLoading={isDeleting}
{...offline}
onClick={onConfirm} onClick={onConfirm}
> >
{t('post.delete.confirm')} {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`. */ /** 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( export async function registerInvestor(
args: RegisterInvestorArgs, args: RegisterInvestorArgs,
{ emit = true }: { emit?: boolean } = {}, { emit = true, signal }: { emit?: boolean; signal?: AbortSignal } = {},
): Promise<SessionPayload> { ): Promise<SessionPayload> {
const session = await authRepository.registerInvestor(args); const session = await authRepository.registerInvestor(args, { signal });
useAuthFlowStore.getState().reset(); useAuthFlowStore.getState().reset();
useAuthFlowStore.getState().markRegistered(session.account.role); useAuthFlowStore.getState().markRegistered(session.account.role);
useAuthStore.getState().setSession(session); useAuthStore.getState().setSession(session);

View File

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

View File

@ -21,6 +21,7 @@ import {
import type { InvestorDetailsPartModel, UseDetailsPartOptions } from './types'; import type { InvestorDetailsPartModel, UseDetailsPartOptions } from './types';
import { useRegisterLeave } from './use-register-leave'; import { useRegisterLeave } from './use-register-leave';
import { useRegistrationAutosave } from './use-registration-autosave'; import { useRegistrationAutosave } from './use-registration-autosave';
import { useRegistrationRequest } from './use-registration-request';
import { useUsernameAvailability } from './use-username-availability'; import { useUsernameAvailability } from './use-username-availability';
/** /**
@ -56,7 +57,9 @@ export function useInvestorDetailsPart({
const [isDone, setIsDone] = useState(false); const [isDone, setIsDone] = useState(false);
const { errors, isSubmitting } = form.formState; const { errors, isSubmitting } = form.formState;
const saveDraft = useRegistrationAutosave(form); const saveDraft = useRegistrationAutosave(form);
const request = useRegistrationRequest();
const leave = useRegisterLeave(!isDone, () => { const leave = useRegisterLeave(!isDone, () => {
request.cancel();
useAuthFlowStore.getState().keepDraft(form.getValues()); useAuthFlowStore.getState().keepDraft(form.getValues());
saveDraft(); saveDraft();
}); });
@ -75,16 +78,18 @@ export function useInvestorDetailsPart({
); );
return; return;
} }
const signal = request.start();
try { try {
await registerInvestor({ await registerInvestor(
phone, { phone, registrationToken: registration.token, ...values },
registrationToken: registration.token, { signal },
...values, );
});
setIsDone(true); setIsDone(true);
showToast({ tone: 'success', message: t('register.details.success') }); showToast({ tone: 'success', message: t('register.details.success') });
router.replace(profileHref); router.replace(profileHref);
} catch (error) { } catch (error) {
// Cancelled because the person left: nothing to show.
if (signal.aborted) return;
if (authErrorCode(error) === AUTH_ERROR_CODES.registrationExpired) { if (authErrorCode(error) === AUTH_ERROR_CODES.registrationExpired) {
onExpired(); onExpired();
return; 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 * 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 * 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 * 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>( export function useRegistrationAutosave<T extends FieldValues & DraftFields>(
form: UseFormReturn<T, unknown, unknown>, form: UseFormReturn<T, unknown, unknown>,
@ -22,6 +23,7 @@ export function useRegistrationAutosave<T extends FieldValues & DraftFields>(
const pending = useRef<DraftFields | null>(null); const pending = useRef<DraftFields | null>(null);
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined); const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const lastSaved = useRef<string | null>(null); const lastSaved = useRef<string | null>(null);
const queue = useRef<Promise<void>>(Promise.resolve());
const flush = useCallback(() => { const flush = useCallback(() => {
clearTimeout(timer.current); clearTimeout(timer.current);
@ -32,16 +34,20 @@ export function useRegistrationAutosave<T extends FieldValues & DraftFields>(
const key = JSON.stringify(fields); const key = JSON.stringify(fields);
if (key === lastSaved.current) return; if (key === lastSaved.current) return;
lastSaved.current = key; lastSaved.current = key;
authRepository const draft = {
.saveRegistrationDraft({ phone,
phone, registrationToken: registration.token,
registrationToken: registration.token, role: role ?? undefined,
role: role ?? undefined, ...fields,
...fields, };
}) queue.current = queue.current
.catch(() => { .then(() => authRepository.saveRegistrationDraft(draft))
lastSaved.current = null; .then(
}); () => undefined,
() => {
if (lastSaved.current === key) lastSaved.current = null;
},
);
}, []); }, []);
useEffect( 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); return toOtpSentPayload(response);
}, },
async registerInvestor(args: RegisterInvestorArgs): Promise<SessionPayload> { async registerInvestor(
args: RegisterInvestorArgs,
{ signal }: { signal?: AbortSignal } = {},
): Promise<SessionPayload> {
const response = await send(() => const response = await send(() =>
authHttp.post<SessionResponseDto>( authHttp.post<SessionResponseDto>(
AUTH_ENDPOINTS.registerInvestor, AUTH_ENDPOINTS.registerInvestor,
toRegisterInvestorDto(args), toRegisterInvestorDto(args),
{ skipRefresh: true }, { skipRefresh: true, signal },
), ),
); );
return toSessionPayload(response); return toSessionPayload(response);

View File

@ -324,9 +324,12 @@ export function useCheckoutPage({
showActionError(error, options); 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 ( const submit = async (
{ tierId: chosen, referralCode: code }: CheckoutFormOutput, { tierId: chosen, referralCode: code }: CheckoutFormOutput,
confirmPriceChange = false, confirmedPriceToman?: number,
) => { ) => {
const tier = tiers.find((item) => item.id === chosen); const tier = tiers.find((item) => item.id === chosen);
setPhase('paying'); setPhase('paying');
@ -337,8 +340,8 @@ export function useCheckoutPage({
creatorId, creatorId,
tierId: chosen, tierId: chosen,
referralCode: code, referralCode: code,
expectedPriceToman: tier?.priceToman ?? undefined, expectedPriceToman:
confirmPriceChange: confirmPriceChange || undefined, confirmedPriceToman ?? tier?.priceToman ?? undefined,
}), }),
); );
} catch (error) { } catch (error) {
@ -440,13 +443,18 @@ export function useCheckoutPage({
isOffline, isOffline,
halt, halt,
confirmPriceChange: () => { confirmPriceChange: () => {
const confirmed = halt?.kind === 'price-changed' ? halt : null;
setHalt(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. // Reactivation pays the live price with no confirmation to send, so it simply goes again.
if (reactivation && selectedTier) { if (reactivation && selectedTier) {
void reactivate(selectedTier.id, reactivation.id); void reactivate(selectedTier.id, reactivation.id);
return; return;
} }
void form.handleSubmit((values) => submit(values, true))(); void form.handleSubmit((values) =>
submit(values, confirmed?.newAmountToman),
)();
}, },
cancelPriceChange: () => { cancelPriceChange: () => {
setHalt(null); setHalt(null);

View File

@ -1,3 +1,4 @@
import { isHttpError } from '@lumina/libs/http';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { useEffect } from 'react'; import { useEffect } from 'react';
@ -9,6 +10,17 @@ import { transactionKeys, transactionRepository } from '../../../transaction';
import { PAYMENT_CONFIRM_TIMEOUT_MS, PAYMENT_POLL_MS } from '../../constants'; import { PAYMENT_CONFIRM_TIMEOUT_MS, PAYMENT_POLL_MS } from '../../constants';
import type { UsePaymentReturnPageOptions } from './types'; 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. * 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 * 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 }) => queryFn: ({ signal }) =>
transactionRepository.getDetail(paymentId ?? '', { signal }), transactionRepository.getDetail(paymentId ?? '', { signal }),
enabled: paymentId !== null && status === 'member', enabled: paymentId !== null && status === 'member',
refetchInterval: (query) => // A failed read (a 502 right after the bank) never throws to the boundary: the page keeps
query.state.data?.confirmation.phase === 'processing' // polling, and the timeout still takes the investor to the result page (0029).
? PAYMENT_POLL_MS throwOnError: false,
: 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 phase = payment.data?.confirmation.phase;
const refused = payment.data === undefined && isFinal(payment.error);
useEffect(() => { useEffect(() => {
if (paymentId === null) { if (paymentId === null) {
router.replace(ROUTES.dashboard.transactions); router.replace(ROUTES.dashboard.transactions);
return; 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)); 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 // 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. // 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, tierId: args.tierId,
referralCode: args.referralCode.trim(), referralCode: args.referralCode.trim(),
expectedPriceToman: args.expectedPriceToman, expectedPriceToman: args.expectedPriceToman,
confirmPriceChange: args.confirmPriceChange,
}; };
} }

View File

@ -243,20 +243,17 @@ export type SubscribeArgs = {
referralCode: string; referralCode: string;
/** The `priceToman` the investor saw; a different live price answers `price-changed`. */ /** The `priceToman` the investor saw; a different live price answers `price-changed`. */
expectedPriceToman?: number; expectedPriceToman?: number;
/** The investor accepted the new price; skips the price check. */
confirmPriceChange?: boolean;
}; };
export type SubscribeDto = { export type SubscribeDto = {
tierId: string; tierId: string;
referralCode: string; referralCode: string;
expectedPriceToman?: number; expectedPriceToman?: number;
confirmPriceChange?: boolean;
}; };
export type SubscribeResponseDto = CheckoutResultEntity; 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 = { export type PriceChangedPayload = {
outcome: 'price-changed'; outcome: 'price-changed';
oldAmountToman: number; oldAmountToman: number;

View File

@ -135,14 +135,28 @@ export function useLedgerPart(): LedgerPartModel {
}, [router, pathname]); }, [router, pathname]);
// The linked row isn't among the rows read yet: read on, a few pages at most, then let it go. // 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 pageCount = list.data.pages.length;
const { hasNextPage, isFetching, fetchNextPage } = list; const { hasNextPage, isFetching, isFetchNextPageError, fetchNextPage } = list;
const isLooking = linked !== null && linkedRow === null; const isLooking = linked !== null && linkedRow === null;
useEffect(() => { useEffect(() => {
if (!isLooking || isFetching) return; 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(); else dropLink();
}, [isLooking, isFetching, hasNextPage, pageCount, fetchNextPage, dropLink]); }, [
isLooking,
isFetching,
isFetchNextPageError,
hasNextPage,
pageCount,
fetchNextPage,
dropLink,
]);
const openDetail = (row: LedgerItemPayload) => { const openDetail = (row: LedgerItemPayload) => {
setDetail(row); setDetail(row);

View File

@ -5,6 +5,7 @@ import {
useQueryClient, useQueryClient,
useSuspenseQuery, useSuspenseQuery,
} from '@tanstack/react-query'; } from '@tanstack/react-query';
import { useRef } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { showActionError } from '../../../../shared/utils'; 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 * تنظیمات اعلان‌ها (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 * 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 * «تنظیمات ذخیره شد.» 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 * are always on and never saved. Saves go one at a time in tap order, and only the last answer
* replaces the screen's view, so a quick second flip is never undone by the first one's 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 { export function useNotificationSettingsPage(): NotificationSettingsPageModel {
const { t } = useTranslation('account'); const { t } = useTranslation('account');
@ -55,6 +57,9 @@ export function useNotificationSettingsPage(): NotificationSettingsPageModel {
const role = useCurrentAccount()?.role ?? 'investor'; const role = useCurrentAccount()?.role ?? 'investor';
const queryKey = notificationSettingsKeys.mine(); const queryKey = notificationSettingsKeys.mine();
const mutationKey = notificationSettingsKeys.update(); 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({ const { data } = useSuspenseQuery({
queryKey, queryKey,
@ -63,6 +68,7 @@ export function useNotificationSettingsPage(): NotificationSettingsPageModel {
const save = useMutation({ const save = useMutation({
mutationKey, mutationKey,
scope: { id: mutationKey.join(':') },
mutationFn: (args: UpdateNotificationSettingArgs) => mutationFn: (args: UpdateNotificationSettingArgs) =>
updateNotificationSetting(args), updateNotificationSetting(args),
onMutate: async (args) => { onMutate: async (args) => {
@ -73,17 +79,26 @@ export function useNotificationSettingsPage(): NotificationSettingsPageModel {
); );
}, },
onSuccess: (settings) => { onSuccess: (settings) => {
if (queryClient.isMutating({ mutationKey }) <= 1) { if (isLast()) {
failedEarlier.current = false;
queryClient.setQueryData(queryKey, settings); queryClient.setQueryData(queryKey, settings);
} }
showToast({ tone: 'success', message: t('notifications.saved') }); showToast({ tone: 'success', message: t('notifications.saved') });
}, },
onError: (error, args) => { onError: (error, args) => {
queryClient.setQueryData<NotificationSettingsPayload>( if (!isLast()) {
queryKey, failedEarlier.current = true;
(current) => } else if (failedEarlier.current) {
current && withSwitch(current, { ...args, enabled: !args.enabled }), // 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)) { if (isHttpError(error) && STALE_CODES.has(error.code)) {
void queryClient.invalidateQueries({ queryKey }); 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 { showToast } from '@lumina/island/molecules/toast';
import { isHttpError } from '@lumina/libs/http'; import { isHttpError } from '@lumina/libs/http';
import { useQueryClient } from '@tanstack/react-query'; 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 { useForm, useWatch } from 'react-hook-form';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useLeaveGuard } from '../../../../app/navigation/hooks/use-leave-guard';
import { applyServerErrors, showActionError } from '../../../../shared/utils'; import { applyServerErrors, showActionError } from '../../../../shared/utils';
import { profileKeys } from '../../../profile'; import { profileKeys } from '../../../profile';
import { postComposerSchema } from '../../../../shared/validations'; import { postComposerSchema } from '../../../../shared/validations';
@ -74,12 +82,14 @@ export function usePostComposerPage({
const isEmpty = !hasText && images.images.length === 0; const isEmpty = !hasText && images.images.length === 0;
const [phase, setPhase] = useState<ComposerPhase>('idle'); const [phase, setPhase] = useState<ComposerPhase>('idle');
const [isConfirmingLeave, setIsConfirmingLeave] = useState(false); 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 // 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. // lost answer never posts twice; any change gets a new one. Refs, so two quick submits before a
const [lastSend, setLastSend] = useState<{ // render share one send.
body: string; const lastSend = useRef<{ body: string; key: string } | null>(null);
key: string; const isSending = useRef(false);
} | null>(null);
const editEndsAt = post?.publishedAt const editEndsAt = post?.publishedAt
? new Date(post.publishedAt).getTime() + POST_LIMITS.editWindowMs ? new Date(post.publishedAt).getTime() + POST_LIMITS.editWindowMs
@ -89,6 +99,13 @@ export function usePostComposerPage({
}); });
const isEditExpired = mode === 'edit' && secondsLeft === 0; 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. // A new post's draft follows every change; an empty composer keeps none.
const keepDraft = useEffectEvent(() => { const keepDraft = useEffectEvent(() => {
if (post) return; if (post) return;
@ -97,12 +114,11 @@ export function usePostComposerPage({
(image): image is ComposerImage & { fileId: string; url: string } => (image): image is ComposerImage & { fileId: string; url: string } =>
image.status === 'ready' && image.fileId !== null && image.url !== null, image.status === 'ready' && image.fileId !== null && image.url !== null,
); );
const store = usePostDraftStore.getState();
if (!caption.trim() && ready.length === 0) { if (!caption.trim() && ready.length === 0) {
store.clearDraft(); clearOwnDraft();
return; return;
} }
store.saveDraft({ usePostDraftStore.getState().saveDraft({
creatorId, creatorId,
caption, caption,
accessLevel, accessLevel,
@ -150,8 +166,8 @@ export function usePostComposerPage({
return changes; return changes;
}; };
const submit = form.handleSubmit(async ({ caption, accessLevel }) => { const send = async ({ caption, accessLevel }: PostComposerFormValues) => {
if (blocker || phase === 'saving' || isEditExpired) return; if (blocker || isSending.current || isEditExpired) return;
const text = caption.trim(); const text = caption.trim();
const media = images.images const media = images.images
.filter((image) => image.status === 'ready' && image.fileId !== null) .filter((image) => image.status === 'ready' && image.fileId !== null)
@ -165,6 +181,7 @@ export function usePostComposerPage({
return; return;
} }
isSending.current = true;
setPhase('saving'); setPhase('saving');
let saved: PostPayload; let saved: PostPayload;
try { try {
@ -183,10 +200,10 @@ export function usePostComposerPage({
}; };
const body = JSON.stringify(args); const body = JSON.stringify(args);
const send = const send =
lastSend?.body === body lastSend.current?.body === body
? lastSend ? lastSend.current
: { body, key: crypto.randomUUID() }; : { body, key: crypto.randomUUID() };
setLastSend(send); lastSend.current = send;
saved = await publishPost(args, { idempotencyKey: send.key }); saved = await publishPost(args, { idempotencyKey: send.key });
} }
} catch (error) { } catch (error) {
@ -210,11 +227,12 @@ export function usePostComposerPage({
} }
// The key went with another post (it never should): the retry sends a new one. // The key went with another post (it never should): the retry sends a new one.
if (isHttpError(error) && error.code === 'IDEMPOTENCY_KEY_REUSED') { 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 // 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. // takes the composer away: a second tap would publish again, or save again and go back twice.
isSending.current = false;
setPhase('idle'); setPhase('idle');
return; return;
} }
@ -227,7 +245,9 @@ export function usePostComposerPage({
showToast({ tone: 'success', message: t('composer.published') }); showToast({ tone: 'success', message: t('composer.published') });
} }
onDone(saved); onDone(saved);
}); };
// Validated inside the press, so the send guard's refs are read only then.
const submit = () => form.handleSubmit(send)();
const hasSomethingToLose = () => { const hasSomethingToLose = () => {
const { caption, accessLevel } = form.getValues(); const { caption, accessLevel } = form.getValues();
@ -245,10 +265,31 @@ export function usePostComposerPage({
const leave = () => { const leave = () => {
images.abortAll(); images.abortAll();
if (!post) usePostDraftStore.getState().clearDraft(); if (!post) clearOwnDraft();
onLeave(); 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 { return {
mode, mode,
form, form,
@ -268,9 +309,18 @@ export function usePostComposerPage({
isConfirmingLeave, isConfirmingLeave,
confirmLeave: () => { confirmLeave: () => {
setIsConfirmingLeave(false); setIsConfirmingLeave(false);
leave(); if (leaveTo === null) {
leave();
return;
}
setLeaveTo(null);
images.abortAll();
router.push(leaveTo);
},
cancelLeave: () => {
setIsConfirmingLeave(false);
setLeaveTo(null);
}, },
cancelLeave: () => setIsConfirmingLeave(false),
minutesLeft: minutesLeft:
secondsLeft === null ? null : Math.ceil(secondsLeft / SECONDS_PER_MINUTE), secondsLeft === null ? null : Math.ceil(secondsLeft / SECONDS_PER_MINUTE),
isEditExpired, isEditExpired,

View File

@ -34,19 +34,21 @@ export function useOwnerPostPart({
: undefined; : undefined;
const secondsLeft = useCountdown(editEndsAt, { intervalMs: MINUTE_MS }); 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({ const remove = useMutation({
mutationFn: () => mutationFn: () =>
deletePost({ postId: post.id, creatorId: post.creatorId }), deletePost({ postId: post.id, creatorId: post.creatorId }),
onSuccess: () => { onSuccess: 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();
},
onError: (error) => { onError: (error) => {
// A published prediction stays as it is (409 PREDICTION_LOCKED); its card offers no delete, // A published prediction stays as it is (409 PREDICTION_LOCKED); its card offers no delete,
// so only a stale one gets here. // so only a stale one gets here.
@ -59,7 +61,13 @@ export function useOwnerPostPart({
}); });
return; 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, { showActionError(error, {
t, t,
failedMessage: t('post.delete.failed'), failedMessage: t('post.delete.failed'),

View File

@ -4,6 +4,7 @@ import { useRouter } from 'next/navigation';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { showActionError } from '../../../../shared/utils'; import { showActionError } from '../../../../shared/utils';
import { postKeys, resetCachedChannel } from '../../../post';
import { closePrediction } from '../../actions/close-prediction'; import { closePrediction } from '../../actions/close-prediction';
import { QUOTE_REFRESH_MS } from '../../repositories/market-data'; import { QUOTE_REFRESH_MS } from '../../repositories/market-data';
import { import {
@ -41,7 +42,12 @@ export function useClosePredictionPart({
const settled = (error: unknown): CloseQuoteState | null => { const settled = (error: unknown): CloseQuoteState | null => {
const code = predictionErrorCode(error); const code = predictionErrorCode(error);
if (code === PREDICTION_ERROR_CODES.closePending) { 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: predictionKeys.own() });
void queryClient.invalidateQueries({
queryKey: postKeys.detail(post.id),
});
resetCachedChannel(queryClient, post.creatorId);
return { kind: 'pending' }; return { kind: 'pending' };
} }
if (code === PREDICTION_ERROR_CODES.quoteUnavailable) { 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 { isHttpError } from '@lumina/libs/http';
import { list, number } from '@lumina/tools/format'; import { list, number } from '@lumina/tools/format';
import { useQuery, useQueryClient } from '@tanstack/react-query'; 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 { useFieldArray, useForm, useWatch } from 'react-hook-form';
import type { FieldPath } from 'react-hook-form'; import type { FieldPath } from 'react-hook-form';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useLeaveGuard } from '../../../../app/navigation/hooks/use-leave-guard';
import { import {
levelPrice, levelPrice,
PREDICTION_FORM_LIMITS, PREDICTION_FORM_LIMITS,
@ -126,9 +134,12 @@ export function usePredictionComposerPage({
}: UsePredictionComposerPageOptions): PredictionComposerPageModel { }: UsePredictionComposerPageOptions): PredictionComposerPageModel {
const { t } = useTranslation(['predictions', 'content']); const { t } = useTranslation(['predictions', 'content']);
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const router = useRouter();
const chart = useChartImage(); const chart = useChartImage();
const [phase, setPhase] = useState<ComposerPhase>('idle'); const [phase, setPhase] = useState<ComposerPhase>('idle');
const [isConfirmingLeave, setIsConfirmingLeave] = useState(false); 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. // What the confirm step opened with, should the price drop out while it is open.
const [confirmed, setConfirmed] = useState<ComposerSummary | null>(null); const [confirmed, setConfirmed] = useState<ComposerSummary | null>(null);
// When the API last said there was no price at publish: a newer price clears it. // When the API last said there was no price at publish: a newer price clears it.
@ -406,6 +417,20 @@ export function usePredictionComposerPage({
onLeave(); 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 { return {
form, form,
markets, markets,
@ -492,8 +517,17 @@ export function usePredictionComposerPage({
isConfirmingLeave, isConfirmingLeave,
confirmLeave: () => { confirmLeave: () => {
setIsConfirmingLeave(false); 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>>({}); const [serverErrors, setServerErrors] = useState<Record<string, string>>({});
// What «ذخیره و خروج» does once this save went through (J10-4n). // What «ذخیره و خروج» does once this save went through (J10-4n).
const onSavedRef = useRef<(() => void) | null>(null); 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 (۴.۳). // A start set on this page is never earlier than the minute it opened (۴.۳).
const [openedAt] = useState(() => { const [openedAt] = useState(() => {
const now = new Date(); const now = new Date();
@ -272,6 +275,7 @@ export function usePricingPage(): PricingPageModel {
const failed = (error: unknown) => { const failed = (error: unknown) => {
onSavedRef.current = null; onSavedRef.current = null;
checkedArgs.current = null;
setConfirmation(null); setConfirmation(null);
setPhase('idle'); setPhase('idle');
if ( if (
@ -285,7 +289,26 @@ export function usePricingPage(): PricingPageModel {
} }
if (isHttpError(error) && error.status === 409) { if (isHttpError(error) && error.status === 409) {
// The lock started since the page was read (a first purchase): show the form as it is now. // 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)) { if (isConnectionError(error)) {
// The banner with «تلاش دوباره» says it (۵.۴); a toast too would say it twice. // The banner with «تلاش دوباره» says it (۵.۴); a toast too would say it twice.
@ -306,10 +329,10 @@ export function usePricingPage(): PricingPageModel {
return; return;
} }
setPhase('checking'); setPhase('checking');
const args = toSavePricingArgs(values);
checkedArgs.current = args;
try { try {
const result = await pricingRepository.validate( const result = await pricingRepository.validate(args);
toSavePricingArgs(values),
);
if (!result.valid) { if (!result.valid) {
onSavedRef.current = null; onSavedRef.current = null;
setServerErrors(result.fieldErrors); setServerErrors(result.fieldErrors);
@ -325,9 +348,11 @@ export function usePricingPage(): PricingPageModel {
}; };
const confirm = async () => { const confirm = async () => {
const args = checkedArgs.current;
if (!args) return;
setPhase('saving'); setPhase('saving');
try { try {
const saved = await savePricing(toSavePricingArgs(values)); const saved = await savePricing(args);
queryClient.setQueryData(pricingKeys.form(), saved); queryClient.setQueryData(pricingKeys.form(), saved);
// The dashboard's figures carry the tiers too, and a first priced plan wakes the invite code. // The dashboard's figures carry the tiers too, and a first priced plan wakes the invite code.
void queryClient.invalidateQueries({ queryKey: overviewKeys.all }); void queryClient.invalidateQueries({ queryKey: overviewKeys.all });
@ -398,6 +423,7 @@ export function usePricingPage(): PricingPageModel {
confirmation, confirmation,
closeConfirmation: () => { closeConfirmation: () => {
onSavedRef.current = null; onSavedRef.current = null;
checkedArgs.current = null;
setConfirmation(null); setConfirmation(null);
setPhase('idle'); setPhase('idle');
}, },

View File

@ -25,6 +25,7 @@ export {
displaySocialUrl, displaySocialUrl,
fromSocialUrl, fromSocialUrl,
toSocialHandle, toSocialHandle,
toSocialLink,
toSocialUrl, toSocialUrl,
toTypedHandle, toTypedHandle,
} from './social-links'; } 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 * A stored link back into a row. The platform is the one its host belongs to; the label only picks
* links fall back to their host, and anything else is a website. A platform link whose path is no * 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: * 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. * 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, url: string,
): { platform: SocialPlatform; handle: string } { ): { platform: SocialPlatform; handle: string } {
const address = parseAddress(url); const address = parseAddress(url);
const byLabel = isHandlePlatform(label) ? label : null; const servesHost = (platform: HandlePlatform) =>
const byHost = address address !== null &&
? (Object.keys(SOCIAL_HANDLE_ADDRESSES) as HandlePlatform[]).find( (SOCIAL_HANDLE_ADDRESSES[platform].hosts as readonly string[]).includes(
(platform) => address.host,
( );
SOCIAL_HANDLE_ADDRESSES[platform].hosts as readonly string[] const byHost = (
).includes(address.host), Object.keys(SOCIAL_HANDLE_ADDRESSES) as HandlePlatform[]
) ).find(servesHost);
: undefined; const platform =
const platform = byLabel ?? byHost; isHandlePlatform(label) && servesHost(label) ? label : byHost;
if (platform && address) { if (platform && address) {
const handle = handleFromPath(platform, address.path).toLowerCase(); const handle = handleFromPath(platform, address.path).toLowerCase();
if (SOCIAL_HANDLE_PATTERN.test(handle)) return { platform, handle }; 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`. */ /** The address as the profile shows it, without the scheme: `t.me/ali_gold`. */
export function displaySocialUrl(url: string): string { export function displaySocialUrl(url: string): string {
return url.replace(/^https?:\/\//i, '').replace(/\/$/, ''); return url.replace(/^https?:\/\//i, '').replace(/\/$/, '');

View File

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