diff --git a/package.json b/package.json index b50a69a..a4d3cad 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "oxlint": "^1.75.0", "postcss": "^8.5.28", "prettier": "~3.6.2", + "svgo": "^4.1.0", "tailwindcss": "^4.3.3", "tslib": "^2.8.1", "typescript": "^6.0.3", @@ -41,6 +42,7 @@ "react": "^19.0.0", "react-dom": "^19.0.0", "server-only": "^0.0.1", + "sonner": "^2.0.8", "tailwind-merge": "^3.7.0", "valibot": "^1.5.0" } diff --git a/packages/island/package.json b/packages/island/package.json index 531e012..71af01c 100644 --- a/packages/island/package.json +++ b/packages/island/package.json @@ -14,6 +14,7 @@ "./organisms/*": "./src/organisms/*/index.ts", "./templates/*": "./src/templates/*/index.ts", "./primitives/*": "./src/primitives/*/index.ts", + "./hooks/*": "./src/hooks/*/index.ts", "./tools/*": "./src/tools/*/index.ts", "./env": "./src/env/index.ts", "./styles/*": "./src/styles/*", @@ -26,7 +27,24 @@ "tags": [ "type:ui", "scope:shared" - ] + ], + "targets": { + "icons": { + "command": "jiti src/tools/icon-sprite-plugin/run.ts", + "options": { + "cwd": "{projectRoot}" + }, + "inputs": [ + "{projectRoot}/src/icons/*.svg", + "{projectRoot}/src/tools/icon-sprite-plugin/**/*" + ], + "outputs": [ + "{projectRoot}/src/atoms/icon/sprite.svg", + "{projectRoot}/src/atoms/icon/icon-names.ts" + ], + "cache": true + } + } }, "dependencies": { "@lumina/libs": "workspace:*", diff --git a/packages/island/src/atoms/amount/.gitkeep b/packages/island/src/atoms/amount/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages/island/src/atoms/amount/Amount.tsx b/packages/island/src/atoms/amount/Amount.tsx new file mode 100644 index 0000000..34ef781 --- /dev/null +++ b/packages/island/src/atoms/amount/Amount.tsx @@ -0,0 +1,71 @@ +import { number, signed as signedNumber } from '@lumina/tools/format'; + +import { cn } from '../../tools/cn'; +import { FlexBox } from '../flex-box'; +import { Typography } from '../typography'; +import { amountWeight } from './constants'; +import type { AmountProps } from './types'; +import { + amountCurrencyVariants, + amountNumberVariants, + amountVariants, +} from './variants'; + +/** + * A Toman amount. The number sits in an LTR isolate, so a sign stays beside the digits in RTL + * text and the unit stays outside it. The font draws the digits in Persian. The root sets the + * size, so the unit can be 0.8em of it. + */ +export function Amount({ + value, + size, + tone = size === 'figure' ? 'figure' : 'ink', + struck = false, + signed = false, + decimals = 0, + currency, + srLabel, + className, + ...props +}: AmountProps) { + const weight = amountWeight({ size, tone, struck }); + + return ( + + + {signed ? signedNumber(value, decimals) : number(value, decimals)} + + {currency != null && ( + + {currency} + + )} + {srLabel && ( + // A leading space and brackets, so it reads as an aside after the amount. + + {` (${srLabel})`} + + )} + + ); +} diff --git a/packages/island/src/atoms/amount/constants.ts b/packages/island/src/atoms/amount/constants.ts new file mode 100644 index 0000000..3b0ecbb --- /dev/null +++ b/packages/island/src/atoms/amount/constants.ts @@ -0,0 +1,21 @@ +import type { AmountProps } from './types'; + +type AmountWeight = 'regular' | 'semibold' | 'bold'; + +/** + * The number's weight, in the design system's cascade order (the last matching rule wins): + * figure 700, then title 600, mute 400, positive 600, struck 400. So `mute` and `struck` stay + * regular even at figure size. + */ +export function amountWeight({ + size, + tone, + struck, +}: Pick): AmountWeight { + if (struck) return 'regular'; + if (tone === 'positive') return 'semibold'; + if (tone === 'mute') return 'regular'; + if (size === 'title') return 'semibold'; + if (size === 'figure' || tone === 'figure') return 'bold'; + return 'semibold'; +} diff --git a/packages/island/src/atoms/amount/index.ts b/packages/island/src/atoms/amount/index.ts new file mode 100644 index 0000000..594e30f --- /dev/null +++ b/packages/island/src/atoms/amount/index.ts @@ -0,0 +1,3 @@ +export { Amount } from './Amount'; +export type { AmountProps } from './types'; +export { amountVariants } from './variants'; diff --git a/packages/island/src/atoms/amount/types.ts b/packages/island/src/atoms/amount/types.ts new file mode 100644 index 0000000..53779a7 --- /dev/null +++ b/packages/island/src/atoms/amount/types.ts @@ -0,0 +1,17 @@ +import type { VariantProps } from 'class-variance-authority'; +import type { ComponentPropsWithRef, ReactNode } from 'react'; + +import type { amountVariants } from './variants'; + +export type AmountProps = Omit, 'children'> & + VariantProps & { + /** Whole Toman. Never Rial, never rounded or abbreviated. */ + value: number; + /** Always shows `+` or `−` (ledger lines). The colour stays; the sign carries the meaning. */ + signed?: boolean; + decimals?: number; + /** The unit after the number, such as «تومان». Omit it where a column header names the unit. */ + currency?: ReactNode; + /** Hidden text that says why, such as «لغو شده» on a struck amount. */ + srLabel?: string; + }; diff --git a/packages/island/src/atoms/amount/variants.ts b/packages/island/src/atoms/amount/variants.ts new file mode 100644 index 0000000..0075a04 --- /dev/null +++ b/packages/island/src/atoms/amount/variants.ts @@ -0,0 +1,52 @@ +import { cva } from 'class-variance-authority'; + +export const amountVariants = cva('whitespace-nowrap', { + variants: { + size: { + /** The one hero figure on a screen: قابل واریز, the checkout total. */ + figure: 'text-display', + /** Tier totals. */ + title: 'text-heading-sm', + body: 'text-body-md', + /** Dense rows. */ + caption: 'text-caption', + }, + tone: { + ink: 'text-text-primary', + /** The hero tone: ink with a bold number (600 at title size, as in the DS). Default at figure size. */ + figure: 'text-text-primary', + /** Per-month equivalents. */ + mute: 'text-text-secondary', + /** A negative balance, with its explanation underneath. */ + negative: 'text-danger-text', + /** Money returned to the investor (بازگشت وجه), with `signed`. */ + positive: 'text-success-text', + }, + /** A cancelled payout, or a standing price beside a promotion. */ + struck: { true: 'text-text-tertiary', false: '' }, + }, + defaultVariants: { size: 'body', tone: 'ink', struck: false }, +}); + +export const amountNumberVariants = cva('', { + variants: { + weight: { + regular: 'font-normal', + semibold: 'font-semibold', + bold: 'font-bold', + }, + struck: { + true: 'line-through decoration-[1.5px]', + false: '', + }, + }, + defaultVariants: { weight: 'semibold', struck: false }, +}); + +export const amountCurrencyVariants = cva('text-[0.8em] font-normal', { + variants: { + /** «تومان» is secondary next to an ink figure, and follows any other tone. */ + muted: { true: 'text-text-secondary', false: '' }, + }, + defaultVariants: { muted: true }, +}); diff --git a/packages/island/src/atoms/avatar/.gitkeep b/packages/island/src/atoms/avatar/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages/island/src/atoms/avatar/Avatar.tsx b/packages/island/src/atoms/avatar/Avatar.tsx new file mode 100644 index 0000000..01f1b85 --- /dev/null +++ b/packages/island/src/atoms/avatar/Avatar.tsx @@ -0,0 +1,78 @@ +import { cn } from '../../tools/cn'; +import { Element } from '../../primitives/element'; +import { GridBox } from '../grid-box'; +import { Icon } from '../icon'; +import { Typography } from '../typography'; +import { AVATAR_INITIAL_VARIANT, AVATAR_MARK_PX, AVATAR_PX } from './constants'; +import type { AvatarProps } from './types'; +import { avatarVariants } from './variants'; + +/** + * A circular creator or user picture. The placeholder sits under the image, so it shows while + * the image loads and when it fails, without client code. + */ +export function Avatar({ + name, + src, + size = 'md', + verified = false, + verifiedLabel, + label, + className, + ...props +}: AvatarProps) { + const px = AVATAR_PX[size]; + + return ( + + + + {Array.from(name)[0] ?? '?'} + + {src && ( + // A broken image with an empty alt draws nothing, so the letter shows through. + + )} + + {verified && ( + + + + )} + + ); +} diff --git a/packages/island/src/atoms/avatar/constants.ts b/packages/island/src/atoms/avatar/constants.ts new file mode 100644 index 0000000..a4491ec --- /dev/null +++ b/packages/island/src/atoms/avatar/constants.ts @@ -0,0 +1,24 @@ +import type { TypographyVariant } from '../typography'; +import type { AvatarSize } from './types'; + +/** px, so the image reserves its box before it loads. */ +export const AVATAR_PX: Record = { + sm: 32, + md: 40, + lg: 56, + xl: 80, +}; + +export const AVATAR_INITIAL_VARIANT: Record = { + sm: 'label', + md: 'body-md', + lg: 'heading-sm', + xl: 'heading-lg', +}; + +export const AVATAR_MARK_PX: Record = { + sm: 12, + md: 14, + lg: 18, + xl: 22, +}; diff --git a/packages/island/src/atoms/avatar/index.ts b/packages/island/src/atoms/avatar/index.ts new file mode 100644 index 0000000..6502cc2 --- /dev/null +++ b/packages/island/src/atoms/avatar/index.ts @@ -0,0 +1,3 @@ +export { Avatar } from './Avatar'; +export type { AvatarProps, AvatarSize } from './types'; +export { avatarVariants } from './variants'; diff --git a/packages/island/src/atoms/avatar/types.ts b/packages/island/src/atoms/avatar/types.ts new file mode 100644 index 0000000..e826ac3 --- /dev/null +++ b/packages/island/src/atoms/avatar/types.ts @@ -0,0 +1,25 @@ +import type { VariantProps } from 'class-variance-authority'; +import type { ComponentPropsWithRef } from 'react'; + +import type { avatarVariants } from './variants'; + +export type AvatarSize = NonNullable< + VariantProps['size'] +>; + +export type AvatarProps = Omit, 'children'> & { + /** The username: its first letter is the placeholder, or `?` while it is empty. */ + name: string; + /** The uploaded image; omit it to show the placeholder. */ + src?: string | null; + size?: AvatarSize; + /** The creator's verification mark at the bottom inline end. */ + verified?: boolean; + /** The mark's accessible name, such as «تأیید‌شده». */ + verifiedLabel?: string; + /** + * The avatar's accessible name. Omit it when the username is next to it, as on a post header, + * so screen readers don't read the name twice. + */ + label?: string; +}; diff --git a/packages/island/src/atoms/avatar/variants.ts b/packages/island/src/atoms/avatar/variants.ts new file mode 100644 index 0000000..09e2ef8 --- /dev/null +++ b/packages/island/src/atoms/avatar/variants.ts @@ -0,0 +1,21 @@ +import { cva } from 'class-variance-authority'; + +/** The placeholder is the username's first letter in white on `action-primary`. */ +export const avatarVariants = cva( + 'relative flex-none overflow-hidden rounded-full bg-action-primary text-text-on-action', + { + variants: { + size: { + /** Compact rows and the top bar. */ + sm: 'size-8', + /** Post headers, subscription cards, list rows. */ + md: 'size-10', + /** Sheet and checkout headers. */ + lg: 'size-14', + /** The channel profile header. */ + xl: 'size-20', + }, + }, + defaultVariants: { size: 'md' }, + }, +); diff --git a/packages/island/src/atoms/button/.gitkeep b/packages/island/src/atoms/button/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages/island/src/atoms/button/Button.tsx b/packages/island/src/atoms/button/Button.tsx new file mode 100644 index 0000000..c57bc5b --- /dev/null +++ b/packages/island/src/atoms/button/Button.tsx @@ -0,0 +1,109 @@ +import NextLink from 'next/link'; +import type { MouseEvent } from 'react'; + +import { cn } from '../../tools/cn'; +import { FlexBox } from '../flex-box'; +import { ButtonContent } from './components/ButtonContent'; +import { FrozenButton } from './components/FrozenButton'; +import { buttonLayout, withoutLinkProps } from './constants'; +import type { ButtonLinkElementProps, ButtonProps } from './types'; +import { buttonVariants } from './variants'; + +/** + * Every tappable action: a full pill (an icon-only button is a circle). No hooks, so a server + * component can render it with no JavaScript; only a frozen button with a reason is a client one. + */ +export function Button({ + variant, + size, + block, + icon, + iconEnd, + label, + frozen = false, + frozenReason, + isLoading = false, + className, + children, + ...props +}: ButtonProps) { + const iconOnly = children == null && icon !== undefined; + const classes = cn( + buttonVariants({ variant, size, block, iconOnly, frozen }), + className, + ); + const content = ( + + {children} + + ); + const ariaLabel = iconOnly ? label : props['aria-label']; + const title = iconOnly && !frozen ? label : undefined; + const isBlocked = frozen || isLoading; + + // A frozen or loading link renders a ` + ); + + return ( + + {digestLabel}{' '} + + {digest} + + + ) + } + icon={icon ?? style.icon} + tone={style.tone} + size={size} + inlineIcon + actions={ + (retry || children) && ( + <> + {retry} + {children} + + ) + } + className={className} + /> + ); +} diff --git a/packages/island/src/molecules/error-state/constants.ts b/packages/island/src/molecules/error-state/constants.ts new file mode 100644 index 0000000..bb9d9e2 --- /dev/null +++ b/packages/island/src/molecules/error-state/constants.ts @@ -0,0 +1,12 @@ +import type { ErrorKind, ErrorKindStyle } from './types'; + +export const ERROR_KIND_STYLES: Record = { + error: { icon: 'alert', tone: 'danger', role: 'alert' }, + server: { icon: 'server', tone: 'danger', role: 'alert' }, + network: { icon: 'wifi-off', tone: 'warning', role: 'alert' }, + offline: { icon: 'wifi-off', tone: 'neutral', role: 'status' }, + timeout: { icon: 'clock', tone: 'warning', role: 'alert' }, + 'not-found': { icon: 'search-x', tone: 'neutral', role: 'status' }, + forbidden: { icon: 'lock', tone: 'neutral', role: 'status' }, + session: { icon: 'log-out', tone: 'neutral', role: 'status' }, +}; diff --git a/packages/island/src/molecules/error-state/index.ts b/packages/island/src/molecules/error-state/index.ts new file mode 100644 index 0000000..b9f4c37 --- /dev/null +++ b/packages/island/src/molecules/error-state/index.ts @@ -0,0 +1,3 @@ +export { ERROR_KIND_STYLES } from './constants'; +export { ErrorState } from './ErrorState'; +export type { ErrorKind, ErrorStateProps } from './types'; diff --git a/packages/island/src/molecules/error-state/types.ts b/packages/island/src/molecules/error-state/types.ts new file mode 100644 index 0000000..f85e97a --- /dev/null +++ b/packages/island/src/molecules/error-state/types.ts @@ -0,0 +1,54 @@ +import type { ReactNode } from 'react'; + +import type { IconName } from '../../atoms/icon'; +import type { StateTone } from '../../atoms/state-art'; + +/** + * error: a render or data failure. server: a 5xx, or an error with a digest. network: the request + * failed while online. offline: `navigator.onLine` is false. timeout: our time limit aborted it. + * not-found: 404. forbidden: 403. session: 401 or an expired OTP session. + */ +export type ErrorKind = + | 'error' + | 'server' + | 'network' + | 'offline' + | 'timeout' + | 'not-found' + | 'forbidden' + | 'session'; + +export type ErrorKindStyle = { + icon: IconName; + tone: StateTone; + /** Offline, not-found, forbidden and session are not alarms. */ + role: 'alert' | 'status'; +}; + +export type ErrorStateProps = { + kind?: ErrorKind; + /** The kind's copy from the translations, such as «مشکلی پیش آمد». */ + title: ReactNode; + description?: ReactNode; + icon?: IconName; + /** Next.js `retry` (error.tsx, catchError) or a refetch. Shows the retry button. */ + onRetry?: () => void; + /** The retry button's label, such as «تلاش مجدد». */ + retryLabel?: ReactNode; + /** The retry button's label while `retrying`, such as «در حال تلاش…». Falls back to `retryLabel`. */ + retryingLabel?: ReactNode; + /** + * The retry is in flight: the button keeps its place (even without `onRetry`), shows a spinner + * and `retryingLabel`, and blocks repeat taps. + */ + retrying?: boolean; + /** Next.js `error.digest`, so support can match server logs. Never show `error.message`. */ + digest?: string; + /** The digest's label, such as «کد پیگیری». */ + digestLabel?: ReactNode; + /** page: a route (error.tsx, not-found.tsx). section: one widget. inline: one row. */ + size?: 'page' | 'section' | 'inline'; + /** One escape route after retry: «بازگشت به خانه», «تماس با پشتیبانی», «ورود دوباره». */ + children?: ReactNode; + className?: string; +}; diff --git a/packages/island/src/molecules/locked-teaser/LockedTeaser.tsx b/packages/island/src/molecules/locked-teaser/LockedTeaser.tsx new file mode 100644 index 0000000..7c84a03 --- /dev/null +++ b/packages/island/src/molecules/locked-teaser/LockedTeaser.tsx @@ -0,0 +1,92 @@ +import { number } from '@lumina/tools/format'; + +import { Button } from '../../atoms/button'; +import { FlexBox } from '../../atoms/flex-box'; +import { GridBox } from '../../atoms/grid-box'; +import { Icon } from '../../atoms/icon'; +import { Tag } from '../../atoms/tag'; +import { Typography } from '../../atoms/typography'; +import { Element } from '../../primitives/element'; +import { ACTION_CLASS } from './constants'; +import type { LockedTeaserProps } from './types'; + +/** + * The one locked premium body, on the channel, the post page and the feed alike: two lines of + * preview fading into a saffron lock, a lock placeholder for the images, a prediction's frame, + * then one message and one CTA on `premium-subtle`. Images are never shown or blurred, not even + * from a blurHash: a blurred chart still leaks the direction. + */ +export function LockedTeaser({ + preview, + mediaCount = 0, + mediaCountLabel, + mediaLabel, + children, + message, + actionLabel, + actionHref, + onAction, + className, +}: LockedTeaserProps) { + return ( + + {preview != null && ( + + + {preview} + + + + + + + + )} + {mediaCount > 0 && ( + + + {mediaCount > 1 && mediaCountLabel && ( + + {mediaCountLabel(number(mediaCount))} + + )} + + )} + {children} + + {message} + {actionHref ? ( + + ) : ( + + )} + + + ); +} diff --git a/packages/island/src/molecules/locked-teaser/constants.ts b/packages/island/src/molecules/locked-teaser/constants.ts new file mode 100644 index 0000000..c1f59d1 --- /dev/null +++ b/packages/island/src/molecules/locked-teaser/constants.ts @@ -0,0 +1,2 @@ +/** Puts the CTA above a card's stretched link (PostCard's), so it keeps its own tap. */ +export const ACTION_CLASS = 'relative z-1'; diff --git a/packages/island/src/molecules/locked-teaser/index.ts b/packages/island/src/molecules/locked-teaser/index.ts new file mode 100644 index 0000000..5a98d4d --- /dev/null +++ b/packages/island/src/molecules/locked-teaser/index.ts @@ -0,0 +1,2 @@ +export { LockedTeaser } from './LockedTeaser'; +export type { LockedTeaserProps } from './types'; diff --git a/packages/island/src/molecules/locked-teaser/types.ts b/packages/island/src/molecules/locked-teaser/types.ts new file mode 100644 index 0000000..1d451e7 --- /dev/null +++ b/packages/island/src/molecules/locked-teaser/types.ts @@ -0,0 +1,26 @@ +import type { ReactNode } from 'react'; + +export type LockedTeaserProps = { + /** `captionPreview` from the API. Clamped to 2 lines, a hard limit so no analysis leaks. */ + preview?: ReactNode; + /** How many images are behind the lock; 0 or omitted shows no image placeholder. */ + mediaCount?: number; + /** The placeholder's count, shown from 2 images: `(n) => <>{n} تصویر` → «۳ تصویر». */ + mediaCountLabel?: (count: string) => ReactNode; + /** The placeholder lock's accessible name, such as «محتوای قفل‌شده». */ + mediaLabel?: string; + /** A locked prediction's frame (PredictionCard `locked`), between the images and the gate. */ + children?: ReactNode; + /** + * The one message for who is looking. A guest: «برای دسترسی به این محتوا، ابتدا وارد شوید یا + * ثبت‌نام کنید.». A member: «برای مشاهده این محتوا، نیاز به اشتراک در کانال آن دارید.». + */ + message: ReactNode; + /** The one primary Button for the same viewer: «ورود/ثبت‌نام» or «اشتراک در کانال». Never both. */ + actionLabel: ReactNode; + /** Where the Button goes (auth, or the channel's tiers); renders a link, so a server can pass it. */ + actionHref?: string; + /** Instead of `actionHref`, such as opening the auth sheet. Client callers only. */ + onAction?: () => void; + className?: string; +}; diff --git a/packages/island/src/molecules/media-carousel/MediaCarousel.tsx b/packages/island/src/molecules/media-carousel/MediaCarousel.tsx new file mode 100644 index 0000000..c661068 --- /dev/null +++ b/packages/island/src/molecules/media-carousel/MediaCarousel.tsx @@ -0,0 +1,48 @@ +import { MediaSlide } from './components/MediaSlide'; +import { MediaTrack } from './components/MediaTrack'; +import { MAX_MEDIA } from './constants'; +import type { MediaCarouselProps } from './types'; + +/** + * A post's images. One shows full width at its own ratio, letterboxed at 400px on + * `surface-sunken`; 2–4 swipe in 280px slides with dots and a «۱ / ۳» count. Server-renderable: + * a single image ships no JavaScript, and only the swipe track is a client component, so every + * prop it takes is serializable except `onOpen`, which only a client caller can pass. + */ +export function MediaCarousel({ + items, + slideLabels, + href, + onOpen, + label, + className, +}: MediaCarouselProps) { + const shown = items.slice(0, MAX_MEDIA); + + if (shown.length === 0) return null; + + if (shown.length === 1) { + return ( + + ); + } + + return ( + + ); +} diff --git a/packages/island/src/molecules/media-carousel/components/MediaSlide.tsx b/packages/island/src/molecules/media-carousel/components/MediaSlide.tsx new file mode 100644 index 0000000..13a0632 --- /dev/null +++ b/packages/island/src/molecules/media-carousel/components/MediaSlide.tsx @@ -0,0 +1,78 @@ +import NextLink from 'next/link'; + +import { GridBox } from '../../../atoms/grid-box'; +import { Element } from '../../../primitives/element'; +import { cn } from '../../../tools/cn'; +import type { MediaSlideProps } from '../types'; +import { mediaImageVariants, mediaSlideVariants } from '../variants'; + +/** + * One image, contained in its box. With `onOpen` the box is the button that opens the Lightbox; + * with `href` a hidden link covers it, so a tap opens the post while the image keeps its alt. + */ +export function MediaSlide({ + item, + index, + single, + label, + href, + onOpen, + className, +}: MediaSlideProps) { + const box = cn(mediaSlideVariants({ single }), className); + const image = ( + + ); + + if (onOpen) { + return ( + onOpen(index)} + aria-label={label ?? (item.alt || undefined)} + className={cn( + box, + 'actionable:cursor-zoom-in', + // A slide's ring would be clipped by the scrolling track, so the track's frame draws it. + single ? 'focus-visible:focus-ring' : 'outline-none', + )} + > + {image} + + ); + } + + return ( + + {image} + {href && ( + // The post's own link carries the keyboard path; this one is only a bigger tap area. + + )} + + ); +} diff --git a/packages/island/src/molecules/media-carousel/components/MediaTrack.tsx b/packages/island/src/molecules/media-carousel/components/MediaTrack.tsx new file mode 100644 index 0000000..d602fab --- /dev/null +++ b/packages/island/src/molecules/media-carousel/components/MediaTrack.tsx @@ -0,0 +1,86 @@ +'use client'; + +import { number } from '@lumina/tools/format'; +import { useState } from 'react'; +import type { UIEvent } from 'react'; + +import { FlexBox } from '../../../atoms/flex-box'; +import { Typography } from '../../../atoms/typography'; +import { Element } from '../../../primitives/element'; +import type { MediaCarouselProps } from '../types'; +import { mediaDotVariants } from '../variants'; +import { MediaSlide } from './MediaSlide'; + +/** + * 2–4 images in a native swipe (scroll snap), with a «۱ / ۳» chip and a dot per image. The only + * client part of a post: it follows the scroll to light the current dot and count. + */ +export function MediaTrack({ + items, + slideLabels, + href, + onOpen, + label, + className, +}: MediaCarouselProps) { + const [current, setCurrent] = useState(0); + const count = items.length; + + // scrollLeft is negative in RTL, so its size gives the slide either way. + const handleScroll = (event: UIEvent) => { + const { scrollLeft, clientWidth } = event.currentTarget; + const index = Math.round(Math.abs(scrollLeft) / Math.max(1, clientWidth)); + setCurrent(Math.min(count - 1, index)); + }; + + return ( + + + + {items.map((item, index) => ( + + ))} + + {/* Each slide button already says «۱ از ۳»; the chip is for the eye only. */} + + + {number(current + 1)} / {number(count)} + + + + + {items.map((item, index) => ( + + ))} + + + ); +} diff --git a/packages/island/src/molecules/media-carousel/constants.ts b/packages/island/src/molecules/media-carousel/constants.ts new file mode 100644 index 0000000..f7b9d8d --- /dev/null +++ b/packages/island/src/molecules/media-carousel/constants.ts @@ -0,0 +1,2 @@ +/** A post carries at most four images. */ +export const MAX_MEDIA = 4; diff --git a/packages/island/src/molecules/media-carousel/index.ts b/packages/island/src/molecules/media-carousel/index.ts new file mode 100644 index 0000000..157358f --- /dev/null +++ b/packages/island/src/molecules/media-carousel/index.ts @@ -0,0 +1,2 @@ +export { MediaCarousel } from './MediaCarousel'; +export type { MediaCarouselProps, MediaItem } from './types'; diff --git a/packages/island/src/molecules/media-carousel/types.ts b/packages/island/src/molecules/media-carousel/types.ts new file mode 100644 index 0000000..cfab787 --- /dev/null +++ b/packages/island/src/molecules/media-carousel/types.ts @@ -0,0 +1,42 @@ +export type MediaItem = { + src: string; + /** Natural size in px, so a single image reserves its box at its own ratio before it loads. */ + width: number; + height: number; + /** Describes the image; `''` only when it adds nothing to the caption. */ + alt: string; +}; + +/** + * Every prop is serializable except `onOpen`, because the swipe track is a client component: a + * server component may render the carousel, and only a client caller can pass `onOpen`. + */ +export type MediaCarouselProps = { + /** 1–4 images; any after the fourth are dropped. One shows alone; more swipe, with dots. */ + items: MediaItem[]; + /** + * Each image button's accessible name, by index and already formatted (strings, not a function, + * so they can cross into the client track): «نمایش تصویر ۱ از ۳، نمودار طلا», or for a single + * image «نمایش تصویر، نمودار طلا». Without it a button is named by its image's `alt`. + */ + slideLabels?: string[]; + /** In a list: a tap on an image opens the post. */ + href?: string; + /** On the post page: a tap opens the Lightbox at that image. Wins over `href`. Client callers only. */ + onOpen?: (index: number) => void; + /** The swipe section's accessible name, such as «تصاویر پست». */ + label?: string; + className?: string; +}; + +export type MediaSlideProps = { + item: MediaItem; + index: number; + /** Alone at its own ratio (max 400px) rather than a 280px slide in the track. */ + single: boolean; + /** The button's accessible name; see `slideLabels`. */ + label?: string; + href?: string; + onOpen?: (index: number) => void; + className?: string; +}; diff --git a/packages/island/src/molecules/media-carousel/variants.ts b/packages/island/src/molecules/media-carousel/variants.ts new file mode 100644 index 0000000..7991fb9 --- /dev/null +++ b/packages/island/src/molecules/media-carousel/variants.ts @@ -0,0 +1,35 @@ +import { cva } from 'class-variance-authority'; + +/** The image's box: letterboxed on `surface-sunken`, the track's ground when it swipes. */ +export const mediaSlideVariants = cva('relative', { + variants: { + single: { + true: 'w-full overflow-hidden rounded-md bg-surface-sunken', + false: 'h-70 max-h-100 w-full flex-none snap-center snap-always', + }, + }, +}); + +/** Contained, never cropped: the Lightbox shows the image whole anyway. */ +export const mediaImageVariants = cva('block object-contain', { + variants: { + single: { + true: 'h-auto max-h-100 w-full', + false: 'h-auto max-h-full w-auto max-w-full', + }, + }, +}); + +/** The current image's dot stretches into an 18px pill. */ +export const mediaDotVariants = cva( + 'h-1.5 rounded-full transition-[width,background-color] duration-200 ease-standard', + { + variants: { + active: { + true: 'w-4.5 bg-action-primary', + false: 'w-1.5 bg-border-strong', + }, + }, + defaultVariants: { active: false }, + }, +); diff --git a/packages/island/src/molecules/network-status/NetworkStatus.tsx b/packages/island/src/molecules/network-status/NetworkStatus.tsx new file mode 100644 index 0000000..151c161 --- /dev/null +++ b/packages/island/src/molecules/network-status/NetworkStatus.tsx @@ -0,0 +1,74 @@ +import { FlexBox } from '../../atoms/flex-box'; +import { Icon } from '../../atoms/icon'; +import { Spinner } from '../../atoms/spinner'; +import { Typography } from '../../atoms/typography'; +import { Element } from '../../primitives/element'; +import { cn } from '../../tools/cn'; +import { NETWORK_ICONS } from './constants'; +import type { NetworkStatusProps } from './types'; +import { networkDescriptionVariants, networkStatusVariants } from './variants'; + +/** + * The connection bar: a full-width strip under the top bar (mobile) or header (desktop) saying the + * app is offline, reconnecting, back online or slow, while the page under it stays usable. Only + * draws the state: the app's network boundary listens to the connection, picks the status and + * slides the online bar away. Announced politely and never takes focus. + */ +export function NetworkStatus({ + status, + title, + description, + onRetry, + retryLabel, + contained = false, + className, +}: NetworkStatusProps) { + return ( + : a page-level bar with a button, not the result of a form. + // oxlint-disable-next-line jsx-a11y/prefer-tag-over-role + role="status" + aria-live="polite" + alignItems="items-center" + gap="gap-3" + className={cn(networkStatusVariants({ status, contained }), className)} + > + {status === 'reconnecting' ? ( + + ) : ( + + )} + + + {title} + + {description != null && ( + + {description} + + )} + + {status === 'offline' && onRetry && ( + + + {retryLabel} + + + )} + + ); +} diff --git a/packages/island/src/molecules/network-status/constants.ts b/packages/island/src/molecules/network-status/constants.ts new file mode 100644 index 0000000..39568b5 --- /dev/null +++ b/packages/island/src/molecules/network-status/constants.ts @@ -0,0 +1,12 @@ +import type { IconName } from '../../atoms/icon'; +import type { NetworkState } from './types'; + +/** reconnecting shows a spinner instead. */ +export const NETWORK_ICONS: Record< + Exclude, + IconName +> = { + offline: 'wifi-off', + online: 'wifi', + slow: 'clock', +}; diff --git a/packages/island/src/molecules/network-status/index.ts b/packages/island/src/molecules/network-status/index.ts new file mode 100644 index 0000000..ed06ac5 --- /dev/null +++ b/packages/island/src/molecules/network-status/index.ts @@ -0,0 +1,3 @@ +export { NetworkStatus } from './NetworkStatus'; +export type { NetworkState, NetworkStatusProps } from './types'; +export { networkStatusVariants } from './variants'; diff --git a/packages/island/src/molecules/network-status/types.ts b/packages/island/src/molecules/network-status/types.ts new file mode 100644 index 0000000..4df62fd --- /dev/null +++ b/packages/island/src/molecules/network-status/types.ts @@ -0,0 +1,22 @@ +import type { ReactNode } from 'react'; + +/** + * offline: no connection. reconnecting: refetching after the `online` event or a retry tap. + * online: back, for 3 seconds after the refetch succeeds. slow: a read has taken over 4 seconds. + */ +export type NetworkState = 'offline' | 'reconnecting' | 'online' | 'slow'; + +export type NetworkStatusProps = { + status: NetworkState; + /** «اینترنت قطع است», «در حال اتصال دوباره…», «دوباره آنلاین شدید» or «اتصال کند است». */ + title: ReactNode; + /** After the title, wrapping under it on narrow screens: «آخرین اطلاعات ذخیره‌شده را می‌بینید.». */ + description?: ReactNode; + /** offline only: shows the retry pill at the end of the bar. */ + onRetry?: () => void; + /** offline only: «تلاش مجدد». */ + retryLabel?: ReactNode; + /** In the flow instead of sticky, for previews and canvases. */ + contained?: boolean; + className?: string; +}; diff --git a/packages/island/src/molecules/network-status/variants.ts b/packages/island/src/molecules/network-status/variants.ts new file mode 100644 index 0000000..05cab38 --- /dev/null +++ b/packages/island/src/molecules/network-status/variants.ts @@ -0,0 +1,32 @@ +import { cva } from 'class-variance-authority'; + +/** Sticky under the top bar: it pushes the page down and never floats over inputs or the CTA. */ +export const networkStatusVariants = cva('min-h-12 w-full px-4 py-2', { + variants: { + status: { + offline: 'bg-surface-inverse text-text-inverse', + reconnecting: 'bg-surface-inverse text-text-inverse', + online: + 'border-b border-success-muted bg-success-subtle text-success-text', + slow: 'border-b border-warning-muted bg-warning-subtle text-warning-text', + }, + contained: { + true: 'relative', + false: 'sticky top-0 z-sticky', + }, + }, + defaultVariants: { status: 'offline', contained: false }, +}); + +/** The description dims on the dark bar and turns grey on the light ones. */ +export const networkDescriptionVariants = cva('font-normal', { + variants: { + status: { + offline: 'opacity-80', + reconnecting: 'opacity-80', + online: 'text-text-secondary', + slow: 'text-text-secondary', + }, + }, + defaultVariants: { status: 'offline' }, +}); diff --git a/packages/island/src/molecules/otp-input/OtpInput.tsx b/packages/island/src/molecules/otp-input/OtpInput.tsx new file mode 100644 index 0000000..f7774a4 --- /dev/null +++ b/packages/island/src/molecules/otp-input/OtpInput.tsx @@ -0,0 +1,173 @@ +'use client'; + +import { latinDigits } from '@lumina/tools/format'; +import { Fragment, useId, useState } from 'react'; +import type { ChangeEvent } from 'react'; + +import { FlexBox } from '../../atoms/flex-box'; +import { GridBox } from '../../atoms/grid-box'; +import { Icon } from '../../atoms/icon'; +import { Typography } from '../../atoms/typography'; +import { Element } from '../../primitives/element'; +import { cn } from '../../tools/cn'; +import { NON_DIGITS, OTP_GROUP, OTP_LENGTH } from './constants'; +import { useWebOtp } from './hooks/use-web-otp'; +import type { OtpInputProps } from './types'; +import { otpCellVariants } from './variants'; + +/** + * The verification code field: ONE real input (SMS autofill, paste and screen readers all work on + * it) drawn as cells, read left to right. The font draws the digits in Persian. On Android Chrome + * it also reads the code from the SMS (WebOTP), through the same path as typing. + */ +export function OtpInput({ + length = OTP_LENGTH, + value: valueProp, + defaultValue = '', + onChange, + onComplete, + error, + status = 'idle', + disabled = false, + autoFocus, + focused, + webOtp = true, + label, + group = length === OTP_LENGTH ? OTP_GROUP : 0, + id: idProp, + name, + className, +}: OtpInputProps) { + const autoId = useId(); + const id = idProp ?? autoId; + const messageId = `${id}-message`; + const [typed, setTyped] = useState(defaultValue); + const [hasFocus, setHasFocus] = useState(false); + const clean = (raw: string) => + latinDigits(raw).replace(NON_DIGITS, '').slice(0, length); + const value = clean(valueProp ?? typed); + + const isBusy = disabled || status === 'verifying'; + const isFocused = focused ?? hasFocus; + const isInvalid = error != null && error !== false; + const message = isInvalid && error !== true ? error : null; + const activeIndex = + isFocused && !isBusy && value.length < length ? value.length : -1; + + // Typing, pasting and the SMS code all arrive here, so they behave the same. + const accept = (raw: string) => { + const next = clean(raw); + if (valueProp === undefined) setTyped(next); + onChange?.(next); + if (next.length === length) onComplete?.(next); + }; + + const handleChange = (event: ChangeEvent) => + accept(event.target.value); + + useWebOtp(webOtp && !isBusy && value.length < length, accept); + + const cellState = (index: number) => + isBusy + ? 'busy' + : isInvalid + ? 'error' + : status === 'success' + ? 'success' + : index === activeIndex + ? 'active' + : 'idle'; + + return ( + + + setHasFocus(true)} + onBlur={() => setHasFocus(false)} + disabled={isBusy} + // The code step exists only to type the code, so it may take focus when it opens. + // oxlint-disable-next-line jsx-a11y/no-autofocus + autoFocus={autoFocus} + aria-label={label} + aria-invalid={isInvalid || undefined} + aria-describedby={message ? messageId : undefined} + aria-busy={status === 'verifying' || undefined} + // Covers the cells, so a tap anywhere focuses it; its own text and caret are invisible. + className="absolute inset-0 z-1 size-full cursor-text border-0 bg-transparent p-0 text-[1rem] tracking-[2em] text-transparent caret-transparent outline-none selection:bg-transparent disabled:cursor-default" + /> + {Array.from({ length }, (_, index) => ( + // Fixed positions that never reorder, so the index is a stable key. + + {group > 0 && index > 0 && index % group === 0 && ( + + )} + + {value[index] ? ( + + {value[index]} + + ) : ( + index === activeIndex && ( + + ) + )} + + + ))} + + {message && ( + + + + {message} + + + )} + + ); +} diff --git a/packages/island/src/molecules/otp-input/constants.ts b/packages/island/src/molecules/otp-input/constants.ts new file mode 100644 index 0000000..730f8d1 --- /dev/null +++ b/packages/island/src/molecules/otp-input/constants.ts @@ -0,0 +1,7 @@ +export const OTP_LENGTH = 6; + +/** Six digits are drawn as two groups of three. */ +export const OTP_GROUP = 3; + +/** Every digit typed or pasted, after Persian and Arabic digits become Latin ones. */ +export const NON_DIGITS = /\D/g; diff --git a/packages/island/src/molecules/otp-input/hooks/use-web-otp.ts b/packages/island/src/molecules/otp-input/hooks/use-web-otp.ts new file mode 100644 index 0000000..008e1db --- /dev/null +++ b/packages/island/src/molecules/otp-input/hooks/use-web-otp.ts @@ -0,0 +1,39 @@ +'use client'; + +import { useEffect, useEffectEvent } from 'react'; + +/** The WebOTP request; TypeScript's DOM types don't include it yet. */ +type OtpRequest = CredentialRequestOptions & { + otp: { transport: ['sms'] }; +}; + +type OtpCredential = Credential & { code: string }; + +/** + * Asks the browser for the code from the SMS (WebOTP, Android Chrome) while `enabled`. The SMS + * must end with the line `@lumina.ir #123456`. The request is aborted on unmount and when + * `enabled` turns off, such as once the code is complete. Elsewhere it does nothing, and + * `autocomplete="one-time-code"` covers iOS. + */ +export function useWebOtp(enabled: boolean, onCode: (code: string) => void) { + // Reads the latest handler without restarting the request on every render. + const deliver = useEffectEvent(onCode); + + useEffect(() => { + if (!enabled || !('OTPCredential' in window)) return undefined; + const controller = new AbortController(); + const request: OtpRequest = { + otp: { transport: ['sms'] }, + signal: controller.signal, + }; + navigator.credentials + .get(request) + .then((credential) => { + const code = (credential as OtpCredential | null)?.code; + if (code) deliver(code); + }) + // Aborted, dismissed or timed out: typing and pasting still work. + .catch(() => undefined); + return () => controller.abort(); + }, [enabled]); +} diff --git a/packages/island/src/molecules/otp-input/index.ts b/packages/island/src/molecules/otp-input/index.ts new file mode 100644 index 0000000..b0c29e8 --- /dev/null +++ b/packages/island/src/molecules/otp-input/index.ts @@ -0,0 +1,2 @@ +export { OtpInput } from './OtpInput'; +export type { OtpInputProps, OtpStatus } from './types'; diff --git a/packages/island/src/molecules/otp-input/types.ts b/packages/island/src/molecules/otp-input/types.ts new file mode 100644 index 0000000..3992d5a --- /dev/null +++ b/packages/island/src/molecules/otp-input/types.ts @@ -0,0 +1,35 @@ +import type { ReactNode } from 'react'; + +export type OtpStatus = 'idle' | 'verifying' | 'success'; + +export type OtpInputProps = { + /** Number of digits, 6 by default. */ + length?: number; + /** Latin digits only. */ + value?: string; + defaultValue?: string; + /** Persian and Arabic digits typed or pasted are normalised to Latin ones. */ + onChange?: (value: string) => void; + /** Fires on the last digit, so the form submits on its own. */ + onComplete?: (value: string) => void; + /** `true` turns the cells red; a node also shows it under them. Clear the value with it. */ + error?: ReactNode; + /** verifying: cells dim while the code is checked. success: cells turn green before redirect. */ + status?: OtpStatus; + disabled?: boolean; + autoFocus?: boolean; + /** Draws the focused state (active cell and caret) without focus, for previews. */ + focused?: boolean; + /** + * Reads the code from the SMS on Android Chrome (WebOTP) and fills it in like typing, so + * `onComplete` fires. On by default; the SMS must end with `@lumina.ir #123456`. + */ + webOtp?: boolean; + /** Accessible name, such as «کد تأیید ۶ رقمی». */ + label: string; + /** Digits per visual group: 3 for six digits, 0 for none. */ + group?: number; + id?: string; + name?: string; + className?: string; +}; diff --git a/packages/island/src/molecules/otp-input/variants.ts b/packages/island/src/molecules/otp-input/variants.ts new file mode 100644 index 0000000..54f1754 --- /dev/null +++ b/packages/island/src/molecules/otp-input/variants.ts @@ -0,0 +1,19 @@ +import { cva } from 'class-variance-authority'; + +export const otpCellVariants = cva( + 'h-14 w-12 rounded-md border bg-surface text-text-primary transition-[border-color,box-shadow,background-color] duration-120 ease-standard max-[374px]:h-13 max-[374px]:w-10.5', + { + variants: { + state: { + idle: 'border-border-default', + /** The cell the next digit goes into. */ + active: 'border-action-primary shadow-focus-field', + error: 'border-danger', + success: 'border-success', + /** Disabled, or verifying the code. */ + busy: 'border-border-subtle bg-surface-sunken text-text-secondary', + }, + }, + defaultVariants: { state: 'idle' }, + }, +); diff --git a/packages/island/src/molecules/resend-code/ResendCode.tsx b/packages/island/src/molecules/resend-code/ResendCode.tsx new file mode 100644 index 0000000..f603098 --- /dev/null +++ b/packages/island/src/molecules/resend-code/ResendCode.tsx @@ -0,0 +1,179 @@ +'use client'; + +import { clock } from '@lumina/tools/format'; + +import { FlexBox } from '../../atoms/flex-box'; +import { Icon } from '../../atoms/icon'; +import { Spinner } from '../../atoms/spinner'; +import { Typography } from '../../atoms/typography'; +import { useCountdown } from '../../hooks/use-countdown'; +import { Element } from '../../primitives/element'; +import { cn } from '../../tools/cn'; +import { + RESEND_LIMIT_SECONDS, + RESEND_WAIT_SECONDS, + RING_CIRCUMFERENCE, + RING_RADIUS, +} from './constants'; +import type { ResendCodeProps } from './types'; +import { resendPillVariants, resendRingVariants } from './variants'; + +const PILL_LAYOUT = { + display: 'inline-flex', + alignItems: 'items-center', + justifyContent: 'justify-center', + gap: 'gap-2', +} as const; + +/** + * The resend control under the code field: a grey pill whose ring drains while the wait runs, + * then the «ارسال دوباره کد» button in the same place. The code keeps working while it waits. + * It counts against the absolute `endsAt`, so a reload keeps the wait; after a resend pass the + * new `endsAt` (and a new `key`, so the ready announcement can play again). + */ +export function ResendCode({ + endsAt, + now, + total = RESEND_WAIT_SECONDS, + limitTotal = RESEND_LIMIT_SECONDS, + status: statusProp = 'auto', + onResend, + labels, + className, +}: ResendCodeProps) { + const isTimed = + statusProp === 'auto' || + statusProp === 'counting' || + statusProp === 'limited'; + const counted = useCountdown(isTimed ? endsAt : undefined, { now }); + // No end means no wait; `null` is the time still unknown while hydrating. + const secondsLeft = endsAt == null ? 0 : counted; + // The block ends like the wait does: at zero the button is back. + const status = !isTimed + ? statusProp + : secondsLeft === 0 + ? 'ready' + : statusProp === 'limited' + ? 'limited' + : 'counting'; + // Keeps the pill's place without showing a guessed time; it fills in once hydrated. + const isPending = isTimed && secondsLeft == null; + + const isLimited = status === 'limited'; + const wait = isLimited ? limitTotal : total; + // The share of the wait still to go: the ring starts full and drains. + const ringShare = isPending + ? 1 + : Math.min(1, Math.max(0, (secondsLeft ?? 0) / wait)); + + let pill; + if (status === 'counting' || isLimited) { + pill = ( + + + + + + + {isLimited ? labels.limited : labels.counting} + + + {clock(secondsLeft ?? 0)} + + + ); + } else if (status === 'sent') { + pill = ( + + + + {labels.sent} + + + ); + } else { + const isSending = status === 'sending'; + pill = ( + + {isSending ? : } + + {isSending ? labels.sending : labels.ready} + + + ); + } + + return ( + + {status === 'ready' && labels.hint != null && ( + + {labels.hint} + + )} + {pill} + + {status === 'ready' + ? labels.readyAnnouncement + : status === 'sent' + ? labels.sent + : ''} + + + ); +} diff --git a/packages/island/src/molecules/resend-code/constants.ts b/packages/island/src/molecules/resend-code/constants.ts new file mode 100644 index 0000000..e1b8fad --- /dev/null +++ b/packages/island/src/molecules/resend-code/constants.ts @@ -0,0 +1,8 @@ +/** A new code may be asked for 2 minutes after the last one. */ +export const RESEND_WAIT_SECONDS = 120; + +/** The block after too many codes. */ +export const RESEND_LIMIT_SECONDS = 600; + +export const RING_RADIUS = 8; +export const RING_CIRCUMFERENCE = 2 * Math.PI * RING_RADIUS; diff --git a/packages/island/src/molecules/resend-code/index.ts b/packages/island/src/molecules/resend-code/index.ts new file mode 100644 index 0000000..39f5ee0 --- /dev/null +++ b/packages/island/src/molecules/resend-code/index.ts @@ -0,0 +1,2 @@ +export { ResendCode } from './ResendCode'; +export type { ResendCodeLabels, ResendCodeProps, ResendStatus } from './types'; diff --git a/packages/island/src/molecules/resend-code/types.ts b/packages/island/src/molecules/resend-code/types.ts new file mode 100644 index 0000000..6cf0042 --- /dev/null +++ b/packages/island/src/molecules/resend-code/types.ts @@ -0,0 +1,47 @@ +import type { DateInput } from '@lumina/tools/format'; +import type { ReactNode } from 'react'; + +/** auto: counting until `endsAt`, then ready. sending and sent after a tap. limited: blocked. */ +export type ResendStatus = + | 'auto' + | 'counting' + | 'ready' + | 'sending' + | 'sent' + | 'limited'; + +/** Every text the control shows, from the translations. */ +export type ResendCodeLabels = { + /** «ارسال دوباره کد تا», before the clock. */ + counting: ReactNode; + /** «ارسال دوباره کد». */ + ready: ReactNode; + /** «در حال ارسال…». */ + sending: ReactNode; + /** «کد جدید ارسال شد.». */ + sent: string; + /** «ارسال دوباره کد پس از», before the clock. */ + limited: ReactNode; + /** «کد را دریافت نکردید؟» above the ready button; omit to hide it. */ + hint?: ReactNode; + /** Announced once when the button appears: «اکنون می‌توانید کد جدید دریافت کنید.». */ + readyAnnouncement: string; +}; + +export type ResendCodeProps = { + /** + * When a new code may be asked for (2:00 after sending), or, when limited, when sending is + * allowed again. Absolute, so a reload keeps the wait. Without it the button is ready. + */ + endsAt?: DateInput; + /** Freezes the clock (previews, tests). Also renders the time on the server. */ + now?: DateInput; + /** The normal wait in seconds, which drives the ring: 120 by default. */ + total?: number; + /** The block after too many codes in seconds, which drives the limited ring: 600 by default. */ + limitTotal?: number; + status?: ResendStatus; + onResend?: () => void; + labels: ResendCodeLabels; + className?: string; +}; diff --git a/packages/island/src/molecules/resend-code/variants.ts b/packages/island/src/molecules/resend-code/variants.ts new file mode 100644 index 0000000..fb1feb5 --- /dev/null +++ b/packages/island/src/molecules/resend-code/variants.ts @@ -0,0 +1,34 @@ +import { cva } from 'class-variance-authority'; + +/** The countdown and the button are one pill, so people see where the action will appear. */ +export const resendPillVariants = cva( + 'min-h-touch-target rounded-full px-4 whitespace-nowrap', + { + variants: { + status: { + /** The wait is normal, not an error: no red. */ + counting: 'bg-surface-sunken text-text-secondary', + /** Too many codes for this number. */ + limited: 'bg-warning-subtle text-warning-text', + ready: + 'border border-border-default bg-surface text-action-primary transition-colors duration-120 ease-standard focus-visible:focus-ring actionable:cursor-pointer actionable:hover:border-action-primary-muted actionable:hover:bg-action-primary-subtle', + sending: + 'cursor-progress border border-border-default bg-surface text-text-secondary', + sent: 'text-success-text', + }, + }, + defaultVariants: { status: 'counting' }, + }, +); + +export const resendRingVariants = cva('flex-none', { + variants: { + tone: { + brand: + '[&>[data-arc]]:stroke-action-primary [&>[data-track]]:stroke-border-subtle', + warning: + '[&>[data-arc]]:stroke-warning [&>[data-track]]:stroke-warning [&>[data-track]]:opacity-25', + }, + }, + defaultVariants: { tone: 'brand' }, +}); diff --git a/packages/island/src/molecules/state-message/StateMessage.tsx b/packages/island/src/molecules/state-message/StateMessage.tsx new file mode 100644 index 0000000..588eca9 --- /dev/null +++ b/packages/island/src/molecules/state-message/StateMessage.tsx @@ -0,0 +1,80 @@ +import { FlexBox } from '../../atoms/flex-box'; +import { StateArt } from '../../atoms/state-art'; +import { Typography } from '../../atoms/typography'; +import { cn } from '../../tools/cn'; +import type { StateMessageProps } from './types'; +import { stateMessageVariants } from './variants'; + +/** The one anatomy of empty and error states: art, title, description, then actions. */ +export function StateMessage({ + title, + description, + footnote, + icon, + tone = 'brand', + size = 'section', + inlineIcon = false, + role, + actions, + className, +}: StateMessageProps) { + const isInline = size === 'inline'; + const isSmall = isInline || size === 'compact'; + + return ( + + {isInline ? ( + inlineIcon && + ) : ( + + )} + + + {title} + + {description != null && ( + + {description} + + )} + {footnote != null && ( + + {footnote} + + )} + + {actions != null && ( + + {actions} + + )} + + ); +} diff --git a/packages/island/src/molecules/state-message/index.ts b/packages/island/src/molecules/state-message/index.ts new file mode 100644 index 0000000..c709aa1 --- /dev/null +++ b/packages/island/src/molecules/state-message/index.ts @@ -0,0 +1,3 @@ +export { StateMessage } from './StateMessage'; +export type { StateMessageProps, StateMessageSize } from './types'; +export { stateMessageVariants } from './variants'; diff --git a/packages/island/src/molecules/state-message/types.ts b/packages/island/src/molecules/state-message/types.ts new file mode 100644 index 0000000..56a022b --- /dev/null +++ b/packages/island/src/molecules/state-message/types.ts @@ -0,0 +1,24 @@ +import type { ReactNode } from 'react'; + +import type { IconName } from '../../atoms/icon'; +import type { StateTone } from '../../atoms/state-art'; + +export type StateMessageSize = 'page' | 'section' | 'compact' | 'inline'; + +export type StateMessageProps = { + title: ReactNode; + /** One or two short sentences: why, and what to do. */ + description?: ReactNode; + /** A small line under the description, such as an error's reference code. */ + footnote?: ReactNode; + icon: IconName; + tone?: StateTone; + size?: StateMessageSize; + /** `inline` only: show the tone's icon disc at the start (errors do, empty rows don't). */ + inlineIcon?: boolean; + /** `alert` for errors, `status` for calm states; omit for empty states. */ + role?: 'alert' | 'status'; + /** At most one primary and one secondary Button or Link. */ + actions?: ReactNode; + className?: string; +}; diff --git a/packages/island/src/molecules/state-message/variants.ts b/packages/island/src/molecules/state-message/variants.ts new file mode 100644 index 0000000..c098273 --- /dev/null +++ b/packages/island/src/molecules/state-message/variants.ts @@ -0,0 +1,18 @@ +import { cva } from 'class-variance-authority'; + +export const stateMessageVariants = cva('text-center', { + variants: { + size: { + /** A whole screen body; top bar, tabs and bottom nav stay. */ + page: 'min-h-90 px-6 py-12', + /** Inside a card, tab or panel. */ + section: 'px-5 py-10', + /** Inside a small card, sheet or table area. */ + compact: 'px-4 py-6', + /** One bordered row inside a list, with no art. */ + inline: + 'rounded-lg border border-border-subtle bg-surface px-4 py-3 text-start', + }, + }, + defaultVariants: { size: 'section' }, +}); diff --git a/packages/island/src/molecules/step-progress/StepProgress.tsx b/packages/island/src/molecules/step-progress/StepProgress.tsx new file mode 100644 index 0000000..f0a7b89 --- /dev/null +++ b/packages/island/src/molecules/step-progress/StepProgress.tsx @@ -0,0 +1,67 @@ +import { FlexBox } from '../../atoms/flex-box'; +import { GridBox } from '../../atoms/grid-box'; +import { Separator } from '../../atoms/separator'; +import { Typography } from '../../atoms/typography'; +import { Element } from '../../primitives/element'; +import { cn } from '../../tools/cn'; +import type { StepProgressProps } from './types'; + +/** + * Where the person is in a multi-step flow: a segmented bar and «مرحله ۲ از ۵ | شماره موبایل». + * Done and current segments are brand; upcoming ones are a hairline. + */ +export function StepProgress({ + steps = [], + total: totalProp, + current, + countLabel, + label, + className, +}: StepProgressProps) { + const total = Math.max(totalProp || steps.length, 1); + const index = Math.min(Math.max(current, 0), total - 1); + const stepName = steps[index]; + const count = countLabel(index + 1, total); + + return ( + + : the bar is drawn as one segment per step, which can't show. + // oxlint-disable-next-line jsx-a11y/prefer-tag-over-role + role="progressbar" + aria-label={label} + aria-valuemin={1} + aria-valuemax={total} + aria-valuenow={index + 1} + aria-valuetext={stepName ? `${count}، ${stepName}` : count} + style={{ gridTemplateColumns: `repeat(${total}, minmax(0, 1fr))` }} + > + {Array.from({ length: total }, (_, stepIndex) => ( + + ))} + + + + {count} + + {stepName && ( + <> + + + {stepName} + + + )} + + + ); +} diff --git a/packages/island/src/molecules/step-progress/index.ts b/packages/island/src/molecules/step-progress/index.ts new file mode 100644 index 0000000..1ebbb9d --- /dev/null +++ b/packages/island/src/molecules/step-progress/index.ts @@ -0,0 +1,2 @@ +export { StepProgress } from './StepProgress'; +export type { StepProgressProps } from './types'; diff --git a/packages/island/src/molecules/step-progress/types.ts b/packages/island/src/molecules/step-progress/types.ts new file mode 100644 index 0000000..b43ad9c --- /dev/null +++ b/packages/island/src/molecules/step-progress/types.ts @@ -0,0 +1,28 @@ +type StepProgressBaseProps = { + /** 0-based. */ + current: number; + /** + * The count from the translations, given the 1-based step and the total: «مرحله ۲ از ۵». Shown + * under the bar and read out as its value. + */ + countLabel: (step: number, total: number) => string; + /** The bar's accessible name, such as «مراحل ثبت‌نام». */ + label: string; + className?: string; +}; + +/** Named steps (the current name shows after the count), or a bare `total` of segments. */ +export type StepProgressProps = StepProgressBaseProps & + ( + | { + /** Step names; the current one shows after the count. */ + steps: readonly string[]; + /** The number of segments when it differs from the names given. */ + total?: number; + } + | { + steps?: readonly string[]; + /** The number of segments, for a flow whose steps have no names. */ + total: number; + } + ); diff --git a/packages/island/src/molecules/text-input/.gitkeep b/packages/island/src/molecules/text-input/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages/island/src/molecules/text-input/TextInput.tsx b/packages/island/src/molecules/text-input/TextInput.tsx new file mode 100644 index 0000000..192af99 --- /dev/null +++ b/packages/island/src/molecules/text-input/TextInput.tsx @@ -0,0 +1,193 @@ +'use client'; + +import { number } from '@lumina/tools/format'; +import { useId, useState } from 'react'; +import type { ChangeEvent } from 'react'; + +import { FlexBox } from '../../atoms/flex-box'; +import { Icon } from '../../atoms/icon'; +import { Typography } from '../../atoms/typography'; +import { Element } from '../../primitives/element'; +import { cn } from '../../tools/cn'; +import type { + TextareaControlProps, + TextInputMessageKind, + TextInputProps, +} from './types'; +import { + TEXT_INPUT_MESSAGE_COLORS, + textInputBoxVariants, + textInputControlVariants, +} from './variants'; + +function lengthOf(value: unknown): number { + return value == null ? 0 : Array.from(String(value)).length; +} + +/** + * A labelled text field with its hint, error, success or lock note underneath. Works with + * react-hook-form's `register` (the ref reaches the control) or as a controlled input. + */ +export function TextInput({ + id: idProp, + label, + hint, + error, + success, + dir, + prefix, + suffix, + multiline = false, + rows = 4, + showCount = false, + limitMessage, + locked = false, + lockedNote, + frozen = false, + maxLength, + value, + defaultValue, + onChange, + readOnly, + disabled, + className, + inputClassName, + ...props +}: TextInputProps) { + const autoId = useId(); + const id = idProp ?? autoId; + const messageId = `${id}-message`; + // Tracks an uncontrolled value's length for the counter; a controlled value wins. + const [typedLength, setTypedLength] = useState(() => lengthOf(defaultValue)); + const length = value === undefined ? typedLength : lengthOf(value); + const ltr = dir === 'ltr'; + const isInvalid = error != null && error !== false; + const hasSuccess = success != null && success !== false; + const atLimit = showCount && maxLength != null && length >= maxLength; + const limitNote = atLimit ? limitMessage : undefined; + + const message = + (isInvalid && error) || + (hasSuccess && success) || + (locked && lockedNote) || + limitNote || + hint; + const messageKind: TextInputMessageKind = + isInvalid || (!hasSuccess && limitNote != null) + ? 'error' + : hasSuccess + ? 'success' + : 'hint'; + + const handleChange = (event: ChangeEvent) => { + if (value === undefined) setTypedLength(lengthOf(event.target.value)); + onChange?.(event); + }; + + const controlProps = { + ...props, + id, + value, + defaultValue, + maxLength, + onChange: handleChange, + dir: ltr ? 'ltr' : undefined, + readOnly: locked || readOnly, + disabled: frozen || disabled, + 'aria-invalid': isInvalid || undefined, + 'aria-describedby': message ? messageId : undefined, + className: cn( + textInputControlVariants({ multiline, locked, ltr }), + inputClassName, + ), + }; + + return ( + + {label != null && ( + + {label} + + )} + + {prefix != null && ( + + {prefix} + + )} + {multiline ? ( + + ) : ( + + )} + {suffix != null && ( + + {suffix} + + )} + {locked ? ( + + ) : hasSuccess ? ( + + ) : isInvalid ? ( + + ) : null} + + {(message || (showCount && maxLength != null)) && ( + + {message && ( + + {message} + + )} + {showCount && maxLength != null && ( + + {number(length)}/{number(maxLength)} + + )} + + )} + + ); +} diff --git a/packages/island/src/molecules/text-input/index.ts b/packages/island/src/molecules/text-input/index.ts new file mode 100644 index 0000000..6ca5413 --- /dev/null +++ b/packages/island/src/molecules/text-input/index.ts @@ -0,0 +1,3 @@ +export { TextInput } from './TextInput'; +export type { TextInputProps } from './types'; +export { textInputBoxVariants, textInputControlVariants } from './variants'; diff --git a/packages/island/src/molecules/text-input/types.ts b/packages/island/src/molecules/text-input/types.ts new file mode 100644 index 0000000..e83d80e --- /dev/null +++ b/packages/island/src/molecules/text-input/types.ts @@ -0,0 +1,38 @@ +import type { ComponentPropsWithRef, ReactNode } from 'react'; + +export type TextInputProps = Omit< + ComponentPropsWithRef<'input'>, + 'prefix' | 'dir' +> & { + label?: ReactNode; + /** A rule given before typing. */ + hint?: ReactNode; + /** Inline error under the field; the entered value is kept. */ + error?: ReactNode; + /** A positive live check, such as «نام کاربری آزاد است». */ + success?: ReactNode; + /** `ltr` for شبا, URLs, usernames, tickers and codes. */ + dir?: 'rtl' | 'ltr'; + /** A fixed affix inside the field, such as `IR` for شبا. */ + prefix?: ReactNode; + /** A fixed affix after the value, such as «تومان». */ + suffix?: ReactNode; + multiline?: boolean; + rows?: number; + /** Shows «n/max» under the field; needs `maxLength`. */ + showCount?: boolean; + /** Shown when the value reaches `maxLength` with `showCount`. */ + limitMessage?: ReactNode; + /** Read-only with a lock, such as an identity field after its first submission. */ + locked?: boolean; + /** Why the field is locked, shown under it. */ + lockedNote?: ReactNode; + /** Visible but unusable now, at 40%. */ + frozen?: boolean; + inputClassName?: string; +}; + +/** The same control props, typed for the multiline `