feat(island): add on-dark and following button variants

Follow controls use on-dark and following instead of secondary, on the
channel and in دنبال‌شده‌ها. Discovery shows a plain label for a followed
analyst and no longer offers unfollow. Adds Vitest and Testing Library,
the repo's first test runner, and the pre-launch plan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Amiram_se 2026-11-02 01:09:08 +04:00
parent 4ae62a96e1
commit 684aa404f2
27 changed files with 994 additions and 214 deletions

View File

@ -0,0 +1,57 @@
# Pre-launch tasks: plan
Six tasks across this repo and the back end at `/home/msi/Documents/dreams/back`. Order: 6, 1, 2, 3, 5, 4.
## Where each thing lives
| Area | Front end | Back end |
|---|---|---|
| Buttons, tokens | `packages/island/src/atoms/button`, `styles/theme.css` | none |
| Auth, sign-up, KYC | `features/auth`, `screens/(auth)` | `apps/user-service`, `apps/gateway/src/auth.controller.ts` |
| Legal documents | `features/legal` (new), `/terms` | `apps/user-service` (`legal_documents`, `legal_acceptances`) |
| Signals (code name `prediction`) | `features/prediction`, `compose/prediction` | `apps/content-service/src/predictions` |
| Pricing, plans, subscriptions | `features/pricing`, `features/subscription` | `apps/subscription-service` |
| Payouts, ledger | `features/finance` | `apps/subscription-service/src/earnings.service.ts` |
| Notifications, SMS | `features/notification` | `apps/notification-service` |
| Admin | `apps/wall-street-plaza`, `platforms/garden-roof` | `apps/admin-api` |
## Migrations
The back end stores these in Mongo, which has no schema migrations, so each is a new collection, a field, or a one-time script:
- `user_service.legal_documents`, `legal_acceptances`: new, seeded at startup when empty.
- `content_service.posts`: `prediction.entryLow`, `entryHigh`, `entryMode`, `targetsHit`. Old rows stay as they are.
- `content_service.signal_stats`: new, one snapshot per analyst.
- `subscription_service.platform_settings`: new, holds `price_floor_monthly`.
- `subscription_service.subscription_tiers`: `off_sale_reason`.
- `scripts/flag-tiers-below-floor.js`: one-time, dry run by default, for running promotions under the new floor.
## Where the spec disagrees with the code
| Spec | Code | Resolution |
|---|---|---|
| One Next.js app for phone and desktop | `apps/bull` and `apps/bear`, sharing `platforms/market` (decision 0001) | Follow the code; UI goes in `platforms/market` |
| SQL tables, check constraints, migrations | Mongo through Mongoose; only payment-service uses Postgres | Collections; constraints become schema validators and service checks |
| `/api/...` routes | Gateway and admin-api serve `/v1/...` | `/v1/...`, same paths otherwise |
| Win rate over target, stop, expired | Closes store `win`, `loss`, `breakeven` and reasons `target`, `stop`, `horizon`, `early`, `admin` | User's answer: `early` and `admin` count by result at close |
| ROI splits the stake across targets | Only the final target closes a signal; earlier hits are not recorded | Record `targetsHit` from now on. Older closes: a `target` close hit every target, any other close is treated as having hit none, because no price history exists to replay |
| «باطل‌شده» | No such state exists | Counted as zero and excluded everywhere, until defined (TODO) |
| Entry stamped from the live quote | Server ignores a client entry today | Client entry accepted per spec; distance limit left as a TODO |
| `stop_loss` NOT NULL | Optional in the schema | Required on publish; old rows untouched |
| Component and API e2e tests | No front-end test runner; back end has Jest specs only, and its playbook says no e2e harness | Vitest and Testing Library added to the front end; back-end API tests run the Nest controllers through HTTP against mocked TCP clients |
| Branch per task | User asked for back-end commits on `main` | Back end: one commit per task, pushed to `main`. This repo: `feat/pre-launch-<n>-<slug>` branches, stacked in task order |
| `secondary` is purple outline | It is a neutral border on white | Same rule applied: no follow control uses it |
## Answers from the user (2026-11-02)
- `early` and `admin` closes count by result: profit is «هدف», loss is «حد ضرر», breakeven is «پایان مهلت».
- The placeholder agreement is minor, so nobody is blocked at deploy. The final text ships as major and then every analyst gets the modal.
- A tier below the floor also blocks renew and reactivate with 409 `tier_unavailable`.
- Running promotions under the new floor count as a raise: one-time script, dry run first, tiers go `below_floor`, analysts get the notice.
## Open questions, left as TODOs in code
- Maximum distance between a typed entry and the live quote.
- When a range-entry signal counts as entered.
- What makes a signal «باطل‌شده», and whether it counts in «کل سیگنال‌ها».
- Final legal text.

