refactor(market): repositories import repository subpaths, one leave guard and dialog route hook, shared composer locked state, detail values through Typography, publish menu close, referral card refresh on capacity decisions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Amiram_se 2026-10-09 19:34:24 +04:00
parent 907bc23e25
commit 7c0b86bfb8
73 changed files with 319 additions and 639 deletions

View File

@ -1,10 +1,11 @@
'use client'; 'use client';
import { buttonVariants } from '@lumina/island/atoms/button'; import { Button } from '@lumina/island/atoms/button';
import { FlexBox } from '@lumina/island/atoms/flex-box'; import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Typography } from '@lumina/island/atoms/typography'; import { Typography } from '@lumina/island/atoms/typography';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { ROUTES } from '../../navigation/navigation';
import { ErrorFallback } from '../error-fallback'; import { ErrorFallback } from '../error-fallback';
import type { AppCrashProps } from './types'; import type { AppCrashProps } from './types';
@ -36,18 +37,9 @@ export function AppCrash({ error }: AppCrashProps) {
size="app" size="app"
onRetry={() => window.location.reload()} onRetry={() => window.location.reload()}
> >
<FlexBox <Button variant="ghost" href={ROUTES.landing} reloadDocument>
tag="a" {tErrors('empty.home')}
href="/" </Button>
display="inline-flex"
alignItems="items-center"
justifyContent="justify-center"
className={buttonVariants({ variant: 'ghost' })}
>
<Typography tag="span" variant="inherit" color="inherit">
{tErrors('empty.home')}
</Typography>
</FlexBox>
</ErrorFallback> </ErrorFallback>
</FlexBox> </FlexBox>
); );

View File

