feat(market): new-look shell — bars, bottom nav, desktop account menu, sign-out confirm, R14 back targets, network bar under the bars; channel header with display name and follower counts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Amiram_se 2026-10-09 17:38:43 +04:00
parent c6c1aa33b2
commit 0005b18d2a
81 changed files with 1471 additions and 542 deletions

View File

@ -13,9 +13,14 @@ import { useSettleAbandonedPayment } from './hooks/use-settle-abandoned-payment'
import type { AppShellProps } from './types';
/**
* The provider shell shared by bull and bear: the query client, i18n, the connection bar, the
* one toast region, and the viewer's session (read once per load in the browser). The app's root client component renders it after running the client
* bootstrap.
* The provider shell shared by bull and bear: the query client, i18n, the connection bar (drawn
* under each page's top bar or header by `NetworkBar`), the one toast region, and the viewer's
* session (read once per load in the browser). The app's root client component renders it after
* running the client bootstrap.
*
* The toasts sit above whatever the screen declares with island's `useToastPlacement`: the bottom
* nav (80px), a pinned footer (152px), the desktop app (32px, declared by bear's root layout), and
* low (24px) on a task page or over a sheet.
*/
export function AppShell({ queryClient, i18n, children }: AppShellProps) {
useSession(queryClient);
@ -29,8 +34,7 @@ export function AppShell({ queryClient, i18n, children }: AppShellProps) {
return (
<QueryClientProvider client={queryClient}>
<I18nextProvider i18n={i18n}>
<NetworkBoundary />
{children}
<NetworkBoundary>{children}</NetworkBoundary>
<Toaster
label={i18n.t('toaster')}
closeLabel={i18n.t('toast-close')}

View File

@ -8,25 +8,36 @@ import {
startTransition,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useTranslation } from 'react-i18next';
import { NETWORK_COPY, ONLINE_NOTICE_MS } from '../constants';
import type { ReconnectPhase } from '../types';
import { NetworkContext } from '../context';
import type {
NetworkBarView,
NetworkBoundaryProps,
ReconnectPhase,
} from '../types';
/**
* The network boundary: owns the connection bar for the whole app. Offline, it says so and the
* page stays readable. When the device comes back it refreshes the route and the queries once
* («در حال اتصال دوباره…»), then confirms for 3 seconds. It never re-submits anything.
*
* The bar draws under the page's sticky top bar or header (`NetworkBar`, which the bars render),
* so it pushes the page down and stays in view on scroll. A page with no such bar gets it here, at
* the top.
*/
export function NetworkBoundary() {
export function NetworkBoundary({ children }: NetworkBoundaryProps) {
const { t } = useTranslation();
const router = useRouter();
const queryClient = useQueryClient();
const isOnline = useOnline();
const [phase, setPhase] = useState<ReconnectPhase>('idle');
const [barCount, setBarCount] = useState(0);
const noticeTimer = useRef<ReturnType<typeof setTimeout>>(undefined);
// Started by the `online` event or the retry button.
@ -50,23 +61,41 @@ export function NetworkBoundary() {
useEffect(() => () => clearTimeout(noticeTimer.current), []);
const register = useCallback(() => {
setBarCount((count) => count + 1);
return () => setBarCount((count) => count - 1);
}, []);
// Offline only: the bar's retry, which waits for the device to report a connection.
const retry = useCallback(() => {
if (navigator.onLine) reconnect();
}, [reconnect]);
const status = isOnline ? (phase === 'idle' ? null : phase) : 'offline';
if (!status) return null;
const copy = NETWORK_COPY[status];
const view = useMemo<NetworkBarView | null>(() => {
if (!status) return null;
const copy = NETWORK_COPY[status];
return {
status,
title: t(copy.title),
description: copy.description && t(copy.description),
retryLabel: t('network.retry'),
};
}, [status, t]);
const value = useMemo(
() => ({ view, retry, register }),
[view, retry, register],
);
return (
<NetworkStatus
status={status}
title={t(copy.title)}
description={copy.description && t(copy.description)}
onRetry={
status === 'offline'
? () => {
if (navigator.onLine) reconnect();
}
: undefined
}
retryLabel={t('network.retry')}
/>
<NetworkContext value={value}>
{view && barCount === 0 && (
<NetworkStatus
{...view}
onRetry={view.status === 'offline' ? retry : undefined}
/>
)}
{children}
</NetworkContext>
);
}

View File

@ -0,0 +1,26 @@
'use client';
import { NetworkStatus } from '@lumina/island/molecules/network-status';
import { use, useEffect } from 'react';
import { NetworkContext } from '../../context';
/**
* The connection bar's place under a sticky top bar or header: render it inside the same sticky
* box, after the bar, so it pushes the page down and never covers the bar or hides under it on
* scroll. While one is mounted the app shell doesn't draw its own at the top.
*/
export function NetworkBar() {
const network = use(NetworkContext);
const register = network?.register;
useEffect(() => register?.(), [register]);
if (!network?.view) return null;
return (
<NetworkStatus
{...network.view}
onRetry={network.view.status === 'offline' ? network.retry : undefined}
contained
/>
);
}

View File

@ -0,0 +1 @@
export { NetworkBar } from './NetworkBar';

View File

@ -0,0 +1,6 @@
import { createContext } from 'react';
import type { NetworkContextValue } from './types';
/** The connection bar's state, shared from the one network boundary to the bar under the header. */
export const NetworkContext = createContext<NetworkContextValue | null>(null);

View File

@ -1,2 +1,3 @@
export { AppShell } from './AppShell';
export { NetworkBar } from './components/network-bar';
export type { AppShellProps } from './types';

View File

@ -1,3 +1,4 @@
import type { NetworkStatusProps } from '@lumina/island/molecules/network-status';
import type { QueryClient } from '@tanstack/react-query';
import type { i18n } from 'i18next';
import type { ReactNode } from 'react';
@ -12,3 +13,19 @@ export type AppShellProps = {
/** The connection bar's moment after the device comes back: refreshing, then confirmed. */
export type ReconnectPhase = 'idle' | 'reconnecting' | 'online';
/** The connection bar to draw, with its copy; `null` while there is nothing to say. */
export type NetworkBarView = Omit<
NetworkStatusProps,
'contained' | 'className' | 'onRetry'
>;
export type NetworkContextValue = {
view: NetworkBarView | null;
/** The offline bar's retry. */
retry: () => void;
/** A bar under a header counts itself while mounted; returns its removal. */
register: () => () => void;
};
export type NetworkBoundaryProps = { children: ReactNode };

View File

@ -1,10 +1,16 @@
import {
ACCOUNT_PATH,
CHANNEL_PREFIX,
CHANNEL_ROUTE_PREFIX,
DASHBOARD_PATH,
SEARCH_PATH,
} from './constants';
import type { NavTabName } from './types';
/** The path itself or a page under it. */
const isUnder = (pathname: string, path: string): boolean =>
pathname === path || pathname.startsWith(`${path}/`);
/**
* The creator's own channel or a page under it, by its public path or the route it is rewritten
* onto, depending on who reads it.
@ -13,21 +19,27 @@ export function isOwnChannelPath(
pathname: string,
ownUsername: string,
): boolean {
return [CHANNEL_PREFIX, CHANNEL_ROUTE_PREFIX].some((prefix) => {
const channel = `${prefix}${ownUsername}`;
return pathname === channel || pathname.startsWith(`${channel}/`);
});
return [CHANNEL_PREFIX, CHANNEL_ROUTE_PREFIX].some((prefix) =>
isUnder(pathname, `${prefix}${ownUsername}`),
);
}
/**
* The tab a page belongs to: the one it was pushed from. داشبورد for its own pages, کانال for the
* creator's own channel and its posts, and خانه for everything else (a channel, a post).
* The tab a page belongs to: the one it was pushed from. داشبورد for its own pages, جستجو for its
* page, کانال for the creator's own channel and its posts, and for a creator's حساب کاربری (J12-1b);
* خانه for everything else (a channel, a post, an investor's حساب کاربری).
*/
export function activeTab(
pathname: string,
ownUsername: string | null,
): NavTabName {
if (pathname.startsWith(DASHBOARD_PATH)) return 'dashboard';
if (ownUsername && isOwnChannelPath(pathname, ownUsername)) return 'channel';
if (isUnder(pathname, DASHBOARD_PATH)) return 'dashboard';
if (isUnder(pathname, SEARCH_PATH)) return 'search';
if (
ownUsername &&
(isOwnChannelPath(pathname, ownUsername) || isUnder(pathname, ACCOUNT_PATH))
) {
return 'channel';
}
return 'home';
}

View File

@ -0,0 +1,23 @@
import { createStore } from 'zustand/vanilla';
/** Where back goes on one page, learned in the browser by a part of it. */
export type BackTarget = { pathname: string; href: string };
/**
* The back target a page's part declared with `useBackTarget`, such as the payment result's
* channel once the payment has loaded. It names its page, so a target left behind by a page that
* is leaving never applies to the next one.
*/
export const backTargetStore = createStore<{ target: BackTarget | null }>()(
() => ({ target: null }),
);
/**
* Whether the page has a page of this site behind it in the tab's history. The Navigation API
* lists only this site's entries in a row, so a page opened from a link, a notification, another
* site or the bank has none; without it, any history counts.
*/
export function hasInAppHistory(): boolean {
const { navigation } = window as { navigation?: { canGoBack: boolean } };
return navigation ? navigation.canGoBack : window.history.length > 1;
}

View File

@ -0,0 +1,121 @@
'use client';
import { Avatar } from '@lumina/island/atoms/avatar';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { GridBox } from '@lumina/island/atoms/grid-box';
import { Typography } from '@lumina/island/atoms/typography';
import { ActionMenu } from '@lumina/island/molecules/action-menu';
import type { ActionMenuItem } from '@lumina/island/molecules/action-menu';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { SignOutConfirm } from '../../../screens/organisms/sign-out-confirm';
import { useIsStandalone } from '../../hooks/use-is-standalone';
import { ROUTES } from '../../navigation';
import type { AccountMenuProps } from './types';
/**
* The desktop header's avatar (J12-1c): it opens the account menu under it. Its header says whose
* account it is (the avatar, the member's own name and `@username`), then حساب کاربری, اطلاعات
* کاربری, تنظیمات اعلان‌ها and نصب اپلیکیشن (hidden in the installed app), and after a separator
* «خروج از حساب» in red, which asks first (J12-1d). Mobile links the avatar to حساب کاربری instead.
*/
export function AccountMenu({ account }: AccountMenuProps) {
const { t } = useTranslation();
const isStandalone = useIsStandalone();
const [isOpen, setIsOpen] = useState(false);
const [isSigningOut, setSigningOut] = useState(false);
// Only the member sees this menu, so it shows their own name; it falls back to the handle.
const name =
`${account.firstName} ${account.lastName}`.trim() || account.username;
const items: ActionMenuItem[] = [
{
href: ROUTES.account.root,
icon: 'user',
label: t('account-menu.account'),
},
{
href: ROUTES.account.profile,
icon: 'edit',
label: t('account-menu.profile'),
},
{
href: ROUTES.account.notifications,
icon: 'bell',
label: t('account-menu.notifications'),
},
...(isStandalone
? []
: [
{
href: ROUTES.account.install,
icon: 'download',
label: t('account-menu.install'),
} as const,
]),
{
onSelect: () => setSigningOut(true),
icon: 'log-out',
label: t('account-menu.sign-out'),
tone: 'danger',
separatorBefore: true,
},
];
return (
<>
<FlexBox display="inline-flex" className="relative">
<GridBox
tag="button"
type="button"
aria-label={t('nav.account')}
aria-haspopup="menu"
aria-expanded={isOpen}
onClick={() => setIsOpen((open) => !open)}
justifyItems="justify-items-center"
alignItems="items-center"
className="size-touch-target cursor-pointer rounded-full hover:bg-surface-sunken focus-visible:focus-ring"
>
<Avatar name={account.username} src={account.avatarUrl} size="sm" />
</GridBox>
<ActionMenu
open={isOpen}
onClose={() => setIsOpen(false)}
label={t('nav.account')}
placement="below"
className="min-w-65"
header={
<>
<Avatar name={account.username} src={account.avatarUrl} />
<FlexBox direction="flex-col" className="min-w-0">
<Typography
tag="span"
variant="inherit"
className="truncate text-[0.9375rem] leading-5.5 font-semibold"
>
{name}
</Typography>
<Typography
tag="bdi"
dir="ltr"
variant="caption"
color="secondary"
className="truncate text-end"
>
@{account.username}
</Typography>
</FlexBox>
</>
}
items={items}
/>
</FlexBox>
<SignOutConfirm
open={isSigningOut}
onClose={() => setSigningOut(false)}
layout="desktop"
/>
</>
);
}

View File

@ -0,0 +1,2 @@
export { AccountMenu } from './AccountMenu';
export type { AccountMenuProps } from './types';

View File

@ -0,0 +1,9 @@
export type AccountMenuProps = {
/** The signed-in member's account. */
account: {
username: string;
firstName: string;
lastName: string;
avatarUrl: string | null;
};
};

View File

@ -1,12 +1,14 @@
'use client';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { useToastPlacement } from '@lumina/island/molecules/toast';
import { Element } from '@lumina/island/primitives/element';
import { usePathname } from 'next/navigation';
import { useTranslation } from 'react-i18next';
import { useCurrentAccount, useViewerStatus } from '../../../../stores/auth';
import { activeTab } from '../../active-tab';
import { SEARCH_ENABLED } from '../../constants';
import { useIsOwnPreview } from '../../hooks/use-is-own-preview';
import { ROUTES } from '../../navigation';
import { PublishMenu } from '../publish-menu';
@ -14,9 +16,10 @@ import { NavTab } from './components/NavTab';
/**
* The mobile bottom nav of a signed-in person, on tab screens and the pages pushed from them, with
* the tab they came from active. An investor: خانه · داشبورد. A creator: کانال · «انتشار» ·
* داشبورد. A guest gets none; until the viewer is known nothing renders, and the bar is fixed, so
* the page doesn't move when it appears.
* the tab they came from active. An investor: خانه · جستجو · داشبورد (جستجو once
* `SEARCH_ENABLED`). A creator: کانال · «انتشار» · داشبورد. A guest gets none; until the viewer is
* known nothing renders, and the bar is fixed, so the page doesn't move when it appears. While it
* shows, toasts sit above it.
*/
export function BottomNav() {
const { t } = useTranslation();
@ -24,8 +27,10 @@ export function BottomNav() {
const account = useCurrentAccount();
const pathname = usePathname();
const isPreview = useIsOwnPreview();
const isShown = status === 'member' && account != null && !isPreview;
useToastPlacement('nav', isShown);
if (status !== 'member' || !account || isPreview) return null;
if (!isShown) return null;
const isCreator = account.role === 'creator';
const active = activeTab(pathname, isCreator ? account.username : null);
@ -59,6 +64,14 @@ export function BottomNav() {
<PublishMenu placement="nav" />
</FlexBox>
)}
{!isCreator && SEARCH_ENABLED && (
<NavTab
href={ROUTES.search}
icon="search"
label={t('nav.search')}
isActive={active === 'search'}
/>
)}
<NavTab
href={
isCreator ? ROUTES.dashboard.plans : ROUTES.dashboard.subscriptions

View File

@ -6,7 +6,7 @@ import NextLink from 'next/link';
import type { NavTabProps } from '../types';
/** One tab: its icon over its name, the active one in the brand colour. */
/** One tab: its icon over its name (12/18/600), the active one in the brand colour. */
export function NavTab({ href, icon, label, isActive }: NavTabProps) {
return (
<FlexBox
@ -17,16 +17,16 @@ export function NavTab({ href, icon, label, isActive }: NavTabProps) {
justifyContent="justify-center"
aria-current={isActive ? 'page' : undefined}
className={cn(
'min-w-touch-target flex-1 no-underline focus-visible:focus-ring',
'min-w-touch-target flex-1 gap-0.5 no-underline focus-visible:focus-ring',
isActive ? 'text-action-primary-text' : 'text-text-secondary',
)}
>
<Icon name={icon} size={24} />
<Typography
tag="span"
variant="micro"
variant="inherit"
color="inherit"
className="font-semibold"
className="text-[0.75rem] leading-4.5 font-semibold"
>
{label}
</Typography>

View File

@ -0,0 +1,62 @@
'use client';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Icon } from '@lumina/island/atoms/icon';
import { Typography } from '@lumina/island/atoms/typography';
import { cn } from '@lumina/island/tools/cn';
import NextLink from 'next/link';
import { useTranslation } from 'react-i18next';
import { useBack } from '../../hooks/use-back';
import type { DeskBackProps } from './types';
/** A 36px pill, 15/24/600, pulled to the column's start edge. */
const DESK_BACK_CLASS =
'min-h-9 self-start rounded-full ps-2 pe-3 -ms-2 text-text-secondary no-underline transition-colors duration-120 ease-standard hover:bg-surface-sunken hover:text-text-primary focus-visible:focus-ring';
/**
* «بازگشت» on desktop (R14): its own row at the top of a pushed page's column, above the page's
* title. Every page opened from another page has it (an installed app has no browser back); tab
* roots don't. Back goes to the page behind it on this site, or the page's `parentHref` when it was
* opened on its own; a fixed `href` (an auth step, the payment result's channel) is a link.
*/
export function DeskBack({ label, ...options }: DeskBackProps) {
const { t } = useTranslation();
const action = useBack(options);
const content = (
<>
<Icon name="chevron-right" size={20} />
<Typography
tag="span"
variant="inherit"
color="inherit"
className="text-[0.9375rem] leading-6 font-semibold"
>
{label ?? t('nav.back')}
</Typography>
</>
);
return action.href ? (
<FlexBox
tag={NextLink}
href={action.href}
alignItems="items-center"
gap="gap-1"
className={DESK_BACK_CLASS}
>
{content}
</FlexBox>
) : (
<FlexBox
tag="button"
type="button"
onClick={action.onClick}
alignItems="items-center"
gap="gap-1"
className={cn(DESK_BACK_CLASS, 'cursor-pointer')}
>
{content}
</FlexBox>
);
}

View File

@ -0,0 +1,2 @@
export { DeskBack } from './DeskBack';
export type { DeskBackProps } from './types';

View File

@ -0,0 +1,6 @@
import type { BackOptions } from '../../types';
export type DeskBackProps = BackOptions & {
/** Its text; defaults to «بازگشت». */
label?: string;
};

View File

@ -1,9 +1,8 @@
'use client';
import { Avatar } from '@lumina/island/atoms/avatar';
import { Button } from '@lumina/island/atoms/button';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { GridBox } from '@lumina/island/atoms/grid-box';
import { Icon } from '@lumina/island/atoms/icon';
import { Typography } from '@lumina/island/atoms/typography';
import { Element } from '@lumina/island/primitives/element';
import NextLink from 'next/link';
@ -11,20 +10,25 @@ import { usePathname } from 'next/navigation';
import { useTranslation } from 'react-i18next';
import { useCurrentAccount, useViewerStatus } from '../../../../stores/auth';
import { NetworkBar } from '../../../app-shell/components/network-bar';
import { SupportEntry } from '../../../screens/organisms/support-entry';
import { activeTab } from '../../active-tab';
import { SEARCH_ENABLED } from '../../constants';
import { useHomeHref } from '../../hooks/use-home-href';
import { loginRoute, ROUTES } from '../../navigation';
import { AccountMenu } from '../account-menu';
import { NotificationBell } from '../notification-bell';
import { PublishMenu } from '../publish-menu';
import { HeaderNavLink } from './components/HeaderNavLink';
/**
* The desktop header on every main page: the brand, the nav, then support, the bell and the
* account at the end. An investor's nav is خانه · داشبورد; a creator's is کانال · داشبورد, with
* «انتشار» before support. A guest sees only the brand, support and «ورود/ثبت‌نام», which returns
* here. The brand goes home, or to a creator's own channel. Who is looking is known only in the
* browser; until then the guest's end holds its place.
* The desktop header on every main page: the brand (21/700), the nav, an investor's search field
* (once `SEARCH_ENABLED`, not on جستجو itself), then support, the bell and the account menu at the
* end. An investor's nav is خانه · داشبورد; a creator's is کانال · داشبورد, with «انتشار» before
* support. A guest sees only the brand, support and «ورود/ثبت‌نام» (secondary), which returns here.
* The brand goes home, or to a creator's own channel. Who is looking is known only in the browser;
* until then the guest's end holds its place. The connection bar draws under it, in the same
* sticky box.
*/
export function DesktopHeader() {
const { t } = useTranslation();
@ -34,88 +38,103 @@ export function DesktopHeader() {
const isCreator = account?.role === 'creator';
const active = activeTab(pathname, isCreator ? account.username : null);
const homeHref = useHomeHref();
const member = status === 'member' ? account : null;
return (
<FlexBox
tag="header"
alignItems="items-center"
gap="gap-8"
className="sticky top-0 z-sticky min-h-16 border-b border-border-subtle bg-surface ps-8 pe-6"
>
<Typography
tag={NextLink}
// Straight to the viewer's home (a creator's is their channel, a guest's the landing), so
// there is no خانه to bounce off.
href={homeHref}
aria-label={t('nav.brand-home')}
variant="heading-sm"
color="brand"
className="rounded-xs no-underline focus-visible:focus-ring"
<FlexBox direction="flex-col" className="sticky top-0 z-sticky">
<FlexBox
tag="header"
alignItems="items-center"
gap="gap-8"
className="min-h-16 border-b border-border-subtle bg-surface ps-8 pe-6"
>
{t('nav.brand')}
</Typography>
{status === 'member' && account && (
<FlexBox
tag="nav"
aria-label={t('nav.label')}
alignItems="items-center"
gap="gap-1"
<Typography
tag={NextLink}
// Straight to the viewer's home (a creator's is their channel, a guest's the landing), so
// there is no خانه to bounce off.
href={homeHref}
aria-label={t('nav.brand-home')}
variant="heading-md"
className="rounded-xs leading-7.5 whitespace-nowrap no-underline focus-visible:focus-ring"
>
{isCreator ? (
{t('nav.brand')}
</Typography>
{member && (
<FlexBox
tag="nav"
aria-label={t('nav.label')}
alignItems="items-center"
gap="gap-1"
>
{isCreator ? (
<HeaderNavLink
href={ROUTES.channel(member.username)}
label={t('nav.channel')}
isActive={active === 'channel'}
/>
) : (
<HeaderNavLink
href={ROUTES.home}
label={t('nav.home')}
isActive={active === 'home'}
/>
)}
<HeaderNavLink
href={ROUTES.channel(account.username)}
label={t('nav.channel')}
isActive={active === 'channel'}
href={
isCreator
? ROUTES.dashboard.plans
: ROUTES.dashboard.subscriptions
}
label={t('nav.dashboard')}
isActive={active === 'dashboard'}
/>
) : (
<HeaderNavLink
href={ROUTES.home}
label={t('nav.home')}
isActive={active === 'home'}
</FlexBox>
)}
{SEARCH_ENABLED && member && !isCreator && active !== 'search' && (
<FlexBox
tag={NextLink}
href={ROUTES.search}
alignItems="items-center"
gap="gap-2"
className="h-10 min-w-0 basis-95 rounded-full border border-border-default bg-surface-sunken px-3.5 no-underline focus-visible:focus-ring"
>
<Icon
name="search"
size={20}
className="flex-none text-text-secondary"
/>
<Typography
tag="span"
variant="body-sm"
color="tertiary"
className="truncate"
>
{t('nav.search-field')}
</Typography>
</FlexBox>
)}
<FlexBox alignItems="items-center" gap="gap-2" className="ms-auto">
{isCreator && <PublishMenu placement="header" />}
<SupportEntry trigger="icon" placement="popover" />
{member && <NotificationBell placement="panel" />}
{status === 'unknown' && (
// Most visitors are guests: their «ورود/ثبت‌نام» holds the end's place, unseen, so it
// doesn't move when the session arrives.
<Element tag="span" aria-hidden className="invisible flex-none">
<Button variant="secondary" tabIndex={-1}>
{t('nav.login')}
</Button>
</Element>
)}
<HeaderNavLink
href={
isCreator
? ROUTES.dashboard.plans
: ROUTES.dashboard.subscriptions
}
label={t('nav.dashboard')}
isActive={active === 'dashboard'}
/>
</FlexBox>
)}
<FlexBox alignItems="items-center" gap="gap-2" className="ms-auto">
{isCreator && <PublishMenu placement="header" />}
<SupportEntry trigger="icon" placement="popover" />
{status === 'member' && <NotificationBell placement="panel" />}
{status === 'unknown' && (
// Most visitors are guests: their «ورود/ثبت‌نام» holds the end's place, unseen, so it
// doesn't move when the session arrives.
<Element tag="span" aria-hidden className="invisible flex-none">
<Button variant="primary" tabIndex={-1}>
{status === 'guest' && (
<Button variant="secondary" href={loginRoute(pathname)}>
{t('nav.login')}
</Button>
</Element>
)}
{status === 'guest' && (
<Button variant="primary" href={loginRoute(pathname)}>
{t('nav.login')}
</Button>
)}
{status === 'member' && account && (
<GridBox
tag={NextLink}
href={ROUTES.account}
aria-label={t('nav.account')}
justifyItems="justify-items-center"
alignItems="items-center"
className="size-touch-target rounded-full focus-visible:focus-ring"
>
<Avatar name={account.username} src={account.avatarUrl} size="sm" />
</GridBox>
)}
)}
{member && <AccountMenu account={member} />}
</FlexBox>
</FlexBox>
<NetworkBar />
</FlexBox>
);
}

View File

@ -4,16 +4,17 @@ import NextLink from 'next/link';
import type { HeaderNavLinkProps } from '../types';
/** A 40px pill in the header nav; the active one on the brand's subtle fill. */
/** A 40px pill in the header nav, 15/600; the active one on the brand's subtle fill. */
export function HeaderNavLink({ href, label, isActive }: HeaderNavLinkProps) {
return (
<Typography
tag={NextLink}
href={href}
variant="inherit"
color={isActive ? 'brand' : 'secondary'}
aria-current={isActive ? 'page' : undefined}
className={cn(
'inline-block rounded-full px-4 py-1.5 font-semibold 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-[0.9375rem] 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',
)}
>

View File

@ -2,21 +2,19 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Typography } from '@lumina/island/atoms/typography';
import { useTranslation } from 'react-i18next';
import { BackButton } from '../mobile-top-bar/components/BackButton';
import { DeskBack } from '../desk-back';
import type { DesktopPageTitleProps } from './types';
/**
* A pushed page's heading on desktop, at the top of its column: back, then the page's name (U9
* ۹.۱, S5 ۲.۱). Back returns where the person came from, or home for a page opened on its own.
* A pushed page's heading on desktop, at the top of its column (U9 ۹.۱, S5 ۲.۱): «بازگشت» on its
* own row (R14), then the page's name. Back returns where the person came from on this site, or
* to the page's parent (home by default) for a page opened on its own.
*/
export function DesktopPageTitle({ title, onBack }: DesktopPageTitleProps) {
const { t } = useTranslation();
export function DesktopPageTitle({ title, ...back }: DesktopPageTitleProps) {
return (
<FlexBox alignItems="items-center" gap="gap-1" className="-ms-2">
<BackButton label={t('nav.back')} onBack={onBack} />
<FlexBox direction="flex-col" alignItems="items-start" gap="gap-4">
<DeskBack {...back} />
<Typography tag="h1" variant="heading-md">
{title}
</Typography>

View File

@ -1,6 +1,6 @@
export type DesktopPageTitleProps = {
import type { BackOptions } from '../../types';
export type DesktopPageTitleProps = BackOptions & {
/** The page's name: «خرید اشتراک». */
title: string;
/** Back asks first; without it back goes back. */
onBack?: () => void;
};

View File

@ -1,7 +1,6 @@
'use client';
import { Avatar } from '@lumina/island/atoms/avatar';
import { Button } from '@lumina/island/atoms/button';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { GridBox } from '@lumina/island/atoms/grid-box';
import { Skeleton } from '@lumina/island/atoms/skeleton';
@ -13,6 +12,7 @@ import { usePathname } from 'next/navigation';
import { useTranslation } from 'react-i18next';
import { useCurrentAccount, useViewerStatus } from '../../../../stores/auth';
import { NetworkBar } from '../../../app-shell/components/network-bar';
import { SupportEntry } from '../../../screens/organisms/support-entry';
import { useHomeHref } from '../../hooks/use-home-href';
import { useIsOwnPreview } from '../../hooks/use-is-own-preview';
@ -22,16 +22,24 @@ import { BackButton } from './components/BackButton';
import { Brand } from './components/Brand';
import type { MobileTopBarProps } from './types';
/** The guest's «ورود/ثبت‌نام»: an indigo text link, 15/600, 44px tall. */
const LOGIN_LINK_CLASS =
'rounded-full px-2 text-[0.9375rem] 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 and support. A guest sees
* the logged-out bar instead (the brand, support and «ورود/ثبت‌نام», which returns here). A tab's
* main screen, and a creator on their own tab, get the tab bar: the brand, the tab's name centred
* when it has one («داشبورد»; خانه has none), support and the member's account (Main A, U8 ۴.۱).
* Who is looking is known only in the browser, so the server and the first browser render show a
* tab's bar with its brand and name, and a pushed page's bar without its start; both hold the
* guest's «ورود/ثبت‌نام» unseen at the end, since most visitors are guests. A creator's brand goes to their own channel, their home tab, and a
* guest's to the landing. A pushed page with nothing behind it drops back (`back={false}`). The tab
* bar carries the bell between support and the account (U5 ۲.۲); a pushed bar has neither.
* The mobile top bar of a page pushed from a tab: back, the page's name (18/30) and support. A
* guest sees back, the brand, support and «ورود/ثبت‌نام», which returns here. A tab's main screen,
* and a creator on their own tab, get the tab bar: the brand, the tab's name centred (16/26) when
* it has one («داشبورد»; خانه has none), support, the bell and the member's account, which opens
* حساب کاربری (Main A, U8 ۴.۱, U5 ۲.۲). Who is looking is known only in the browser, so the server
* and the first browser render show a tab's bar with its brand and name, and a pushed page's bar
* with back and a skeleton for its name; both hold the guest's «ورود/ثبت‌نام» unseen at the end,
* since most visitors are guests. A creator's brand goes to their own channel, a guest's to the
* landing.
*
* Every page opened from another page has back (R14): to the page behind it on this site, or to
* `parentHref` (home by default) when it was opened on its own; `backHref` is a fixed target.
* The connection bar draws under the bar, in the same sticky box.
*/
export function MobileTopBar({
title,
@ -39,6 +47,8 @@ export function MobileTopBar({
tabOwnerId,
onBack,
back = true,
backHref,
parentHref,
previewTitle,
}: MobileTopBarProps) {
const { t } = useTranslation();
@ -49,75 +59,101 @@ export function MobileTopBar({
const homeHref = useHomeHref();
// While the viewer is unknown, account is null, so only a tab's main screen gets the tab bar.
const isTabBar = isTab || (account != null && account.id === tabOwnerId);
// The creator's own tab can't tell yet whether its bar is the tab bar, so it holds back too.
const isUndecided = status === 'unknown' && tabOwnerId != null;
const hasBack = !isTabBar && back && !isUndecided;
return (
<FlexBox
tag="header"
alignItems="items-center"
gap="gap-1"
className="sticky top-0 z-sticky min-h-14 border-b border-border-subtle bg-surface px-2"
>
{status === 'unknown' && !isTabBar && (
<FlexBox className="flex-1 px-2">
<Skeleton width="6rem" />
</FlexBox>
)}
{(status === 'guest' || isTabBar) && (
<Brand
label={t('nav.brand')}
homeLabel={t('nav.brand-home')}
href={homeHref}
/>
)}
{status !== 'guest' && isTab && title && (
<Typography
tag="span"
variant="heading-sm"
className="pointer-events-none absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 whitespace-nowrap"
>
{title}
</Typography>
)}
{status === 'member' && !isTabBar && (
<>
{back && <BackButton label={t('nav.back')} onBack={onBack} />}
<FlexBox direction="flex-col" className="sticky top-0 z-sticky">
<FlexBox
tag="header"
alignItems="items-center"
gap="gap-1"
className={cn(
'relative min-h-14 border-b border-border-subtle bg-surface pe-2',
hasBack ? 'ps-1' : 'ps-4',
)}
>
{hasBack && (
<BackButton
label={t('nav.back')}
href={backHref}
parentHref={parentHref}
onBack={onBack}
/>
)}
{(status === 'guest' || isTabBar) && (
<Brand
label={t('nav.brand')}
homeLabel={t('nav.brand-home')}
href={homeHref}
/>
)}
{status === 'unknown' && !isTabBar && (
<FlexBox className="flex-1">
<Skeleton width="6rem" />
</FlexBox>
)}
{status !== 'guest' && isTab && title && (
<Typography
tag="span"
variant="heading-sm"
className={cn('flex-1 truncate', !back && 'ps-2')}
variant="body-md"
className="pointer-events-none absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 leading-6.5 font-semibold whitespace-nowrap"
>
{title}
</Typography>
)}
{status === 'member' && !isTabBar && (
<Typography
tag="span"
variant="body-lg"
className="min-w-0 flex-1 truncate leading-7.5 font-semibold"
>
{isPreview && previewTitle ? previewTitle : title}
</Typography>
</>
)}
<SupportEntry trigger="icon" placement="bottom" />
{status === 'member' && isTabBar && <NotificationBell placement="link" />}
{status === 'guest' && (
<Button variant="ghost" size="sm" href={loginRoute(pathname)}>
{t('nav.login')}
</Button>
)}
{status === 'unknown' && (
// Most visitors are guests: their «ورود/ثبت‌نام» holds the end's place, unseen, so the bar
// doesn't move when the session arrives.
<Element tag="span" aria-hidden className="invisible flex-none">
<Button variant="ghost" size="sm" tabIndex={-1}>
)}
<SupportEntry trigger="icon" placement="bottom" />
{status === 'member' && isTabBar && (
<NotificationBell placement="link" />
)}
{status === 'guest' && (
<Typography
tag={NextLink}
href={loginRoute(pathname)}
variant="inherit"
color="link"
className={LOGIN_LINK_CLASS}
>
{t('nav.login')}
</Button>
</Element>
)}
{status === 'member' && isTabBar && account && (
<GridBox
tag={NextLink}
href={ROUTES.account}
aria-label={t('nav.account')}
justifyItems="justify-items-center"
alignItems="items-center"
className="size-touch-target rounded-full focus-visible:focus-ring"
>
<Avatar name={account.username} src={account.avatarUrl} size="sm" />
</GridBox>
)}
</Typography>
)}
{status === 'unknown' && (
// Most visitors are guests: their «ورود/ثبت‌نام» holds the end's place, unseen, so the bar
// doesn't move when the session arrives.
<Element tag="span" aria-hidden className="invisible flex-none">
<Typography
tag="span"
variant="inherit"
className={LOGIN_LINK_CLASS}
>
{t('nav.login')}
</Typography>
</Element>
)}
{status === 'member' && isTabBar && account && (
<GridBox
tag={NextLink}
href={ROUTES.account.root}
aria-label={t('nav.account')}
justifyItems="justify-items-center"
alignItems="items-center"
className="size-touch-target rounded-full focus-visible:focus-ring"
>
<Avatar name={account.username} src={account.avatarUrl} size="sm" />
</GridBox>
)}
</FlexBox>
<NetworkBar />
</FlexBox>
);
}

View File

@ -1,28 +1,30 @@
'use client';
import { Button } from '@lumina/island/atoms/button';
import { useRouter } from 'next/navigation';
import { useHomeHref } from '../../../hooks/use-home-href';
import { useBack } from '../../../hooks/use-back';
import type { BackButtonProps } from '../types';
/**
* Back to where the person came from; a page opened on its own (a shared link) goes home. A page
* that may lose work passes `onBack` and asks first.
* The bar's back (R14): to the page behind it on this site, or the page's parent when it was
* opened on its own (a link, a notification). A fixed `href` is a link; a page that may lose work
* passes `onBack` and asks first.
*/
export function BackButton({ label, onBack }: BackButtonProps) {
const router = useRouter();
const homeHref = useHomeHref();
return (
export function BackButton({ label, ...options }: BackButtonProps) {
const action = useBack(options);
return action.href ? (
<Button
variant="ghost"
icon="chevron-right"
label={label}
onClick={() => {
if (onBack) onBack();
else if (window.history.length > 1) router.back();
else router.push(homeHref);
}}
href={action.href}
/>
) : (
<Button
variant="ghost"
icon="chevron-right"
label={label}
onClick={action.onClick}
/>
);
}

View File

@ -5,17 +5,16 @@ import NextLink from 'next/link';
import { ROUTES } from '../../../navigation';
import type { BrandProps } from '../types';
/** «لومینا», linking home (a creator's is their channel); it takes the bar's free space. */
/** «لومینا» (21/30/700), linking home (a creator's is their channel); it takes the bar's free space. */
export function Brand({ label, homeLabel, href = ROUTES.home }: BrandProps) {
return (
<FlexBox className="flex-1 px-2">
<FlexBox className="min-w-0 flex-1">
<Typography
tag={NextLink}
href={href}
aria-label={homeLabel}
variant="heading-sm"
color="brand"
className="rounded-xs no-underline focus-visible:focus-ring"
variant="heading-md"
className="rounded-xs leading-7.5 whitespace-nowrap no-underline focus-visible:focus-ring"
>
{label}
</Typography>

View File

@ -1,4 +1,6 @@
/** A page pushed from a tab: back and its name for a member. */
import type { BackOptions } from '../../types';
/** A page pushed from a tab: back and its name for a member; back and the brand for a guest. */
type PushedBarProps = {
/** The page's name: «کانال», «پست». */
title: string;
@ -11,10 +13,14 @@ type PushedBarProps = {
/** Back asks first (a composer with unsaved text); without it back goes back. */
onBack?: () => void;
/**
* `false`: nothing behind the page to go back to, such as the payment result with the bank behind
* it (U10 ۹.۱), so the bar has only the name and support.
* `false`: nothing behind the page to go back to, so the bar has only the name and support. Most
* pages keep back (R14): give the payment result a `backHref` instead.
*/
back?: boolean;
/** A fixed back target, followed whatever the history: the previous step, the paid channel. */
backHref?: BackOptions['href'];
/** Where back goes when the page was opened on its own (a link, a notification); home by default. */
parentHref?: BackOptions['parentHref'];
/** The title while the page is in the creator's preview (`?preview`): «پیش‌نمایش پست». */
previewTitle?: string;
};
@ -27,12 +33,14 @@ type TabBarProps = {
tabOwnerId?: never;
onBack?: never;
back?: never;
backHref?: never;
parentHref?: never;
previewTitle?: never;
};
export type MobileTopBarProps = PushedBarProps | TabBarProps;
export type BackButtonProps = { label: string; onBack?: () => void };
export type BackButtonProps = BackOptions & { label: string };
export type BrandProps = {
/** «لومینا». */

View File

@ -3,6 +3,7 @@
import { Button } from '@lumina/island/atoms/button';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { ActionMenu } from '@lumina/island/molecules/action-menu';
import { Element } from '@lumina/island/primitives/element';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
@ -17,7 +18,9 @@ const isBlocked = (standing: string): standing is BlockedStanding =>
/**
* «انتشار» (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.
* 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
* nav; a press on the scrim closes it.
*/
export function PublishMenu({ placement }: PublishMenuProps) {
const { t } = useTranslation();
@ -28,43 +31,56 @@ export function PublishMenu({ placement }: PublishMenuProps) {
const blocked = isBlocked(standing) ? standing : null;
return (
<FlexBox display="inline-flex" className="relative">
<Button
variant="primary"
icon={isOpen ? 'close' : 'plus'}
aria-haspopup={blocked ? 'dialog' : 'menu'}
aria-expanded={blocked ? isExplaining : isOpen}
frozen={blocked !== null}
// The press explains why, in a dialog rather than a tooltip.
pressableWhenFrozen
onClick={() =>
blocked ? setIsExplaining(true) : setIsOpen((open) => !open)
}
>
{t('publish.menu')}
</Button>
<ActionMenu
open={isOpen}
onClose={() => setIsOpen(false)}
label={t('publish.menu')}
placement={placement === 'nav' ? 'above' : 'below'}
items={[
{ href: ROUTES.composePost, icon: 'edit', label: t('publish.post') },
{
href: ROUTES.composePrediction,
icon: 'trend-up',
label: t('publish.prediction'),
},
]}
/>
{blocked && (
<BlockedPublishDialog
standing={blocked}
open={isExplaining}
onClose={() => setIsExplaining(false)}
layout={placement === 'nav' ? 'mobile' : 'desktop'}
<>
{placement === 'nav' && isOpen && (
// Outside the trigger's box, so a press on it counts as outside and closes the menu.
<Element
aria-hidden
className="fixed inset-x-0 top-0 bottom-16 bg-scrim/33"
/>
)}
</FlexBox>
<FlexBox display="inline-flex" className="relative">
<Button
variant="primary"
icon={isOpen ? 'close' : 'plus'}
aria-haspopup={blocked ? 'dialog' : 'menu'}
aria-expanded={blocked ? isExplaining : isOpen}
frozen={blocked !== null}
// The press explains why, in a dialog rather than a tooltip.
pressableWhenFrozen
onClick={() =>
blocked ? setIsExplaining(true) : setIsOpen((open) => !open)
}
>
{t('publish.menu')}
</Button>
<ActionMenu
open={isOpen}
onClose={() => setIsOpen(false)}
label={t('publish.menu')}
placement={placement === 'nav' ? 'above' : 'below'}
items={[
{
href: ROUTES.composePost,
icon: 'edit',
label: t('publish.post'),
},
{
href: ROUTES.composePrediction,
icon: 'trend-up',
label: t('publish.prediction'),
},
]}
/>
{blocked && (
<BlockedPublishDialog
standing={blocked}
open={isExplaining}
onClose={() => setIsExplaining(false)}
layout={placement === 'nav' ? 'mobile' : 'desktop'}
/>
)}
</FlexBox>
</>
);
}

View File

@ -44,7 +44,7 @@ export function BlockedPublishDialog({
size={layout === 'mobile' ? 'lg' : 'md'}
/>
) : (
<Button variant="primary" size={size} block href={ROUTES.account}>
<Button variant="primary" size={size} block href={ROUTES.account.root}>
{t(`publish.${standing}.action`)}
</Button>
);

View File

@ -15,3 +15,15 @@ export const SUBSCRIBE_PARAM = 'subscribe';
/** The investor's dashboard and the creator's live under one path; it marks داشبورد active. */
export const DASHBOARD_PATH = '/dashboard';
/** حساب کاربری and its pages: they belong to the role's home tab (خانه, or a creator's کانال). */
export const ACCOUNT_PATH = '/account';
/** جستجو's path; it marks its tab active. */
export const SEARCH_PATH = '/search';
/**
* The investor's جستجو (the bottom nav's middle tab and the desktop header's search field). Off
* until the `/search` page exists (J04-4); turn it on in the commit that adds the page.
*/
export const SEARCH_ENABLED = false;

View File

@ -0,0 +1,33 @@
'use client';
import { usePathname } from 'next/navigation';
import { useEffect } from 'react';
import { useStore } from 'zustand';
import { backTargetStore } from '../back-target';
/**
* Declares where this page's back goes, for a part that learns it only in the browser, such as the
* payment result once it knows the channel. It wins over the bar's own target and the history while
* the part is on screen; `undefined` declares nothing.
*/
export function useBackTarget(href: string | undefined): void {
const pathname = usePathname();
useEffect(() => {
if (!href) return undefined;
const target = { pathname, href };
backTargetStore.setState({ target });
return () => {
if (backTargetStore.getState().target === target) {
backTargetStore.setState({ target: null });
}
};
}, [pathname, href]);
}
/** The back target a part of the current page declared, if any. */
export function useDeclaredBackTarget(): string | undefined {
const pathname = usePathname();
const target = useStore(backTargetStore, (state) => state.target);
return target?.pathname === pathname ? target.href : undefined;
}

View File

@ -0,0 +1,30 @@
'use client';
import { useRouter } from 'next/navigation';
import { hasInAppHistory } from '../back-target';
import type { BackAction, BackOptions } from '../types';
import { useDeclaredBackTarget } from './use-back-target';
import { useHomeHref } from './use-home-href';
/**
* What back does on a page (R14), for the mobile bar's back and the desktop «بازگشت». A page that
* may lose work asks first (`onBack`). A target a part declared, or the page's own `href`, is a
* link. Otherwise back returns to the page behind it on this site, and a page opened on its own
* (a link, a notification) goes to its `parentHref`, or home.
*/
export function useBack({ href, parentHref, onBack }: BackOptions): BackAction {
const router = useRouter();
const homeHref = useHomeHref();
const declared = useDeclaredBackTarget();
const target = declared ?? href;
if (target && !onBack) return { href: target };
return {
onClick: () => {
if (onBack) onBack();
else if (hasInAppHistory()) router.back();
else router.push(parentHref ?? homeHref);
},
};
}

View File

@ -0,0 +1,27 @@
'use client';
import { useSyncExternalStore } from 'react';
const STANDALONE_QUERY = '(display-mode: standalone)';
function subscribe(onChange: () => void) {
const query = window.matchMedia(STANDALONE_QUERY);
query.addEventListener('change', onChange);
return () => query.removeEventListener('change', onChange);
}
/** iOS Safari says so on `navigator.standalone` instead of the display mode. */
const getSnapshot = () =>
window.matchMedia(STANDALONE_QUERY).matches ||
(navigator as { standalone?: boolean }).standalone === true;
/** The server can't know; a browser tab is the common case. */
const getServerSnapshot = () => false;
/**
* Whether the app runs installed (standalone display mode), where «نصب اپلیکیشن» is hidden and
* in-app back is the only way back.
*/
export function useIsStandalone(): boolean {
return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}

View File

@ -1,12 +1,23 @@
export { AccountMenu } from './components/account-menu';
export type { AccountMenuProps } from './components/account-menu';
export { BottomNav } from './components/bottom-nav';
export { DeskBack } from './components/desk-back';
export type { DeskBackProps } from './components/desk-back';
export { DesktopHeader } from './components/desktop-header';
export { DesktopPageTitle } from './components/desktop-page-title';
export { MobileTopBar } from './components/mobile-top-bar';
export type { DesktopPageTitleProps } from './components/desktop-page-title';
export type { MobileTopBarProps } from './components/mobile-top-bar';
export { CHANNEL_PREFIX, PREVIEW_PARAM, ROLE_PARAM } from './constants';
export {
CHANNEL_PREFIX,
PREVIEW_PARAM,
ROLE_PARAM,
SEARCH_ENABLED,
} from './constants';
export { useAuthRoutes } from './hooks/use-auth-routes';
export { useBackTarget } from './hooks/use-back-target';
export { useHomeHref } from './hooks/use-home-href';
export { useIsStandalone } from './hooks/use-is-standalone';
export {
homeRoute,
loginRoute,
@ -16,4 +27,4 @@ export {
withReturnPath,
} from './navigation';
export { safeReturnPath } from './return-path';
export type { AuthRoutes } from './types';
export type { AuthRoutes, BackOptions } from './types';

View File

@ -1,5 +1,11 @@
import type { SignedInViewer, UserRole } from '../../features/auth';
import { CHANNEL_PREFIX, ROLE_PARAM, SUBSCRIBE_PARAM } from './constants';
import {
ACCOUNT_PATH,
CHANNEL_PREFIX,
ROLE_PARAM,
SEARCH_PATH,
SUBSCRIBE_PARAM,
} from './constants';
const channel = (username: string) =>
`${CHANNEL_PREFIX}${encodeURIComponent(username)}`;
@ -20,7 +26,15 @@ export const ROUTES = {
verify: '/auth/register/verify',
details: '/auth/register/details',
},
account: '/account',
/** حساب کاربری and its pages (J12). */
account: {
root: ACCOUNT_PATH,
profile: '/account/profile',
notifications: '/account/notifications',
install: '/account/install',
},
/** جستجو, the investor's analyst search (J04-4); its tab and the header field wait for `SEARCH_ENABLED`. */
search: SEARCH_PATH,
channel,
post: (username: string, id: string) =>
`${channel(username)}/posts/${encodeURIComponent(id)}`,

View File

@ -21,4 +21,28 @@ export type AuthRoutes = {
};
/** The bottom nav's and the desktop header's tabs; a page belongs to the one it was pushed from. */
export type NavTabName = 'home' | 'dashboard' | 'channel';
export type NavTabName = 'home' | 'search' | 'dashboard' | 'channel';
/**
* Where a page's back goes (R14), given by the page or its template. Every page opened from
* another page has back, on mobile and desktop; tab roots have none.
*/
export type BackOptions = {
/**
* A fixed target, followed as a link whatever the history: the previous auth step, or the
* payment result's channel, with the bank behind it.
*/
href?: string;
/**
* Where back goes when no page of this site is behind it (opened from a link or a notification):
* the page's parent, such as a post's channel or an account page's حساب کاربری. Defaults to home.
*/
parentHref?: string;
/** Back asks first, such as a composer with unsaved text. */
onBack?: () => void;
};
/** A link to a fixed target, or a press that goes back. */
export type BackAction =
| { href: string; onClick?: never }
| { href?: never; onClick: () => void };

View File

@ -5,6 +5,8 @@ import { Typography } from '@lumina/island/atoms/typography';
import { useTranslation } from 'react-i18next';
import { usePaymentResultPage } from '../../../../../../../../features/checkout';
import { useBackTarget } from '../../../../../../../navigation/hooks/use-back-target';
import { ROUTES } from '../../../../../../../navigation/navigation';
import { SupportEntry } from '../../../../../../organisms/support-entry';
import { ResultActions } from './components/ResultActions';
import { ResultFrame } from './components/ResultFrame';
@ -21,6 +23,9 @@ import type { PaymentResultProps } from './types';
export function PaymentResult({ paymentId, layout }: PaymentResultProps) {
const { t } = useTranslation('payment');
const { payment, kind, copyReference } = usePaymentResultPage({ paymentId });
// Back goes to the channel paid for (R14), not to the bank behind the page.
const username = payment?.creator.username;
useBackTarget(username ? ROUTES.channel(username) : undefined);
if (!payment || !kind) {
return (

View File

@ -1,16 +1,18 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Typography } from '@lumina/island/atoms/typography';
import { SectionHeading } from '@lumina/island/molecules/section-heading';
import { AnalystCard } from '@lumina/island/organisms/analyst-card';
import { Element } from '@lumina/island/primitives/element';
import { AnalystCard } from './components/AnalystCard';
import { ROUTES } from '../../../../navigation/navigation';
import { AnalystCarousel } from './components/AnalystCarousel';
import type { FeaturedAnalystsProps } from './types';
/**
* تحلیلگران: the analysts Lumina features, live, in the admin's order: no ranking and no «برترین».
* A swipe row on the phone, two then three cards with arrows from 720px, and a note under it on
* who chooses them and that past results promise nothing.
* who chooses them and that past results promise nothing. Each is island's AnalystCard, linking
* to the channel; a guest's landing has no follow button.
*/
export function FeaturedAnalysts({
titleId,
@ -38,7 +40,21 @@ export function FeaturedAnalysts({
tag="li"
className="w-4/5 max-w-80 flex-none snap-start tablet:w-[calc((100%-1rem)/2)] tablet:max-w-none desktop:w-[calc((100%-2rem)/3)]"
>
<AnalystCard creator={creator} labels={labels.card} />
<AnalystCard
analyst={{
username: creator.username,
displayName: creator.displayName,
avatar: creator.avatarUrl,
verified: creator.verified,
markets: creator.markets.map(
(market) => labels.card.marketNames[market],
),
bio: creator.bio,
stats: creator.stats,
}}
href={ROUTES.channel(creator.username)}
labels={labels.card}
/>
</FlexBox>
))}
</AnalystCarousel>

View File

@ -1,146 +0,0 @@
import { Avatar } from '@lumina/island/atoms/avatar';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { GridBox } from '@lumina/island/atoms/grid-box';
import { Icon } from '@lumina/island/atoms/icon';
import { Tag } from '@lumina/island/atoms/tag';
import { Typography } from '@lumina/island/atoms/typography';
import { Card } from '@lumina/island/molecules/card';
import { Element } from '@lumina/island/primitives/element';
import { number, percent, signedPercent } from '@lumina/tools/format';
import NextLink from 'next/link';
import { ROUTES } from '../../../../../navigation/navigation';
import type { AnalystCardProps } from '../types';
/**
* One featured analyst, linking to their public channel: avatar, name with the verified mark,
* @username, market tags, a two-line bio and three outcome tiles. Never follower or subscriber
* counts, or prices. Page-only: a second screen that needs it moves it into island first.
*/
export function AnalystCard({ creator, labels }: AnalystCardProps) {
const name = creator.displayName ?? `@${creator.username}`;
const roi = creator.stats.avgRoiPercent;
const stats = [
{
key: 'win-rate',
label: labels.winRate,
value: percent(creator.stats.winRate),
},
{
key: 'predictions',
label: labels.predictions,
value: number(creator.stats.totalPredictions),
},
{
key: 'avg-roi',
label: labels.avgRoi,
value: signedPercent(roi),
color: roi > 0 ? 'success' : roi < 0 ? 'danger' : 'primary',
},
] as const;
return (
<Card
tag={NextLink}
href={ROUTES.channel(creator.username)}
aria-label={labels.open(name)}
interactive
padding="none"
className="flex-1 no-underline"
>
<FlexBox direction="flex-col" gap="gap-3" className="h-full p-5">
<FlexBox alignItems="items-center" gap="gap-3">
<Avatar name={creator.username} src={creator.avatarUrl} size="lg" />
<FlexBox direction="flex-col" className="min-w-0">
<FlexBox alignItems="items-center" gap="gap-1">
<Typography
tag="span"
variant="heading-sm"
className="truncate font-bold"
>
{name}
</Typography>
{creator.verified && (
<Icon
name="check-circle"
size={16}
label={labels.verified}
className="flex-none text-action-primary"
/>
)}
</FlexBox>
{creator.displayName && (
<Typography
tag="span"
variant="caption"
color="secondary"
className="self-start"
>
<Element tag="bdi" dir="ltr">
@{creator.username}
</Element>
</Typography>
)}
</FlexBox>
</FlexBox>
{creator.markets.length > 0 && (
<FlexBox
tag="ul"
aria-label={labels.markets}
wrap="flex-wrap"
className="gap-1.5"
>
{creator.markets.map((market) => (
<Element tag="li" key={market}>
<Tag>{labels.marketNames[market]}</Tag>
</Element>
))}
</FlexBox>
)}
<Typography
variant="body-sm"
color="secondary"
className="line-clamp-2 min-h-12"
>
{creator.bio}
</Typography>
<GridBox tag="dl" cols="grid-cols-3" gap="gap-2">
{stats.map((stat) => (
<FlexBox
key={stat.key}
direction="flex-col-reverse"
className="gap-0.5 rounded-md bg-surface-sunken p-2.5"
>
<Typography tag="dt" variant="micro" color="secondary">
{stat.label}
</Typography>
<Typography
tag="dd"
variant="heading-sm"
color={'color' in stat ? stat.color : 'primary'}
className="m-0 font-bold"
>
{stat.value}
</Typography>
</FlexBox>
))}
</GridBox>
<FlexBox
alignItems="items-center"
gap="gap-1"
className="mt-auto text-action-primary"
>
<Typography
tag="span"
variant="label"
color="inherit"
className="font-bold"
>
{labels.view}
</Typography>
<Icon name="chevron-left" size={16} />
</FlexBox>
</FlexBox>
</Card>
);
}

View File

@ -14,6 +14,7 @@ export type FeaturedAnalystsLabels = {
next: string;
/** Who chooses them, and that past results promise nothing. */
note: string;
/** Island AnalystCard's texts, plus each market's name. */
card: {
/** The card link's accessible name: `(name) => «کانال سارا مرادی»`. */
open: (name: string) => string;
@ -37,11 +38,6 @@ export type FeaturedAnalystsProps = {
labels: FeaturedAnalystsLabels;
};
export type AnalystCardProps = {
creator: FeaturedCreatorPayload;
labels: FeaturedAnalystsLabels['card'];
};
export type AnalystCarouselProps = {
/** The section heading, beside the arrows. */
heading: ReactNode;

View File

@ -12,6 +12,7 @@ export async function ChannelFeed({ channel, now, layout }: ChannelFeedProps) {
<ChannelFeedList
creatorId={channel.creatorId}
username={channel.username}
displayName={channel.displayName}
avatarUrl={channel.avatarUrl}
firstPage={firstPage}
now={now}

View File

@ -41,6 +41,7 @@ const PostLightbox = dynamic(() =>
export function ChannelFeedList({
creatorId,
username,
displayName,
avatarUrl,
firstPage,
now,
@ -83,6 +84,7 @@ export function ChannelFeedList({
key={post.id}
post={post}
username={username}
displayName={displayName}
avatarUrl={avatarUrl}
variant="compact"
linked

View File

@ -13,6 +13,7 @@ export type ChannelFeedProps = {
export type ChannelFeedListProps = {
creatorId: string;
username: string;
displayName: string | null;
avatarUrl: string | null;
firstPage: PostPagePayload;
now: string;

View File

@ -6,20 +6,21 @@ import { Typography } from '@lumina/island/atoms/typography';
import { Card } from '@lumina/island/molecules/card';
import { Element } from '@lumina/island/primitives/element';
import { ChannelCounts } from './components/ChannelCounts';
import { ChannelLinks } from './components/ChannelLinks';
import type { ChannelHeaderProps } from './types';
/**
* The channel header (U6), the same for every visitor; only the action area differs, and it loads
* in the browser. Fixed order: the avatar, @username with the verified mark and the channel's
* address, the bio in full, the market chips, the links, the track record and the actions.
* Optional blocks leave no gap. Every channel the API returns is approved, so every public one is
* verified; the creator's own pending, rejected or suspended tab has no mark (C6 ۱.۲, ۱.۳).
* Desktop moves the actions up under the identity row.
* The channel header (U6, DS ChannelHeader), the same for every visitor; only the action area and
* the owner's subscriber count differ, and they load in the browser. One order on both layouts:
* the 72px avatar with the display name (h1) and the verified mark over @username, the counts,
* the bio in full, the market chips, the links, then the actions. Optional blocks leave no gap.
* The track record follows as its own block: the padded column's first item on mobile, its own
* card on desktop. Every channel the API returns is approved, so every public one is verified; the
* creator's own pending, rejected or suspended tab has no mark (C6 ۱.۲, ۱.۳).
*/
export function ChannelHeader({
channel,
channelUrl,
layout,
share,
stats,
@ -29,48 +30,55 @@ export function ChannelHeader({
verified = true,
}: ChannelHeaderProps) {
const isDesktop = layout === 'desktop';
const identity = (
<FlexBox alignItems="items-center" gap={isDesktop ? 'gap-5' : 'gap-3'}>
<Avatar
name={channel.username}
src={channel.avatarUrl}
size={isDesktop ? '2xl' : 'xl'}
muted={muted}
/>
<FlexBox direction="flex-col" className="min-w-0 flex-1">
<FlexBox alignItems="items-center" gap="gap-1">
<Typography tag="h1" variant="heading-md" className="truncate">
<Element tag="bdi" dir="ltr">
@{channel.username}
</Element>
</Typography>
{verified && (
<Icon
name="check-circle"
size={20}
label={labels.verified}
className="flex-none text-action-primary-text"
/>
)}
</FlexBox>
<Typography
tag="span"
variant="caption"
color="secondary"
className="truncate"
>
<Element tag="bdi" dir="ltr">
{channelUrl}
</Element>
</Typography>
</FlexBox>
{share}
</FlexBox>
const handle = (
<Element tag="bdi" dir="ltr">
@{channel.username}
</Element>
);
const body = (
const content = (
<>
<FlexBox alignItems="items-center" className="gap-3.5">
<Avatar
name={channel.username}
src={channel.avatarUrl}
size="xl"
muted={muted}
/>
<FlexBox direction="flex-col" className="min-w-0 flex-1">
<FlexBox alignItems="items-center" className="min-w-0 gap-1.5">
<Typography tag="h1" variant="heading-md" className="truncate">
{channel.displayName ?? handle}
</Typography>
{verified && (
<Icon
name="check-circle"
size={20}
label={labels.verified}
className="flex-none text-action-primary-text"
/>
)}
</FlexBox>
{channel.displayName && (
<Typography
tag="span"
variant="caption"
color="secondary"
className="max-w-full self-start truncate"
>
{handle}
</Typography>
)}
</FlexBox>
{share}
</FlexBox>
{/* A suspended creator's own tab shows nothing past the name. */}
{!muted && (
<ChannelCounts
creatorId={channel.creatorId}
followerCount={channel.followerCount}
/>
)}
{channel.bio && (
<Typography className="wrap-anywhere whitespace-pre-line">
{channel.bio}
@ -81,7 +89,7 @@ export function ChannelHeader({
tag="ul"
aria-label={labels.markets}
wrap="flex-wrap"
gap="gap-2"
className="gap-1.5"
>
{channel.markets.map((market) => (
<Element tag="li" key={market}>
@ -93,32 +101,38 @@ export function ChannelHeader({
{channel.socialLinks.length > 0 && (
<ChannelLinks links={channel.socialLinks} labels={labels} />
)}
{stats}
{actions}
</>
);
if (isDesktop) {
return (
<Card tag="section" padding="lg">
<FlexBox direction="flex-col" gap="gap-4">
{identity}
{actions}
{body}
</FlexBox>
</Card>
<>
<Card tag="section" padding="lg">
<FlexBox direction="flex-col" className="gap-3.5">
{content}
</FlexBox>
</Card>
{stats}
</>
);
}
return (
<FlexBox
tag="section"
direction="flex-col"
gap="gap-4"
className="border-b border-border-subtle bg-surface px-4 py-5"
>
{identity}
{body}
{actions}
</FlexBox>
<>
<FlexBox
tag="section"
direction="flex-col"
className="gap-3.5 border-b border-border-subtle bg-surface px-4 py-5"
>
{content}
</FlexBox>
{stats != null && (
// Collapses when the record renders nothing (below the threshold, or hidden).
<FlexBox direction="flex-col" className="px-4 pt-4 empty:hidden">
{stats}
</FlexBox>
)}
</>
);
}

View File

@ -0,0 +1,79 @@
'use client';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Skeleton } from '@lumina/island/atoms/skeleton';
import { Typography } from '@lumina/island/atoms/typography';
import { number } from '@lumina/tools/format';
import { useTranslation } from 'react-i18next';
import { useChannelCountsPart } from '../../../../../../../../features/channel';
import type { ChannelCount, ChannelCountsProps } from '../types';
/**
* «۳۴۸ دنبال‌کننده» for everyone, and «۳۱ مشترک فعال» beside it for the creator on their own
* channel only (R15). The follower count arrives with the server render; the subscriber count
* depends on the viewer, so it joins the row in the browser. A count that fails is left out.
*/
export function ChannelCounts({
creatorId,
followerCount,
}: ChannelCountsProps) {
const { t } = useTranslation('channel');
const { followers, isPending, subscribers } = useChannelCountsPart({
creatorId,
followerCount,
});
// Read in the browser: the row keeps its height meanwhile.
if (isPending) {
return (
<FlexBox alignItems="items-center" className="h-7">
<Skeleton className="h-4 w-28" />
</FlexBox>
);
}
const counts: ChannelCount[] = [];
if (followers != null) {
counts.push({
key: 'followers',
value: followers,
label: t('header.followers'),
});
}
if (subscribers != null) {
counts.push({
key: 'subscribers',
value: subscribers,
label: t('header.subscribers'),
});
}
if (counts.length === 0) return null;
return (
<FlexBox
tag="dl"
wrap="flex-wrap"
xGap="gap-x-5"
yGap="gap-y-1"
className="m-0"
>
{counts.map(({ key, value, label }) => (
// dt before dd for the list's semantics; the number reads first.
<FlexBox
key={key}
direction="flex-row-reverse"
alignItems="items-baseline"
gap="gap-1"
>
<Typography tag="dt" variant="caption" color="secondary">
{label}
</Typography>
<Typography tag="dd" className="m-0 font-bold">
{number(value)}
</Typography>
</FlexBox>
))}
</FlexBox>
);
}

View File

@ -1,7 +1,9 @@
export { ChannelCounts } from './components/ChannelCounts';
export { ChannelHeader } from './ChannelHeader';
export { ChannelHeaderSkeleton } from './ChannelHeaderSkeleton';
export { channelHeaderLabels } from './labels';
export type {
ChannelCountsProps,
ChannelHeaderLabels,
ChannelHeaderProps,
ChannelHeaderSkeletonProps,

View File

@ -21,27 +21,47 @@ export type ChannelHeaderLabels = {
};
export type ChannelHeaderProps = {
/** Its `followerCount`, from the server's `getChannel`, renders the follower count at once. */
channel: PublicCreatorPayload;
/** The channel's address without the scheme: «lumina.ir/@sara_gold». */
channelUrl: string;
/**
* @deprecated No longer shown: the sub-line is @username (DS v6.1, R15). Kept so the callers
* still type-check until they stop passing it.
*/
channelUrl?: string;
/** mobile: flush under the top bar. desktop: a panel in the 640 column. */
layout: 'mobile' | 'desktop';
/** The share button, at the identity row's end. */
share: ReactNode;
/** CreatorStats in its boundary; renders nothing below the threshold. */
/**
* CreatorStats in its boundary; renders nothing below the threshold. Its own block after the
* header: the first item of the padded column on mobile, its own card on desktop.
*/
stats: ReactNode;
/** Subscribe and follow, which load in the browser. */
actions: ReactNode;
/** The creator's own suspended channel: a greyed avatar. */
/** The creator's own suspended channel: a greyed avatar and no counts. */
muted?: boolean;
/**
* The verified mark after @username. Every public channel is approved, so `true` by default;
* The verified mark after the name. Every public channel is approved, so `true` by default;
* the creator's own pending, rejected or suspended tab passes `false` (C6 ۱.۲, ۱.۳).
*/
verified?: boolean;
labels: ChannelHeaderLabels;
};
export type ChannelCountsProps = {
/** The creator's account id. */
creatorId: string;
/** The server render's count; absent or `null`, the browser reads it. */
followerCount?: number | null;
};
export type ChannelCount = {
key: 'followers' | 'subscribers';
value: number;
label: string;
};
export type ChannelLinksProps = Pick<ChannelHeaderProps, 'labels'> & {
links: PublicCreatorPayload['socialLinks'];
};

View File

@ -39,7 +39,7 @@ export function OwnPendingChannel({
const { channel, standing, rejectionReason } = own;
const banner =
standing === 'rejected' ? (
<Banner tone="danger" href={ROUTES.account}>
<Banner tone="danger" href={ROUTES.account.root}>
{rejectionReason
? t('own.rejected-reason', { reason: rejectionReason })
: t('own.rejected')}

View File

@ -7,11 +7,14 @@ import { Element } from '@lumina/island/primitives/element';
import NextLink from 'next/link';
import { ROUTES } from '../../../../../../../../navigation/navigation';
import { ChannelCounts } from '../../../../organisms/channel-header';
import type { PostChannelBarProps } from './types';
/**
* The post page's mini header (C4b, U8): the creator, linking to the channel, over the same
* subscribe and follow controls as the channel header, so a shared link can convert on the spot.
* The post page's mini header (C4b, U8; DS ChannelHeader `layout="card"` on both layouts): the
* creator's avatar, display name and verified mark over @username, linking to the channel, then
* the follower count, then the same subscribe and follow controls as the channel header, so a
* shared link can convert on the spot. No bio, markets or links.
*/
export function PostChannelBar({
channel,
@ -19,46 +22,65 @@ export function PostChannelBar({
actions,
verifiedLabel,
}: PostChannelBarProps) {
const content = (
<FlexBox direction="flex-col" gap="gap-3">
<FlexBox
tag={NextLink}
href={ROUTES.channel(channel.username)}
alignItems="items-center"
gap="gap-3"
className="min-h-touch-target min-w-0 self-start rounded-xs text-text-primary no-underline focus-visible:focus-ring"
>
<Avatar name={channel.username} src={channel.avatarUrl} />
<Typography
tag="span"
color="inherit"
className="truncate font-semibold"
>
<Element tag="bdi" dir="ltr">
@{channel.username}
</Element>
</Typography>
<Icon
name="check-circle"
size={20}
label={verifiedLabel}
className="flex-none text-action-primary-text"
/>
</FlexBox>
{actions}
</FlexBox>
);
return layout === 'desktop' ? (
<Card tag="section" padding="lg">
{content}
</Card>
) : (
<Element
tag="section"
className="border-b border-border-subtle bg-surface p-4"
>
{content}
const handle = (
<Element tag="bdi" dir="ltr">
@{channel.username}
</Element>
);
const card = (
<Card tag="section" padding={layout === 'desktop' ? 'lg' : 'md'}>
<FlexBox direction="flex-col" className="gap-3.5">
<FlexBox
tag={NextLink}
href={ROUTES.channel(channel.username)}
alignItems="items-center"
className="max-w-full min-w-0 gap-3.5 self-start rounded-xs text-text-primary no-underline focus-visible:focus-ring"
>
<Avatar name={channel.username} src={channel.avatarUrl} size="xl" />
<FlexBox direction="flex-col" className="min-w-0">
<FlexBox alignItems="items-center" className="min-w-0 gap-1.5">
<Typography
tag="span"
variant="heading-md"
color="inherit"
className="truncate"
>
{channel.displayName ?? handle}
</Typography>
<Icon
name="check-circle"
size={20}
label={verifiedLabel}
className="flex-none text-action-primary-text"
/>
</FlexBox>
{channel.displayName && (
<Typography
tag="span"
variant="caption"
color="secondary"
className="max-w-full self-start truncate"
>
{handle}
</Typography>
)}
</FlexBox>
</FlexBox>
<ChannelCounts
creatorId={channel.creatorId}
followerCount={channel.followerCount}
/>
{actions}
</FlexBox>
</Card>
);
// Mobile: a card in the padded column, over the post (J05-4).
return layout === 'desktop' ? (
card
) : (
<FlexBox direction="flex-col" className="px-4 pt-4">
{card}
</FlexBox>
);
}

View File

@ -3,8 +3,9 @@ import type { ReactNode } from 'react';
import type { PublicCreatorPayload } from '../../../../../../../../../features/channel';
export type PostChannelBarProps = {
/** Its `followerCount`, from the server's `getChannel`, renders the follower count at once. */
channel: PublicCreatorPayload;
/** mobile: flush under the top bar. desktop: a panel in the 640 column. */
/** mobile: a card in a padded strip under the top bar. desktop: a panel in the 640 column. */
layout: 'mobile' | 'desktop';
/** Subscribe and follow, the same part as the channel header's. */
actions: ReactNode;

View File

@ -43,6 +43,7 @@ const PostLightbox = dynamic(() =>
export function PostView({
post: serverPost,
username,
displayName,
avatarUrl,
now,
layout,
@ -82,6 +83,7 @@ export function PostView({
<ChannelPostCard
post={post}
username={username}
displayName={displayName}
avatarUrl={avatarUrl}
variant="expanded"
linked={false}

View File

@ -4,6 +4,8 @@ import type { PostPreview } from '../../../../../../organisms/channel-post-card'
export type PostViewProps = {
post: PostPayload;
username: string;
/** The creator's display name for the card's header; absent, @username alone. */
displayName?: string | null;
avatarUrl: string | null;
/** What the time counts from: the server render's time. */
now: string;

View File

@ -41,6 +41,7 @@ const isMarket = (market: string): market is Market =>
export function ChannelPostCard({
post,
username,
displayName,
avatarUrl,
verified = true,
variant,
@ -106,7 +107,7 @@ export function ChannelPostCard({
}
: { onShare, onCopyLink };
const common = {
author: { username, avatar: avatarUrl, verified },
author: { username, displayName, avatar: avatarUrl, verified },
channelHref: ROUTES.channel(username),
href: linked ? path : undefined,
publishedAt: post.publishedAt ?? post.createdAt,

View File

@ -10,6 +10,8 @@ export type ChannelPostCardProps = {
post: PostPayload;
/** The channel the post belongs to: its header shows them, and its links lead there. */
username: string;
/** The creator's display name, shown with @username beside it (R15); absent, @username alone. */
displayName?: string | null;
avatarUrl: string | null;
/** The verified mark on the avatar: on the channel and the post page, not on the home feed (U7). */
verified?: boolean;

View File

@ -72,6 +72,7 @@ export function HomeFeed({ layout, exampleChannelUrl }: HomeFeedProps) {
key={post.id}
post={post}
username={post.creator.username}
displayName={post.creator.displayName}
avatarUrl={post.creator.avatarUrl}
verified={false}
variant="compact"

View File

@ -0,0 +1,70 @@
'use client';
import { Button } from '@lumina/island/atoms/button';
import { Typography } from '@lumina/island/atoms/typography';
import { Modal } from '@lumina/island/molecules/modal';
import { Sheet } from '@lumina/island/molecules/sheet';
import { useTranslation } from 'react-i18next';
import { useSignOut } from './hooks/use-sign-out';
import type { SignOutConfirmProps } from './types';
/**
* «خروج از حساب» (J12-1d): asks before signing this device out, and says the next login needs a
* code by SMS to the member's number. «خروج از حساب» first, then «انصراف». A bottom sheet on
* mobile (from حساب کاربری), a 420 modal on desktop (from the avatar menu). While it signs out the
* confirm spins and the dialog can't be dismissed; on success the landing loads.
*/
export function SignOutConfirm({ open, onClose, layout }: SignOutConfirmProps) {
const { t } = useTranslation();
const { phone, isSigningOut, confirm } = useSignOut();
const size = layout === 'mobile' ? 'lg' : undefined;
const buttons = (
<>
<Button
variant="primary"
size={size}
block
isLoading={isSigningOut}
onClick={confirm}
>
{t('sign-out.confirm')}
</Button>
<Button
variant="secondary"
size={size}
block
disabled={isSigningOut}
onClick={onClose}
>
{t('sign-out.cancel')}
</Button>
</>
);
// The number reads left to right inside the sentence.
const body = (
<Typography>{t('sign-out.body', { phone: `⁦${phone}⁩` })}</Typography>
);
return layout === 'mobile' ? (
<Sheet
open={open}
title={t('sign-out.title')}
onClose={onClose}
dismissible={!isSigningOut}
footer={buttons}
>
{body}
</Sheet>
) : (
<Modal
open={open}
title={t('sign-out.title')}
onClose={onClose}
dismissible={!isSigningOut}
actions={buttons}
>
{body}
</Modal>
);
}

View File

@ -0,0 +1,52 @@
'use client';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { logout } from '../../../../../features/auth';
import { formatMobile, showActionError } from '../../../../../shared/utils';
import { useAuthStore, useCurrentAccount } from '../../../../../stores/auth';
import { ROUTES } from '../../../../navigation/navigation';
import type { SignOutModel } from '../types';
/** Sends the tab to the landing as a fresh load, so nothing of the old account stays in memory. */
function leaveForLanding(): void {
window.location.replace(ROUTES.landing);
}
/**
* J12-1d: signs this device out. `logout` revokes the session and emits `auth.logout`, on which
* the app shell drops the cached queries, the post and checkout drafts and every `session.` key.
* Then the landing loads afresh, which also keeps a guarded page from sending the person to login.
* A failure keeps the dialog and says so; a session that had already ended counts as signed out.
*/
export function useSignOut(): SignOutModel {
const { t } = useTranslation();
const account = useCurrentAccount();
const [isSigningOut, setSigningOut] = useState(false);
const signOut = async () => {
setSigningOut(true);
try {
await logout();
leaveForLanding();
} catch (error) {
if (useAuthStore.getState().status === 'guest') {
leaveForLanding();
return;
}
setSigningOut(false);
showActionError(error, {
t,
failedMessage: t('sign-out.failed'),
retry: () => void signOut(),
});
}
};
return {
phone: formatMobile(account?.phone ?? ''),
isSigningOut,
confirm: () => void signOut(),
};
}

View File

@ -0,0 +1,2 @@
export { SignOutConfirm } from './SignOutConfirm';
export type { SignOutConfirmProps } from './types';

View File

@ -0,0 +1,16 @@
export type SignOutConfirmProps = {
open: boolean;
onClose: () => void;
/** mobile: a bottom sheet (the حساب کاربری page). desktop: a 420 modal (the avatar menu). */
layout: 'mobile' | 'desktop';
};
/** The sign-out dialog's state and its one action. */
export type SignOutModel = {
/** The member's number as `0912 345 6789`: the next login's code goes to it. */
phone: string;
/** Signing out is in flight: the confirm spins and the dialog stays. */
isSigningOut: boolean;
/** Signs out of this device, then opens the landing with nothing of the account left. */
confirm: () => void;
};

View File

@ -8,8 +8,16 @@ import type { PublicCreatorPayload } from '../repositories/channel';
/**
* The channel at `/@username`, once per render per username: the page and its metadata share one
* request. Pass the username as the API stores it (no «@», lower case). 404 reaches the caller.
* It carries the public follower count for the header; a failed count is left to the browser.
*/
export const getChannel = cache(
(username: string): Promise<PublicCreatorPayload> =>
channelRepository.getCreatorByUsername({ username }),
async (username: string): Promise<PublicCreatorPayload> => {
const channel = await channelRepository.getCreatorByUsername({ username });
// A suspended channel shows no header, so no count.
if (channel.suspended) return channel;
const followerCount = await channelRepository
.getFollowerCount({ creatorId: channel.creatorId })
.catch(() => null);
return { ...channel, followerCount };
},
);

View File

@ -0,0 +1 @@
export type { FollowerCountEntity } from './types';

View File

@ -0,0 +1,6 @@
/** content-service `getFollowerCount`: how many investors follow the creator. Public. */
export type FollowerCountEntity = {
/** The creator's account id. */
creatorId: string;
followerCount: number;
};

View File

@ -13,6 +13,11 @@ export type {
ChannelViewer,
UseChannelActionsPartOptions,
} from './models/channel';
export { useChannelCountsPart } from './models/channel-counts';
export type {
ChannelCountsPartModel,
UseChannelCountsPartOptions,
} from './models/channel-counts';
export { syncFollowCaches } from './models/follow-caches';
export { useFollowingPart } from './models/following';
export type { FollowingPartModel } from './models/following';

View File

@ -0,0 +1,5 @@
export { useChannelCountsPart } from './use-channel-counts-part';
export type {
ChannelCountsPartModel,
UseChannelCountsPartOptions,
} from './types';

View File

@ -0,0 +1,18 @@
export type UseChannelCountsPartOptions = {
/** The creator's account id. */
creatorId: string;
/**
* The server render's count (`PublicCreatorPayload.followerCount`). Absent or `null`, the
* browser reads it.
*/
followerCount?: number | null;
};
export type ChannelCountsPartModel = {
/** Public; `null` while the browser reads it, or after that read failed. */
followers: number | null;
/** The browser is still reading the follower count: the row keeps its place with a skeleton. */
isPending: boolean;
/** «مشترک فعال», the creator's own channel only (R15); `null` for everyone else. */
subscribers: number | null;
};

View File

@ -0,0 +1,37 @@
import { useQuery } from '@tanstack/react-query';
import { useCurrentAccount } from '../../../../stores/auth';
import { useOwnSubscriberCount } from '../../../overview';
import { channelKeys, channelRepository } from '../../repositories/channel';
import type {
ChannelCountsPartModel,
UseChannelCountsPartOptions,
} from './types';
/**
* The channel header's counts. The follower count is public: it starts from the server render
* (decision 0021), else the browser reads it, and a follow or unfollow moves it in place
* (`syncFollowCaches`). The active subscriber count depends on the viewer, so only the creator on
* their own channel reads it, in the browser. Neither read throws: a failed count is left out.
*/
export function useChannelCountsPart({
creatorId,
followerCount,
}: UseChannelCountsPartOptions): ChannelCountsPartModel {
const account = useCurrentAccount();
const isOwner = account?.id === creatorId;
const followers = useQuery({
queryKey: channelKeys.followerCount(creatorId),
queryFn: ({ signal }) =>
channelRepository.getFollowerCount({ creatorId }, { signal }),
initialData: followerCount ?? undefined,
throwOnError: false,
});
const subscribers = useOwnSubscriberCount({ enabled: isOwner });
return {
followers: followers.data ?? null,
isPending: followers.isPending,
subscribers: isOwner ? subscribers : null,
};
}

View File

@ -7,8 +7,8 @@ import type { ChannelStanding } from '../channel';
/**
* A follow or unfollow of the creator succeeded, on their channel or in the following list: their
* channel's standing shows it, and the home feed and the following list read again. No follower
* count is cached in the browser: the channel's counts come from its server render.
* channel's standing shows it, and the home feed, the following list and the channel's follower
* count read again. The count is read, not stepped, so quick follow-unfollow taps never drift.
*/
export function syncFollowCaches(
queryClient: QueryClient,
@ -18,6 +18,9 @@ export function syncFollowCaches(
channelKeys.standing(creatorId),
(standing) => standing && { ...standing, following },
);
void queryClient.invalidateQueries({
queryKey: channelKeys.followerCount(creatorId),
});
void queryClient.invalidateQueries({ queryKey: feedKeys.all });
void queryClient.invalidateQueries({ queryKey: followKeys.following() });
}

View File

@ -2,6 +2,7 @@ import { channelHttp } from '../../http';
import { CHANNEL_ENDPOINTS } from './constants';
import {
toFeaturedCreatorsPayload,
toFollowerCount,
toPublicCreatorPayload,
toPublicTiersPayload,
} from './mappers';
@ -10,6 +11,7 @@ import type {
ChannelByUsernameArgs,
FeaturedCreatorPayload,
FeaturedCreatorsResponseDto,
FollowerCountResponseDto,
PublicCreatorPayload,
PublicCreatorResponseDto,
PublicTierPayload,
@ -54,6 +56,18 @@ export const channelRepository = {
return toPublicTiersPayload(response);
},
/** How many investors follow the creator; public, so it reads the same for every visitor. */
async getFollowerCount(
args: ChannelArgs,
{ signal }: { signal?: AbortSignal } = {},
): Promise<number> {
const response = await channelHttp.get<FollowerCountResponseDto>(
CHANNEL_ENDPOINTS.followerCount(args.creatorId),
{ signal },
);
return toFollowerCount(response);
},
/** The analysts the landing features, in the admin's order; at most 10. */
async listFeatured({ signal }: { signal?: AbortSignal } = {}): Promise<
FeaturedCreatorPayload[]

View File

@ -4,6 +4,8 @@ export const CHANNEL_ENDPOINTS = {
`/traders/by-username/${encodeURIComponent(username)}`,
tiers: (creatorId: string) =>
`/subscriptions/creators/${encodeURIComponent(creatorId)}/tiers`,
followerCount: (creatorId: string) =>
`/creators/${encodeURIComponent(creatorId)}/followers-count`,
/** The landing's analysts; not in the API yet, so it answers 404 and the section stays hidden. */
featured: '/creators/featured',
} as const;
@ -16,6 +18,9 @@ export const channelKeys = {
[...channelKeys.creator(creatorId), 'profile'] as const,
tiers: (creatorId: string) =>
[...channelKeys.creator(creatorId), 'tiers'] as const,
/** The public follower count; a follow or unfollow moves it in place. */
followerCount: (creatorId: string) =>
[...channelKeys.creator(creatorId), 'follower-count'] as const,
byUsername: (username: string) =>
[...channelKeys.all, 'username', username] as const,
/** The signed-in investor's follow and subscription with this creator. */

View File

@ -3,6 +3,7 @@ import type { PublicTierEntity } from '../../entities/public-tier';
import type {
FeaturedCreatorPayload,
FeaturedCreatorsResponseDto,
FollowerCountResponseDto,
PublicCreatorPayload,
PublicCreatorResponseDto,
PublicTierPayload,
@ -56,6 +57,10 @@ export function toPublicTiersPayload(
return dto.items.map(toPublicTierPayload);
}
export function toFollowerCount(dto: FollowerCountResponseDto): number {
return dto.followerCount;
}
export function toFeaturedCreatorsPayload(
dto: FeaturedCreatorsResponseDto,
): FeaturedCreatorPayload[] {

View File

@ -5,6 +5,7 @@ import type {
} from '../../../../shared/constants';
import type { SocialLinkPayload, TradingStyle } from '../../../profile';
import type { FeaturedCreatorEntity } from '../../entities/featured-creator';
import type { FollowerCountEntity } from '../../entities/follower-count';
import type { PublicCreatorEntity } from '../../entities/public-creator';
import type { PublicTierEntity } from '../../entities/public-tier';
@ -16,7 +17,7 @@ export type ChannelByUsernameArgs = { username: string };
/**
* An approved creator's public page header. Unapproved creators answer 404, so every creator here
* is verified. Follower counts are never shown publicly, so none are fetched.
* is verified.
*/
export type PublicCreatorPayload = {
profileId: string;
@ -31,6 +32,12 @@ export type PublicCreatorPayload = {
markets: Market[];
/** Suspended: no header, posts or actions for anyone, only «این کانال در دسترس نیست». */
suspended: boolean;
/**
* The public follower count, read with the channel only by the server's `getChannel`, so the
* header renders it: absent from every other read, and `null` when that read failed. Either
* way the header reads it again in the browser.
*/
followerCount?: number | null;
};
export type PublicCreatorResponseDto = PublicCreatorEntity;
@ -66,6 +73,8 @@ export type PublicTierPayload = {
export type PublicTiersResponseDto = { items: PublicTierEntity[] };
export type FollowerCountResponseDto = FollowerCountEntity;
/** An analyst on the landing, as its card shows them. */
export type FeaturedCreatorPayload = {
username: string;

View File

@ -9,6 +9,11 @@ export type FeedCreatorEntity = {
id: string;
/** Without the «@». */
username: string;
/**
* The creator's display name. trader-service's card doesn't send it yet (`findCardsByUserIds`
* selects only userId, username, avatar and statuses); until it does, cards show @username.
*/
displayName?: string | null;
/** A root-relative upload path (`/uploads/avatars/…`); `null` without a photo. */
avatar: string | null;
/** trader-service `verificationStatus` is `approved`. */

View File

@ -15,6 +15,7 @@ function toFeedCreatorPayload(dto: FeedCreatorEntity): FeedCreatorPayload {
return {
id: dto.id,
username: dto.username,
displayName: dto.displayName?.trim() || null,
avatarUrl: toApiUrl(dto.avatar),
verified: dto.verified,
suspended: dto.suspended,

View File

@ -20,6 +20,8 @@ export type FeedCreatorPayload = {
id: string;
/** Without the «@». */
username: string;
/** Shown as the name with @username beside it; `null` until the API sends it. */
displayName: string | null;
/** Absolute, through the API proxy; `null` without a photo. */
avatarUrl: string | null;
verified: boolean;

View File

@ -6,6 +6,7 @@ export type {
PostMediaEntity,
PostStatus,
PostType,
PredictionCloseReason,
PredictionDirection,
PredictionEntity,
PredictionOutcome,

View File

@ -16,6 +16,17 @@ export type PredictionStatus = 'open' | 'closed';
/** Derived by the API on close: the close price against the entry, in the prediction's direction. */
export type PredictionOutcome = 'win' | 'loss' | 'breakeven';
/**
* Why a prediction closed, stamped by the system with the close price: the final target, the stop
* loss, the end of the horizon, the creator's early close, or an admin's correction.
*/
export type PredictionCloseReason =
| 'target'
| 'stop'
| 'horizon'
| 'early'
| 'admin';
/** One image of an `image` post (content-service `PostMedia`). Always a `private` file. */
export type PostMediaEntity = {
fileId: string;
@ -44,6 +55,10 @@ export type PredictionEntity = {
outcome?: PredictionOutcome;
closedPrice?: number;
closedAt?: string;
/** Not in the API yet (content-service `PredictionData` has no such field). */
closeReason?: PredictionCloseReason;
/** Where the close price came from: `TGJU`, `Binance`. Not in the API yet. */
priceSource?: string;
};
/**

View File

@ -6,6 +6,7 @@ export type {
PostEntity,
PostStatus,
PostType,
PredictionCloseReason,
PredictionDirection,
PredictionOutcome,
PredictionStatus,

View File

@ -35,6 +35,8 @@ export function toPredictionPayload(
outcome: entity.outcome ?? null,
closedPrice: entity.closedPrice ?? null,
closedAt: entity.closedAt ?? null,
closeReason: entity.closeReason ?? null,
priceSource: entity.priceSource ?? null,
};
}

View File

@ -3,6 +3,7 @@ import type {
PostEntity,
PostStatus,
PostType,
PredictionCloseReason,
PredictionDirection,
PredictionOutcome,
PredictionStatus,
@ -28,6 +29,10 @@ export type PredictionPayload = {
outcome: PredictionOutcome | null;
closedPrice: number | null;
closedAt: string | null;
/** Why it closed; `null` while open, or until the API sends it. */
closeReason: PredictionCloseReason | null;
/** Where the close price came from; `null` while open, or until the API sends it. */
priceSource: string | null;
};
/**

View File

@ -123,6 +123,30 @@ export function predictionCardLabels(t: ContentT): PredictionCardLabels {
),
immutable: t('prediction.immutable'),
closePrediction: t('prediction.close-prediction'),
closeReason: {
label: (reason) => (
<>
{t('prediction.close-reason.label')} {reason}
</>
),
reasons: {
target: t('prediction.close-reason.target'),
stop: t('prediction.close-reason.stop'),
horizon: t('prediction.close-reason.horizon'),
early: t('prediction.close-reason.early'),
admin: t('prediction.close-reason.admin'),
},
finalTarget: t('prediction.close-reason.final-target'),
priceSource: (source) => (
<>
{t('prediction.close-reason.price-source')} {source}
</>
),
},
preview: {
title: t('prediction.preview-seal.title'),
note: t('prediction.preview-seal.note'),
},
locked: {
title: t('prediction.locked.title'),
description: t('prediction.locked.description'),

View File

@ -13,6 +13,8 @@
"loading": "در حال بارگذاری کانال…",
"header": {
"verified": "تأییدشده",
"followers": "دنبال‌کننده",
"subscribers": "مشترک فعال",
"share": "اشتراک‌گذاری کانال",
"markets": "بازارهای تخصصی",
"links": "لینک‌های تحلیلگر",

View File

@ -55,11 +55,13 @@
"brand": "لومینا",
"brand-home": "صفحه اصلی لومینا",
"home": "خانه",
"search": "جستجو",
"dashboard": "داشبورد",
"channel": "کانال",
"back": "بازگشت",
"login": "ورود/ثبت‌نام",
"account": "حساب کاربری"
"account": "حساب کاربری",
"search-field": "جستجوی تحلیلگر با نام یا نام کاربری"
},
"publish": {
"menu": "انتشار",
@ -81,5 +83,19 @@
"reason": "حساب شما تعلیق شده است. امکان انتشار پست وجود ندارد."
}
},
"account-menu": {
"account": "حساب کاربری",
"profile": "اطلاعات کاربری",
"notifications": "تنظیمات اعلان‌ها",
"install": "نصب اپلیکیشن",
"sign-out": "خروج از حساب"
},
"sign-out": {
"title": "خروج از حساب",
"body": "برای ورود دوباره، کد تأیید به {{phone}} پیامک می‌شود.",
"confirm": "خروج از حساب",
"cancel": "انصراف",
"failed": "خروج از حساب انجام نشد"
},
"currency": "تومان"
}

View File

@ -97,7 +97,21 @@
"horizon-progress": "زمان سپری‌شده از افق",
"seal": "ثبت‌شده در",
"immutable": "غیرقابل ویرایش",
"close-prediction": "بستن پیش‌بینی",
"close-prediction": "بستن زودهنگام",
"close-reason": {
"label": "علت:",
"target": "رسیدن به هدف",
"final-target": "رسیدن به هدف نهایی",
"stop": "فعال‌شدن حد ضرر",
"horizon": "پایان افق",
"early": "بستن زودهنگام تحلیلگر",
"admin": "اصلاح توسط ادمین",
"price-source": "منبع قیمت:"
},
"preview-seal": {
"title": "پیش‌نمایش",
"note": "پس از انتشار، غیرقابل ویرایش و حذف"
},
"locked": {
"title": "پیش‌بینی پریمیوم",
"description": "دارایی، جهت، ورود، اهداف و حد ضرر پنهان است.",