From aec09a0ecd77f888c4a5cede9330d987841aa7c8 Mon Sep 17 00:00:00 2001 From: Amiram_se Date: Sat, 10 Oct 2026 18:28:58 +0400 Subject: [PATCH] refactor: code review --- apps/bear/next.config.ts | 24 ++++- .../app/(flow)/checkout/[username]/page.tsx | 19 +++- .../app/(main)/channels/[username]/page.tsx | 19 +++- apps/bear/src/constants/api.ts | 6 ++ apps/bear/src/constants/index.ts | 7 +- apps/bull/next.config.ts | 24 ++++- .../app/(flow)/checkout/[username]/page.tsx | 19 +++- .../app/(main)/channels/[username]/page.tsx | 19 +++- apps/bull/src/constants/api.ts | 6 ++ apps/bull/src/constants/index.ts | 7 +- .../src/atoms/count-badge/CountBadge.tsx | 11 ++- packages/island/src/atoms/dialog/Dialog.tsx | 86 +++++++++++++++--- packages/island/src/atoms/switch/Switch.tsx | 18 ++-- packages/island/src/atoms/switch/variants.ts | 2 +- .../molecules/avatar-field/AvatarField.tsx | 17 +++- .../src/molecules/file-field/FileField.tsx | 6 +- .../island/src/molecules/info-tip/InfoTip.tsx | 18 ++-- .../src/molecules/media-strip/MediaStrip.tsx | 32 ++++++- .../sheet/components/SheetPopover.tsx | 34 ++++++- .../src/molecules/sheet/hooks/use-dismiss.ts | 9 +- .../post-card/components/PostSharePopover.tsx | 6 +- .../prediction-card/components/LevelGlyph.tsx | 32 +++---- .../components/PredictionRange.tsx | 17 ++-- .../src/organisms/prediction-card/variants.ts | 35 ++++---- packages/libs/src/http/http-client.ts | 33 +++++-- packages/libs/src/http/http-error.ts | 16 ++++ packages/libs/src/http/refresh.ts | 44 +++++++--- packages/libs/src/http/types.ts | 2 +- packages/libs/src/pwa/service-worker.ts | 47 ++++++---- .../market/src/app/app-shell/constants.ts | 3 + .../src/app/app-shell/hooks/use-session.ts | 39 ++++++-- .../market/src/app/navigation/back-target.ts | 20 ++++- .../src/app/navigation/hooks/use-back.ts | 17 +++- platforms/market/src/app/navigation/index.ts | 1 + .../market/src/app/navigation/navigation.ts | 18 ++++ .../checkout-panel/CheckoutPanel.tsx | 6 +- .../checkout-panel/CheckoutSkeleton.tsx | 6 +- .../components/CheckoutHalts.tsx | 7 +- .../checkout-panel/components/NoCodeSheet.tsx | 10 +-- .../post-composer/components/ComposerBody.tsx | 5 +- .../post-composer/components/ComposerForm.tsx | 18 ++-- .../components/ChartField.tsx | 7 +- .../components/ComposerPage.tsx | 11 ++- .../components/ConfirmPublish.tsx | 5 +- .../components/PublishButton.tsx | 10 ++- .../payment-result/PaymentResultSkeleton.tsx | 6 +- .../NotificationSettings.tsx | 10 ++- .../components/SettingsSection.tsx | 9 +- .../organisms/notification-settings/types.ts | 2 + .../components/GuestActions.tsx | 3 +- .../components/InvestorActions.tsx | 3 + .../components/ChannelLinks.tsx | 10 +-- .../organisms/renewal-sheet/RenewalSheet.tsx | 23 ++++- .../renewal-sheet/components/RenewalForm.tsx | 13 ++- .../organisms/renewal-sheet/types.ts | 2 + .../notification-centre/NotificationPanel.tsx | 24 +++-- .../ClosePredictionSheet.tsx | 6 +- .../delete-post-confirm/DeletePostConfirm.tsx | 5 +- .../auth/actions/register-investor/actions.ts | 4 +- .../use-creator-identity-part.ts | 7 ++ .../use-investor-details-part.ts | 15 ++-- .../use-registration-autosave.ts | 28 +++--- .../use-registration-request.ts | 25 ++++++ .../features/auth/repositories/auth/auth.ts | 7 +- .../models/checkout/use-checkout-page.ts | 16 +++- .../payment-return/use-payment-return-page.ts | 32 +++++-- .../checkout/repositories/checkout/mappers.ts | 1 - .../checkout/repositories/checkout/types.ts | 5 +- .../finance/models/ledger/use-ledger-part.ts | 20 ++++- .../use-notification-settings-page.ts | 31 +++++-- .../models/composer/use-post-composer-page.ts | 88 +++++++++++++++---- .../models/owner-post/use-owner-post-part.ts | 30 ++++--- .../use-close-prediction-part.ts | 6 ++ .../use-prediction-composer-page.ts | 40 ++++++++- .../models/pricing/use-pricing-page.ts | 36 ++++++-- platforms/market/src/shared/utils/index.ts | 1 + .../market/src/shared/utils/social-links.ts | 37 +++++--- .../src/stores/auth-flow/auth-flow-store.ts | 10 ++- 78 files changed, 1037 insertions(+), 316 deletions(-) create mode 100644 platforms/market/src/features/auth/models/register-details/use-registration-request.ts diff --git a/apps/bear/next.config.ts b/apps/bear/next.config.ts index 72850ad..405d1b1 100644 --- a/apps/bear/next.config.ts +++ b/apps/bear/next.config.ts @@ -8,7 +8,11 @@ import { import type { NextConfig } from 'next'; import path from 'node:path'; -import { API_PROXY_PATH, API_PROXY_TIMEOUT_MS } from './src/constants'; +import { + API_PROXY_MAX_BODY, + API_PROXY_PATH, + API_PROXY_TIMEOUT_MS, +} from './src/constants'; import { apiInternalUrl } from './src/env/env.config'; // Fonts and the icon sprite keep fixed names; a changed font gets a new name, and the sprite a new @@ -17,12 +21,25 @@ const immutable = [ { key: 'Cache-Control', value: 'public, max-age=31536000, immutable' }, ]; +// No page may be framed by another site (checkout, finance and account pages act on a click), and +// the browser never guesses a type or sends full URLs to other sites. +const security = [ + { key: 'Content-Security-Policy', value: "frame-ancestors 'none'" }, + { key: 'X-Frame-Options', value: 'DENY' }, + { key: 'X-Content-Type-Options', value: 'nosniff' }, + { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' }, +]; + const nextConfig: NextConfig = { // Every visitor gets the metadata in , where Chrome looks for the manifest and Safari for // its home-screen tags; Next.js would otherwise stream it to the end of (0054). htmlLimitedBots: /.*/, - // The `/api` proxy's wait for the gateway (0018); uploads outlast Next.js's 30-second default. - experimental: { proxyTimeout: API_PROXY_TIMEOUT_MS }, + // The `/api` proxy's wait for the gateway (0018); uploads outlast Next.js's 30-second default + // and two ID images come close to its 10 MB body limit. + experimental: { + proxyTimeout: API_PROXY_TIMEOUT_MS, + proxyClientMaxBodySize: API_PROXY_MAX_BODY, + }, // Workspace packages export TypeScript source, so Next.js compiles them. transpilePackages: [ '@lumina/market', @@ -55,6 +72,7 @@ const nextConfig: NextConfig = { // island's plugins write theirs. Next runs from the app's folder, as every Nx target does. writeServiceWorker({ publicDir: path.join(process.cwd(), 'public') }); return [ + { source: '/:path*', headers: security }, { source: '/fonts/:path*', headers: immutable }, { source: '/icons/:path*', headers: immutable }, // Revalidated on every update check, so a new worker reaches visitors at their next diff --git a/apps/bear/src/app/(flow)/checkout/[username]/page.tsx b/apps/bear/src/app/(flow)/checkout/[username]/page.tsx index a099195..f2acc2f 100644 --- a/apps/bear/src/app/(flow)/checkout/[username]/page.tsx +++ b/apps/bear/src/app/(flow)/checkout/[username]/page.tsx @@ -1,4 +1,4 @@ -import { ROUTES } from '@lumina/market/app/navigation'; +import { ROUTES, withSearchParams } from '@lumina/market/app/navigation'; import { getChannel, readOnServer } from '@lumina/market/server'; import { toChannelUsername } from '@lumina/market/shared/utils'; import type { Metadata } from 'next'; @@ -7,7 +7,10 @@ import { notFound, permanentRedirect, redirect } from 'next/navigation'; import { i18n } from '../../../../i18n'; import { CheckoutTemplate } from './templates/checkout-template'; -type CheckoutPageProps = { params: Promise<{ username: string }> }; +type CheckoutPageProps = { + params: Promise<{ username: string }>; + searchParams: Promise>; +}; export const metadata: Metadata = { title: i18n.t('payment:checkout.title'), @@ -20,11 +23,19 @@ export const metadata: Metadata = { * browser. Another spelling of the username redirects to the stored one; a suspended channel * sends the visitor to the channel, which says it is unavailable. */ -export default async function CheckoutPage({ params }: CheckoutPageProps) { +export default async function CheckoutPage({ + params, + searchParams, +}: CheckoutPageProps) { const segment = (await params).username; const username = toChannelUsername(segment); if (!username) notFound(); - if (username !== segment) permanentRedirect(ROUTES.checkout(username)); + // The invite link's `?code=` goes along (0059). + if (username !== segment) { + permanentRedirect( + withSearchParams(ROUTES.checkout(username), await searchParams), + ); + } const channel = await readOnServer(() => getChannel(username)); if (channel.status !== 'ok') notFound(); if (channel.data.suspended) redirect(ROUTES.channel(username)); diff --git a/apps/bear/src/app/(main)/channels/[username]/page.tsx b/apps/bear/src/app/(main)/channels/[username]/page.tsx index 87bf5d5..b418001 100644 --- a/apps/bear/src/app/(main)/channels/[username]/page.tsx +++ b/apps/bear/src/app/(main)/channels/[username]/page.tsx @@ -1,4 +1,4 @@ -import { ROUTES } from '@lumina/market/app/navigation'; +import { ROUTES, withSearchParams } from '@lumina/market/app/navigation'; import { channelMetadata, getChannel, @@ -13,7 +13,10 @@ import { displayUrl } from '../../../../configs'; import { i18n } from '../../../../i18n'; import { ChannelTemplate } from './templates/channel-template'; -type ChannelPageProps = { params: Promise<{ username: string }> }; +type ChannelPageProps = { + params: Promise<{ username: string }>; + searchParams: Promise>; +}; // 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 (0054), waits for that @@ -43,11 +46,19 @@ export async function generateMetadata({ * track record and the first posts; subscribe, follow and the locked posts' gates load in the * browser. Any other spelling of the username redirects to the one the API stores. */ -export default async function ChannelPage({ params }: ChannelPageProps) { +export default async function ChannelPage({ + params, + searchParams, +}: ChannelPageProps) { const segment = (await params).username; const username = toChannelUsername(segment); if (!username) notFound(); - if (username !== segment) permanentRedirect(ROUTES.channel(username)); + // An invite link's `?code=` goes along (0059). + if (username !== segment) { + permanentRedirect( + withSearchParams(ROUTES.channel(username), await searchParams), + ); + } const channel = await readOnServer(() => getChannel(username)); if (channel.status !== 'ok') notFound(); diff --git a/apps/bear/src/constants/api.ts b/apps/bear/src/constants/api.ts index 8f30a63..8ec7915 100644 --- a/apps/bear/src/constants/api.ts +++ b/apps/bear/src/constants/api.ts @@ -14,3 +14,9 @@ export const API_PROXY_PATH = '/api'; * sets no timeout for uploads. */ export const API_PROXY_TIMEOUT_MS = 120_000; + +/** + * The largest request body the `/api` proxy passes on (Next.js cuts at 10 MB by default). Creator + * registration and verification send two 5 MB ID images plus the form in one request. + */ +export const API_PROXY_MAX_BODY = '12mb'; diff --git a/apps/bear/src/constants/index.ts b/apps/bear/src/constants/index.ts index bbd4610..1f14e50 100644 --- a/apps/bear/src/constants/index.ts +++ b/apps/bear/src/constants/index.ts @@ -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'; diff --git a/apps/bull/next.config.ts b/apps/bull/next.config.ts index 72850ad..405d1b1 100644 --- a/apps/bull/next.config.ts +++ b/apps/bull/next.config.ts @@ -8,7 +8,11 @@ import { import type { NextConfig } from 'next'; import path from 'node:path'; -import { API_PROXY_PATH, API_PROXY_TIMEOUT_MS } from './src/constants'; +import { + API_PROXY_MAX_BODY, + API_PROXY_PATH, + API_PROXY_TIMEOUT_MS, +} from './src/constants'; import { apiInternalUrl } from './src/env/env.config'; // Fonts and the icon sprite keep fixed names; a changed font gets a new name, and the sprite a new @@ -17,12 +21,25 @@ const immutable = [ { key: 'Cache-Control', value: 'public, max-age=31536000, immutable' }, ]; +// No page may be framed by another site (checkout, finance and account pages act on a click), and +// the browser never guesses a type or sends full URLs to other sites. +const security = [ + { key: 'Content-Security-Policy', value: "frame-ancestors 'none'" }, + { key: 'X-Frame-Options', value: 'DENY' }, + { key: 'X-Content-Type-Options', value: 'nosniff' }, + { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' }, +]; + const nextConfig: NextConfig = { // Every visitor gets the metadata in , where Chrome looks for the manifest and Safari for // its home-screen tags; Next.js would otherwise stream it to the end of (0054). htmlLimitedBots: /.*/, - // The `/api` proxy's wait for the gateway (0018); uploads outlast Next.js's 30-second default. - experimental: { proxyTimeout: API_PROXY_TIMEOUT_MS }, + // The `/api` proxy's wait for the gateway (0018); uploads outlast Next.js's 30-second default + // and two ID images come close to its 10 MB body limit. + experimental: { + proxyTimeout: API_PROXY_TIMEOUT_MS, + proxyClientMaxBodySize: API_PROXY_MAX_BODY, + }, // Workspace packages export TypeScript source, so Next.js compiles them. transpilePackages: [ '@lumina/market', @@ -55,6 +72,7 @@ const nextConfig: NextConfig = { // island's plugins write theirs. Next runs from the app's folder, as every Nx target does. writeServiceWorker({ publicDir: path.join(process.cwd(), 'public') }); return [ + { source: '/:path*', headers: security }, { source: '/fonts/:path*', headers: immutable }, { source: '/icons/:path*', headers: immutable }, // Revalidated on every update check, so a new worker reaches visitors at their next diff --git a/apps/bull/src/app/(flow)/checkout/[username]/page.tsx b/apps/bull/src/app/(flow)/checkout/[username]/page.tsx index a099195..f2acc2f 100644 --- a/apps/bull/src/app/(flow)/checkout/[username]/page.tsx +++ b/apps/bull/src/app/(flow)/checkout/[username]/page.tsx @@ -1,4 +1,4 @@ -import { ROUTES } from '@lumina/market/app/navigation'; +import { ROUTES, withSearchParams } from '@lumina/market/app/navigation'; import { getChannel, readOnServer } from '@lumina/market/server'; import { toChannelUsername } from '@lumina/market/shared/utils'; import type { Metadata } from 'next'; @@ -7,7 +7,10 @@ import { notFound, permanentRedirect, redirect } from 'next/navigation'; import { i18n } from '../../../../i18n'; import { CheckoutTemplate } from './templates/checkout-template'; -type CheckoutPageProps = { params: Promise<{ username: string }> }; +type CheckoutPageProps = { + params: Promise<{ username: string }>; + searchParams: Promise>; +}; export const metadata: Metadata = { title: i18n.t('payment:checkout.title'), @@ -20,11 +23,19 @@ export const metadata: Metadata = { * browser. Another spelling of the username redirects to the stored one; a suspended channel * sends the visitor to the channel, which says it is unavailable. */ -export default async function CheckoutPage({ params }: CheckoutPageProps) { +export default async function CheckoutPage({ + params, + searchParams, +}: CheckoutPageProps) { const segment = (await params).username; const username = toChannelUsername(segment); if (!username) notFound(); - if (username !== segment) permanentRedirect(ROUTES.checkout(username)); + // The invite link's `?code=` goes along (0059). + if (username !== segment) { + permanentRedirect( + withSearchParams(ROUTES.checkout(username), await searchParams), + ); + } const channel = await readOnServer(() => getChannel(username)); if (channel.status !== 'ok') notFound(); if (channel.data.suspended) redirect(ROUTES.channel(username)); diff --git a/apps/bull/src/app/(main)/channels/[username]/page.tsx b/apps/bull/src/app/(main)/channels/[username]/page.tsx index 87bf5d5..b418001 100644 --- a/apps/bull/src/app/(main)/channels/[username]/page.tsx +++ b/apps/bull/src/app/(main)/channels/[username]/page.tsx @@ -1,4 +1,4 @@ -import { ROUTES } from '@lumina/market/app/navigation'; +import { ROUTES, withSearchParams } from '@lumina/market/app/navigation'; import { channelMetadata, getChannel, @@ -13,7 +13,10 @@ import { displayUrl } from '../../../../configs'; import { i18n } from '../../../../i18n'; import { ChannelTemplate } from './templates/channel-template'; -type ChannelPageProps = { params: Promise<{ username: string }> }; +type ChannelPageProps = { + params: Promise<{ username: string }>; + searchParams: Promise>; +}; // 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 (0054), waits for that @@ -43,11 +46,19 @@ export async function generateMetadata({ * track record and the first posts; subscribe, follow and the locked posts' gates load in the * browser. Any other spelling of the username redirects to the one the API stores. */ -export default async function ChannelPage({ params }: ChannelPageProps) { +export default async function ChannelPage({ + params, + searchParams, +}: ChannelPageProps) { const segment = (await params).username; const username = toChannelUsername(segment); if (!username) notFound(); - if (username !== segment) permanentRedirect(ROUTES.channel(username)); + // An invite link's `?code=` goes along (0059). + if (username !== segment) { + permanentRedirect( + withSearchParams(ROUTES.channel(username), await searchParams), + ); + } const channel = await readOnServer(() => getChannel(username)); if (channel.status !== 'ok') notFound(); diff --git a/apps/bull/src/constants/api.ts b/apps/bull/src/constants/api.ts index 8f30a63..8ec7915 100644 --- a/apps/bull/src/constants/api.ts +++ b/apps/bull/src/constants/api.ts @@ -14,3 +14,9 @@ export const API_PROXY_PATH = '/api'; * sets no timeout for uploads. */ export const API_PROXY_TIMEOUT_MS = 120_000; + +/** + * The largest request body the `/api` proxy passes on (Next.js cuts at 10 MB by default). Creator + * registration and verification send two 5 MB ID images plus the form in one request. + */ +export const API_PROXY_MAX_BODY = '12mb'; diff --git a/apps/bull/src/constants/index.ts b/apps/bull/src/constants/index.ts index bbd4610..1f14e50 100644 --- a/apps/bull/src/constants/index.ts +++ b/apps/bull/src/constants/index.ts @@ -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'; diff --git a/packages/island/src/atoms/count-badge/CountBadge.tsx b/packages/island/src/atoms/count-badge/CountBadge.tsx index 96750fc..b2ecf7d 100644 --- a/packages/island/src/atoms/count-badge/CountBadge.tsx +++ b/packages/island/src/atoms/count-badge/CountBadge.tsx @@ -1,6 +1,6 @@ import { number } from '@lumina/tools/format'; -import { Element } from '../../primitives/element'; +import { GridBox } from '../grid-box'; import { cn } from '../../tools/cn'; import type { CountBadgeProps } from './types'; @@ -18,16 +18,19 @@ export function CountBadge({ if (count <= 0) return null; return ( - {count > cap ? `${number(cap)}+` : number(count)} - + ); } diff --git a/packages/island/src/atoms/dialog/Dialog.tsx b/packages/island/src/atoms/dialog/Dialog.tsx index 656e472..c113454 100644 --- a/packages/island/src/atoms/dialog/Dialog.tsx +++ b/packages/island/src/atoms/dialog/Dialog.tsx @@ -14,6 +14,13 @@ import { } from './constants'; import type { DialogProps } from './types'; +/** The modal dialogs in the top layer now, other than `dialog`. */ +function otherModals(dialog: HTMLDialogElement): Element[] { + return Array.from(document.querySelectorAll('dialog[open]')).filter( + (other) => other !== dialog && other.matches(':modal'), + ); +} + function announce(type: string, dialog: HTMLDialogElement): void { document.dispatchEvent(new CustomEvent(type, { detail: dialog })); } @@ -76,12 +83,34 @@ export function Dialog({ if (open && !isPresent) setIsPresent(true); // Where the last press started, so a drag out of the panel (selecting text) never closes it. const pressedLayer = useRef(false); + // Whether this dialog announced itself open to the toasts and hasn't announced its close yet, so + // each open is matched by exactly one close, however the dialog leaves. + const announced = useRef(false); + // Whether it was shown and hasn't left yet, so `onExited` runs once however it leaves. + const shown = useRef(false); + // `open` as last rendered, for the browser's own close to check after the parent answered. + const openRef = useRef(open); + useEffect(() => { + openRef.current = open; + }); - const show = useEffectEvent((dialog: HTMLDialogElement) => - showDialog(dialog, raiseToasts), - ); + const show = (dialog: HTMLDialogElement) => { + showDialog(dialog, raiseToasts && !announced.current); + if (raiseToasts) announced.current = true; + shown.current = true; + }; + const showOnOpen = useEffectEvent(show); + // Stops a re-show still waiting after the browser closed the dialog (handleNativeClose). + const stopReshow = useRef<(() => void) | null>(null); + const cancelReshow = () => { + stopReshow.current?.(); + stopReshow.current = null; + }; + const cancelReshowOnClose = useEffectEvent(cancelReshow); const left = useEffectEvent((dialog: HTMLDialogElement) => { - if (raiseToasts) announce(DIALOG_CLOSE_EVENT, dialog); + if (announced.current) announce(DIALOG_CLOSE_EVENT, dialog); + announced.current = false; + shown.current = false; onExited?.(); }); @@ -91,10 +120,17 @@ export function Dialog({ if (open) { // Reopened mid-close: the exit transitions run back from where they are. dialog.removeAttribute('data-closing'); - if (!dialog.open) show(dialog); + if (!dialog.open) showOnOpen(dialog); + return undefined; + } + cancelReshowOnClose(); + // The browser already closed it (see handleNativeClose) and the parent agreed: nothing to + // animate, only the close to announce. + if (!dialog.open) { + if (shown.current) left(dialog); + setIsPresent(false); return undefined; } - if (!dialog.open) return undefined; dialog.setAttribute('data-closing', ''); let cancelled = false; @@ -114,7 +150,8 @@ export function Dialog({ useEffect(() => { const dialog = ref.current; return () => { - if (dialog?.open) left(dialog); + cancelReshowOnClose(); + if (dialog && shown.current) left(dialog); }; }, []); @@ -128,12 +165,41 @@ export function Dialog({ // The browser can close the dialog without asking: Chrome makes a repeated Escape uncancelable // when the page has had no user activation (right after the ZarinPal return), and a - // `
` closes it too. Our own close() runs only once `open` is false. + // `` 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) => { const dialog = event.currentTarget; if (event.target !== dialog || !open || dialog.open) return; - if (dismissible && onClose) onClose(); - else showDialog(dialog, raiseToasts); + if (!dismissible || !onClose) { + show(dialog); + return; + } + // Dialogs already open beneath this one never count as covering it. + const beneath = new Set(otherModals(dialog)); + onClose(); + cancelReshow(); + const attempt = () => { + if (!openRef.current || !dialog.isConnected || dialog.open) { + cancelReshow(); + return; + } + // Covered by a dialog the close opened: wait for it to close. + if (otherModals(dialog).some((other) => !beneath.has(other))) return; + cancelReshow(); + show(dialog); + }; + // After the parent's answer has rendered, and again after each dialog's close. + const timers = new Set>(); + 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 diff --git a/packages/island/src/atoms/switch/Switch.tsx b/packages/island/src/atoms/switch/Switch.tsx index c2d5596..1f755a8 100644 --- a/packages/island/src/atoms/switch/Switch.tsx +++ b/packages/island/src/atoms/switch/Switch.tsx @@ -30,10 +30,14 @@ export function Switch({ const hasText = children != null || description != null; return ( - )} - - - + + ); } diff --git a/packages/island/src/atoms/switch/variants.ts b/packages/island/src/atoms/switch/variants.ts index 6fd761e..f8830eb 100644 --- a/packages/island/src/atoms/switch/variants.ts +++ b/packages/island/src/atoms/switch/variants.ts @@ -2,7 +2,7 @@ import { cva } from 'class-variance-authority'; /** The 44×24 track; the knob slides to the end when on, mirrored in RTL. */ export const switchTrackVariants = cva( - 'relative inline-flex h-6 w-11 flex-none items-center rounded-full border-[1.5px] p-0.5 transition-colors duration-120 ease-standard', + 'relative h-6 w-11 flex-none rounded-full border-[1.5px] p-0.5 transition-colors duration-120 ease-standard', { variants: { checked: { diff --git a/packages/island/src/molecules/avatar-field/AvatarField.tsx b/packages/island/src/molecules/avatar-field/AvatarField.tsx index 218802f..0011f72 100644 --- a/packages/island/src/molecules/avatar-field/AvatarField.tsx +++ b/packages/island/src/molecules/avatar-field/AvatarField.tsx @@ -35,6 +35,12 @@ export function AvatarField({ className, }: AvatarFieldProps) { const inputRef = useRef(null); + // Remove and retry leave with the state they change: focus stays on the picker beside them. + const pickRef = useRef(null); + const thenFocusPick = (action: () => void) => () => { + action(); + pickRef.current?.focus(); + }; const messageId = useId(); const isUploading = status === 'uploading'; const isFailed = status === 'failed'; @@ -63,6 +69,7 @@ export function AvatarField({ /> ) : ( - + {labels.remove} ))} @@ -109,7 +120,7 @@ export function AvatarField({ standalone iconStart="refresh" disabled={disabled} - onClick={onRetry} + onClick={thenFocusPick(onRetry)} > {labels.retry} diff --git a/packages/island/src/molecules/file-field/FileField.tsx b/packages/island/src/molecules/file-field/FileField.tsx index 9258d75..2a4ef3d 100644 --- a/packages/island/src/molecules/file-field/FileField.tsx +++ b/packages/island/src/molecules/file-field/FileField.tsx @@ -151,7 +151,11 @@ export function FileField({ icon="trash" label={labels.remove} disabled={disabled} - onClick={() => onChange(null)} + onClick={() => { + onChange(null); + // The button leaves with the file: focus goes to the picker in its place. + inputRef.current?.focus(); + }} className="flex-none" /> )} diff --git a/packages/island/src/molecules/info-tip/InfoTip.tsx b/packages/island/src/molecules/info-tip/InfoTip.tsx index a64035c..acdc460 100644 --- a/packages/island/src/molecules/info-tip/InfoTip.tsx +++ b/packages/island/src/molecules/info-tip/InfoTip.tsx @@ -2,9 +2,9 @@ import { useEffect, useId, useRef, useState } from 'react'; +import { FlexBox } from '../../atoms/flex-box'; import { Icon } from '../../atoms/icon'; import { Typography } from '../../atoms/typography'; -import { Element } from '../../primitives/element'; import { cn } from '../../tools/cn'; import type { InfoTipProps } from './types'; import { infoTipVariants } from './variants'; @@ -44,23 +44,27 @@ export function InfoTip({ }, [isOpen]); return ( - setIsOpen(false)} > - 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" > - + {children} - + ); } diff --git a/packages/island/src/molecules/media-strip/MediaStrip.tsx b/packages/island/src/molecules/media-strip/MediaStrip.tsx index dc39833..b891ef8 100644 --- a/packages/island/src/molecules/media-strip/MediaStrip.tsx +++ b/packages/island/src/molecules/media-strip/MediaStrip.tsx @@ -1,3 +1,5 @@ +import { useRef } from 'react'; + import { FlexBox } from '../../atoms/flex-box'; import { GridBox } from '../../atoms/grid-box'; import { Icon } from '../../atoms/icon'; @@ -14,7 +16,8 @@ const IMAGE_CLASS = 'block size-full object-cover'; * A form's picked images (DS MediaStrip), such as the post composer's: thumbnails in the order * they were added, each with a 28px ✕; one uploading sits under a light veil with a spinner, a * failed one has a danger frame and, with `onRetry`, sends again on tap. A dashed «افزودن» tile - * ends the strip until `max`. It wraps; 76px thumbnails, 96px at `lg`. + * ends the strip until `max`. It wraps; 76px thumbnails, 96px at `lg`. A ✕ or retry that leaves + * with its tile or state hands focus on: the ✕ now in that place, else «افزودن». */ export function MediaStrip({ items, @@ -28,6 +31,18 @@ export function MediaStrip({ disabled = false, className, }: MediaStripProps) { + const listRef = useRef(null); + // After the parent's update has rendered. + const focusRemoveAt = (index: number) => + setTimeout(() => { + const list = listRef.current; + if (!list) return; + const removes = list.querySelectorAll('[data-remove]'); + const target = + removes[Math.min(index, removes.length - 1)] ?? + list.querySelector('[data-add]'); + target?.focus(); + }); const canAdd = onAdd != null && addLabel != null && !disabled && items.length < max; if (items.length === 0 && !canAdd) return null; @@ -44,12 +59,13 @@ export function MediaStrip({ return ( - {items.map((item) => { + {items.map((item, index) => { const status = item.status ?? 'ready'; const retry = status === 'error' && onRetry && item.retryLabel ? onRetry : null; @@ -64,7 +80,10 @@ export function MediaStrip({ retry(item.key)} + onClick={() => { + retry(item.key); + focusRemoveAt(index); + }} disabled={disabled} aria-label={item.retryLabel} className="block size-full cursor-pointer focus-visible:focus-ring disabled:cursor-not-allowed" @@ -86,9 +105,13 @@ export function MediaStrip({ onRemove(item.key)} + onClick={() => { + onRemove(item.key); + focusRemoveAt(index); + }} disabled={disabled} aria-label={item.removeLabel} + data-remove justifyItems="justify-items-center" alignItems="items-center" className="absolute end-1 top-1 z-1 size-7 cursor-pointer rounded-full bg-scrim-chip text-text-inverse focus-visible:focus-ring disabled:frozen" @@ -104,6 +127,7 @@ export function MediaStrip({ tag="button" type="button" onClick={onAdd} + data-add justifyItems="justify-items-center" alignContent="content-center" className={cn(mediaStripAddVariants({ size }), 'gap-0.5')} diff --git a/packages/island/src/molecules/sheet/components/SheetPopover.tsx b/packages/island/src/molecules/sheet/components/SheetPopover.tsx index 898f68b..2da7107 100644 --- a/packages/island/src/molecules/sheet/components/SheetPopover.tsx +++ b/packages/island/src/molecules/sheet/components/SheetPopover.tsx @@ -1,6 +1,6 @@ 'use client'; -import { useId, useRef } from 'react'; +import { useEffect, useId, useRef } from 'react'; import { FlexBox } from '../../../atoms/flex-box'; import { Typography } from '../../../atoms/typography'; @@ -16,7 +16,8 @@ import { SheetHead } from './SheetHead'; * A desktop popover, 320px (360px `wide`, the DS SharePopover), anchored by its caller in a positioned container next to the * trigger. It hangs under the trigger at the inline end, and flips above or to the inline start * when it would run off the screen. No scrim and not modal: Escape, the ✕ or a press outside - * closes it. + * closes it. Escape and the ✕ return focus to the trigger (`[aria-haspopup]` beside it); a press + * outside leaves focus where the press put it. */ export function SheetPopover({ open, @@ -31,7 +32,32 @@ export function SheetPopover({ }: SheetPopoverProps) { const ref = useRef(null); const titleId = useId(); - useDismiss(ref, open, onClose); + // Where focus was as it opened: the trigger when the press focused it. + const opener = useRef(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( + '[aria-haspopup]', + ) ?? [], + ).find((element) => !popover?.contains(element)); + const previous = opener.current; + const trigger = + beside ?? + (previous?.isConnected && previous !== document.body + ? previous + : undefined); + onClose?.(); + trigger?.focus(); + }; + const close = onClose && closeToTrigger; + useDismiss(ref, open, onClose, close); useFlip(ref, open); if (!open) return null; @@ -50,7 +76,7 @@ export function SheetPopover({ diff --git a/packages/island/src/molecules/sheet/hooks/use-dismiss.ts b/packages/island/src/molecules/sheet/hooks/use-dismiss.ts index 193314e..ddf97e7 100644 --- a/packages/island/src/molecules/sheet/hooks/use-dismiss.ts +++ b/packages/island/src/molecules/sheet/hooks/use-dismiss.ts @@ -4,20 +4,23 @@ import { useEffect, useEffectEvent } from 'react'; import type { RefObject } from 'react'; /** - * Closes a non-modal layer on Escape or a press outside it. "Outside" also excludes the layer's - * positioned parent, which holds its trigger, so a press on the trigger doesn't close and reopen. + * Closes a non-modal layer on Escape (`onEscape`, by default `onDismiss`) or a press outside it. + * "Outside" also excludes the layer's positioned parent, which holds its trigger, so a press on + * the trigger doesn't close and reopen. */ export function useDismiss( ref: RefObject, isOpen: boolean, onDismiss?: () => void, + onEscape: (() => void) | undefined = onDismiss, ): void { const dismiss = useEffectEvent(() => onDismiss?.()); + const escape = useEffectEvent(() => onEscape?.()); useEffect(() => { if (!isOpen) return undefined; const handleKeyDown = (event: KeyboardEvent) => { - if (event.key === 'Escape') dismiss(); + if (event.key === 'Escape') escape(); }; const handlePointerDown = (event: PointerEvent) => { const area = ref.current?.parentElement ?? ref.current; diff --git a/packages/island/src/organisms/post-card/components/PostSharePopover.tsx b/packages/island/src/organisms/post-card/components/PostSharePopover.tsx index 6238c67..5fbe267 100644 --- a/packages/island/src/organisms/post-card/components/PostSharePopover.tsx +++ b/packages/island/src/organisms/post-card/components/PostSharePopover.tsx @@ -1,6 +1,6 @@ 'use client'; -import { useState } from 'react'; +import { useRef, useState } from 'react'; import { Button } from '../../../atoms/button'; import { FlexBox } from '../../../atoms/flex-box'; @@ -23,10 +23,12 @@ export function PostSharePopover({ url, }: PostSharePopoverProps) { const [isOpen, setIsOpen] = useState(false); + const triggerRef = useRef(null); return (