@ -92,7 +92,7 @@ export function AccountMenu({ account }: AccountMenuProps) {
<Typography <Typography
tag="span" tag="span"
variant="inherit" variant="inherit"
className="truncate text-[0.9375rem] leading-5.5 font-semibold" className="truncate text-body-compact leading-5.5 font-semibold"
> >
{name} {name}
</Typography> </Typography>

View File

@ -30,7 +30,7 @@ export function DeskBack({ label, ...options }: DeskBackProps) {
tag="span" tag="span"
variant="inherit" variant="inherit"
color="inherit" color="inherit"
className="text-[0.9375rem] leading-6 font-semibold" className="text-body-compact leading-6 font-semibold"
> >
{label ?? t('nav.back')} {label ?? t('nav.back')}
</Typography> </Typography>

View File

@ -14,7 +14,7 @@ export function HeaderNavLink({ href, label, isActive }: HeaderNavLinkProps) {
color={isActive ? 'brand' : 'secondary'} color={isActive ? 'brand' : 'secondary'}
aria-current={isActive ? 'page' : undefined} aria-current={isActive ? 'page' : undefined}
className={cn( className={cn(
'inline-block rounded-full px-4 py-2 text-[0.9375rem] leading-6 font-semibold whitespace-nowrap no-underline transition-colors duration-120 ease-standard hover:text-text-primary focus-visible:focus-ring', 'inline-block rounded-full px-4 py-2 text-body-compact leading-6 font-semibold whitespace-nowrap no-underline transition-colors duration-120 ease-standard hover:text-text-primary focus-visible:focus-ring',
isActive && 'bg-action-primary-subtle', isActive && 'bg-action-primary-subtle',
)} )}
> >

View File

@ -24,7 +24,7 @@ import type { MobileTopBarProps } from './types';
/** The guest's «ورود/ثبت‌نام»: an indigo text link, 15/600, 44px tall. */ /** The guest's «ورود/ثبت‌نام»: an indigo text link, 15/600, 44px tall. */
const LOGIN_LINK_CLASS = const LOGIN_LINK_CLASS =
'rounded-full px-2 text-[0.9375rem] leading-11 font-semibold whitespace-nowrap no-underline focus-visible:focus-ring'; 'rounded-full px-2 text-body-compact leading-11 font-semibold whitespace-nowrap no-underline focus-visible:focus-ring';
/** /**
* The mobile top bar of a page pushed from a tab: back, the page's name (18/30) and support. A * The mobile top bar of a page pushed from a tab: back, the page's name (18/30) and support. A

View File

@ -20,7 +20,7 @@ const isBlocked = (standing: string): standing is BlockedStanding =>
* «انتشار» (C4 ۱.۱, ۱.۲, ۷.۱): a verified creator gets the menu, «پست جدید» or «پیش‌بینی جدید». A * «انتشار» (C4 ۱.۱, ۱.۲, ۷.۱): a verified creator gets the menu, «پست جدید» or «پیش‌بینی جدید». A
* creator who can't publish sees it frozen, and a press explains why instead of a tooltip. On * creator who can't publish sees it frozen, and a press explains why instead of a tooltip. On
* mobile the open menu sits centred over the nav, on a light scrim that dims the page down to the * mobile the open menu sits centred over the nav, on a light scrim that dims the page down to the
* nav; a press on the scrim closes it. * nav; a press on the scrim closes it, and the FAB turns into an icon-only ✕ «بستن» (J08-1b).
*/ */
export function PublishMenu({ placement }: PublishMenuProps) { export function PublishMenu({ placement }: PublishMenuProps) {
const { t } = useTranslation(); const { t } = useTranslation();
@ -29,6 +29,8 @@ export function PublishMenu({ placement }: PublishMenuProps) {
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const [isExplaining, setIsExplaining] = useState(false); const [isExplaining, setIsExplaining] = useState(false);
const blocked = isBlocked(standing) ? standing : null; const blocked = isBlocked(standing) ? standing : null;
// J08-1b-M: the open FAB is just the ✕, named «بستن»; desktop keeps «انتشار» beside it.
const isClosingFab = placement === 'nav' && isOpen;
return ( return (
<> <>
@ -43,6 +45,7 @@ export function PublishMenu({ placement }: PublishMenuProps) {
<Button <Button
variant="primary" variant="primary"
icon={isOpen ? 'close' : 'plus'} icon={isOpen ? 'close' : 'plus'}
label={isClosingFab ? t('publish.close') : undefined}
aria-haspopup={blocked ? 'dialog' : 'menu'} aria-haspopup={blocked ? 'dialog' : 'menu'}
aria-expanded={blocked ? isExplaining : isOpen} aria-expanded={blocked ? isExplaining : isOpen}
frozen={blocked !== null} frozen={blocked !== null}
@ -52,7 +55,7 @@ export function PublishMenu({ placement }: PublishMenuProps) {
blocked ? setIsExplaining(true) : setIsOpen((open) => !open) blocked ? setIsExplaining(true) : setIsOpen((open) => !open)
} }
> >
{t('publish.menu')} {isClosingFab ? undefined : t('publish.menu')}
</Button> </Button>
<ActionMenu <ActionMenu
open={isOpen} open={isOpen}

View File

@ -1,22 +1,19 @@
'use client'; 'use client';
import { Button } from '@lumina/island/atoms/button'; import { Button } from '@lumina/island/atoms/button';
import { GridBox } from '@lumina/island/atoms/grid-box';
import { Icon } from '@lumina/island/atoms/icon';
import { Typography } from '@lumina/island/atoms/typography'; import { Typography } from '@lumina/island/atoms/typography';
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 { cn } from '@lumina/island/tools/cn';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { SupportEntry } from '../../../../screens/organisms/support-entry'; import { SupportEntry } from '../../../../screens/organisms/support-entry';
import { ROUTES } from '../../../navigation'; import { ROUTES } from '../../../navigation';
import { BLOCKED_ART } from '../constants';
import type { BlockedPublishDialogProps } from '../types'; import type { BlockedPublishDialogProps } from '../types';
/** /**
* Why «انتشار» can't publish (C4 ۲.۱–۲.۳), with the one way forward: the identity review's status, * Why «انتشار» can't publish (C4 ۲.۱–۲.۳), with the one way forward: the identity review's status,
* resubmitting it, or support for a suspended account. «بستن» under it; no ✕. * resubmitting it, or support for a suspended account. «بستن» under it; no ✕ and no icon tile
* (J08-1f): the title and the reason only.
*/ */
export function BlockedPublishDialog({ export function BlockedPublishDialog({
standing, standing,
@ -26,16 +23,6 @@ export function BlockedPublishDialog({
}: BlockedPublishDialogProps) { }: BlockedPublishDialogProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const size = layout === 'mobile' ? 'lg' : undefined; const size = layout === 'mobile' ? 'lg' : undefined;
const art = BLOCKED_ART[standing];
const icon = (
<GridBox
justifyItems="justify-items-center"
alignItems="items-center"
className={cn('size-13 rounded-lg', art.className)}
>
<Icon name={art.icon} size={24} />
</GridBox>
);
const next = const next =
standing === 'suspended' ? ( standing === 'suspended' ? (
<SupportEntry <SupportEntry
@ -74,7 +61,6 @@ export function BlockedPublishDialog({
<Sheet <Sheet
open={open} open={open}
title={t(`publish.${standing}.title`)} title={t(`publish.${standing}.title`)}
icon={icon}
onClose={onClose} onClose={onClose}
footer={buttons} footer={buttons}
> >
@ -84,7 +70,6 @@ export function BlockedPublishDialog({
<Modal <Modal
open={open} open={open}
title={t(`publish.${standing}.title`)} title={t(`publish.${standing}.title`)}
icon={icon}
onClose={onClose} onClose={onClose}
actions={buttons} actions={buttons}
> >

View File

@ -1,16 +0,0 @@
import type { IconName } from '@lumina/island/atoms/icon';
import type { BlockedStanding } from './types';
/** Each blocked standing's art: its icon and its tile's tone. */
export const BLOCKED_ART: Record<
BlockedStanding,
{ icon: IconName; className: string }
> = {
pending: {
icon: 'clock',
className: 'bg-surface-sunken text-text-secondary',
},
rejected: { icon: 'alert', className: 'bg-danger-subtle text-danger-text' },
suspended: { icon: 'lock', className: 'bg-surface-sunken text-text-primary' },
};

View File

@ -1,14 +1,16 @@
'use client';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { useState } from 'react'; import { useState } from 'react';
import type { DialogRoute } from '../types'; import type { DialogRoute } from '../types';
/** /**
* The dialog that intercepts /compose/post plays its exit before its route changes. Closed, it goes * A dialog that intercepts a route (/compose/post, /compose/prediction) plays its exit before its
* back to the page under it, or to `fallback` when there is no history to go back to. Finished, it * route changes. Closed, it goes back to the page under it, or to `fallback` when there is no
* goes to `href` so back never reopens an empty composer, the `@modal` slot empties there, and * history to go back to. Finished, it goes to `href` so back never reopens an empty composer, the
* `href` is read again from the server: back when `href` is the page under it, else in place of * `@modal` slot empties there, and `href` is read again from the server: back when `href` is the
* its own history entry. * page under it, else in place of its own history entry.
*/ */
export function useDialogRoute(fallback: string): DialogRoute { export function useDialogRoute(fallback: string): DialogRoute {
const router = useRouter(); const router = useRouter();
@ -21,7 +23,7 @@ export function useDialogRoute(fallback: string): DialogRoute {
setExit('done'); setExit('done');
if (isUnder) { if (isUnder) {
// Replacing would leave that page in history twice, and the next back would seem to do // Replacing would leave that page in history twice, and the next back would seem to do
// nothing. The refresh waits for the back to land, or it would read /compose/post again. // nothing. The refresh waits for the back to land, or it would read the composer again.
window.addEventListener('popstate', () => router.refresh(), { window.addEventListener('popstate', () => router.refresh(), {
once: true, once: true,
}); });

View File

@ -1,3 +1,5 @@
'use client';
import { useEffect } from 'react'; import { useEffect } from 'react';
/** A plain click on a link to another page of this site, which the app would navigate to itself. */ /** A plain click on a link to another page of this site, which the app would navigate to itself. */
@ -24,16 +26,17 @@ function leavingHref(event: MouseEvent): string | null {
} }
/** /**
* While a block holds unsaved changes, leaving asks first: a link inside the app (the header, the * While a form holds unsaved changes (`active`), leaving asks first. A link inside the app (the
* account menu) opens the page's own dialog with where it leads (J03-1g), and closing or reloading * header, the account menu, the brand) is held and handed to `onLeaveRequest` with where it leads,
* the tab gets the browser's prompt. Back is asked about by the bar's `onBack`. * which asks and navigates there itself; closing or reloading the tab gets the browser's prompt.
* Back is the caller's: the bar's `onBack` asks before it leaves. Keep `onLeaveRequest` stable.
*/ */
export function useLeaveGuard( export function useLeaveGuard(
isDirty: boolean, active: boolean,
onLeaveRequest: (href: string) => void, onLeaveRequest: (href: string) => void,
): void { ): void {
useEffect(() => { useEffect(() => {
if (!isDirty) return undefined; if (!active) return undefined;
const askOnUnload = (event: BeforeUnloadEvent) => event.preventDefault(); const askOnUnload = (event: BeforeUnloadEvent) => event.preventDefault();
// Capture, so it runs before the app's own link handling and can stop it. // Capture, so it runs before the app's own link handling and can stop it.
const askOnLink = (event: MouseEvent) => { const askOnLink = (event: MouseEvent) => {
@ -49,5 +52,5 @@ export function useLeaveGuard(
window.removeEventListener('beforeunload', askOnUnload); window.removeEventListener('beforeunload', askOnUnload);
document.removeEventListener('click', askOnLink, true); document.removeEventListener('click', askOnLink, true);
}; };
}, [isDirty, onLeaveRequest]); }, [active, onLeaveRequest]);
} }

View File

@ -16,8 +16,10 @@ export {
} from './constants'; } from './constants';
export { useAuthRoutes } from './hooks/use-auth-routes'; export { useAuthRoutes } from './hooks/use-auth-routes';
export { useBackTarget } from './hooks/use-back-target'; export { useBackTarget } from './hooks/use-back-target';
export { useDialogRoute } from './hooks/use-dialog-route';
export { useHomeHref } from './hooks/use-home-href'; export { useHomeHref } from './hooks/use-home-href';
export { useIsStandalone } from './hooks/use-is-standalone'; export { useIsStandalone } from './hooks/use-is-standalone';
export { useLeaveGuard } from './hooks/use-leave-guard';
export { export {
homeRoute, homeRoute,
loginRoute, loginRoute,
@ -27,4 +29,4 @@ export {
withReturnPath, withReturnPath,
} from './navigation'; } from './navigation';
export { safeReturnPath } from './return-path'; export { safeReturnPath } from './return-path';
export type { AuthRoutes, BackOptions } from './types'; export type { AuthRoutes, BackOptions, DialogRoute } from './types';

View File

@ -46,3 +46,18 @@ export type BackOptions = {
export type BackAction = export type BackAction =
| { href: string; onClick?: never } | { href: string; onClick?: never }
| { href?: never; onClick: () => void }; | { href?: never; onClick: () => void };
/** How a dialog that intercepts a route (bear's `@modal`) leaves it (0023, C4 ۷.۳). */
export type DialogRoute = {
/** Until it starts closing. */
open: boolean;
/** Closes it, then goes back to the page under it. */
close: () => void;
/**
* Closes it and goes to `href`, read again: back, when `href` is the page under it (`isUnder`),
* else in place of the dialog's history entry.
*/
finish: (href: string, options?: { isUnder?: boolean }) => void;
/** The Modal's `onExited`. */
onExited: () => void;
};

View File

@ -1,14 +1,10 @@
'use client'; 'use client';
import { Button } from '@lumina/island/atoms/button'; import { Button } from '@lumina/island/atoms/button';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Icon } from '@lumina/island/atoms/icon';
import { Typography } from '@lumina/island/atoms/typography';
import { FileField } from '@lumina/island/molecules/file-field'; import { FileField } from '@lumina/island/molecules/file-field';
import { FormSection } from '@lumina/island/molecules/form-section';
import { TextInput } from '@lumina/island/molecules/text-input'; import { TextInput } from '@lumina/island/molecules/text-input';
import { number } from '@lumina/tools/format'; import { number } from '@lumina/tools/format';
import { useId } from 'react';
import type { ReactNode } from 'react';
import { Controller } from 'react-hook-form'; import { Controller } from 'react-hook-form';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
@ -29,56 +25,6 @@ const ID_CARD_SIDES = [
const BYTES_PER_MB = 1024 * 1024; const BYTES_PER_MB = 1024 * 1024;
/**
* A labelled group with its privacy line: what investors see, and what only the review sees (its
* heading carries the lock).
*/
function Group({
title,
note,
titleIcon,
children,
}: {
title: string;
note: string;
titleIcon?: 'lock';
children: ReactNode;
}) {
const titleId = useId();
return (
<FlexBox
tag="section"
aria-labelledby={titleId}
direction="flex-col"
gap="gap-4"
>
<FlexBox direction="flex-col" className="gap-0.5">
<FlexBox
tag="h2"
alignItems="items-center"
className="gap-1.5"
id={titleId}
>
<Typography tag="span" variant="heading-sm">
{title}
</Typography>
{titleIcon && (
<Icon
name={titleIcon}
size={16}
className="flex-none text-text-secondary"
/>
)}
</FlexBox>
<Typography tag="span" variant="caption" color="secondary">
{note}
</Typography>
</FlexBox>
{children}
</FlexBox>
);
}
/** /**
* Step 4 for a creator: the public username, then the private identity (names, national code, * Step 4 for a creator: the public username, then the private identity (names, national code,
* both sides of the ID card) for the admin review. The images upload with a bar; repeat taps are * both sides of the ID card) for the admin review. The images upload with a bar; repeat taps are
@ -120,9 +66,10 @@ export function CreatorIdentityForm(props: DetailsFormProps) {
</> </>
} }
> >
<Group {/* What investors see, and what only the review sees (its heading carries the lock). */}
<FormSection
title={t('register.identity.public-title')} title={t('register.identity.public-title')}
note={t('register.identity.public-description')} hint={t('register.identity.public-description')}
> >
<UsernameField <UsernameField
control={form.control} control={form.control}
@ -131,10 +78,10 @@ export function CreatorIdentityForm(props: DetailsFormProps) {
note={t('register.identity.username-note')} note={t('register.identity.username-note')}
availability={username} availability={username}
/> />
</Group> </FormSection>
<Group <FormSection
title={t('register.identity.private-title')} title={t('register.identity.private-title')}
note={t('register.identity.private-description')} hint={t('register.identity.private-description')}
titleIcon="lock" titleIcon="lock"
> >
<NameFields control={form.control} isPaired={props.size === 'md'} /> <NameFields control={form.control} isPaired={props.size === 'md'} />
@ -191,7 +138,7 @@ export function CreatorIdentityForm(props: DetailsFormProps) {
)} )}
/> />
))} ))}
</Group> </FormSection>
</DetailsFrame> </DetailsFrame>
); );
} }

View File

@ -11,10 +11,10 @@ import {
MobileTopBar, MobileTopBar,
ROUTES, ROUTES,
useHomeHref, useHomeHref,
useLeaveGuard,
} from '../../../../../../navigation'; } from '../../../../../../navigation';
import { CreatorProfileEditSkeleton } from './CreatorProfileEditSkeleton'; import { CreatorProfileEditSkeleton } from './CreatorProfileEditSkeleton';
import { EditContent } from './components/EditContent'; import { EditContent } from './components/EditContent';
import { useLeaveGuard } from './hooks/use-leave-guard';
import type { CreatorProfileEditProps, LeaveTarget } from './types'; import type { CreatorProfileEditProps, LeaveTarget } from './types';
/** /**

View File

@ -80,6 +80,9 @@ export function ProfileFields({ page, photo, layout }: ProfileFieldsProps) {
error={translateMessage(t, photo.error)} error={translateMessage(t, photo.error)}
accept={AVATAR_IMAGE.types.join(',')} accept={AVATAR_IMAGE.types.join(',')}
disabled={photo.isRemoving} disabled={photo.isRemoving}
// J12-2: the DS lg 52px photo and a small ghost «حذف تصویر».
size="lg"
removeStyle="ghost"
onPick={photo.pick} onPick={photo.pick}
onRemove={photo.remove} onRemove={photo.remove}
labels={{ labels={{

View File

@ -3,15 +3,15 @@ import { Card } from '@lumina/island/molecules/card';
import { ResultPanel } from '@lumina/island/molecules/result-panel'; import { ResultPanel } from '@lumina/island/molecules/result-panel';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { MobileTopBar } from '../../../../../../../navigation/components/mobile-top-bar'; import { MobileTopBar } from '../../../../../navigation/components/mobile-top-bar';
import { LOCKED_PANEL } from '../constants'; import { LockedActions } from './components/LockedActions';
import type { ComposerLockedProps } from '../types'; import { LOCKED_PANEL } from './constants';
import { LockedActions } from './LockedActions'; import type { ComposerLockedProps } from './types';
/** /**
* The composer's address opened by a creator who may not publish (C4 ۲.۱–۲.۳, J08-1f…1j): what * A composer's address opened by a creator who may not publish (C4 ۲.۱–۲.۳, J08-1f…1j, J09-1e):
* «انتشار» would explain in its sheet, as the page, with the one way forward and «بستن». Mobile: * what «انتشار» would explain in its sheet, as the page, with the one way forward and «بستن».
* the pushed page's bar over the panel; desktop: the 640px card. * Mobile: the pushed page's bar over the panel; desktop: the 640px card.
*/ */
export function ComposerLocked({ export function ComposerLocked({
standing, standing,

View File

@ -2,13 +2,13 @@ import { Typography } from '@lumina/island/atoms/typography';
import { Modal } from '@lumina/island/molecules/modal'; import { Modal } from '@lumina/island/molecules/modal';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { ROUTES } from '../../../../../../../navigation/navigation'; import { useDialogRoute } from '../../../../../navigation/hooks/use-dialog-route';
import { useDialogRoute } from '../hooks/use-dialog-route'; import { ROUTES } from '../../../../../navigation/navigation';
import type { ComposerLockedDialogProps } from '../types'; import { LockedActions } from './components/LockedActions';
import { LockedActions } from './LockedActions'; import type { ComposerLockedDialogProps } from './types';
/** /**
* The composer dialog's route opened by a creator who may not publish (J08-1f-D): the 420px * A composer dialog's route opened by a creator who may not publish (J08-1f-D, J09-1e): the 420px
* question «انتشار» would have asked, title, reason and actions only, over the page. «بستن», * question «انتشار» would have asked, title, reason and actions only, over the page. «بستن»,
* Escape and the scrim go back to that page. * Escape and the scrim go back to that page.
*/ */

View File

@ -2,13 +2,14 @@ import { Button } from '@lumina/island/atoms/button';
import { FlexBox } from '@lumina/island/atoms/flex-box'; import { FlexBox } from '@lumina/island/atoms/flex-box';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { ROUTES } from '../../../../../../../navigation/navigation'; import { ROUTES } from '../../../../../../navigation/navigation';
import { SupportEntry } from '../../../../../../organisms/support-entry'; import { SupportEntry } from '../../../../../organisms/support-entry';
import type { LockedActionsProps } from '../types'; import type { LockedActionsProps } from '../types';
/** /**
* Why-not's actions (C4 ۲.۱–۲.۳): the identity review's status for a pending creator, its form to * Why-not's actions (C4 ۲.۱–۲.۳, J09-1e, as «انتشار» explains it): the identity review's status for
* correct and send again for a rejected one, support for a suspended one; «بستن» under it. * a pending creator, its form to correct and send again for a rejected one, support for a
* suspended one; «بستن» under it.
*/ */
export function LockedActions({ export function LockedActions({
standing, standing,

View File

@ -0,0 +1,14 @@
import type { IconName } from '@lumina/island/atoms/icon';
import type { ResultPanelTone } from '@lumina/island/molecules/result-panel';
import type { BlockedStanding } from '../../../../../../features/post';
/** The blocked composer page's panel for each standing: its tone and icon (J08-1f…1j, J09-1e). */
export const LOCKED_PANEL: Record<
BlockedStanding,
{ tone: ResultPanelTone; icon: IconName }
> = {
pending: { tone: 'info', icon: 'clock' },
rejected: { tone: 'danger', icon: 'alert' },
suspended: { tone: 'danger', icon: 'lock' },
};

View File

@ -0,0 +1,7 @@
export { ComposerLocked } from './ComposerLocked';
export { ComposerLockedDialog } from './ComposerLockedDialog';
export type {
ComposerLockedDialogProps,
ComposerLockedLayout,
ComposerLockedProps,
} from './types';

View File

@ -0,0 +1,25 @@
import type { BlockedStanding } from '../../../../../../features/post';
export type ComposerLockedLayout = 'mobile' | 'desktop';
export type ComposerLockedProps = {
standing: BlockedStanding;
layout: ComposerLockedLayout;
/** The composer's own title for the mobile bar: «پست جدید», «ویرایش پست», «پیش‌بینی جدید». */
title: string;
/** «بستن»: back to where the composer was opened, or the creator's channel. */
onClose: () => void;
};
export type ComposerLockedDialogProps = {
standing: BlockedStanding;
/** The creator's own: their channel is where «بستن» goes with no history. */
username: string;
};
/** The blocked composer's way forward over «بستن», in a page or a dialog. */
export type LockedActionsProps = {
standing: BlockedStanding;
layout: ComposerLockedLayout;
onClose: () => void;
};

View File

@ -8,7 +8,7 @@ import { usePublishAccess } from '../../../../../../../features/post';
import { useCurrentAccount } from '../../../../../../../stores/auth'; import { useCurrentAccount } from '../../../../../../../stores/auth';
import { ROUTES } from '../../../../../../navigation/navigation'; import { ROUTES } from '../../../../../../navigation/navigation';
import { ComposerForm } from './components/ComposerForm'; import { ComposerForm } from './components/ComposerForm';
import { ComposerLocked } from './components/ComposerLocked'; import { ComposerLocked } from '../../../organisms/composer-locked';
import { EditComposer } from './components/EditComposer'; import { EditComposer } from './components/EditComposer';
import type { PostComposerProps } from './types'; import type { PostComposerProps } from './types';

View File

@ -8,7 +8,7 @@ import { StatusEmptyState } from '../../../../../../error-boundaries';
import { ROUTES } from '../../../../../../navigation/navigation'; import { ROUTES } from '../../../../../../navigation/navigation';
import { ComposerDialog } from './components/ComposerDialog'; import { ComposerDialog } from './components/ComposerDialog';
import { ComposerDialogPlaceholder } from './components/ComposerDialogPlaceholder'; import { ComposerDialogPlaceholder } from './components/ComposerDialogPlaceholder';
import { ComposerLockedDialog } from './components/ComposerLockedDialog'; import { ComposerLockedDialog } from '../../../organisms/composer-locked';
import { EditComposerDialog } from './components/EditComposerDialog'; import { EditComposerDialog } from './components/EditComposerDialog';
import { PostComposerDialogSkeleton } from './PostComposerDialogSkeleton'; import { PostComposerDialogSkeleton } from './PostComposerDialogSkeleton';
import type { PostComposerDialogProps } from './types'; import type { PostComposerDialogProps } from './types';

View File

@ -7,7 +7,7 @@ import {
usePostComposerPage, usePostComposerPage,
} from '../../../../../../../../features/post'; } from '../../../../../../../../features/post';
import { ROUTES } from '../../../../../../../navigation/navigation'; import { ROUTES } from '../../../../../../../navigation/navigation';
import { useDialogRoute } from '../hooks/use-dialog-route'; import { useDialogRoute } from '../../../../../../../navigation/hooks/use-dialog-route';
import type { ComposerDialogProps } from '../types'; import type { ComposerDialogProps } from '../types';
import { ComposerDialogFrame } from './ComposerDialogFrame'; import { ComposerDialogFrame } from './ComposerDialogFrame';
import { ComposerPanel } from './ComposerPanel'; import { ComposerPanel } from './ComposerPanel';

View File

@ -2,7 +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 { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useDialogRoute } from '../hooks/use-dialog-route'; import { useDialogRoute } from '../../../../../../../navigation/hooks/use-dialog-route';
import type { ComposerDialogPlaceholderProps } from '../types'; import type { ComposerDialogPlaceholderProps } from '../types';
import { ComposerDialogFrame } from './ComposerDialogFrame'; import { ComposerDialogFrame } from './ComposerDialogFrame';

View File

@ -1,17 +1,2 @@
import type { IconName } from '@lumina/island/atoms/icon';
import type { ResultPanelTone } from '@lumina/island/molecules/result-panel';
import type { BlockedStanding } from '../../../../../../../features/post';
/** What the file picker offers: the image types the API takes. */ /** What the file picker offers: the image types the API takes. */
export const IMAGE_ACCEPT = 'image/jpeg,image/png,image/webp'; export const IMAGE_ACCEPT = 'image/jpeg,image/png,image/webp';
/** The blocked composer page's panel for each standing: its tone and icon. */
export const LOCKED_PANEL: Record<
BlockedStanding,
{ tone: ResultPanelTone; icon: IconName }
> = {
pending: { tone: 'info', icon: 'clock' },
rejected: { tone: 'danger', icon: 'alert' },
suspended: { tone: 'danger', icon: 'lock' },
};

View File

@ -2,7 +2,6 @@ import type { ReactNode, RefObject } from 'react';
import type { Control } from 'react-hook-form'; import type { Control } from 'react-hook-form';
import type { import type {
BlockedStanding,
ComposerImagesModel, ComposerImagesModel,
PostComposerPageModel, PostComposerPageModel,
UnlockedPostPayload, UnlockedPostPayload,
@ -121,39 +120,3 @@ export type LeaveConfirmProps = {
model: PostComposerPageModel; model: PostComposerPageModel;
layout: ComposerLayout; layout: ComposerLayout;
}; };
export type ComposerLockedProps = {
standing: BlockedStanding;
layout: ComposerLayout;
/** The composer's own title, «پست جدید» or «ویرایش پست», for the mobile bar. */
title: string;
/** «بستن»: back to where the composer was opened, or the creator's channel. */
onClose: () => void;
};
/** The blocked composer's way forward over «بستن», in a page or a dialog. */
export type LockedActionsProps = {
standing: BlockedStanding;
layout: ComposerLayout;
onClose: () => void;
};
export type ComposerLockedDialogProps = {
standing: BlockedStanding;
username: string;
};
/** How the intercepted dialog leaves its route (C4 ۷.۳). */
export type DialogRoute = {
/** Until it starts closing. */
open: boolean;
/** Closes it, then goes back to the page under it. */
close: () => void;
/**
* Closes it and goes to `href`, read again: back, when `href` is the page under it (`isUnder`),
* else in place of the dialog's history entry.
*/
finish: (href: string, options?: { isUnder?: boolean }) => void;
/** The Modal's `onExited`. */
onExited: () => void;
};

View File

@ -7,7 +7,7 @@ import { useTranslation } from 'react-i18next';
import { usePublishAccess } from '../../../../../../../features/post'; import { usePublishAccess } from '../../../../../../../features/post';
import { useCurrentAccount } from '../../../../../../../stores/auth'; import { useCurrentAccount } from '../../../../../../../stores/auth';
import { ROUTES } from '../../../../../../navigation/navigation'; import { ROUTES } from '../../../../../../navigation/navigation';
import { ComposerLocked } from './components/ComposerLocked'; import { ComposerLocked } from '../../../organisms/composer-locked';
import { ComposerPage } from './components/ComposerPage'; import { ComposerPage } from './components/ComposerPage';
import type { PredictionComposerProps } from './types'; import type { PredictionComposerProps } from './types';
@ -39,6 +39,7 @@ export function PredictionComposer({ layout }: PredictionComposerProps) {
<ComposerLocked <ComposerLocked
standing={access.standing} standing={access.standing}
layout={layout} layout={layout}
title={t('composer.title')}
onClose={() => { onClose={() => {
if (window.history.length > 1) router.back(); if (window.history.length > 1) router.back();
else router.push(ROUTES.channel(account.username)); else router.push(ROUTES.channel(account.username));

View File

@ -6,7 +6,7 @@ import { StatusEmptyState } from '../../../../../../error-boundaries';
import { ROUTES } from '../../../../../../navigation/navigation'; import { ROUTES } from '../../../../../../navigation/navigation';
import { ComposerDialog } from './components/ComposerDialog'; import { ComposerDialog } from './components/ComposerDialog';
import { ComposerDialogPlaceholder } from './components/ComposerDialogPlaceholder'; import { ComposerDialogPlaceholder } from './components/ComposerDialogPlaceholder';
import { LockedDialog } from './components/LockedDialog'; import { ComposerLockedDialog } from '../../../organisms/composer-locked';
import { PredictionComposerDialogSkeleton } from './PredictionComposerDialogSkeleton'; import { PredictionComposerDialogSkeleton } from './PredictionComposerDialogSkeleton';
/** /**
@ -32,7 +32,10 @@ export function PredictionComposerDialog() {
if (access.status === 'pending') return <PredictionComposerDialogSkeleton />; if (access.status === 'pending') return <PredictionComposerDialogSkeleton />;
if (access.status === 'blocked') { if (access.status === 'blocked') {
return ( return (
<LockedDialog standing={access.standing} username={account.username} /> <ComposerLockedDialog
standing={access.standing}
username={account.username}
/>
); );
} }
return <ComposerDialog creatorId={account.id} username={account.username} />; return <ComposerDialog creatorId={account.id} username={account.username} />;

View File

@ -3,7 +3,7 @@ import { useQueryClient } from '@tanstack/react-query';
import { isChannelOnScreen } from '../../../../../../../../features/post'; import { isChannelOnScreen } from '../../../../../../../../features/post';
import { usePredictionComposerPage } from '../../../../../../../../features/prediction'; import { usePredictionComposerPage } from '../../../../../../../../features/prediction';
import { ROUTES } from '../../../../../../../navigation/navigation'; import { ROUTES } from '../../../../../../../navigation/navigation';
import { useDialogRoute } from '../hooks/use-dialog-route'; import { useDialogRoute } from '../../../../../../../navigation/hooks/use-dialog-route';
import type { ComposerDialogProps } from '../types'; import type { ComposerDialogProps } from '../types';
import { ComposerFrame } from './ComposerFrame'; import { ComposerFrame } from './ComposerFrame';
import { ComposerWorkspace } from './ComposerWorkspace'; import { ComposerWorkspace } from './ComposerWorkspace';

View File

@ -1,6 +1,6 @@
import { FlexBox } from '@lumina/island/atoms/flex-box'; import { FlexBox } from '@lumina/island/atoms/flex-box';
import { useDialogRoute } from '../hooks/use-dialog-route'; import { useDialogRoute } from '../../../../../../../navigation/hooks/use-dialog-route';
import type { ComposerDialogPlaceholderProps } from '../types'; import type { ComposerDialogPlaceholderProps } from '../types';
import { ComposerFrame } from './ComposerFrame'; import { ComposerFrame } from './ComposerFrame';

View File

@ -1,50 +0,0 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Card } from '@lumina/island/molecules/card';
import { ResultPanel } from '@lumina/island/molecules/result-panel';
import { useTranslation } from 'react-i18next';
import { MobileTopBar } from '../../../../../../../navigation/components/mobile-top-bar';
import { LOCKED_PANEL } from '../constants';
import type { ComposerLockedProps } from '../types';
import { LockedActions } from './LockedActions';
/**
* /compose/prediction opened by a creator who may not publish (J09-1e): pending, rejected or
* suspended, what «انتشار» would explain, as the page, with the one way forward and «بستن».
* Mobile: the pushed page's bar over the panel; desktop: a card.
*/
export function ComposerLocked({
standing,
layout,
onClose,
}: ComposerLockedProps) {
const { t } = useTranslation(['common', 'predictions']);
const { tone, icon } = LOCKED_PANEL[standing];
const panel = (
<ResultPanel
tone={tone}
icon={icon}
title={t(`publish.${standing}.title`)}
body={t(`publish.${standing}.reason`)}
actions={
<LockedActions standing={standing} layout={layout} onClose={onClose} />
}
/>
);
if (layout === 'mobile') {
return (
<FlexBox direction="flex-col" className="min-h-dvh bg-surface">
<MobileTopBar title={t('predictions:composer.title')} />
<FlexBox tag="main" direction="flex-col" className="flex-1 px-4 py-8">
{panel}
</FlexBox>
</FlexBox>
);
}
return (
<Card tag="section" padding="lg" className="w-full max-w-content">
{panel}
</Card>
);
}

View File

@ -7,7 +7,6 @@ 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';
import { Sheet } from '@lumina/island/molecules/sheet'; import { Sheet } from '@lumina/island/molecules/sheet';
import { Element } from '@lumina/island/primitives/element';
import { date, number, price } from '@lumina/tools/format'; import { date, number, price } from '@lumina/tools/format';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
@ -30,9 +29,9 @@ export function ConfirmPublish({ model, layout }: ComposerPartProps) {
<FlexBox direction="flex-col" gap="gap-4"> <FlexBox direction="flex-col" gap="gap-4">
<KeyValue tone="soft"> <KeyValue tone="soft">
<DetailRow label={t('composer.confirm.prediction')} strong> <DetailRow label={t('composer.confirm.prediction')} strong>
<Element tag="bdi" dir="ltr"> <Typography tag="bdi" dir="ltr" variant="inherit" color="inherit">
{summary.symbol} {summary.symbol}
</Element> </Typography>
<Separator /> <Separator />
<Icon <Icon
name={summary.direction === 'long' ? 'trend-up' : 'trend-down'} name={summary.direction === 'long' ? 'trend-up' : 'trend-down'}
@ -43,11 +42,11 @@ export function ConfirmPublish({ model, layout }: ComposerPartProps) {
</Typography> </Typography>
</DetailRow> </DetailRow>
<DetailRow label={t('composer.confirm.entry')} strong> <DetailRow label={t('composer.confirm.entry')} strong>
<Element tag="bdi" dir="ltr"> <Typography tag="bdi" dir="ltr" variant="inherit" color="inherit">
{t('composer.confirm.entry-value', { {t('composer.confirm.entry-value', {
price: price(summary.entryPrice), price: price(summary.entryPrice),
})} })}
</Element> </Typography>
<Separator /> <Separator />
<Typography tag="span" variant="caption" color="secondary"> <Typography tag="span" variant="caption" color="secondary">
{t('composer.confirm.entry-note')} {t('composer.confirm.entry-note')}

View File

@ -1,53 +0,0 @@
import { Button } from '@lumina/island/atoms/button';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { useTranslation } from 'react-i18next';
import { ROUTES } from '../../../../../../../navigation/navigation';
import { SupportEntry } from '../../../../../../organisms/support-entry';
import type { LockedActionsProps } from '../types';
/**
* Why-not's actions (J09-1e, as «انتشار» explains it): the identity review for a pending creator,
* its form to correct and send again for a rejected one, support for a suspended one; «بستن»
* under it.
*/
export function LockedActions({
standing,
layout,
onClose,
}: LockedActionsProps) {
const { t } = useTranslation('common');
const isMobile = layout === 'mobile';
const size = isMobile ? 'lg' : undefined;
return (
<>
{standing === 'suspended' ? (
// A desktop popover hangs from a positioned parent that also holds its trigger.
<FlexBox direction="flex-col" className="relative">
<SupportEntry
trigger="button"
placement={isMobile ? 'bottom' : 'popover'}
size={isMobile ? 'lg' : 'md'}
/>
</FlexBox>
) : (
<Button
variant="primary"
size={size}
block
href={
standing === 'rejected'
? `${ROUTES.account.profile}#identity`
: ROUTES.account.profile
}
>
{t(`publish.${standing}.action`)}
</Button>
)}
<Button variant="secondary" size={size} block onClick={onClose}>
{t('publish.close')}
</Button>
</>
);
}

View File

@ -1,37 +0,0 @@
import { Typography } from '@lumina/island/atoms/typography';
import { Modal } from '@lumina/island/molecules/modal';
import { useTranslation } from 'react-i18next';
import { ROUTES } from '../../../../../../../navigation/navigation';
import { useDialogRoute } from '../hooks/use-dialog-route';
import type { LockedDialogProps } from '../types';
import { LockedActions } from './LockedActions';
/**
* The composer dialog's route opened by a creator who may not publish (J09-1e): the 420px question
* «انتشار» would have asked, over the page. «بستن», Escape and the scrim go back to that page.
*/
export function LockedDialog({ standing, username }: LockedDialogProps) {
const { t } = useTranslation('common');
const route = useDialogRoute(ROUTES.channel(username));
return (
<Modal
open={route.open}
title={t(`publish.${standing}.title`)}
onClose={route.close}
onExited={route.onExited}
actions={
<LockedActions
standing={standing}
layout="desktop"
onClose={route.close}
/>
}
>
<Typography color="secondary">
{t(`publish.${standing}.reason`)}
</Typography>
</Modal>
);
}

View File

@ -1,17 +1,2 @@
import type { IconName } from '@lumina/island/atoms/icon';
import type { ResultPanelTone } from '@lumina/island/molecules/result-panel';
import type { BlockedStanding } from '../../../../../../../features/post';
/** What the chart picker offers: the image types the API takes. */ /** What the chart picker offers: the image types the API takes. */
export const CHART_ACCEPT = 'image/jpeg,image/png,image/webp'; export const CHART_ACCEPT = 'image/jpeg,image/png,image/webp';
/** The blocked composer page's panel for each standing: its tone and icon (J09-1e). */
export const LOCKED_PANEL: Record<
BlockedStanding,
{ tone: ResultPanelTone; icon: IconName }
> = {
pending: { tone: 'info', icon: 'clock' },
rejected: { tone: 'danger', icon: 'alert' },
suspended: { tone: 'danger', icon: 'lock' },
};

View File

@ -1,42 +0,0 @@
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import type { DialogRoute } from '../types';
/**
* The dialog that intercepts /compose/prediction plays its exit before its route changes. Closed,
* it goes back to the page under it, or to `fallback` when there is no history to go back to.
* Finished, it goes to `href` so back never reopens an empty composer, the `@modal` slot empties
* there, and `href` is read again from the server: back when `href` is the page under it, else in
* place of its own history entry.
*/
export function useDialogRoute(fallback: string): DialogRoute {
const router = useRouter();
const [exit, setExit] = useState<'back' | 'done' | null>(null);
return {
open: exit === null,
close: () => setExit('back'),
finish: (href, { isUnder = false } = {}) => {
setExit('done');
if (isUnder) {
// Replacing would leave that page in history twice. The refresh waits for the back to
// land, or it would read /compose/prediction again.
window.addEventListener('popstate', () => router.refresh(), {
once: true,
});
router.back();
return;
}
router.replace(href);
// Over the creator's own channel `href` is already rendered under the dialog: the refresh,
// queued after the replace, renders it again with the new prediction.
router.refresh();
},
onExited: () => {
if (exit !== 'back') return;
if (window.history.length > 1) router.back();
else router.push(fallback);
},
};
}

View File

@ -1,6 +1,5 @@
import type { ReactNode, RefObject } from 'react'; import type { ReactNode, RefObject } from 'react';
import type { BlockedStanding } from '../../../../../../../features/post';
import type { PredictionComposerPageModel } from '../../../../../../../features/prediction'; import type { PredictionComposerPageModel } from '../../../../../../../features/prediction';
/** mobile: a pushed page with a pinned footer. desktop: the 960px workspace, as page or dialog. */ /** mobile: a pushed page with a pinned footer. desktop: the 960px workspace, as page or dialog. */
@ -64,35 +63,3 @@ export type FieldGroupProps = {
caption?: ReactNode; caption?: ReactNode;
children: ReactNode; children: ReactNode;
}; };
export type ComposerLockedProps = {
standing: BlockedStanding;
layout: ComposerLayout;
onClose: () => void;
};
export type LockedDialogProps = {
standing: BlockedStanding;
username: string;
};
export type LockedActionsProps = {
standing: BlockedStanding;
layout: ComposerLayout;
onClose: () => void;
};
/** How the intercepted dialog leaves its route (0023). */
export type DialogRoute = {
/** Until it starts closing. */
open: boolean;
/** Closes it, then goes back to the page under it. */
close: () => void;
/**
* Closes it and goes to `href`, read again: back, when `href` is the page under it (`isUnder`),
* else in place of the dialog's history entry.
*/
finish: (href: string, options?: { isUnder?: boolean }) => void;
/** The Modal's `onExited`. */
onExited: () => void;
};

View File

@ -59,8 +59,8 @@ function clampParts(
/** /**
* The Shamsi date and time picker (C7 ۴.۳, 0035): day, month, year, hour and minute, each a native * The Shamsi date and time picker (C7 ۴.۳, 0035): day, month, year, hour and minute, each a native
* select (a wheel on phones), and for an end «بدون تاریخ پایان», so ending is one decision in one * select (a wheel on phones), and for an end «بدون تاریخ پایان», so ending is one decision in one
* place. Nothing before now can be picked, nor an end before its start: those options are left * place. Nothing before now can be picked, nor an end before its start: those options show
* out, and «تأیید» raises the pick to the earliest allowed. A bottom sheet on mobile, a centred * disabled, and «تأیید» raises the pick to the earliest allowed. A bottom sheet on mobile, a centred
* modal on desktop (۸.۱). * modal on desktop (۸.۱).
*/ */
export function DateTimeDialog({ export function DateTimeDialog({
@ -154,14 +154,9 @@ function PickerBody({
const onMinMonth = onMinYear && parts.month === min.month; const onMinMonth = onMinYear && parts.month === min.month;
const onMinDay = onMinMonth && parts.day === min.day; const onMinDay = onMinMonth && parts.day === min.day;
const onMinHour = onMinDay && parts.hour === min.hour; const onMinHour = onMinDay && parts.hour === min.hour;
const months = MONTHS.filter((month) => !onMinYear || month >= min.month);
const days = Array.from( const days = Array.from(
{ length: jalaliMonthLength(parts.year, parts.month) }, { length: jalaliMonthLength(parts.year, parts.month) },
(_, index) => index + 1, (_, index) => index + 1,
).filter((day) => !onMinMonth || day >= min.day);
const hours = HOURS.filter((hour) => !onMinDay || hour >= min.hour);
const minutes = MINUTES.filter(
(minute) => !onMinHour || minute >= min.minute,
); );
const set = (key: keyof JalaliDateTime, next: number) => const set = (key: keyof JalaliDateTime, next: number) =>
@ -178,6 +173,7 @@ function PickerBody({
options={days.map((day) => ({ options={days.map((day) => ({
value: String(day), value: String(day),
label: number(day), label: number(day),
disabled: onMinMonth && day < min.day,
}))} }))}
/> />
<Select <Select
@ -185,9 +181,10 @@ function PickerBody({
value={String(parts.month)} value={String(parts.month)}
disabled={open} disabled={open}
onChange={(event) => set('month', Number(event.target.value))} onChange={(event) => set('month', Number(event.target.value))}
options={months.map((month) => ({ options={MONTHS.map((month) => ({
value: String(month), value: String(month),
label: t(`picker.months.${month}` as 'picker.months.1'), label: t(`picker.months.${month}` as 'picker.months.1'),
disabled: onMinYear && month < min.month,
}))} }))}
/> />
<Select <Select
@ -207,9 +204,10 @@ function PickerBody({
value={String(parts.hour)} value={String(parts.hour)}
disabled={open} disabled={open}
onChange={(event) => set('hour', Number(event.target.value))} onChange={(event) => set('hour', Number(event.target.value))}
options={hours.map((hour) => ({ options={HOURS.map((hour) => ({
value: String(hour), value: String(hour),
label: pad(hour), label: pad(hour),
disabled: onMinDay && hour < min.hour,
}))} }))}
/> />
<Select <Select
@ -217,9 +215,10 @@ function PickerBody({
value={String(parts.minute)} value={String(parts.minute)}
disabled={open} disabled={open}
onChange={(event) => set('minute', Number(event.target.value))} onChange={(event) => set('minute', Number(event.target.value))}
options={minutes.map((minute) => ({ options={MINUTES.map((minute) => ({
value: String(minute), value: String(minute),
label: pad(minute), label: pad(minute),
disabled: onMinHour && minute < min.minute,
}))} }))}
/> />
</GridBox> </GridBox>

View File

@ -89,6 +89,8 @@ export function OwnerShareSheet({
return ( return (
<Sheet <Sheet
placement={isMobile ? 'bottom' : 'popover'} placement={isMobile ? 'bottom' : 'popover'}
// The DS SharePopover's 360px.
popoverWidth="wide"
open={model.isOpen} open={model.isOpen}
title={t('share.owner.title')} title={t('share.owner.title')}
onClose={model.close} onClose={model.close}

View File

@ -42,6 +42,8 @@ export function BalanceSummary() {
{/* The ⓘ's 44px target reaches into the tile's padding; its icon keeps the 6px gap. */} {/* The ⓘ's 44px target reaches into the tile's padding; its icon keeps the 6px gap. */}
<InfoTip <InfoTip
label={t('balance.available-info')} label={t('balance.available-info')}
// J10-6e: above the tile, so it never covers the figure it explains.
placement="above"
className="-ms-3.5 -me-2" className="-ms-3.5 -me-2"
> >
{t('balance.available-tip')} {t('balance.available-tip')}

View File

@ -11,7 +11,6 @@ import { Lightbox } from '@lumina/island/organisms/lightbox';
import { Element } from '@lumina/island/primitives/element'; import { Element } from '@lumina/island/primitives/element';
import { price } from '@lumina/tools/format'; import { price } from '@lumina/tools/format';
import { useId } from 'react'; import { useId } from 'react';
import type { MouseEvent } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { import {
@ -36,28 +35,6 @@ export function Ledger({ layout }: LedgerProps) {
const receipt = model.lightboxReceipt; const receipt = model.lightboxReceipt;
const receiptRow = model.detail?.kind === 'payout' ? model.detail : null; const receiptRow = model.detail?.kind === 'payout' ? model.detail : null;
// The tabs are real links (a new tab, a copied address), but a plain click switches in place,
// so the page keeps its scroll instead of jumping to the top (0034).
const switchInPlace = (event: MouseEvent<HTMLElement>) => {
if (
event.button !== 0 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey
)
return;
const href = (event.target as HTMLElement)
.closest('a')
?.getAttribute('href');
const next = LEDGER_FILTERS.find(
(filter) => model.filterHref(filter) === href,
);
if (!next) return;
event.preventDefault();
model.setFilter(next);
};
return ( return (
<Element <Element
tag="section" tag="section"
@ -66,17 +43,19 @@ export function Ledger({ layout }: LedgerProps) {
> >
<FlexBox direction="flex-col" gap="gap-3"> <FlexBox direction="flex-col" gap="gap-3">
<SectionTitle title={t('ledger.title')} titleId={headingId} /> <SectionTitle title={t('ledger.title')} titleId={headingId} />
<Element tag="div" onClickCapture={switchInPlace}> {/* Real links (a new tab, a copied address) that switch in place: the entry is replaced and
<TabLinks the page keeps its scroll instead of jumping to the top (0034). */}
label={t('ledger.filter')} <TabLinks
fill={layout === 'mobile'} label={t('ledger.filter')}
items={LEDGER_FILTERS.map((filter) => ({ fill={layout === 'mobile'}
href: model.filterHref(filter), replace
label: t(`ledger.filters.${filter}`), scroll={false}
isActive: model.filter === filter, items={LEDGER_FILTERS.map((filter) => ({
}))} href: model.filterHref(filter),
/> label: t(`ledger.filters.${filter}`),
</Element> isActive: model.filter === filter,
}))}
/>
{model.isEmpty ? ( {model.isEmpty ? (
<EmptyState <EmptyState
title={t(`ledger.empty.${model.filter}`)} title={t(`ledger.empty.${model.filter}`)}

View File

@ -56,7 +56,7 @@ export function LedgerRow({ row, isOpen, onOpen }: LedgerRowProps) {
} }
chevron chevron
onClick={onOpen} onClick={onOpen}
className={isOpen ? 'bg-surface-sunken' : undefined} selected={isOpen}
/> />
); );
} }

View File

@ -9,8 +9,8 @@ import type { DashboardTabsProps } from './types';
/** /**
* The داشبورد's section row, full width, the current one underlined: the investor's «اشتراک‌ها» · * The داشبورد's section row, full width, the current one underlined: the investor's «اشتراک‌ها» ·
* «تراکنش‌ها» · «دنبال‌شده‌ها» (U8 ۴.۱, ۶.۱; U8 ۵.۲), or the creator's «طرح‌های اشتراک» · «مالی» * «تراکنش‌ها» · «دنبال‌شده‌ها» (U8 ۴.۱, ۶.۱; U8 ۵.۲), or the creator's «طرح‌های اشتراک» ·
* (Creator Dashboard ۱.۱). The dashboard layout renders it once, so it stays put while a section * «پیش‌بینی‌ها» · «مالی» (Creator Dashboard ۱.۱, J10-0, 0034). The dashboard layout renders it once, so it stays put while a section
* loads; the current one comes from the URL, which the server render already knows. * loads; the current one comes from the URL, which the server render already knows.
*/ */
export function DashboardTabs({ export function DashboardTabs({

View File

@ -1,6 +1,6 @@
export type DashboardTabsProps = { export type DashboardTabsProps = {
/** mobile: the surface band under the top bar. desktop: in the 640 column, under the heading. */ /** mobile: the surface band under the top bar. desktop: in the 640 column, under the heading. */
layout: 'mobile' | 'desktop'; layout: 'mobile' | 'desktop';
/** Whose داشبورد: the investor's three sections, or the creator's two tabs. Default investor. */ /** Whose داشبورد: the investor's three sections, or the creator's three tabs. Default investor. */
role?: 'investor' | 'creator'; role?: 'investor' | 'creator';
}; };

View File

@ -18,11 +18,12 @@ export function InviteShareSheet({ model, layout }: InviteShareSheetProps) {
return ( return (
<Sheet <Sheet
placement={isMobile ? 'bottom' : 'popover'} placement={isMobile ? 'bottom' : 'popover'}
// The DS SharePopover's 360px.
popoverWidth="wide"
open={model.isOpen} open={model.isOpen}
title={t('invite.share.title')} title={t('invite.share.title')}
onClose={model.close} onClose={model.close}
closeLabel={t('invite.share.close')} closeLabel={t('invite.share.close')}
className={isMobile ? undefined : 'w-90'}
footer={ footer={
<> <>
<Button <Button

View File

@ -8,6 +8,8 @@ import { useTranslation } from 'react-i18next';
import { MARKETS } from '../../../../../../../shared/constants'; import { MARKETS } from '../../../../../../../shared/constants';
import type { Market } from '../../../../../../../shared/constants'; import type { Market } from '../../../../../../../shared/constants';
import { predictionCardLabels } from '../../../../../../../shared/labels'; import { predictionCardLabels } from '../../../../../../../shared/labels';
import { useCurrentAccount } from '../../../../../../../stores/auth';
import { ROUTES } from '../../../../../../navigation/navigation';
import type { OwnPredictionCardProps } from './types'; import type { OwnPredictionCardProps } from './types';
// Only an open card closes: the sheet and its price poll load on the first tap. // Only an open card closes: the sheet and its price poll load on the first tap.
@ -22,14 +24,16 @@ const isMarket = (market: string): market is Market =>
/** /**
* One of the creator's own predictions on its own (J10-3, J10-3f, J10-3g): پریمیوم when it is, an * One of the creator's own predictions on its own (J10-3, J10-3f, J10-3g): پریمیوم when it is, an
* open one with «بستن زودهنگام», a closed one with why and at whose price it closed. Closing it * open one with «بستن زودهنگام», a closed one with why and at whose price it closed. A tap on the
* here updates it in place. * card opens its post, as the DS card links to it. Closing it here updates it in place.
*/ */
export function OwnPredictionCard({ post, layout }: OwnPredictionCardProps) { export function OwnPredictionCard({ post, layout }: OwnPredictionCardProps) {
const { t } = useTranslation('content'); const { t } = useTranslation('content');
const { t: tCommon } = useTranslation('common'); const { t: tCommon } = useTranslation('common');
const labels = useMemo(() => predictionCardLabels(t), [t]); const labels = useMemo(() => predictionCardLabels(t), [t]);
const [isClosing, setIsClosing] = useState(false); const [isClosing, setIsClosing] = useState(false);
// The creator's own: the dashboard's guard renders it for them only.
const username = useCurrentAccount()?.username;
const { prediction } = post; const { prediction } = post;
return ( return (
@ -41,6 +45,7 @@ export function OwnPredictionCard({ post, layout }: OwnPredictionCardProps) {
? tCommon(`markets.${prediction.market}`) ? tCommon(`markets.${prediction.market}`)
: prediction.market, : prediction.market,
}} }}
href={username ? ROUTES.post(username, post.id) : undefined}
premium={post.accessLevel === 'premium'} premium={post.accessLevel === 'premium'}
publishedAt={post.publishedAt ?? post.createdAt} publishedAt={post.publishedAt ?? post.createdAt}
onClosePrediction={ onClosePrediction={

View File

@ -152,28 +152,37 @@ export function RenewalForm({ subscriptionId, layout }: RenewalFormProps) {
className="m-0 gap-0.5 rounded-md bg-surface-sunken px-4 py-3" className="m-0 gap-0.5 rounded-md bg-surface-sunken px-4 py-3"
> >
<FlexBox justifyContent="justify-between" gap="gap-3"> <FlexBox justifyContent="justify-between" gap="gap-3">
<Element tag="dt"> <Typography tag="dt" variant="inherit" color="inherit">
{isRenew {isRenew
? t('subscriptions.renewal.from') ? t('subscriptions.renewal.from')
: t('subscriptions.renewal.start')} : t('subscriptions.renewal.start')}
</Element> </Typography>
<Element tag="dd" className="m-0 font-semibold"> <Typography
tag="dd"
variant="inherit"
color="inherit"
className="m-0 font-semibold"
>
{from && {from &&
(isRenew (isRenew
? date(from, { time: false }) ? date(from, { time: false })
: t('subscriptions.renewal.today', { : t('subscriptions.renewal.today', {
date: date(from, { time: false }), date: date(from, { time: false }),
}))} }))}
</Element> </Typography>
</FlexBox> </FlexBox>
<FlexBox justifyContent="justify-between" gap="gap-3"> <FlexBox justifyContent="justify-between" gap="gap-3">
<Element tag="dt">{t('subscriptions.renewal.to')}</Element> <Typography tag="dt" variant="inherit" color="inherit">
<Element {t('subscriptions.renewal.to')}
</Typography>
<Typography
tag="dd" tag="dd"
variant="inherit"
color="inherit"
className={selectedTier ? 'm-0 font-semibold' : 'm-0'} className={selectedTier ? 'm-0 font-semibold' : 'm-0'}
> >
{selectedTier ? date(selectedTier.periodTo, { time: false }) : '—'} {selectedTier ? date(selectedTier.periodTo, { time: false }) : '—'}
</Element> </Typography>
</FlexBox> </FlexBox>
</FlexBox> </FlexBox>
{selectedTier?.priceChanged && ( {selectedTier?.priceChanged && (

View File

@ -149,9 +149,14 @@ export function TransactionDetail({ model, layout }: TransactionDetailProps) {
{row.refund?.shebaLast4 && ( {row.refund?.shebaLast4 && (
<DetailRow label={t('transactions.sheba')} strong ltr> <DetailRow label={t('transactions.sheba')} strong ltr>
{/* Banks print شبا in Latin digits; only its last four are kept. */} {/* Banks print شبا in Latin digits; only its last four are kept. */}
<Element tag="span" className="font-latin"> <Typography
tag="span"
variant="inherit"
color="inherit"
className="font-latin"
>
{`IR•• •••• •••• •••• ${row.refund.shebaLast4}`} {`IR•• •••• •••• •••• ${row.refund.shebaLast4}`}
</Element> </Typography>
</DetailRow> </DetailRow>
)} )}
</KeyValue> </KeyValue>
@ -182,9 +187,14 @@ export function TransactionDetail({ model, layout }: TransactionDetailProps) {
)} )}
{row.status !== 'pending' && row.reference && ( {row.status !== 'pending' && row.reference && (
<DetailRow label={t('transactions.reference')} strong ltr> <DetailRow label={t('transactions.reference')} strong ltr>
<Element tag="span" className="font-latin"> <Typography
tag="span"
variant="inherit"
color="inherit"
className="font-latin"
>
{row.reference} {row.reference}
</Element> </Typography>
</DetailRow> </DetailRow>
)} )}
</KeyValue> </KeyValue>

View File

@ -6,7 +6,7 @@ import { useRouter } from 'next/navigation';
import { useMemo } from 'react'; import { useMemo } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useShareLink } from '../../../../../features/channel'; import { useDisplayLink, useShareLink } from '../../../../../features/channel';
import { useOwnerPostPart } from '../../../../../features/post'; import { useOwnerPostPart } from '../../../../../features/post';
import { MARKETS } from '../../../../../shared/constants'; import { MARKETS } from '../../../../../shared/constants';
import type { Market } from '../../../../../shared/constants'; import type { Market } from '../../../../../shared/constants';
@ -33,7 +33,7 @@ const isMarket = (market: string): market is Market =>
* locked post shows the gate for who is looking: «ورود/ثبت‌نام» back to this page for a guest, * locked post shows the gate for who is looking: «ورود/ثبت‌نام» back to this page for a guest,
* «اشتراک در کانال» into checkout for an investor, and that CTA frozen for another creator, who * «اشتراک در کانال» into checkout for an investor, and that CTA frozen for another creator, who
* can't subscribe. Everyone may share it: the device's share sheet on * can't subscribe. Everyone may share it: the device's share sheet on
* mobile, a menu with «کپی لینک» on desktop (C4b ۳.۴, ۶.۱). The creator's own post gets the * mobile, a popover with the link and «کپی لینک» on desktop (C4b ۳.۴, ۶.۱; J05-5c, J08-4g). The creator's own post gets the
* owner's footer: preview (premium), share, edit (frozen after 15 minutes), delete, and closing an * owner's footer: preview (premium), share, edit (frozen after 15 minutes), delete, and closing an
* open prediction; past the 15 minutes a channel card also shows its access level, frozen with it * open prediction; past the 15 minutes a channel card also shows its access level, frozen with it
* (C5 ۱.۶). In the creator's preview it renders as others see it, with nothing that acts. Their * (C5 ۱.۶). In the creator's preview it renders as others see it, with nothing that acts. Their
@ -68,10 +68,11 @@ export function ChannelPostCard({
const owner = useOwnerPostPart({ post, enabled: isOwner, onDeleted }); const owner = useOwnerPostPart({ post, enabled: isOwner, onDeleted });
const path = ROUTES.post(username, post.id); const path = ROUTES.post(username, post.id);
const displayLink = useDisplayLink(path);
const isPremium = post.accessLevel === 'premium'; const isPremium = post.accessLevel === 'premium';
const onShare = () => const onShare = () =>
void share({ kind: 'post', path, native: layout === 'mobile' }); void share({ kind: 'post', path, native: layout === 'mobile' });
// Desktop has no share sheet: share opens the one-item menu, which copies the link. // Desktop has no share sheet: share opens the popover, whose one button copies the link.
const onCopyLink = const onCopyLink =
layout === 'desktop' layout === 'desktop'
? () => void share({ kind: 'post', path, native: false }) ? () => void share({ kind: 'post', path, native: false })
@ -122,6 +123,7 @@ export function ChannelPostCard({
predictionLabels, predictionLabels,
labels, labels,
className, className,
shareUrl: layout === 'desktop' ? displayLink : undefined,
...footer, ...footer,
}; };
const marketName = (market: string) => const marketName = (market: string) =>

View File

@ -3,7 +3,6 @@ import { Separator } from '@lumina/island/atoms/separator';
import { Typography } from '@lumina/island/atoms/typography'; import { Typography } from '@lumina/island/atoms/typography';
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 { Element } from '@lumina/island/primitives/element';
import { price } from '@lumina/tools/format'; import { price } from '@lumina/tools/format';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
@ -21,9 +20,9 @@ export function PredictionSummary({ post, children }: PredictionSummaryProps) {
return ( return (
<KeyValue tone="soft"> <KeyValue tone="soft">
<DetailRow label={t('close.prediction')} strong> <DetailRow label={t('close.prediction')} strong>
<Element tag="bdi" dir="ltr"> <Typography tag="bdi" dir="ltr" variant="inherit" color="inherit">
{prediction.symbol} {prediction.symbol}
</Element> </Typography>
<Separator /> <Separator />
<Icon <Icon
name={prediction.direction === 'long' ? 'trend-up' : 'trend-down'} name={prediction.direction === 'long' ? 'trend-up' : 'trend-down'}

View File

@ -7,7 +7,7 @@ import { Typography } from '@lumina/island/atoms/typography';
import { ErrorState } from '@lumina/island/molecules/error-state'; import { ErrorState } from '@lumina/island/molecules/error-state';
import { List, ListRow } from '@lumina/island/molecules/list-row'; import { List, ListRow } from '@lumina/island/molecules/list-row';
import { Element } from '@lumina/island/primitives/element'; import { Element } from '@lumina/island/primitives/element';
import { number } from '@lumina/tools/format'; import { list, number } from '@lumina/tools/format';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { ROUTES } from '../../../../../../navigation/navigation'; import { ROUTES } from '../../../../../../navigation/navigation';
@ -45,9 +45,9 @@ export function SearchResults({ layout, search, onOpen }: SearchResultsProps) {
) : ( ) : (
<List> <List>
{results.map((analyst) => { {results.map((analyst) => {
const markets = analyst.markets const markets = list(
.map((market) => t(`common:markets.${market}`)) analyst.markets.map((market) => t(`common:markets.${market}`)),
.join('، '); );
return ( return (
<ListRow <ListRow
key={analyst.creatorId} key={analyst.creatorId}

View File

@ -4,6 +4,7 @@ import { useCallback, 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 type { Market } from '../../../../shared/constants'; import type { Market } from '../../../../shared/constants';
import { applyServerErrors, formatMobile } from '../../../../shared/utils'; import { applyServerErrors, formatMobile } from '../../../../shared/utils';
import { accountProfileSchema } from '../../../../shared/validations'; import { accountProfileSchema } from '../../../../shared/validations';
@ -19,7 +20,6 @@ import type {
LeaveTarget, LeaveTarget,
UseAccountProfilePageOptions, UseAccountProfilePageOptions,
} from './types'; } from './types';
import { useLeaveGuard } from './use-leave-guard';
type SavedValues = { firstName: string; lastName: string; markets: Market[] }; type SavedValues = { firstName: string; lastName: string; markets: Market[] };

View File

@ -1,53 +0,0 @@
import { useEffect } from 'react';
/** A plain click on a link to another page of this site, which the app would navigate to itself. */
function leavingHref(event: MouseEvent): string | null {
if (
event.defaultPrevented ||
event.button !== 0 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey
) {
return null;
}
const link =
event.target instanceof Element ? event.target.closest('a[href]') : null;
if (!(link instanceof HTMLAnchorElement) || link.target === '_blank') {
return null;
}
const url = new URL(link.href, window.location.href);
const here = window.location;
if (url.origin !== here.origin || url.pathname === here.pathname) return null;
return `${url.pathname}${url.search}${url.hash}`;
}
/**
* While the form holds unsaved changes, leaving asks first: a link inside the app (the header, the
* account menu) opens the page's dialog with where it leads (J03-1g), and closing or reloading the
* tab gets the browser's prompt. Back is asked about by the bar's `onBack`.
*/
export function useLeaveGuard(
hasChanges: boolean,
onLeaveRequest: (href: string) => void,
): void {
useEffect(() => {
if (!hasChanges) return undefined;
const askOnUnload = (event: BeforeUnloadEvent) => event.preventDefault();
// Capture, so it runs before the app's own link handling and can stop it.
const askOnLink = (event: MouseEvent) => {
const href = leavingHref(event);
if (href === null) return;
event.preventDefault();
event.stopPropagation();
onLeaveRequest(href);
};
window.addEventListener('beforeunload', askOnUnload);
document.addEventListener('click', askOnLink, true);
return () => {
window.removeEventListener('beforeunload', askOnUnload);
document.removeEventListener('click', askOnLink, true);
};
}, [hasChanges, onLeaveRequest]);
}

View File

@ -0,0 +1,24 @@
import { useRouter } from 'next/navigation';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useLeaveGuard } from '../../../../app/navigation/hooks/use-leave-guard';
/**
* While step 4 holds unsent values, leaving asks first, with the browser's own prompt (R2 2.1):
* closing or reloading the tab, and following a link inside the app, such as the brand, which goes
* on once confirmed. The browser's back button is not asked about: Next.js has no way to hold a
* navigation back.
*/
export function useConfirmLeave(isDirty: boolean): void {
const { t } = useTranslation('auth');
const router = useRouter();
const message = t('register.leave-confirm');
const confirmLeave = useCallback(
(href: string) => {
if (window.confirm(message)) router.push(href);
},
[message, router],
);
useLeaveGuard(isDirty, confirmLeave);
}

View File

@ -27,7 +27,7 @@ import type {
IdCardSide, IdCardSide,
UseDetailsPartOptions, UseDetailsPartOptions,
} from './types'; } from './types';
import { useLeaveGuard } from './use-leave-guard'; import { useConfirmLeave } from './use-confirm-leave';
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. */
@ -79,7 +79,7 @@ export function useCreatorIdentityPart({
}); });
const username = useUsernameAvailability(form); const username = useUsernameAvailability(form);
const { errors, isSubmitting, isDirty } = form.formState; const { errors, isSubmitting, isDirty } = form.formState;
useLeaveGuard(isDirty && submission.phase !== 'done'); useConfirmLeave(isDirty && submission.phase !== 'done');
const pickImage = (side: IdCardSide, file: File | null) => { const pickImage = (side: IdCardSide, file: File | null) => {
const checked = file ? v.safeParse(idCardImage, file) : null; const checked = file ? v.safeParse(idCardImage, file) : null;

View File

@ -19,7 +19,7 @@ import {
authErrorCode, authErrorCode,
} from '../../repositories/auth'; } from '../../repositories/auth';
import type { InvestorDetailsPartModel, UseDetailsPartOptions } from './types'; import type { InvestorDetailsPartModel, UseDetailsPartOptions } from './types';
import { useLeaveGuard } from './use-leave-guard'; import { useConfirmLeave } from './use-confirm-leave';
import { useUsernameAvailability } from './use-username-availability'; import { useUsernameAvailability } from './use-username-availability';
/** /**
@ -53,7 +53,7 @@ export function useInvestorDetailsPart({
const username = useUsernameAvailability(form); const username = useUsernameAvailability(form);
const [isDone, setIsDone] = useState(false); const [isDone, setIsDone] = useState(false);
const { errors, isSubmitting, isDirty } = form.formState; const { errors, isSubmitting, isDirty } = form.formState;
useLeaveGuard(isDirty && !isDone); useConfirmLeave(isDirty && !isDone);
const submit = form.handleSubmit(async (values) => { const submit = form.handleSubmit(async (values) => {
const { phone, registration } = useAuthFlowStore.getState(); const { phone, registration } = useAuthFlowStore.getState();

View File

@ -1,52 +0,0 @@
import { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
/** A plain click on a link to another page of this site, which the app would navigate to itself. */
function leavingHref(event: MouseEvent): string | null {
if (
event.defaultPrevented ||
event.button !== 0 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey
) {
return null;
}
const link =
event.target instanceof Element ? event.target.closest('a[href]') : null;
if (!(link instanceof HTMLAnchorElement) || link.target === '_blank') {
return null;
}
const url = new URL(link.href, window.location.href);
const here = window.location;
if (url.origin !== here.origin) return null;
return url.pathname === here.pathname ? null : url.href;
}
/**
* While step 4 holds unsent values, leaving asks first, with the browser's own prompt (R2 2.1):
* closing or reloading the tab, and following a link inside the app, such as the brand. The
* browser's back button is not asked about: Next.js has no way to hold a navigation back.
*/
export function useLeaveGuard(isDirty: boolean): void {
const { t } = useTranslation('auth');
const message = t('register.leave-confirm');
useEffect(() => {
if (!isDirty) return undefined;
const askOnUnload = (event: BeforeUnloadEvent) => event.preventDefault();
// Capture, so it runs before the app's own link handling and can stop it.
const askOnLink = (event: MouseEvent) => {
if (leavingHref(event) === null || window.confirm(message)) return;
event.preventDefault();
event.stopPropagation();
};
window.addEventListener('beforeunload', askOnUnload);
document.addEventListener('click', askOnLink, true);
return () => {
window.removeEventListener('beforeunload', askOnUnload);
document.removeEventListener('click', askOnLink, true);
};
}, [isDirty, message]);
}

View File

@ -26,6 +26,7 @@ export type { OwnChannelModel } from './models/own-channel';
export { export {
SHARE_CAPTION_MAX_LENGTH, SHARE_CAPTION_MAX_LENGTH,
useChannelShareSheet, useChannelShareSheet,
useDisplayLink,
useShareLink, useShareLink,
} from './models/share'; } from './models/share';
export type { export type {

View File

@ -1,5 +1,6 @@
export { SHARE_CAPTION_MAX_LENGTH } from './constants'; export { SHARE_CAPTION_MAX_LENGTH } from './constants';
export { useChannelShareSheet } from './use-channel-share-sheet'; export { useChannelShareSheet } from './use-channel-share-sheet';
export { useDisplayLink } from './use-display-link';
export { useShareLink } from './use-share-link'; export { useShareLink } from './use-share-link';
export type { export type {
ChannelShareSheetModel, ChannelShareSheetModel,

View File

@ -0,0 +1,18 @@
import { useSyncExternalStore } from 'react';
// The address never changes while the page is open: nothing to subscribe to.
const subscribe = () => () => undefined;
/**
* A path on this site as a share popover shows it, the host and the path without the scheme:
* `lumina.ir/@sara_gold/posts/1042`, the address `useShareLink` copies. Undefined in the server
* render, which can't know the host the visitor uses.
*/
export function useDisplayLink(path: string): string | undefined {
const host = useSyncExternalStore(
subscribe,
() => window.location.host,
() => '',
);
return host ? `${host}${path}` : undefined;
}

View File

@ -2,7 +2,7 @@ import { isHttpError } from '@lumina/libs/http';
import { toApiUrl } from '../../../../shared/utils'; import { toApiUrl } from '../../../../shared/utils';
import type { PublicTierEntity } from '../../../channel'; import type { PublicTierEntity } from '../../../channel';
import { toAccessConfirmationPayload } from '../../../transaction'; import { toAccessConfirmationPayload } from '../../../transaction/repositories/transaction';
import type { import type {
CheckoutResultEntity, CheckoutResultEntity,
PriceChangedDetailsEntity, PriceChangedDetailsEntity,

View File

@ -1,5 +1,5 @@
import { toApiUrl } from '../../../../shared/utils'; import { toApiUrl } from '../../../../shared/utils';
import { toPostPayload } from '../../../post'; import { toPostPayload } from '../../../post/repositories/post';
import type { import type {
FeedCreatorEntity, FeedCreatorEntity,
FeedItemEntity, FeedItemEntity,

View File

@ -6,6 +6,7 @@ import { useTranslation } from 'react-i18next';
import { ROUTES } from '../../../../app/navigation/navigation'; import { ROUTES } from '../../../../app/navigation/navigation';
import { showActionError } from '../../../../shared/utils'; import { showActionError } from '../../../../shared/utils';
import { channelRepository } from '../../../channel'; import { channelRepository } from '../../../channel';
import { referralKeys } from '../../../referral';
import { REACTIVATE_PARAM } from '../../../subscription'; import { REACTIVATE_PARAM } from '../../../subscription';
import { import {
notificationKeys, notificationKeys,
@ -74,6 +75,16 @@ export function useNotificationCentre(): NotificationCentreModel {
gcTime: 0, gcTime: 0,
}); });
const hasUnread = inbox.data.unreadCount > 0; const hasUnread = inbox.data.unreadCount > 0;
// The team's answer to a capacity request (J10-2): the invite-code card reads again, so it shows
// the new capacity or the decline wherever it is mounted next.
const hasCapacityResult = inbox.data.items.some(
(item) => item.type === 'capacity_request_result' && !item.read,
);
useEffect(() => {
if (!hasCapacityResult) return;
void queryClient.invalidateQueries({ queryKey: referralKeys.card() });
}, [hasCapacityResult, queryClient]);
useEffect(() => { useEffect(() => {
if (markedRead.current || !hasUnread) return; if (markedRead.current || !hasUnread) return;

View File

@ -1,7 +1,7 @@
import { valibotResolver } from '@hookform/resolvers/valibot'; import { valibotResolver } from '@hookform/resolvers/valibot';
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 { 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 { useEffect, useEffectEvent, useRef, useState } from 'react';
import { useFieldArray, useForm, useWatch } from 'react-hook-form'; import { useFieldArray, useForm, useWatch } from 'react-hook-form';
@ -274,7 +274,6 @@ export function usePredictionComposerPage({
errors.root?.chart && t('composer.fields.chart'), errors.root?.chart && t('composer.fields.chart'),
].filter((label): label is string => typeof label === 'string'); ].filter((label): label is string => typeof label === 'string');
const list = (labels: string[]) => labels.join('، ');
const reason = invalid.length const reason = invalid.length
? t('composer.invalid', { fields: list(invalid) }) ? t('composer.invalid', { fields: list(invalid) })
: missing.length : missing.length

View File

@ -1,5 +1,5 @@
import { toPostPayload } from '../../../post'; import type { PostEntity } from '../../../post/entities/post';
import type { PostEntity } from '../../../post'; import { toPostPayload } from '../../../post/repositories/post';
import type { import type {
CloseQuotePayload, CloseQuotePayload,
CloseQuoteResponseDto, CloseQuoteResponseDto,

View File

@ -1,5 +1,5 @@
import { toPostPayload } from '../../../post'; import { toPostPayload } from '../../../post/repositories/post';
import type { PostPayload } from '../../../post'; import type { PostPayload } from '../../../post/repositories/post';
import { predictionHttp } from '../../http'; import { predictionHttp } from '../../http';
import { PREDICTION_ENDPOINTS } from './constants'; import { PREDICTION_ENDPOINTS } from './constants';
import { import {

View File

@ -2,8 +2,8 @@ import {
toCheckoutError, toCheckoutError,
toCheckoutResultPayload, toCheckoutResultPayload,
toPriceChangedPayload, toPriceChangedPayload,
} from '../../../checkout'; } from '../../../checkout/repositories/checkout';
import type { CheckoutResultPayload } from '../../../checkout'; import type { CheckoutResultPayload } from '../../../checkout/repositories/checkout';
import { subscriptionHttp } from '../../http'; import { subscriptionHttp } from '../../http';
import { SUBSCRIPTION_ENDPOINTS } from './constants'; import { SUBSCRIPTION_ENDPOINTS } from './constants';
import { import {

View File

@ -1,5 +1,5 @@
import { toAccountPayload } from '../../../auth'; import { toAccountPayload } from '../../../auth/repositories/account';
import { toCreatorProfilePayload } from '../../../profile'; import { toCreatorProfilePayload } from '../../../profile/repositories/profile';
import type { import type {
ResubmitVerificationArgs, ResubmitVerificationArgs,
ResubmitVerificationResponseDto, ResubmitVerificationResponseDto,

View File

@ -407,6 +407,25 @@ export type {
RefundLedgerItemPayload, RefundLedgerItemPayload,
SavePayoutAccountArgs, SavePayoutAccountArgs,
} from './features/finance'; } from './features/finance';
export {
IDENTITY_ANCHOR,
resubmitVerification,
useIdentityBlock,
VERIFICATION_ERROR_CODES,
VERIFICATION_EVENTS,
verificationErrorCode,
verificationRepository,
} from './features/verification';
export type {
IdentityBlockFormOutput,
IdentityBlockFormValues,
IdentityBlockModel,
ResubmitVerificationArgs,
UseIdentityBlockOptions,
VerificationErrorCode,
VerificationResubmittedEntity,
VerificationResubmittedPayload,
} from './features/verification';
export { export {
useAuthStore, useAuthStore,
useCurrentAccount, useCurrentAccount,

View File

@ -2,7 +2,7 @@ import type { CreatorStatsLabels } from '@lumina/island/organisms/creator-stats'
import type { LightboxLabels } from '@lumina/island/organisms/lightbox'; import type { LightboxLabels } from '@lumina/island/organisms/lightbox';
import type { PostCardLabels } from '@lumina/island/organisms/post-card'; import type { PostCardLabels } from '@lumina/island/organisms/post-card';
import type { PredictionCardLabels } from '@lumina/island/organisms/prediction-card'; import type { PredictionCardLabels } from '@lumina/island/organisms/prediction-card';
import { number } from '@lumina/tools/format'; import { list, number } from '@lumina/tools/format';
import type { ContentT } from './types'; import type { ContentT } from './types';
@ -27,6 +27,7 @@ export function postCardLabels(t: ContentT): PostCardLabels {
imageCount: (n) => t('post.image-count', { n }), imageCount: (n) => t('post.image-count', { n }),
share: t('post.share'), share: t('post.share'),
copyLink: t('post.copy-link'), copyLink: t('post.copy-link'),
close: t('post.close'),
owner: { owner: {
preview: t('post.owner.preview'), preview: t('post.owner.preview'),
edit: t('post.owner.edit'), edit: t('post.owner.edit'),
@ -110,7 +111,7 @@ export function predictionCardLabels(t: ContentT): PredictionCardLabels {
close && t('prediction.range.close', { price: close }), close && t('prediction.range.close', { price: close }),
]; ];
return t('prediction.range.label', { return t('prediction.range.label', {
values: values.filter(Boolean).join('، '), values: list(values.filter((value): value is string => Boolean(value))),
}); });
}, },
horizonElapsed: (duration) => t('prediction.horizon-elapsed', { duration }), horizonElapsed: (duration) => t('prediction.horizon-elapsed', { duration }),
@ -182,7 +183,7 @@ export function creatorStatsLabels(t: ContentT): CreatorStatsLabels {
trendWindow: (n) => t('stats.trend-window', { n }), trendWindow: (n) => t('stats.trend-window', { n }),
tally: (wins, total) => t('stats.tally', { wins, total }), tally: (wins, total) => t('stats.tally', { wins, total }),
curveLabel: (n, outcomes) => curveLabel: (n, outcomes) =>
t('stats.curve-label', { n, outcomes: outcomes.join('، ') }), t('stats.curve-label', { n, outcomes: list(outcomes) }),
newestPoint: (outcome) => t('stats.newest-point', { outcome }), newestPoint: (outcome) => t('stats.newest-point', { outcome }),
older: t('stats.older'), older: t('stats.older'),
newest: t('stats.newest'), newest: t('stats.newest'),

View File

@ -132,9 +132,7 @@
"pending": "حساب شما در انتظار تأیید است. پس از تأیید تیم پشتیبانی می‌توانید محتوا منتشر کنید.", "pending": "حساب شما در انتظار تأیید است. پس از تأیید تیم پشتیبانی می‌توانید محتوا منتشر کنید.",
"rejected": "احراز هویت شما تأیید نشد. برای انتشار پست، ابتدا اطلاعات هویتی خود را اصلاح و ارسال مجدد کنید.", "rejected": "احراز هویت شما تأیید نشد. برای انتشار پست، ابتدا اطلاعات هویتی خود را اصلاح و ارسال مجدد کنید.",
"rejected-reason": "احراز هویت شما تأیید نشد. دلیل: {{reason}}", "rejected-reason": "احراز هویت شما تأیید نشد. دلیل: {{reason}}",
"empty-title": "هنوز پستی منتشر نکرده‌اید.", "empty-title": "هنوز پستی منتشر نکرده‌اید",
"draft-title": "پیش‌نویس ذخیره شد",
"draft-description": "پس از تأیید احراز هویت می‌توانید منتشر کنید.",
"suspended": "حساب شما تعلیق شده است." "suspended": "حساب شما تعلیق شده است."
} }
} }

View File

@ -13,6 +13,7 @@
"image-count": "{{n}} تصویر", "image-count": "{{n}} تصویر",
"share": "اشتراک‌گذاری پست", "share": "اشتراک‌گذاری پست",
"copy-link": "کپی لینک", "copy-link": "کپی لینک",
"close": "بستن",
"owner": { "owner": {
"preview": "مشاهده به عنوان کاربر", "preview": "مشاهده به عنوان کاربر",
"edit": "ویرایش پست", "edit": "ویرایش پست",