View File

@ -19,11 +19,15 @@
"@swc/core": "~1.15.5",
"@swc/helpers": "~0.5.18",
"@tailwindcss/postcss": "^4.3.3",
"@testing-library/dom": "^10.4.2",
"@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.8",
"@types/node": "^22.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"eslint": "^9.8.0",
"jiti": "^2.7.0",
"jsdom": "^30.1.3",
"nx": "23.2.1",
"oxlint": "^1.75.0",
"postcss": "^8.5.28",
@ -32,7 +36,8 @@
"tailwindcss": "^4.3.3",
"tslib": "^2.8.1",
"typescript": "^6.0.3",
"typescript-eslint": "^8.58.0"
"typescript-eslint": "^8.58.0",
"vitest": "^5.0.5"
},
"dependencies": {
"@hookform/resolvers": "^5.9.1",

View File

@ -2,6 +2,9 @@
"name": "@lumina/island",
"version": "0.0.1",
"private": true,
"scripts": {
"test": "vitest run --config ../../vitest.config.ts"
},
"type": "module",
"sideEffects": [
"**/*.css"

View File

@ -0,0 +1,15 @@
import { render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { ActionLabel } from './ActionLabel';
describe('ActionLabel', () => {
it('is not a button and has no pointer', () => {
render(<ActionLabel>دنبال می‌کنید</ActionLabel>);
expect(screen.queryByRole('button')).toBeNull();
const label = screen.getByText('دنبال می‌کنید').parentElement!;
expect(label.tagName).toBe('SPAN');
expect(label.className).toContain('cursor-default');
expect(label.className).toContain('bg-action-quiet');
});
});

View File

@ -0,0 +1,30 @@
import { cn } from '../../tools/cn';
import { FlexBox } from '../flex-box';
import { Icon } from '../icon';
import { Typography } from '../typography';
import type { ActionLabelProps } from './types';
import { actionLabelVariants } from './variants';
/** A state in a button's shape where the action isn't offered: no button role, no pointer. */
export function ActionLabel({
variant,
icon,
className,
children,
}: ActionLabelProps) {
return (
<FlexBox
tag="span"
display="inline-flex"
alignItems="items-center"
justifyContent="justify-center"
gap="gap-2"
className={cn(actionLabelVariants({ variant }), className)}
>
{icon && <Icon name={icon} size={16} className="flex-none" />}
<Typography tag="span" color="inherit" variant="label">
{children}
</Typography>
</FlexBox>
);
}

View File

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

View File

@ -0,0 +1,11 @@
import type { VariantProps } from 'class-variance-authority';
import type { ReactNode } from 'react';
import type { IconName } from '../icon';
import type { actionLabelVariants } from './variants';
export type ActionLabelProps = VariantProps<typeof actionLabelVariants> & {
icon?: IconName;
className?: string;
children: ReactNode;
};

View File

@ -0,0 +1,15 @@
import { cva } from 'class-variance-authority';
/** Drawn like a button of the same variant, with no hover, focus or pointer: nothing to press. */
export const actionLabelVariants = cva(
'min-h-control-sm cursor-default rounded-full border px-3 text-label leading-5 font-semibold whitespace-nowrap',
{
variants: {
variant: {
following:
'border-action-quiet-border bg-action-quiet text-action-quiet-text',
},
},
defaultVariants: { variant: 'following' },
},
);

View File

@ -0,0 +1,37 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';
import { Button } from './Button';
describe('Button follow variants', () => {
it('paints on-dark from its own tokens', () => {
render(<Button variant="on-dark">دنبال کردن</Button>);
const button = screen.getByRole('button', { name: 'دنبال کردن' });
expect(button.className).toContain('bg-action-dark');
expect(button.className).toContain('text-text-on-action');
expect(button.className).toContain('rounded-full');
});
it('paints following from its own tokens, with a border', () => {
render(<Button variant="following">دنبال می‌کنید</Button>);
const button = screen.getByRole('button', { name: 'دنبال می‌کنید' });
expect(button.className).toContain('bg-action-quiet');
expect(button.className).toContain('border-action-quiet-border');
expect(button.className).toContain('text-action-quiet-text');
});
it('keeps a frozen following button visible and explains it, without calling back', async () => {
const onClick = vi.fn();
render(
<Button variant="following" frozen frozenReason="دلیل" onClick={onClick}>
دنبال می‌کنید
</Button>,
);
const button = screen.getByText('دنبال می‌کنید').closest('button')!;
expect(button.classList.contains('frozen')).toBe(true);
await userEvent.click(button);
expect(onClick).not.toHaveBeenCalled();
expect(screen.getByText('دلیل')).toBeTruthy();
});
});

View File

@ -15,6 +15,10 @@ export const buttonVariants = cva(
'border-danger bg-surface text-danger-text actionable:hover:bg-danger-subtle',
'danger-solid':
'bg-danger-solid text-text-on-action actionable:hover:bg-danger-solid-hover actionable:active:bg-danger-solid-pressed',
'on-dark':
'bg-action-dark text-text-on-action actionable:hover:bg-action-dark-hover',
following:
'border-action-quiet-border bg-action-quiet text-action-quiet-text actionable:hover:bg-action-quiet-hover',
},
size: {
sm: 'min-h-control-sm min-w-control-sm px-3 text-label leading-5',

View File

@ -275,6 +275,14 @@
--action-primary-subtle: var(--indigo-50);
--action-primary-muted: var(--indigo-100);
--action-primary-text: var(--indigo-700);
/* «دنبال کردن»: dark beside the indigo «اشتراک», so the two never compete. */
--action-dark: var(--indigo-950);
--action-dark-hover: #2a2d78;
/* «دنبال می‌کنید»: a quiet state, not a call to act. */
--action-quiet: #f6f9fc;
--action-quiet-hover: #edf1f6;
--action-quiet-border: #e3e8ee;
--action-quiet-text: #273951;
--premium: var(--indigo-950);
--premium-on: var(--saffron-300);
--premium-accent: var(--saffron-600);
@ -344,6 +352,12 @@
--color-action-primary-subtle: var(--action-primary-subtle);
--color-action-primary-muted: var(--action-primary-muted);
--color-action-primary-text: var(--action-primary-text);
--color-action-dark: var(--action-dark);
--color-action-dark-hover: var(--action-dark-hover);
--color-action-quiet: var(--action-quiet);
--color-action-quiet-hover: var(--action-quiet-hover);
--color-action-quiet-border: var(--action-quiet-border);
--color-action-quiet-text: var(--action-quiet-text);
--color-premium: var(--premium);
--color-premium-on: var(--premium-on);
--color-premium-accent: var(--premium-accent);

View File

@ -2,6 +2,9 @@
"name": "@lumina/market",
"version": "0.0.1",
"private": true,
"scripts": {
"test": "vitest run --config ../../vitest.config.ts"
},
"type": "module",
"sideEffects": false,
"exports": {

View File

@ -55,12 +55,13 @@ export function GuestActions({
/>
)}
{followsToSubscribe ? (
<Button variant="secondary" href={toSubscribe}>
<Button variant="on-dark" icon="plus" href={toSubscribe}>
{t('actions.follow')}
</Button>
) : (
<Button
variant="secondary"
variant="on-dark"
icon="plus"
aria-haspopup="dialog"
onClick={openGuestPrompt}
>

View File

@ -0,0 +1,55 @@
import { render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import type { InvestorActionsProps } from '../types';
import { InvestorActions } from './InvestorActions';
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
const props = (standing: object) =>
({
username: 'analyst',
layout: 'desktop',
standing: { following: false, subscribed: false, ...standing },
follow: vi.fn(),
askUnfollow: vi.fn(),
isConfirmingUnfollow: false,
confirmUnfollow: vi.fn(),
cancelUnfollow: vi.fn(),
leaveWaitlist: vi.fn(),
isLeavingWaitlist: false,
requestSaleNotice: vi.fn(),
cancelSaleNotice: vi.fn(),
}) as unknown as InvestorActionsProps;
const followControl = (label: string) =>
screen.getByText(label).closest('button')!;
describe('InvestorActions follow control', () => {
it('not following: on-dark «دنبال کردن»', () => {
render(<InvestorActions {...props({})} />);
const control = followControl('actions.follow');
expect(control.className).toContain('bg-action-dark');
expect(control.classList.contains('frozen')).toBe(false);
});
it('following: live following button that asks first', () => {
render(<InvestorActions {...props({ following: true })} />);
const control = followControl('actions.following');
expect(control.className).toContain('bg-action-quiet');
expect(control.getAttribute('aria-haspopup')).toBe('dialog');
expect(control.classList.contains('frozen')).toBe(false);
});
it('subscriber: frozen following button with the reason', () => {
render(
<InvestorActions {...props({ following: true, subscribed: true })} />,
);
const control = followControl('actions.following');
expect(control.className).toContain('bg-action-quiet');
expect(control.classList.contains('frozen')).toBe(true);
expect(screen.getByText('actions.unfollow-frozen')).toBeTruthy();
});
});

View File

@ -95,26 +95,34 @@ export function InvestorActions({
const followControl = standing.subscribed ? (
<Button
variant="secondary"
variant="following"
icon="check"
frozen
frozenReason={t('actions.unfollow-frozen')}
// The row's last control, at the screen's end on a phone: the reason grows inward.
frozenAlign="end"
>
{t('actions.unfollow')}
{t('actions.following')}
</Button>
) : standing.following ? (
<Button
variant="secondary"
variant="following"
icon="check"
aria-haspopup="dialog"
onClick={askUnfollow}
frozenAlign="end"
{...offline}
>
{t('actions.unfollow')}
{t('actions.following')}
</Button>
) : (
<Button variant="secondary" onClick={follow} frozenAlign="end" {...offline}>
<Button
variant="on-dark"
icon="plus"
onClick={follow}
frozenAlign="end"
{...offline}
>
{t('actions.follow')}
</Button>
);

View File

@ -10,7 +10,7 @@ import type { FollowingRowProps } from '../types';
/**
* One followed creator as a list row (U8 ۴.۱, ۶.۱, J07-4): the avatar, the @username left to
* right with the display name under it, and «دنبال نکردن» at the end. The handle is a link stretched over the row, so a tap
* right with the display name under it, and «دنبال می‌کنید» at the end. The handle is a link stretched over the row, so a tap
* anywhere but the button opens the channel. A suspended creator's row is dimmed, opens nothing
* and says why under the handle, while the unfollow stays live (U8 ۴.۴, J07-4c). An active
* subscription freezes the unfollow, suspended or not, because the API refuses it (U8 ۴.۷); so
@ -58,7 +58,8 @@ export function FollowingRow({ row, offline, onUnfollow }: FollowingRowProps) {
<Element tag="span" className="relative">
{subscribed || offline ? (
<Button
variant="secondary"
variant="following"
icon="check"
frozen
frozenReason={
subscribed
@ -68,16 +69,17 @@ export function FollowingRow({ row, offline, onUnfollow }: FollowingRowProps) {
frozenAlign="end"
aria-label={unfollowLabel}
>
{t('channel:actions.unfollow')}
{t('channel:actions.following')}
</Button>
) : (
<Button
variant="secondary"
variant="following"
icon="check"
aria-haspopup="dialog"
aria-label={unfollowLabel}
onClick={onUnfollow}
>
{t('channel:actions.unfollow')}
{t('channel:actions.following')}
</Button>
)}
</Element>

View File

@ -10,7 +10,6 @@ import { useTranslation } from 'react-i18next';
import { useAnalystFollowPart } from '../../../../../features/discovery';
import type { CreatorSummaryPayload } from '../../../../../features/discovery';
import { ROUTES } from '../../../../navigation/navigation';
import { UnfollowConfirm } from '../unfollow-confirm';
import { AnalystFollowButton } from './components/AnalystFollowButton';
import { DESKTOP_COLUMNS } from './constants';
import { analystCardLabels } from './labels';
@ -21,7 +20,7 @@ import type { AnalystListProps } from './types';
* and search. One per row on mobile, a grid on desktop. The list is the same for every visitor and
* renders on the server; an investor's follow buttons join in the browser once their follows are
* read (`useAnalystFollowPart`), in the card's foot, which keeps its height meanwhile. A guest and a
* creator get none. Unfollow asks first: a sheet on mobile, a modal on desktop (J04-3c).
* creator get none. A followed analyst shows a label; unfollowing is not offered here.
*/
export function AnalystList({
analysts,
@ -44,65 +43,51 @@ export function AnalystList({
};
return (
<>
<GridBox
tag="ul"
aria-label={label}
cols={isDesktop ? DESKTOP_COLUMNS[columns] : 'grid-cols-1'}
gap={isDesktop ? 'gap-4' : 'gap-3'}
className="m-0 list-none p-0"
>
{analysts.map((analyst) => {
const state = follow.stateOf(analyst.creatorId);
return (
<Element
tag="li"
key={analyst.creatorId}
onClickCapture={onOpen ? openedFrom(analyst) : undefined}
className="min-w-0"
>
<AnalystCard
analyst={{
username: analyst.username,
displayName: analyst.displayName,
avatar: analyst.avatarUrl,
verified: analyst.verified,
markets: analyst.markets.map((market) =>
tCommon(`markets.${market}`),
),
bio: analyst.bio,
followers: analyst.followersCount,
stats: analyst.stats,
}}
href={ROUTES.channel(analyst.username)}
action={
state === 'follow' ||
state === 'following' ||
state === 'frozen' ? (
<AnalystFollowButton
analyst={analyst}
state={state}
onFollow={follow.follow}
onUnfollow={follow.askUnfollow}
/>
) : undefined
}
labels={labels}
className="h-full"
/>
</Element>
);
})}
</GridBox>
{follow.unfollowTarget && (
<UnfollowConfirm
open={follow.isConfirmingUnfollow}
username={follow.unfollowTarget.username}
layout={layout}
onConfirm={follow.confirmUnfollow}
onCancel={follow.cancelUnfollow}
/>
)}
</>
<GridBox
tag="ul"
aria-label={label}
cols={isDesktop ? DESKTOP_COLUMNS[columns] : 'grid-cols-1'}
gap={isDesktop ? 'gap-4' : 'gap-3'}
className="m-0 list-none p-0"
>
{analysts.map((analyst) => {
const state = follow.stateOf(analyst.creatorId);
return (
<Element
tag="li"
key={analyst.creatorId}
onClickCapture={onOpen ? openedFrom(analyst) : undefined}
className="min-w-0"
>
<AnalystCard
analyst={{
username: analyst.username,
displayName: analyst.displayName,
avatar: analyst.avatarUrl,
verified: analyst.verified,
markets: analyst.markets.map((market) =>
tCommon(`markets.${market}`),
),
bio: analyst.bio,
followers: analyst.followersCount,
stats: analyst.stats,
}}
href={ROUTES.channel(analyst.username)}
action={
state === 'follow' || state === 'following' ? (
<AnalystFollowButton
analyst={analyst}
state={state}
onFollow={follow.follow}
/>
) : undefined
}
labels={labels}
className="h-full"
/>
</Element>
);
})}
</GridBox>
);
}

View File

@ -0,0 +1,41 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';
import type { CreatorSummaryPayload } from '../../../../../../features/discovery';
import { AnalystFollowButton } from './AnalystFollowButton';
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
const analyst = { creatorId: '1' } as CreatorSummaryPayload;
describe('AnalystFollowButton', () => {
it('offers a follow on the dark button', async () => {
const onFollow = vi.fn();
render(
<AnalystFollowButton
analyst={analyst}
state="follow"
onFollow={onFollow}
/>,
);
const button = screen.getByRole('button', { name: 'actions.follow' });
expect(button.className).toContain('bg-action-dark');
await userEvent.click(button);
expect(onFollow).toHaveBeenCalledWith(analyst);
});
it('shows a followed analyst as a label with nothing to press', () => {
render(
<AnalystFollowButton
analyst={analyst}
state="following"
onFollow={vi.fn()}
/>,
);
expect(screen.queryByRole('button')).toBeNull();
expect(screen.getByText('actions.following')).toBeTruthy();
});
});

View File

@ -1,5 +1,6 @@
'use client';
import { ActionLabel } from '@lumina/island/atoms/action-label';
import { Button } from '@lumina/island/atoms/button';
import { useOfflineFreeze } from '@lumina/island/hooks/use-online';
import { useTranslation } from 'react-i18next';
@ -7,55 +8,30 @@ import { useTranslation } from 'react-i18next';
import type { AnalystFollowButtonProps } from '../types';
/**
* A card's follow control (DS AnalystCard): «دنبال کردن» with a plus, or «دنبال نکردن», which asks
* first; frozen with its reason while a subscription to the channel is active, or offline.
* A card's follow control (DS AnalystCard): «دنبال کردن» with a plus, or the plain «دنبال می‌کنید»
* label once followed. Unfollowing happens only on the channel or in دنبال‌شده‌ها.
*/
export function AnalystFollowButton({
analyst,
state,
onFollow,
onUnfollow,
}: AnalystFollowButtonProps) {
const { t } = useTranslation(['channel', 'common']);
const offline = useOfflineFreeze(t('common:network.frozen'));
if (state === 'follow') {
return (
<Button
variant="secondary"
size="sm"
icon="plus"
onClick={() => onFollow(analyst)}
frozenAlign="end"
{...offline}
>
{t('actions.follow')}
</Button>
);
}
if (state === 'frozen') {
return (
<Button
variant="secondary"
size="sm"
frozen
frozenReason={t('actions.unfollow-frozen')}
frozenAlign="end"
>
{t('actions.unfollow')}
</Button>
);
if (state === 'following') {
return <ActionLabel icon="check">{t('actions.following')}</ActionLabel>;
}
return (
<Button
variant="secondary"
variant="on-dark"
size="sm"
aria-haspopup="dialog"
onClick={() => onUnfollow(analyst)}
icon="plus"
onClick={() => onFollow(analyst)}
frozenAlign="end"
{...offline}
>
{t('actions.unfollow')}
{t('actions.follow')}
</Button>
);
}

View File

@ -32,7 +32,6 @@ export type AnalystListSkeletonProps = {
export type AnalystFollowButtonProps = {
analyst: CreatorSummaryPayload;
state: 'follow' | 'following' | 'frozen';
state: 'follow' | 'following';
onFollow: (analyst: CreatorSummaryPayload) => void;
onUnfollow: (analyst: CreatorSummaryPayload) => void;
};

View File

@ -2,15 +2,10 @@ import type { CreatorSummaryPayload } from '../../repositories/discovery';
/**
* An analyst card's follow control. `hidden`: no control (a guest, a creator, or the viewer's
* follows couldn't be read). `pending`: the viewer or their follows are on their way. `frozen`:
* followed with an active subscription, so unfollow can't be used and says why.
* follows couldn't be read). `pending`: the viewer or their follows are on their way. `following`:
* a plain label, since unfollowing happens only on the channel or in دنبال‌شده‌ها.
*/
export type AnalystFollowState =
| 'hidden'
| 'pending'
| 'follow'
| 'following'
| 'frozen';
export type AnalystFollowState = 'hidden' | 'pending' | 'follow' | 'following';
export type UseAnalystFollowPartOptions = {
/**
@ -24,12 +19,4 @@ export type AnalystFollowPartModel = {
stateOf: (creatorId: string) => AnalystFollowState;
/** Follows at once (optimistic); a failure turns it back and says so. */
follow: (analyst: CreatorSummaryPayload) => void;
/** Opens the unfollow question for this analyst. */
askUnfollow: (analyst: CreatorSummaryPayload) => void;
/** The analyst asked about; it stays after the question closes, so it closes on the same name. */
unfollowTarget: CreatorSummaryPayload | null;
isConfirmingUnfollow: boolean;
/** Unfollows at once (optimistic) and closes the question. */
confirmUnfollow: () => void;
cancelUnfollow: () => void;
};

View File

@ -1,5 +1,3 @@
import { showToast } from '@lumina/island/molecules/toast';
import { isHttpError } from '@lumina/libs/http';
import {
useInfiniteQuery,
useMutation,
@ -16,7 +14,6 @@ import {
FOLLOWING_PAGE_LIMIT,
followKeys,
followRepository,
unfollowCreator,
} from '../../../follow';
import type { CreatorSummaryPayload } from '../../repositories/discovery';
import type {
@ -25,17 +22,15 @@ import type {
UseAnalystFollowPartOptions,
} from './types';
type FollowChange = { analyst: CreatorSummaryPayload; following: boolean };
/**
* Follow and unfollow on analyst cards (empty خانه, «تحلیلگران منتخب», search). Only an investor
* gets the control. Whom they follow is their following list, read in the browser and merged per
* card, never kept with the analysts, which are the same for every visitor. Both changes show at
* once and turn back with the one error toast if the request fails (U8); unfollow asks first. A
* 409 means a subscription freezes the unfollow: the list is read again, so the card freezes too.
* Changes go one at a time, in the order tapped; each one refreshes the channel, the following
* list and the follower counts, and marks خانه's feed stale for its next visit; a follow with
* `onFollowed` (the empty خانه) also tells the caller, which reads the feed again in place (J04-2b).
* Follow on analyst cards (empty خانه, «تحلیلگران منتخب», search). Only an investor gets the
* control. Whom they follow is their following list, read in the browser and merged per card, never
* kept with the analysts, which are the same for every visitor. A follow shows at once and turns
* back with the one error toast if the request fails (U8). A followed analyst shows a plain label:
* unfollowing happens only on the channel or in دنبال‌شده‌ها. Follows go one at a time, in the order
* tapped; each one refreshes the channel, the following list and the follower counts, and marks
* خانه's feed stale for its next visit; with `onFollowed` (the empty خانه) it also tells the caller,
* which reads the feed again in place (J04-2b).
*/
export function useAnalystFollowPart({
onFollowed,
@ -45,10 +40,7 @@ export function useAnalystFollowPart({
const status = useViewerStatus();
const account = useCurrentAccount();
const isInvestor = status === 'member' && account?.role === 'investor';
const [changes, setChanges] = useState<Record<string, boolean>>({});
const [unfollowTarget, setUnfollowTarget] =
useState<CreatorSummaryPayload | null>(null);
const [isConfirmingUnfollow, setIsConfirmingUnfollow] = useState(false);
const [followedNow, setFollowedNow] = useState<Record<string, true>>({});
const following = useInfiniteQuery({
queryKey: followKeys.following(),
@ -63,19 +55,18 @@ export function useAnalystFollowPart({
enabled: isInvestor,
throwOnError: false,
});
// Whom they follow, and whether a subscription freezes the unfollow.
const followed = useMemo(
() =>
new Map(
new Set(
following.data?.pages
.flatMap((page) => page.items)
.map((row) => [row.creatorId, row.subscribed]),
.map((row) => row.creatorId),
),
[following.data],
);
const forget = (creatorId: string) =>
setChanges((current) => {
setFollowedNow((current) => {
const next = { ...current };
delete next[creatorId];
return next;
@ -85,37 +76,19 @@ export function useAnalystFollowPart({
const change = useMutation({
scope: { id: 'discovery-follow' },
mutationFn: ({ analyst, following: next }: FollowChange) =>
next
? followCreator({ creatorId: analyst.creatorId })
: unfollowCreator({ creatorId: analyst.creatorId }),
onMutate: ({ analyst, following: next }) =>
setChanges((current) => ({ ...current, [analyst.creatorId]: next })),
onSuccess: (_change, { analyst, following: next }) => {
mutationFn: (analyst: CreatorSummaryPayload) =>
followCreator({ creatorId: analyst.creatorId }),
onMutate: (analyst) =>
setFollowedNow((current) => ({ ...current, [analyst.creatorId]: true })),
onSuccess: (_change, analyst) => {
syncFollowCaches(queryClient, {
creatorId: analyst.creatorId,
following: next,
following: true,
});
if (next) {
onFollowed?.(analyst);
} else {
showToast({
tone: 'success',
message: t('follow.unfollowed', { username: analyst.username }),
});
}
onFollowed?.(analyst);
},
onError: (error, { analyst }) => {
onError: (error, analyst) => {
forget(analyst.creatorId);
if (isHttpError(error) && error.status === 409) {
reloadFollowing();
showToast({
tone: 'error',
message: t('follow.failed'),
description: t('actions.unfollow-frozen'),
});
return;
}
showActionError(error, {
t,
failedMessage: t('follow.failed'),
@ -129,26 +102,13 @@ export function useAnalystFollowPart({
if (!isInvestor) return 'hidden';
if (following.isPending) return 'pending';
if (following.isError) return 'hidden';
const subscribed = followed.get(creatorId);
if (!(changes[creatorId] ?? subscribed !== undefined)) return 'follow';
return subscribed ? 'frozen' : 'following';
return followedNow[creatorId] || followed.has(creatorId)
? 'following'
: 'follow';
};
return {
stateOf,
follow: (analyst) => change.mutate({ analyst, following: true }),
askUnfollow: (analyst) => {
setUnfollowTarget(analyst);
setIsConfirmingUnfollow(true);
},
unfollowTarget,
isConfirmingUnfollow,
confirmUnfollow: () => {
setIsConfirmingUnfollow(false);
if (unfollowTarget) {
change.mutate({ analyst: unfollowTarget, following: false });
}
},
cancelUnfollow: () => setIsConfirmingUnfollow(false),
follow: (analyst) => change.mutate(analyst),
};
}

View File

@ -33,7 +33,7 @@
"subscribe": "اشتراک",
"subscribed": "مشترک هستید",
"follow": "دنبال کردن",
"unfollow": "دنبال نکردن",
"following": "دنبال می‌کنید",
"unfollow-frozen": "تا زمانی که اشتراک این کانال فعال است، امکان لغو دنبال‌کردن وجود ندارد.",
"pending": "پرداخت در حال بررسی",
"pending-description": "پرداخت شما در حال بررسی است. پس از تأیید، اشتراک شما فعال می‌شود. اگر پرداخت انجام شده و اشتراک فعال نشد، با پشتیبانی در ارتباط باشید.",

View File

@ -10,7 +10,7 @@
"label": "تحلیلگرانی که دنبال می‌کنید",
"loading": "در حال بارگذاری دنبال‌شده‌ها…",
"error": "خطا در بارگذاری لیست. دوباره تلاش کنید.",
"unfollow": "دنبال نکردن ⁦@{{username}}⁩",
"unfollow": "دنبال می‌کنید ⁦@{{username}}⁩",
"unavailable": "در دسترس نیست",
"suspended": "کانال این تحلیلگر موقتاً در دسترس نیست.",
"more": "نمایش تحلیلگران بیشتر",

File diff suppressed because it is too large Load Diff

4
tools/vitest-setup.ts Normal file
View File

@ -0,0 +1,4 @@
import { cleanup } from '@testing-library/react';
import { afterEach } from 'vitest';
afterEach(cleanup);

14
vitest.config.ts Normal file
View File

@ -0,0 +1,14 @@
import { defineConfig } from 'vitest/config';
// Component and unit tests of every project; each project's `test` script runs its own folder.
export default defineConfig({
esbuild: { jsx: 'automatic' },
oxc: { jsx: { runtime: 'automatic' } },
resolve: { conditions: ['@lumina/source'] },
test: {
environment: 'jsdom',
include: ['src/**/*.test.{ts,tsx}'],
setupFiles: [`${import.meta.dirname}/tools/vitest-setup.ts`],
restoreMocks: true,
},
});