diff --git a/platforms/market/src/app/app-shell/AppShell.tsx b/platforms/market/src/app/app-shell/AppShell.tsx index 9bef1e4..30fc205 100644 --- a/platforms/market/src/app/app-shell/AppShell.tsx +++ b/platforms/market/src/app/app-shell/AppShell.tsx @@ -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 ( - - {children} + {children} ('idle'); + const [barCount, setBarCount] = useState(0); const noticeTimer = useRef>(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(() => { + 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 ( - { - if (navigator.onLine) reconnect(); - } - : undefined - } - retryLabel={t('network.retry')} - /> + + {view && barCount === 0 && ( + + )} + {children} + ); } diff --git a/platforms/market/src/app/app-shell/components/network-bar/NetworkBar.tsx b/platforms/market/src/app/app-shell/components/network-bar/NetworkBar.tsx new file mode 100644 index 0000000..3b7deb2 --- /dev/null +++ b/platforms/market/src/app/app-shell/components/network-bar/NetworkBar.tsx @@ -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 ( + + ); +} diff --git a/platforms/market/src/app/app-shell/components/network-bar/index.ts b/platforms/market/src/app/app-shell/components/network-bar/index.ts new file mode 100644 index 0000000..36ec3b6 --- /dev/null +++ b/platforms/market/src/app/app-shell/components/network-bar/index.ts @@ -0,0 +1 @@ +export { NetworkBar } from './NetworkBar'; diff --git a/platforms/market/src/app/app-shell/context.ts b/platforms/market/src/app/app-shell/context.ts new file mode 100644 index 0000000..45c5909 --- /dev/null +++ b/platforms/market/src/app/app-shell/context.ts @@ -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(null); diff --git a/platforms/market/src/app/app-shell/index.ts b/platforms/market/src/app/app-shell/index.ts index 237554b..3f3ccb8 100644 --- a/platforms/market/src/app/app-shell/index.ts +++ b/platforms/market/src/app/app-shell/index.ts @@ -1,2 +1,3 @@ export { AppShell } from './AppShell'; +export { NetworkBar } from './components/network-bar'; export type { AppShellProps } from './types'; diff --git a/platforms/market/src/app/app-shell/types.ts b/platforms/market/src/app/app-shell/types.ts index 4dd041b..030ae58 100644 --- a/platforms/market/src/app/app-shell/types.ts +++ b/platforms/market/src/app/app-shell/types.ts @@ -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 }; diff --git a/platforms/market/src/app/navigation/active-tab.ts b/platforms/market/src/app/navigation/active-tab.ts index c1874c0..d38ccfd 100644 --- a/platforms/market/src/app/navigation/active-tab.ts +++ b/platforms/market/src/app/navigation/active-tab.ts @@ -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'; } diff --git a/platforms/market/src/app/navigation/back-target.ts b/platforms/market/src/app/navigation/back-target.ts new file mode 100644 index 0000000..b32673f --- /dev/null +++ b/platforms/market/src/app/navigation/back-target.ts @@ -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; +} diff --git a/platforms/market/src/app/navigation/components/account-menu/AccountMenu.tsx b/platforms/market/src/app/navigation/components/account-menu/AccountMenu.tsx new file mode 100644 index 0000000..3774d3b --- /dev/null +++ b/platforms/market/src/app/navigation/components/account-menu/AccountMenu.tsx @@ -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 ( + <> + + 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" + > + + + setIsOpen(false)} + label={t('nav.account')} + placement="below" + className="min-w-65" + header={ + <> + + + + {name} + + + @{account.username} + + + + } + items={items} + /> + + setSigningOut(false)} + layout="desktop" + /> + + ); +} diff --git a/platforms/market/src/app/navigation/components/account-menu/index.ts b/platforms/market/src/app/navigation/components/account-menu/index.ts new file mode 100644 index 0000000..036dcad --- /dev/null +++ b/platforms/market/src/app/navigation/components/account-menu/index.ts @@ -0,0 +1,2 @@ +export { AccountMenu } from './AccountMenu'; +export type { AccountMenuProps } from './types'; diff --git a/platforms/market/src/app/navigation/components/account-menu/types.ts b/platforms/market/src/app/navigation/components/account-menu/types.ts new file mode 100644 index 0000000..747d04f --- /dev/null +++ b/platforms/market/src/app/navigation/components/account-menu/types.ts @@ -0,0 +1,9 @@ +export type AccountMenuProps = { + /** The signed-in member's account. */ + account: { + username: string; + firstName: string; + lastName: string; + avatarUrl: string | null; + }; +}; diff --git a/platforms/market/src/app/navigation/components/bottom-nav/BottomNav.tsx b/platforms/market/src/app/navigation/components/bottom-nav/BottomNav.tsx index 7e1fc3c..f45be82 100644 --- a/platforms/market/src/app/navigation/components/bottom-nav/BottomNav.tsx +++ b/platforms/market/src/app/navigation/components/bottom-nav/BottomNav.tsx @@ -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() { )} + {!isCreator && SEARCH_ENABLED && ( + + )} {label} diff --git a/platforms/market/src/app/navigation/components/desk-back/DeskBack.tsx b/platforms/market/src/app/navigation/components/desk-back/DeskBack.tsx new file mode 100644 index 0000000..cdb0fb8 --- /dev/null +++ b/platforms/market/src/app/navigation/components/desk-back/DeskBack.tsx @@ -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 = ( + <> + + + {label ?? t('nav.back')} + + + ); + + return action.href ? ( + + {content} + + ) : ( + + {content} + + ); +} diff --git a/platforms/market/src/app/navigation/components/desk-back/index.ts b/platforms/market/src/app/navigation/components/desk-back/index.ts new file mode 100644 index 0000000..0e8f6fc --- /dev/null +++ b/platforms/market/src/app/navigation/components/desk-back/index.ts @@ -0,0 +1,2 @@ +export { DeskBack } from './DeskBack'; +export type { DeskBackProps } from './types'; diff --git a/platforms/market/src/app/navigation/components/desk-back/types.ts b/platforms/market/src/app/navigation/components/desk-back/types.ts new file mode 100644 index 0000000..52039c8 --- /dev/null +++ b/platforms/market/src/app/navigation/components/desk-back/types.ts @@ -0,0 +1,6 @@ +import type { BackOptions } from '../../types'; + +export type DeskBackProps = BackOptions & { + /** Its text; defaults to «بازگشت». */ + label?: string; +}; diff --git a/platforms/market/src/app/navigation/components/desktop-header/DesktopHeader.tsx b/platforms/market/src/app/navigation/components/desktop-header/DesktopHeader.tsx index d4ff6e6..9642f9a 100644 --- a/platforms/market/src/app/navigation/components/desktop-header/DesktopHeader.tsx +++ b/platforms/market/src/app/navigation/components/desktop-header/DesktopHeader.tsx @@ -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 ( - - + - {t('nav.brand')} - - {status === 'member' && account && ( - - {isCreator ? ( + {t('nav.brand')} + + {member && ( + + {isCreator ? ( + + ) : ( + + )} - ) : ( - + )} + {SEARCH_ENABLED && member && !isCreator && active !== 'search' && ( + + + + {t('nav.search-field')} + + + )} + + {isCreator && } + + {member && } + {status === 'unknown' && ( + // Most visitors are guests: their «ورود/ثبت‌نام» holds the end's place, unseen, so it + // doesn't move when the session arrives. + + + )} - - - )} - - {isCreator && } - - {status === 'member' && } - {status === 'unknown' && ( - // Most visitors are guests: their «ورود/ثبت‌نام» holds the end's place, unseen, so it - // doesn't move when the session arrives. - - - - )} - {status === 'guest' && ( - - )} - {status === 'member' && account && ( - - - - )} + )} + {member && } + + ); } diff --git a/platforms/market/src/app/navigation/components/desktop-header/components/HeaderNavLink.tsx b/platforms/market/src/app/navigation/components/desktop-header/components/HeaderNavLink.tsx index da3be95..c4d93ce 100644 --- a/platforms/market/src/app/navigation/components/desktop-header/components/HeaderNavLink.tsx +++ b/platforms/market/src/app/navigation/components/desktop-header/components/HeaderNavLink.tsx @@ -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 ( diff --git a/platforms/market/src/app/navigation/components/desktop-page-title/DesktopPageTitle.tsx b/platforms/market/src/app/navigation/components/desktop-page-title/DesktopPageTitle.tsx index 3f9d859..6f4cdf0 100644 --- a/platforms/market/src/app/navigation/components/desktop-page-title/DesktopPageTitle.tsx +++ b/platforms/market/src/app/navigation/components/desktop-page-title/DesktopPageTitle.tsx @@ -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 ( - - + + {title} diff --git a/platforms/market/src/app/navigation/components/desktop-page-title/types.ts b/platforms/market/src/app/navigation/components/desktop-page-title/types.ts index 446be34..734f9f2 100644 --- a/platforms/market/src/app/navigation/components/desktop-page-title/types.ts +++ b/platforms/market/src/app/navigation/components/desktop-page-title/types.ts @@ -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; }; diff --git a/platforms/market/src/app/navigation/components/mobile-top-bar/MobileTopBar.tsx b/platforms/market/src/app/navigation/components/mobile-top-bar/MobileTopBar.tsx index b1f2032..a8dcd5e 100644 --- a/platforms/market/src/app/navigation/components/mobile-top-bar/MobileTopBar.tsx +++ b/platforms/market/src/app/navigation/components/mobile-top-bar/MobileTopBar.tsx @@ -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 ( - - {status === 'unknown' && !isTabBar && ( - - - - )} - {(status === 'guest' || isTabBar) && ( - - )} - {status !== 'guest' && isTab && title && ( - - {title} - - )} - {status === 'member' && !isTabBar && ( - <> - {back && } + + + {hasBack && ( + + )} + {(status === 'guest' || isTabBar) && ( + + )} + {status === 'unknown' && !isTabBar && ( + + + + )} + {status !== 'guest' && isTab && title && ( + {title} + + )} + {status === 'member' && !isTabBar && ( + {isPreview && previewTitle ? previewTitle : title} - - )} - - {status === 'member' && isTabBar && } - {status === 'guest' && ( - - )} - {status === 'unknown' && ( - // Most visitors are guests: their «ورود/ثبت‌نام» holds the end's place, unseen, so the bar - // doesn't move when the session arrives. - - - - )} - {status === 'member' && isTabBar && account && ( - - - - )} + + )} + {status === 'unknown' && ( + // Most visitors are guests: their «ورود/ثبت‌نام» holds the end's place, unseen, so the bar + // doesn't move when the session arrives. + + + {t('nav.login')} + + + )} + {status === 'member' && isTabBar && account && ( + + + + )} + + ); } diff --git a/platforms/market/src/app/navigation/components/mobile-top-bar/components/BackButton.tsx b/platforms/market/src/app/navigation/components/mobile-top-bar/components/BackButton.tsx index e97284a..4568bcd 100644 --- a/platforms/market/src/app/navigation/components/mobile-top-bar/components/BackButton.tsx +++ b/platforms/market/src/app/navigation/components/mobile-top-bar/components/BackButton.tsx @@ -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 ? ( - 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 && ( - 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. + )} - + + + 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 && ( + setIsExplaining(false)} + layout={placement === 'nav' ? 'mobile' : 'desktop'} + /> + )} + + ); } diff --git a/platforms/market/src/app/navigation/components/publish-menu/components/BlockedPublishDialog.tsx b/platforms/market/src/app/navigation/components/publish-menu/components/BlockedPublishDialog.tsx index eb547e0..46842c0 100644 --- a/platforms/market/src/app/navigation/components/publish-menu/components/BlockedPublishDialog.tsx +++ b/platforms/market/src/app/navigation/components/publish-menu/components/BlockedPublishDialog.tsx @@ -44,7 +44,7 @@ export function BlockedPublishDialog({ size={layout === 'mobile' ? 'lg' : 'md'} /> ) : ( - ); diff --git a/platforms/market/src/app/navigation/constants.ts b/platforms/market/src/app/navigation/constants.ts index 1667702..e83ad2c 100644 --- a/platforms/market/src/app/navigation/constants.ts +++ b/platforms/market/src/app/navigation/constants.ts @@ -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; diff --git a/platforms/market/src/app/navigation/hooks/use-back-target.ts b/platforms/market/src/app/navigation/hooks/use-back-target.ts new file mode 100644 index 0000000..463760a --- /dev/null +++ b/platforms/market/src/app/navigation/hooks/use-back-target.ts @@ -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; +} diff --git a/platforms/market/src/app/navigation/hooks/use-back.ts b/platforms/market/src/app/navigation/hooks/use-back.ts new file mode 100644 index 0000000..d2f91fa --- /dev/null +++ b/platforms/market/src/app/navigation/hooks/use-back.ts @@ -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); + }, + }; +} diff --git a/platforms/market/src/app/navigation/hooks/use-is-standalone.ts b/platforms/market/src/app/navigation/hooks/use-is-standalone.ts new file mode 100644 index 0000000..fd1effc --- /dev/null +++ b/platforms/market/src/app/navigation/hooks/use-is-standalone.ts @@ -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); +} diff --git a/platforms/market/src/app/navigation/index.ts b/platforms/market/src/app/navigation/index.ts index c272907..55b50e4 100644 --- a/platforms/market/src/app/navigation/index.ts +++ b/platforms/market/src/app/navigation/index.ts @@ -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'; diff --git a/platforms/market/src/app/navigation/navigation.ts b/platforms/market/src/app/navigation/navigation.ts index 3541971..1d2228a 100644 --- a/platforms/market/src/app/navigation/navigation.ts +++ b/platforms/market/src/app/navigation/navigation.ts @@ -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)}`, diff --git a/platforms/market/src/app/navigation/types.ts b/platforms/market/src/app/navigation/types.ts index 4249115..3ce5756 100644 --- a/platforms/market/src/app/navigation/types.ts +++ b/platforms/market/src/app/navigation/types.ts @@ -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 }; diff --git a/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/PaymentResult.tsx b/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/PaymentResult.tsx index 74b0e11..dcaa8ff 100644 --- a/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/PaymentResult.tsx +++ b/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/PaymentResult.tsx @@ -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 ( diff --git a/platforms/market/src/app/screens/(landing)/organisms/featured-analysts/FeaturedAnalysts.tsx b/platforms/market/src/app/screens/(landing)/organisms/featured-analysts/FeaturedAnalysts.tsx index 36e64f2..e81fc0f 100644 --- a/platforms/market/src/app/screens/(landing)/organisms/featured-analysts/FeaturedAnalysts.tsx +++ b/platforms/market/src/app/screens/(landing)/organisms/featured-analysts/FeaturedAnalysts.tsx @@ -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)]" > - + labels.card.marketNames[market], + ), + bio: creator.bio, + stats: creator.stats, + }} + href={ROUTES.channel(creator.username)} + labels={labels.card} + /> ))} diff --git a/platforms/market/src/app/screens/(landing)/organisms/featured-analysts/components/AnalystCard.tsx b/platforms/market/src/app/screens/(landing)/organisms/featured-analysts/components/AnalystCard.tsx deleted file mode 100644 index eeef30b..0000000 --- a/platforms/market/src/app/screens/(landing)/organisms/featured-analysts/components/AnalystCard.tsx +++ /dev/null @@ -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 ( - - - - - - - - {name} - - {creator.verified && ( - - )} - - {creator.displayName && ( - - - @{creator.username} - - - )} - - - {creator.markets.length > 0 && ( - - {creator.markets.map((market) => ( - - {labels.marketNames[market]} - - ))} - - )} - - {creator.bio} - - - {stats.map((stat) => ( - - - {stat.label} - - - {stat.value} - - - ))} - - - - {labels.view} - - - - - - ); -} diff --git a/platforms/market/src/app/screens/(landing)/organisms/featured-analysts/types.ts b/platforms/market/src/app/screens/(landing)/organisms/featured-analysts/types.ts index 8fbb008..c4eafc5 100644 --- a/platforms/market/src/app/screens/(landing)/organisms/featured-analysts/types.ts +++ b/platforms/market/src/app/screens/(landing)/organisms/featured-analysts/types.ts @@ -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; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/ChannelFeed.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/ChannelFeed.tsx index c563efd..b512f33 100644 --- a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/ChannelFeed.tsx +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/ChannelFeed.tsx @@ -12,6 +12,7 @@ export async function ChannelFeed({ channel, now, layout }: ChannelFeedProps) { 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 diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/types.ts b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/types.ts index c55ea90..94f75fa 100644 --- a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/types.ts +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/types.ts @@ -13,6 +13,7 @@ export type ChannelFeedProps = { export type ChannelFeedListProps = { creatorId: string; username: string; + displayName: string | null; avatarUrl: string | null; firstPage: PostPagePayload; now: string; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/ChannelHeader.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/ChannelHeader.tsx index 85fe493..8613da3 100644 --- a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/ChannelHeader.tsx +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/ChannelHeader.tsx @@ -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 = ( - - - - - - - @{channel.username} - - - {verified && ( - - )} - - - - {channelUrl} - - - - {share} - + const handle = ( + + @{channel.username} + ); - const body = ( + const content = ( <> + + + + + + {channel.displayName ?? handle} + + {verified && ( + + )} + + {channel.displayName && ( + + {handle} + + )} + + {share} + + {/* A suspended creator's own tab shows nothing past the name. */} + {!muted && ( + + )} {channel.bio && ( {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) => ( @@ -93,32 +101,38 @@ export function ChannelHeader({ {channel.socialLinks.length > 0 && ( )} - {stats} + {actions} ); if (isDesktop) { return ( - - - {identity} - {actions} - {body} - - + <> + + + {content} + + + {stats} + ); } return ( - - {identity} - {body} - {actions} - + <> + + {content} + + {stats != null && ( + // Collapses when the record renders nothing (below the threshold, or hidden). + + {stats} + + )} + ); } diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/components/ChannelCounts.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/components/ChannelCounts.tsx new file mode 100644 index 0000000..7179da4 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/components/ChannelCounts.tsx @@ -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 ( + + + + ); + } + + 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 ( + + {counts.map(({ key, value, label }) => ( + // dt before dd for the list's semantics; the number reads first. + + + {label} + + + {number(value)} + + + ))} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/index.ts b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/index.ts index 22f076f..4e307bf 100644 --- a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/index.ts +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/index.ts @@ -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, diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/types.ts b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/types.ts index 0be3f7f..a71c457 100644 --- a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/types.ts +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/types.ts @@ -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 & { links: PublicCreatorPayload['socialLinks']; }; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/components/OwnPendingChannel.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/components/OwnPendingChannel.tsx index bde08ca..8a48192 100644 --- a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/components/OwnPendingChannel.tsx +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/components/OwnPendingChannel.tsx @@ -39,7 +39,7 @@ export function OwnPendingChannel({ const { channel, standing, rejectionReason } = own; const banner = standing === 'rejected' ? ( - + {rejectionReason ? t('own.rejected-reason', { reason: rejectionReason }) : t('own.rejected')} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/PostChannelBar.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/PostChannelBar.tsx index 54e3fb7..29762e4 100644 --- a/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/PostChannelBar.tsx +++ b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/PostChannelBar.tsx @@ -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 = ( - - - - - - @{channel.username} - - - - - {actions} - - ); - - return layout === 'desktop' ? ( - - {content} - - ) : ( - - {content} + const handle = ( + + @{channel.username} ); + const card = ( + + + + + + + + {channel.displayName ?? handle} + + + + {channel.displayName && ( + + {handle} + + )} + + + + {actions} + + + ); + + // Mobile: a card in the padded column, over the post (J05-4). + return layout === 'desktop' ? ( + card + ) : ( + + {card} + + ); } diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/types.ts b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/types.ts index d6a04ce..a459c92 100644 --- a/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/types.ts +++ b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/types.ts @@ -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; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/PostView.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/PostView.tsx index c78465a..ba3b069 100644 --- a/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/PostView.tsx +++ b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/PostView.tsx @@ -43,6 +43,7 @@ const PostLightbox = dynamic(() => export function PostView({ post: serverPost, username, + displayName, avatarUrl, now, layout, @@ -82,6 +83,7 @@ export function PostView({ 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, diff --git a/platforms/market/src/app/screens/(main)/organisms/channel-post-card/types.ts b/platforms/market/src/app/screens/(main)/organisms/channel-post-card/types.ts index 9f8df45..729a7a1 100644 --- a/platforms/market/src/app/screens/(main)/organisms/channel-post-card/types.ts +++ b/platforms/market/src/app/screens/(main)/organisms/channel-post-card/types.ts @@ -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; diff --git a/platforms/market/src/app/screens/(main)/organisms/home-feed/HomeFeed.tsx b/platforms/market/src/app/screens/(main)/organisms/home-feed/HomeFeed.tsx index b31cd2d..c7a25a3 100644 --- a/platforms/market/src/app/screens/(main)/organisms/home-feed/HomeFeed.tsx +++ b/platforms/market/src/app/screens/(main)/organisms/home-feed/HomeFeed.tsx @@ -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" diff --git a/platforms/market/src/app/screens/organisms/sign-out-confirm/SignOutConfirm.tsx b/platforms/market/src/app/screens/organisms/sign-out-confirm/SignOutConfirm.tsx new file mode 100644 index 0000000..7468890 --- /dev/null +++ b/platforms/market/src/app/screens/organisms/sign-out-confirm/SignOutConfirm.tsx @@ -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 = ( + <> + + + + ); + // The number reads left to right inside the sentence. + const body = ( + {t('sign-out.body', { phone: `⁦${phone}⁩` })} + ); + + return layout === 'mobile' ? ( + + {body} + + ) : ( + + {body} + + ); +} diff --git a/platforms/market/src/app/screens/organisms/sign-out-confirm/hooks/use-sign-out.ts b/platforms/market/src/app/screens/organisms/sign-out-confirm/hooks/use-sign-out.ts new file mode 100644 index 0000000..ee5f3b8 --- /dev/null +++ b/platforms/market/src/app/screens/organisms/sign-out-confirm/hooks/use-sign-out.ts @@ -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(), + }; +} diff --git a/platforms/market/src/app/screens/organisms/sign-out-confirm/index.ts b/platforms/market/src/app/screens/organisms/sign-out-confirm/index.ts new file mode 100644 index 0000000..5be173b --- /dev/null +++ b/platforms/market/src/app/screens/organisms/sign-out-confirm/index.ts @@ -0,0 +1,2 @@ +export { SignOutConfirm } from './SignOutConfirm'; +export type { SignOutConfirmProps } from './types'; diff --git a/platforms/market/src/app/screens/organisms/sign-out-confirm/types.ts b/platforms/market/src/app/screens/organisms/sign-out-confirm/types.ts new file mode 100644 index 0000000..f97afe3 --- /dev/null +++ b/platforms/market/src/app/screens/organisms/sign-out-confirm/types.ts @@ -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; +}; diff --git a/platforms/market/src/features/channel/caches/channel.ts b/platforms/market/src/features/channel/caches/channel.ts index 3e019a5..3b12623 100644 --- a/platforms/market/src/features/channel/caches/channel.ts +++ b/platforms/market/src/features/channel/caches/channel.ts @@ -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 => - channelRepository.getCreatorByUsername({ username }), + async (username: string): Promise => { + 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 }; + }, ); diff --git a/platforms/market/src/features/channel/entities/follower-count/index.ts b/platforms/market/src/features/channel/entities/follower-count/index.ts new file mode 100644 index 0000000..bbc9410 --- /dev/null +++ b/platforms/market/src/features/channel/entities/follower-count/index.ts @@ -0,0 +1 @@ +export type { FollowerCountEntity } from './types'; diff --git a/platforms/market/src/features/channel/entities/follower-count/types.ts b/platforms/market/src/features/channel/entities/follower-count/types.ts new file mode 100644 index 0000000..1fbd537 --- /dev/null +++ b/platforms/market/src/features/channel/entities/follower-count/types.ts @@ -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; +}; diff --git a/platforms/market/src/features/channel/index.ts b/platforms/market/src/features/channel/index.ts index d47ca1d..d75d94a 100644 --- a/platforms/market/src/features/channel/index.ts +++ b/platforms/market/src/features/channel/index.ts @@ -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'; diff --git a/platforms/market/src/features/channel/models/channel-counts/index.ts b/platforms/market/src/features/channel/models/channel-counts/index.ts new file mode 100644 index 0000000..71a51af --- /dev/null +++ b/platforms/market/src/features/channel/models/channel-counts/index.ts @@ -0,0 +1,5 @@ +export { useChannelCountsPart } from './use-channel-counts-part'; +export type { + ChannelCountsPartModel, + UseChannelCountsPartOptions, +} from './types'; diff --git a/platforms/market/src/features/channel/models/channel-counts/types.ts b/platforms/market/src/features/channel/models/channel-counts/types.ts new file mode 100644 index 0000000..de389ed --- /dev/null +++ b/platforms/market/src/features/channel/models/channel-counts/types.ts @@ -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; +}; diff --git a/platforms/market/src/features/channel/models/channel-counts/use-channel-counts-part.ts b/platforms/market/src/features/channel/models/channel-counts/use-channel-counts-part.ts new file mode 100644 index 0000000..c6221c3 --- /dev/null +++ b/platforms/market/src/features/channel/models/channel-counts/use-channel-counts-part.ts @@ -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, + }; +} diff --git a/platforms/market/src/features/channel/models/follow-caches/sync-follow-caches.ts b/platforms/market/src/features/channel/models/follow-caches/sync-follow-caches.ts index ad90599..b97dc55 100644 --- a/platforms/market/src/features/channel/models/follow-caches/sync-follow-caches.ts +++ b/platforms/market/src/features/channel/models/follow-caches/sync-follow-caches.ts @@ -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() }); } diff --git a/platforms/market/src/features/channel/repositories/channel/channel.ts b/platforms/market/src/features/channel/repositories/channel/channel.ts index 7528171..0257761 100644 --- a/platforms/market/src/features/channel/repositories/channel/channel.ts +++ b/platforms/market/src/features/channel/repositories/channel/channel.ts @@ -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 { + const response = await channelHttp.get( + 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[] diff --git a/platforms/market/src/features/channel/repositories/channel/constants.ts b/platforms/market/src/features/channel/repositories/channel/constants.ts index f6841fb..a798940 100644 --- a/platforms/market/src/features/channel/repositories/channel/constants.ts +++ b/platforms/market/src/features/channel/repositories/channel/constants.ts @@ -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. */ diff --git a/platforms/market/src/features/channel/repositories/channel/mappers.ts b/platforms/market/src/features/channel/repositories/channel/mappers.ts index 463f676..8599f59 100644 --- a/platforms/market/src/features/channel/repositories/channel/mappers.ts +++ b/platforms/market/src/features/channel/repositories/channel/mappers.ts @@ -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[] { diff --git a/platforms/market/src/features/channel/repositories/channel/types.ts b/platforms/market/src/features/channel/repositories/channel/types.ts index 3dda529..882c74b 100644 --- a/platforms/market/src/features/channel/repositories/channel/types.ts +++ b/platforms/market/src/features/channel/repositories/channel/types.ts @@ -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; diff --git a/platforms/market/src/features/feed/entities/feed-item/types.ts b/platforms/market/src/features/feed/entities/feed-item/types.ts index 881dc35..8dadc08 100644 --- a/platforms/market/src/features/feed/entities/feed-item/types.ts +++ b/platforms/market/src/features/feed/entities/feed-item/types.ts @@ -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`. */ diff --git a/platforms/market/src/features/feed/repositories/feed/mappers.ts b/platforms/market/src/features/feed/repositories/feed/mappers.ts index e13be9b..16e85ad 100644 --- a/platforms/market/src/features/feed/repositories/feed/mappers.ts +++ b/platforms/market/src/features/feed/repositories/feed/mappers.ts @@ -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, diff --git a/platforms/market/src/features/feed/repositories/feed/types.ts b/platforms/market/src/features/feed/repositories/feed/types.ts index 99449ca..e975e71 100644 --- a/platforms/market/src/features/feed/repositories/feed/types.ts +++ b/platforms/market/src/features/feed/repositories/feed/types.ts @@ -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; diff --git a/platforms/market/src/features/post/entities/post/index.ts b/platforms/market/src/features/post/entities/post/index.ts index cf46ada..4b8985d 100644 --- a/platforms/market/src/features/post/entities/post/index.ts +++ b/platforms/market/src/features/post/entities/post/index.ts @@ -6,6 +6,7 @@ export type { PostMediaEntity, PostStatus, PostType, + PredictionCloseReason, PredictionDirection, PredictionEntity, PredictionOutcome, diff --git a/platforms/market/src/features/post/entities/post/types.ts b/platforms/market/src/features/post/entities/post/types.ts index 88a6af2..d7e4ef7 100644 --- a/platforms/market/src/features/post/entities/post/types.ts +++ b/platforms/market/src/features/post/entities/post/types.ts @@ -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; }; /** diff --git a/platforms/market/src/features/post/index.ts b/platforms/market/src/features/post/index.ts index 375d6c7..b390f20 100644 --- a/platforms/market/src/features/post/index.ts +++ b/platforms/market/src/features/post/index.ts @@ -6,6 +6,7 @@ export type { PostEntity, PostStatus, PostType, + PredictionCloseReason, PredictionDirection, PredictionOutcome, PredictionStatus, diff --git a/platforms/market/src/features/post/repositories/post/mappers.ts b/platforms/market/src/features/post/repositories/post/mappers.ts index 388b769..23a3d80 100644 --- a/platforms/market/src/features/post/repositories/post/mappers.ts +++ b/platforms/market/src/features/post/repositories/post/mappers.ts @@ -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, }; } diff --git a/platforms/market/src/features/post/repositories/post/types.ts b/platforms/market/src/features/post/repositories/post/types.ts index 4e5dc29..725769f 100644 --- a/platforms/market/src/features/post/repositories/post/types.ts +++ b/platforms/market/src/features/post/repositories/post/types.ts @@ -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; }; /** diff --git a/platforms/market/src/shared/labels/content-labels.tsx b/platforms/market/src/shared/labels/content-labels.tsx index a60fe2d..6a45ee3 100644 --- a/platforms/market/src/shared/labels/content-labels.tsx +++ b/platforms/market/src/shared/labels/content-labels.tsx @@ -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'), diff --git a/platforms/market/src/shared/locales/fa/channel.json b/platforms/market/src/shared/locales/fa/channel.json index b3d6399..a73c7f7 100644 --- a/platforms/market/src/shared/locales/fa/channel.json +++ b/platforms/market/src/shared/locales/fa/channel.json @@ -13,6 +13,8 @@ "loading": "در حال بارگذاری کانال…", "header": { "verified": "تأییدشده", + "followers": "دنبال‌کننده", + "subscribers": "مشترک فعال", "share": "اشتراک‌گذاری کانال", "markets": "بازارهای تخصصی", "links": "لینک‌های تحلیلگر", diff --git a/platforms/market/src/shared/locales/fa/common.json b/platforms/market/src/shared/locales/fa/common.json index 23f42a5..406be94 100644 --- a/platforms/market/src/shared/locales/fa/common.json +++ b/platforms/market/src/shared/locales/fa/common.json @@ -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": "تومان" } diff --git a/platforms/market/src/shared/locales/fa/content.json b/platforms/market/src/shared/locales/fa/content.json index a531a75..756d5ba 100644 --- a/platforms/market/src/shared/locales/fa/content.json +++ b/platforms/market/src/shared/locales/fa/content.json @@ -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": "دارایی، جهت، ورود، اهداف و حد ضرر پنهان است.",