feat(private-room): connect moments feed
Docker Image / Build and Push Docker Image (push) Successful in 9m29s
Docker Image / Build and Push Docker Image (push) Successful in 9m29s
This commit is contained in:
@@ -1,63 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import { type Dispatch, useEffect, useRef } from "react";
|
||||
import {
|
||||
type UseGuestLoginBootstrapInput,
|
||||
shouldSubmitGuestLogin,
|
||||
useGuestLoginBootstrap,
|
||||
} from "@/hooks/use-guest-login-bootstrap";
|
||||
|
||||
import type { LoginStatus } from "@/data/dto/auth";
|
||||
import type { AuthEvent } from "@/stores/auth/auth-events";
|
||||
export type UseChatGuestLoginInput = UseGuestLoginBootstrapInput;
|
||||
export { shouldSubmitGuestLogin };
|
||||
|
||||
export interface GuestLoginState {
|
||||
hasInitialized: boolean;
|
||||
isLoading: boolean;
|
||||
loginStatus: LoginStatus;
|
||||
}
|
||||
|
||||
export interface ShouldSubmitGuestLoginInput extends GuestLoginState {
|
||||
alreadyRequested: boolean;
|
||||
}
|
||||
|
||||
export interface UseChatGuestLoginInput extends GuestLoginState {
|
||||
dispatch: Dispatch<AuthEvent>;
|
||||
}
|
||||
|
||||
export function shouldSubmitGuestLogin({
|
||||
alreadyRequested,
|
||||
hasInitialized,
|
||||
isLoading,
|
||||
loginStatus,
|
||||
}: ShouldSubmitGuestLoginInput): boolean {
|
||||
if (!hasInitialized || isLoading) return false;
|
||||
if (loginStatus !== "notLoggedIn") return false;
|
||||
return !alreadyRequested;
|
||||
}
|
||||
|
||||
export function useChatGuestLogin({
|
||||
dispatch,
|
||||
hasInitialized,
|
||||
isLoading,
|
||||
loginStatus,
|
||||
}: UseChatGuestLoginInput): void {
|
||||
const guestLoginRequestedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasInitialized || isLoading) return;
|
||||
|
||||
if (loginStatus !== "notLoggedIn") {
|
||||
guestLoginRequestedRef.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
!shouldSubmitGuestLogin({
|
||||
alreadyRequested: guestLoginRequestedRef.current,
|
||||
hasInitialized,
|
||||
isLoading,
|
||||
loginStatus,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
guestLoginRequestedRef.current = true;
|
||||
dispatch({ type: "AuthGuestLoginSubmitted" });
|
||||
}, [dispatch, hasInitialized, isLoading, loginStatus]);
|
||||
export function useChatGuestLogin(input: UseChatGuestLoginInput): void {
|
||||
useGuestLoginBootstrap(input);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import { PrivateRoomScreen } from "./private-room-screen";
|
||||
|
||||
export default function PrivateRoomPage() {
|
||||
return <PrivateRoomScreen />;
|
||||
}
|
||||
+185
-46
@@ -90,7 +90,6 @@
|
||||
}
|
||||
|
||||
.avatarFrame {
|
||||
position: relative;
|
||||
display: grid;
|
||||
width: clamp(68px, 16.667vw, 90px);
|
||||
height: clamp(68px, 16.667vw, 90px);
|
||||
@@ -122,9 +121,13 @@
|
||||
line-height: 0.95;
|
||||
}
|
||||
|
||||
.handle,
|
||||
.bio {
|
||||
color: #755f66;
|
||||
}
|
||||
|
||||
.handle {
|
||||
margin: 7px 0 0;
|
||||
color: #a56f7b;
|
||||
font-size: clamp(13px, 3.148vw, 17px);
|
||||
font-weight: 720;
|
||||
}
|
||||
@@ -132,39 +135,32 @@
|
||||
.bio {
|
||||
max-width: 360px;
|
||||
margin: 0;
|
||||
color: #755f66;
|
||||
font-size: clamp(14px, 3.333vw, 18px);
|
||||
font-weight: 620;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.primaryCta {
|
||||
.primaryCta,
|
||||
.loadMoreButton {
|
||||
display: inline-flex;
|
||||
min-height: 48px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 9px;
|
||||
padding: 0 18px;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
background: linear-gradient(135deg, #262026, #7f5861);
|
||||
color: #ffffff;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-size: clamp(13px, 3.148vw, 16px);
|
||||
font-weight: 850;
|
||||
box-shadow: 0 14px 30px rgba(47, 35, 40, 0.18);
|
||||
transition: transform 0.18s ease, box-shadow 0.18s ease, filter 0.18s ease;
|
||||
}
|
||||
|
||||
.primaryCta:hover {
|
||||
filter: brightness(1.04);
|
||||
box-shadow: 0 18px 36px rgba(47, 35, 40, 0.23);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.primaryCta:active {
|
||||
transform: translateY(1px) scale(0.99);
|
||||
.primaryCta {
|
||||
padding: 0 18px;
|
||||
background: linear-gradient(135deg, #262026, #7f5861);
|
||||
color: #ffffff;
|
||||
font-size: clamp(13px, 3.148vw, 16px);
|
||||
box-shadow: 0 14px 30px rgba(47, 35, 40, 0.18);
|
||||
}
|
||||
|
||||
.postsSection {
|
||||
@@ -217,13 +213,17 @@
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.postCard {
|
||||
padding: clamp(14px, 3.704vw, 20px);
|
||||
.postCard,
|
||||
.statusCard {
|
||||
border: 1px solid rgba(44, 29, 34, 0.07);
|
||||
border-radius: clamp(22px, 5.926vw, 32px);
|
||||
background: rgba(255, 255, 255, 0.86);
|
||||
box-shadow: 0 16px 42px rgba(131, 72, 85, 0.1);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
.postCard {
|
||||
padding: clamp(14px, 3.704vw, 20px);
|
||||
animation: riseIn 0.42s ease both;
|
||||
animation-delay: calc(var(--reveal-index, 0) * 90ms + 80ms);
|
||||
}
|
||||
@@ -250,8 +250,13 @@
|
||||
box-shadow: 0 8px 18px rgba(131, 72, 85, 0.12);
|
||||
}
|
||||
|
||||
.authorName {
|
||||
.authorName,
|
||||
.authorSubline,
|
||||
.postText {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.authorName {
|
||||
color: #26191d;
|
||||
font-size: clamp(14px, 3.333vw, 17px);
|
||||
font-weight: 820;
|
||||
@@ -259,7 +264,7 @@
|
||||
}
|
||||
|
||||
.authorSubline {
|
||||
margin: 3px 0 0;
|
||||
margin-top: 3px;
|
||||
color: #a58b92;
|
||||
font-size: clamp(11px, 2.778vw, 13px);
|
||||
font-weight: 680;
|
||||
@@ -272,6 +277,14 @@
|
||||
font-weight: 760;
|
||||
}
|
||||
|
||||
.postText {
|
||||
margin-top: 14px;
|
||||
color: #4c3a40;
|
||||
font-size: clamp(14px, 3.333vw, 17px);
|
||||
font-weight: 650;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.lockedPreview {
|
||||
display: grid;
|
||||
width: 100%;
|
||||
@@ -293,21 +306,9 @@
|
||||
transition: border-color 0.18s ease, box-shadow 0.18s ease, transform 0.18s ease;
|
||||
}
|
||||
|
||||
.lockedPreview:hover {
|
||||
border-color: rgba(255, 82, 139, 0.45);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.9), 0 18px 36px rgba(255, 116, 159, 0.18);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.lockedPreview:active {
|
||||
transform: translateY(1px) scale(0.995);
|
||||
}
|
||||
|
||||
.lockedPreview:focus-visible,
|
||||
.primaryCta:focus-visible,
|
||||
.navButton:focus-visible {
|
||||
outline: 2px solid #ff5d95;
|
||||
outline-offset: 3px;
|
||||
.lockedPreview:disabled {
|
||||
cursor: wait;
|
||||
opacity: 0.72;
|
||||
}
|
||||
|
||||
.previewIcon {
|
||||
@@ -350,6 +351,49 @@
|
||||
font-weight: 760;
|
||||
}
|
||||
|
||||
.imageGrid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
|
||||
gap: 10px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
|
||||
.unlockedImage {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
aspect-ratio: 1;
|
||||
border-radius: 22px;
|
||||
object-fit: cover;
|
||||
box-shadow: 0 14px 32px rgba(131, 72, 85, 0.14);
|
||||
}
|
||||
|
||||
.statusCard {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
margin-bottom: 14px;
|
||||
padding: 18px;
|
||||
color: #755f66;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.statusCard p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.statusCard button,
|
||||
.loadMoreButton {
|
||||
padding: 0 18px;
|
||||
background: rgba(255, 93, 149, 0.12);
|
||||
color: #a94c64;
|
||||
}
|
||||
|
||||
.loadMoreButton {
|
||||
width: 100%;
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.bottomNav {
|
||||
position: fixed;
|
||||
right: max(calc((100vw - var(--app-max-width, 540px)) / 2), 0px);
|
||||
@@ -386,16 +430,6 @@
|
||||
font: inherit;
|
||||
font-size: clamp(12px, 2.963vw, 14px);
|
||||
font-weight: 820;
|
||||
transition: background 0.18s ease, color 0.18s ease, transform 0.18s ease;
|
||||
}
|
||||
|
||||
.navButton:hover {
|
||||
background: rgba(255, 116, 159, 0.08);
|
||||
color: #2d2024;
|
||||
}
|
||||
|
||||
.navButton:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
.navButtonActive {
|
||||
@@ -405,6 +439,111 @@
|
||||
box-shadow: 0 10px 24px rgba(255, 116, 159, 0.12);
|
||||
}
|
||||
|
||||
.dialogOverlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 40;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 24px;
|
||||
background: rgba(34, 23, 28, 0.36);
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.dialog {
|
||||
width: min(100%, 360px);
|
||||
padding: 22px;
|
||||
border-radius: 26px;
|
||||
background: #ffffff;
|
||||
box-shadow: 0 24px 70px rgba(34, 23, 28, 0.22);
|
||||
}
|
||||
|
||||
.dialogTitle {
|
||||
margin: 0;
|
||||
color: #21171b;
|
||||
font-size: 22px;
|
||||
font-weight: 900;
|
||||
}
|
||||
|
||||
.dialogCopy,
|
||||
.dialogError {
|
||||
margin: 10px 0 0;
|
||||
color: #755f66;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.dialogError {
|
||||
color: #c63f67;
|
||||
}
|
||||
|
||||
.dialogActions {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.dialogPrimary,
|
||||
.dialogSecondary {
|
||||
min-height: 46px;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-weight: 850;
|
||||
}
|
||||
|
||||
.dialogPrimary {
|
||||
background: linear-gradient(135deg, #ff7aa9, #ffb36d);
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.dialogSecondary {
|
||||
background: rgba(44, 29, 34, 0.08);
|
||||
color: #5f4b52;
|
||||
}
|
||||
|
||||
.toast {
|
||||
position: fixed;
|
||||
right: max(calc((100vw - var(--app-max-width, 540px)) / 2 + 18px), 18px);
|
||||
bottom: calc(var(--app-safe-bottom, 0px) + 92px);
|
||||
left: max(calc((100vw - var(--app-max-width, 540px)) / 2 + 18px), 18px);
|
||||
z-index: 45;
|
||||
padding: 14px 16px;
|
||||
border-radius: 18px;
|
||||
background: rgba(33, 23, 27, 0.88);
|
||||
color: #ffffff;
|
||||
font-size: 14px;
|
||||
font-weight: 750;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.primaryCta:hover,
|
||||
.lockedPreview:hover,
|
||||
.loadMoreButton:hover {
|
||||
filter: brightness(1.04);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.primaryCta:active,
|
||||
.lockedPreview:active,
|
||||
.loadMoreButton:active,
|
||||
.navButton:active {
|
||||
transform: translateY(1px) scale(0.99);
|
||||
}
|
||||
|
||||
.primaryCta:focus-visible,
|
||||
.lockedPreview:focus-visible,
|
||||
.navButton:focus-visible,
|
||||
.loadMoreButton:focus-visible,
|
||||
.dialogPrimary:focus-visible,
|
||||
.dialogSecondary:focus-visible {
|
||||
outline: 2px solid #ff5d95;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
@keyframes riseIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
@@ -0,0 +1,440 @@
|
||||
"use client";
|
||||
|
||||
import type { CSSProperties } from "react";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import Image from "next/image";
|
||||
import {
|
||||
Camera,
|
||||
ImageIcon,
|
||||
LockKeyhole,
|
||||
MessageCircle,
|
||||
RefreshCw,
|
||||
Sparkles,
|
||||
} from "lucide-react";
|
||||
|
||||
import type { PrivateRoomMoment } from "@/data/dto/private-room";
|
||||
import { MobileShell } from "@/app/_components/core";
|
||||
import { useGuestLoginBootstrap } from "@/hooks/use-guest-login-bootstrap";
|
||||
import { ROUTES } from "@/router/routes";
|
||||
import { useAppNavigator } from "@/router/use-app-navigator";
|
||||
import { useAuthDispatch, useAuthState } from "@/stores/auth/auth-context";
|
||||
import {
|
||||
usePrivateRoomDispatch,
|
||||
usePrivateRoomState,
|
||||
} from "@/stores/private-room";
|
||||
import { useUserDispatch } from "@/stores/user/user-context";
|
||||
|
||||
import styles from "./private-room-screen.module.css";
|
||||
|
||||
const FALLBACK_PROFILE = {
|
||||
name: "Elio Silvestri",
|
||||
handle: "@elio.private",
|
||||
avatar: "/images/chat/pic-chat-elio.png",
|
||||
title: "Elio Private room",
|
||||
subtitle: "Join me, unlock my private room",
|
||||
bio: "Soft moments, private photos, and a little sweetness just for you.",
|
||||
} as const;
|
||||
|
||||
export function PrivateRoomScreen() {
|
||||
const navigator = useAppNavigator();
|
||||
const authState = useAuthState();
|
||||
const authDispatch = useAuthDispatch();
|
||||
const userDispatch = useUserDispatch();
|
||||
const state = usePrivateRoomState();
|
||||
const dispatch = usePrivateRoomDispatch();
|
||||
const previousLoginStatusRef = useRef(authState.loginStatus);
|
||||
const lastUnlockSuccessNonceRef = useRef(0);
|
||||
|
||||
useGuestLoginBootstrap({
|
||||
dispatch: authDispatch,
|
||||
hasInitialized: authState.hasInitialized,
|
||||
isLoading: authState.isLoading,
|
||||
loginStatus: authState.loginStatus,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!authState.hasInitialized || authState.isLoading) return;
|
||||
if (authState.loginStatus === "notLoggedIn") return;
|
||||
|
||||
const previousLoginStatus = previousLoginStatusRef.current;
|
||||
previousLoginStatusRef.current = authState.loginStatus;
|
||||
|
||||
if (state.status === "idle") {
|
||||
dispatch({ type: "PrivateRoomInit" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
previousLoginStatus !== authState.loginStatus &&
|
||||
state.status !== "loading"
|
||||
) {
|
||||
dispatch({ type: "PrivateRoomRefresh" });
|
||||
}
|
||||
}, [
|
||||
authState.hasInitialized,
|
||||
authState.isLoading,
|
||||
authState.loginStatus,
|
||||
dispatch,
|
||||
state.status,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
const request = state.unlockPaywallRequest;
|
||||
if (!request) return;
|
||||
|
||||
if (
|
||||
authState.loginStatus === "guest" ||
|
||||
authState.loginStatus === "notLoggedIn"
|
||||
) {
|
||||
navigator.openAuth(ROUTES.privateRoom);
|
||||
} else {
|
||||
navigator.openSubscription({ type: "topup" });
|
||||
}
|
||||
dispatch({ type: "PrivateRoomUnlockPaywallConsumed" });
|
||||
}, [
|
||||
authState.loginStatus,
|
||||
dispatch,
|
||||
navigator,
|
||||
state.unlockPaywallRequest,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (state.unlockSuccessNonce <= lastUnlockSuccessNonceRef.current) return;
|
||||
lastUnlockSuccessNonceRef.current = state.unlockSuccessNonce;
|
||||
userDispatch({ type: "UserFetch" });
|
||||
}, [state.unlockSuccessNonce, userDispatch]);
|
||||
|
||||
const profile = state.profile;
|
||||
const displayName =
|
||||
profile?.displayName || profile?.authorName || FALLBACK_PROFILE.name;
|
||||
const avatarUrl = profile?.avatarUrl || FALLBACK_PROFILE.avatar;
|
||||
const title = profile?.title || FALLBACK_PROFILE.title;
|
||||
const subtitle = profile?.subtitle || FALLBACK_PROFILE.subtitle;
|
||||
const pendingMoment = useMemo(
|
||||
() =>
|
||||
state.items.find(
|
||||
(item) => item.momentId === state.pendingConfirmMomentId,
|
||||
) ?? null,
|
||||
[state.items, state.pendingConfirmMomentId],
|
||||
);
|
||||
|
||||
const handleTopUpClick = () => {
|
||||
if (
|
||||
authState.loginStatus === "guest" ||
|
||||
authState.loginStatus === "notLoggedIn"
|
||||
) {
|
||||
navigator.openAuth(ROUTES.privateRoom);
|
||||
return;
|
||||
}
|
||||
navigator.openSubscription({ type: "topup" });
|
||||
};
|
||||
|
||||
return (
|
||||
<MobileShell background="#fff7ed">
|
||||
<main className={styles.shell}>
|
||||
<div className={styles.backgroundGlowOne} />
|
||||
<div className={styles.backgroundGlowTwo} />
|
||||
|
||||
<section className={styles.hero} aria-labelledby="private-room-title">
|
||||
<div className={styles.heroTopline}>
|
||||
<span className={styles.liveDot} aria-hidden="true" />
|
||||
<span>Private room is open</span>
|
||||
</div>
|
||||
|
||||
<div className={styles.identity}>
|
||||
<div className={styles.avatarFrame}>
|
||||
<Image
|
||||
src={avatarUrl}
|
||||
alt={displayName}
|
||||
width={72}
|
||||
height={72}
|
||||
priority
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.identityText}>
|
||||
<h1 id="private-room-title" className={styles.title}>
|
||||
{displayName}
|
||||
</h1>
|
||||
<p className={styles.handle}>{title}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className={styles.bio}>{subtitle || FALLBACK_PROFILE.bio}</p>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className={styles.primaryCta}
|
||||
onClick={handleTopUpClick}
|
||||
>
|
||||
<Sparkles size={16} aria-hidden="true" />
|
||||
<span>Top up credits</span>
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<section className={styles.postsSection} aria-labelledby="posts-title">
|
||||
<div className={styles.sectionHeader}>
|
||||
<div>
|
||||
<p className={styles.kicker}>Posts</p>
|
||||
<h2 id="posts-title" className={styles.sectionTitle}>
|
||||
Private moments
|
||||
</h2>
|
||||
</div>
|
||||
<span className={styles.postCount}>{state.items.length}</span>
|
||||
</div>
|
||||
|
||||
{state.errorMessage ? (
|
||||
<StatusCard
|
||||
message={state.errorMessage}
|
||||
actionLabel="Retry"
|
||||
onAction={() => dispatch({ type: "PrivateRoomRefresh" })}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{state.isLoading && state.items.length === 0 ? (
|
||||
<StatusCard message="Loading private moments..." />
|
||||
) : null}
|
||||
|
||||
{!state.isLoading && state.items.length === 0 && !state.errorMessage ? (
|
||||
<StatusCard
|
||||
message="No private moments yet."
|
||||
actionLabel="Refresh"
|
||||
onAction={() => dispatch({ type: "PrivateRoomRefresh" })}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<div className={styles.timeline}>
|
||||
{state.items.map((moment, index) => (
|
||||
<PrivateRoomPostCard
|
||||
key={moment.momentId}
|
||||
moment={moment}
|
||||
displayName={displayName}
|
||||
avatarUrl={avatarUrl}
|
||||
index={index}
|
||||
isUnlocking={state.unlockingMomentId === moment.momentId}
|
||||
onUnlock={() =>
|
||||
dispatch({
|
||||
type: "PrivateRoomUnlockRequested",
|
||||
momentId: moment.momentId,
|
||||
})
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{state.hasMore ? (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.loadMoreButton}
|
||||
disabled={state.isLoadingMore}
|
||||
onClick={() => dispatch({ type: "PrivateRoomLoadMore" })}
|
||||
>
|
||||
<RefreshCw size={15} aria-hidden="true" />
|
||||
{state.isLoadingMore ? "Loading..." : "Load more"}
|
||||
</button>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
<nav className={styles.bottomNav} aria-label="Private room navigation">
|
||||
<button
|
||||
type="button"
|
||||
className={styles.navButton}
|
||||
onClick={() => navigator.openChat({ replace: false })}
|
||||
>
|
||||
<MessageCircle size={20} aria-hidden="true" />
|
||||
<span>Chat</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`${styles.navButton} ${styles.navButtonActive}`}
|
||||
aria-current="page"
|
||||
>
|
||||
<Camera size={20} aria-hidden="true" />
|
||||
<span>Elio Private room</span>
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
{pendingMoment ? (
|
||||
<UnlockConfirmDialog
|
||||
moment={pendingMoment}
|
||||
isUnlocking={state.isUnlocking}
|
||||
errorMessage={state.unlockErrorMessage}
|
||||
onCancel={() => dispatch({ type: "PrivateRoomUnlockCancelled" })}
|
||||
onConfirm={() => dispatch({ type: "PrivateRoomUnlockConfirmed" })}
|
||||
/>
|
||||
) : state.unlockErrorMessage ? (
|
||||
<div className={styles.toast} role="status">
|
||||
{state.unlockErrorMessage}
|
||||
</div>
|
||||
) : null}
|
||||
</main>
|
||||
</MobileShell>
|
||||
);
|
||||
}
|
||||
|
||||
function PrivateRoomPostCard({
|
||||
moment,
|
||||
displayName,
|
||||
avatarUrl,
|
||||
index,
|
||||
isUnlocking,
|
||||
onUnlock,
|
||||
}: {
|
||||
moment: PrivateRoomMoment;
|
||||
displayName: string;
|
||||
avatarUrl: string;
|
||||
index: number;
|
||||
isUnlocking: boolean;
|
||||
onUnlock: () => void;
|
||||
}) {
|
||||
const isLocked = moment.locked || moment.lockDetail.locked;
|
||||
const imageUrls = moment.images
|
||||
.filter((image) => !image.locked && image.url)
|
||||
.map((image) => image.url as string);
|
||||
const photoCount = moment.mediaCount || moment.images.length || 1;
|
||||
|
||||
return (
|
||||
<article
|
||||
className={styles.postCard}
|
||||
style={{ "--reveal-index": index } as CSSProperties}
|
||||
>
|
||||
<header className={styles.postHeader}>
|
||||
<div className={styles.postAuthor}>
|
||||
<Image
|
||||
src={avatarUrl}
|
||||
alt=""
|
||||
width={38}
|
||||
height={38}
|
||||
className={styles.postAvatar}
|
||||
/>
|
||||
<div>
|
||||
<p className={styles.authorName}>{moment.author.name || displayName}</p>
|
||||
<p className={styles.authorSubline}>
|
||||
{moment.title || "Private room drop"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<time className={styles.postTime}>
|
||||
{moment.timeText || formatMomentTime(moment.publishedAt)}
|
||||
</time>
|
||||
</header>
|
||||
|
||||
{moment.text || moment.content ? (
|
||||
<p className={styles.postText}>{moment.text || moment.content}</p>
|
||||
) : null}
|
||||
|
||||
{isLocked ? (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.lockedPreview}
|
||||
disabled={isUnlocking}
|
||||
onClick={onUnlock}
|
||||
aria-label={`Unlock ${photoCount} private room photos from ${displayName}`}
|
||||
>
|
||||
<div className={styles.previewIcon}>
|
||||
<LockKeyhole size={18} aria-hidden="true" />
|
||||
</div>
|
||||
<div className={styles.previewText}>
|
||||
<strong>{moment.unlockCost} credits</strong>
|
||||
<span>{moment.textPreview || "Unlock to view"}</span>
|
||||
<small>
|
||||
<ImageIcon size={13} aria-hidden="true" />
|
||||
{photoCount} {photoCount === 1 ? "photo" : "photos"}
|
||||
</small>
|
||||
</div>
|
||||
</button>
|
||||
) : (
|
||||
<div className={styles.imageGrid}>
|
||||
{imageUrls.map((url, imageIndex) => (
|
||||
<Image
|
||||
key={`${moment.momentId}-${imageIndex}`}
|
||||
src={url}
|
||||
alt=""
|
||||
width={420}
|
||||
height={420}
|
||||
className={styles.unlockedImage}
|
||||
sizes="(max-width: 540px) 86vw, 460px"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
function UnlockConfirmDialog({
|
||||
moment,
|
||||
isUnlocking,
|
||||
errorMessage,
|
||||
onCancel,
|
||||
onConfirm,
|
||||
}: {
|
||||
moment: PrivateRoomMoment;
|
||||
isUnlocking: boolean;
|
||||
errorMessage: string | null;
|
||||
onCancel: () => void;
|
||||
onConfirm: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className={styles.dialogOverlay} role="alertdialog" aria-modal="true">
|
||||
<div className={styles.dialog}>
|
||||
<h2 className={styles.dialogTitle}>Unlock private moment?</h2>
|
||||
<p className={styles.dialogCopy}>
|
||||
This will use {moment.unlockCost} credits.
|
||||
</p>
|
||||
{errorMessage ? (
|
||||
<p className={styles.dialogError}>{errorMessage}</p>
|
||||
) : null}
|
||||
<div className={styles.dialogActions}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.dialogSecondary}
|
||||
disabled={isUnlocking}
|
||||
onClick={onCancel}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.dialogPrimary}
|
||||
disabled={isUnlocking}
|
||||
onClick={onConfirm}
|
||||
>
|
||||
{isUnlocking ? "Unlocking..." : "Unlock"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StatusCard({
|
||||
message,
|
||||
actionLabel,
|
||||
onAction,
|
||||
}: {
|
||||
message: string;
|
||||
actionLabel?: string;
|
||||
onAction?: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className={styles.statusCard}>
|
||||
<p>{message}</p>
|
||||
{actionLabel && onAction ? (
|
||||
<button type="button" onClick={onAction}>
|
||||
{actionLabel}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatMomentTime(value: string | null): string {
|
||||
if (!value) return "";
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return "";
|
||||
return date.toLocaleDateString(undefined, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ProfileScreen } from "./profile-screen";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export default function ProfilePage() {
|
||||
return <ProfileScreen />;
|
||||
redirect("/private-room");
|
||||
}
|
||||
|
||||
@@ -1,164 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import Image from "next/image";
|
||||
import { Camera, ImageIcon, LockKeyhole, MessageCircle, Sparkles } from "lucide-react";
|
||||
|
||||
import { MobileShell } from "@/app/_components/core";
|
||||
import { useAppNavigator } from "@/router/use-app-navigator";
|
||||
|
||||
import styles from "./profile-screen.module.css";
|
||||
|
||||
const PROFILE = {
|
||||
name: "Elio Silvestri",
|
||||
handle: "@elio.private",
|
||||
avatar: "/images/chat/pic-chat-elio.png",
|
||||
postsCount: 10,
|
||||
cta: "Join Me, unlock my private zoom",
|
||||
bio: "Soft moments, private photos, and a little sweetness just for you.",
|
||||
} as const;
|
||||
|
||||
const POSTS = [
|
||||
{
|
||||
id: "private-zoom-1",
|
||||
timeAgo: "1 day ago",
|
||||
price: "XXX coins",
|
||||
photoCount: "7 photos",
|
||||
},
|
||||
{
|
||||
id: "private-zoom-2",
|
||||
timeAgo: "30 days ago",
|
||||
price: "XXX coins",
|
||||
photoCount: "7 photos",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export function ProfileScreen() {
|
||||
const navigator = useAppNavigator();
|
||||
|
||||
const openVipSubscription = () => {
|
||||
navigator.openSubscription({ type: "vip" });
|
||||
};
|
||||
|
||||
return (
|
||||
<MobileShell background="#fff7ed">
|
||||
<main className={styles.shell}>
|
||||
<div className={styles.backgroundGlowOne} />
|
||||
<div className={styles.backgroundGlowTwo} />
|
||||
|
||||
<section className={styles.hero} aria-labelledby="profile-title">
|
||||
<div className={styles.heroTopline}>
|
||||
<span className={styles.liveDot} aria-hidden="true" />
|
||||
<span>Private zoom is open</span>
|
||||
</div>
|
||||
|
||||
<div className={styles.identity}>
|
||||
<div className={styles.avatarFrame}>
|
||||
<Image
|
||||
src={PROFILE.avatar}
|
||||
alt={PROFILE.name}
|
||||
width={72}
|
||||
height={72}
|
||||
priority
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.identityText}>
|
||||
<h1 id="profile-title" className={styles.title}>
|
||||
{PROFILE.name}
|
||||
</h1>
|
||||
<p className={styles.handle}>{PROFILE.handle}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className={styles.bio}>{PROFILE.bio}</p>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className={styles.primaryCta}
|
||||
onClick={openVipSubscription}
|
||||
>
|
||||
<Sparkles size={16} aria-hidden="true" />
|
||||
<span>{PROFILE.cta}</span>
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<section className={styles.postsSection} aria-labelledby="posts-title">
|
||||
<div className={styles.sectionHeader}>
|
||||
<div>
|
||||
<p className={styles.kicker}>Posts</p>
|
||||
<h2 id="posts-title" className={styles.sectionTitle}>
|
||||
Private moments
|
||||
</h2>
|
||||
</div>
|
||||
<span className={styles.postCount}>{PROFILE.postsCount}</span>
|
||||
</div>
|
||||
|
||||
<div className={styles.timeline}>
|
||||
{POSTS.map((post, index) => (
|
||||
<article
|
||||
key={post.id}
|
||||
className={styles.postCard}
|
||||
style={{ "--reveal-index": index } as React.CSSProperties}
|
||||
>
|
||||
<header className={styles.postHeader}>
|
||||
<div className={styles.postAuthor}>
|
||||
<Image
|
||||
src={PROFILE.avatar}
|
||||
alt=""
|
||||
width={38}
|
||||
height={38}
|
||||
className={styles.postAvatar}
|
||||
/>
|
||||
<div>
|
||||
<p className={styles.authorName}>{PROFILE.name}</p>
|
||||
<p className={styles.authorSubline}>Private zoom drop</p>
|
||||
</div>
|
||||
</div>
|
||||
<time className={styles.postTime}>{post.timeAgo}</time>
|
||||
</header>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className={styles.lockedPreview}
|
||||
onClick={openVipSubscription}
|
||||
aria-label={`Unlock ${post.photoCount} from ${PROFILE.name}`}
|
||||
>
|
||||
<div className={styles.previewIcon}>
|
||||
<LockKeyhole size={18} aria-hidden="true" />
|
||||
</div>
|
||||
<div className={styles.previewText}>
|
||||
<strong>{post.price}</strong>
|
||||
<span>Unlock to view</span>
|
||||
<small>
|
||||
<ImageIcon size={13} aria-hidden="true" />
|
||||
{post.photoCount}
|
||||
</small>
|
||||
</div>
|
||||
</button>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<nav className={styles.bottomNav} aria-label="Profile navigation">
|
||||
<button
|
||||
type="button"
|
||||
className={styles.navButton}
|
||||
onClick={() => navigator.openChat({ replace: false })}
|
||||
>
|
||||
<MessageCircle size={20} aria-hidden="true" />
|
||||
<span>Chat</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`${styles.navButton} ${styles.navButtonActive}`}
|
||||
aria-current="page"
|
||||
>
|
||||
<Camera size={20} aria-hidden="true" />
|
||||
<span>Elio Private zoom</span>
|
||||
</button>
|
||||
</nav>
|
||||
</main>
|
||||
</MobileShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
PrivateRoomMomentsResponse,
|
||||
PrivateRoomUnlockResponse,
|
||||
} from "@/data/dto/private-room";
|
||||
import { ApiPath } from "@/data/services/api";
|
||||
|
||||
const lockedMoment = {
|
||||
momentId: "schedule:91",
|
||||
source: "elio_schedules",
|
||||
sourceId: "91",
|
||||
characterId: "elio",
|
||||
author: {
|
||||
id: "elio",
|
||||
name: "Elio Silvestri",
|
||||
avatarUrl: null,
|
||||
},
|
||||
createdAt: "2026-07-01T08:11:35+00:00",
|
||||
publishedAt: "2026-07-01T08:11:35+00:00",
|
||||
timeText: "7 days ago",
|
||||
title: "Paris morning",
|
||||
content: null,
|
||||
text: null,
|
||||
textPreview: "Unlock to view private room photos",
|
||||
mediaCount: 1,
|
||||
images: [
|
||||
{
|
||||
url: null,
|
||||
type: "image",
|
||||
locked: true,
|
||||
index: 0,
|
||||
},
|
||||
],
|
||||
locked: true,
|
||||
unlocked: false,
|
||||
unlockCost: 40,
|
||||
unlockCostPerImage: 40,
|
||||
requiredCredits: 40,
|
||||
currency: "credits",
|
||||
lockDetail: {
|
||||
locked: true,
|
||||
showContent: false,
|
||||
showUpgrade: true,
|
||||
reason: "private_room_moment",
|
||||
hint: "40 credits · Unlock photo",
|
||||
actionLabel: "Unlock",
|
||||
type: "private_room_moment",
|
||||
requiredCredits: 40,
|
||||
currentCredits: 100,
|
||||
shortfallCredits: 0,
|
||||
mediaCount: 1,
|
||||
unlockCostPerImage: 40,
|
||||
},
|
||||
};
|
||||
|
||||
describe("PrivateRoom DTOs", () => {
|
||||
it("parses locked moments without image URLs", () => {
|
||||
const response = PrivateRoomMomentsResponse.from({
|
||||
profile: {
|
||||
characterId: "elio",
|
||||
displayName: "Elio Silvestri",
|
||||
authorName: "Elio Silvestri",
|
||||
avatarUrl: null,
|
||||
coverUrl: null,
|
||||
title: "Elio Private room",
|
||||
subtitle: "Join me, unlock my private room",
|
||||
},
|
||||
items: [lockedMoment],
|
||||
nextCursor: null,
|
||||
hasMore: false,
|
||||
creditBalance: 100,
|
||||
unlockCostDefault: 40,
|
||||
unlockCostPerImage: 40,
|
||||
currency: "credits",
|
||||
source: "elio_schedules",
|
||||
});
|
||||
|
||||
expect(response.items[0]?.locked).toBe(true);
|
||||
expect(response.items[0]?.images[0]?.url).toBeNull();
|
||||
expect(response.items[0]?.unlockCost).toBe(40);
|
||||
expect(response.profile.displayName).toBe("Elio Silvestri");
|
||||
});
|
||||
|
||||
it("parses unlock success with real image URLs", () => {
|
||||
const response = PrivateRoomUnlockResponse.from({
|
||||
...lockedMoment,
|
||||
locked: false,
|
||||
unlocked: true,
|
||||
content: "A quiet morning in Paris.",
|
||||
text: "A quiet morning in Paris.",
|
||||
images: [
|
||||
{
|
||||
url: "https://lehwkihwnlqkavhcspel.supabase.co/storage/v1/object/public/elio-schedules/schedules/91/photo.jpg",
|
||||
type: "image",
|
||||
locked: false,
|
||||
index: 0,
|
||||
},
|
||||
],
|
||||
reason: "ok",
|
||||
creditsCharged: 40,
|
||||
creditBalance: 60,
|
||||
previousCreditBalance: 100,
|
||||
persisted: true,
|
||||
});
|
||||
|
||||
expect(response.unlocked).toBe(true);
|
||||
expect(response.reason).toBe("ok");
|
||||
expect(response.images[0]?.url).toContain("https://");
|
||||
expect(response.creditBalance).toBe(60);
|
||||
});
|
||||
|
||||
it("parses insufficient credits as business data", () => {
|
||||
const response = PrivateRoomUnlockResponse.from({
|
||||
...lockedMoment,
|
||||
reason: "insufficient_credits",
|
||||
currentCredits: 10,
|
||||
shortfallCredits: 30,
|
||||
creditBalance: 10,
|
||||
});
|
||||
|
||||
expect(response.unlocked).toBe(false);
|
||||
expect(response.locked).toBe(true);
|
||||
expect(response.reason).toBe("insufficient_credits");
|
||||
expect(response.images[0]?.url).toBeNull();
|
||||
});
|
||||
|
||||
it("encodes moment id in the unlock path", () => {
|
||||
expect(ApiPath.privateRoomMomentUnlock("schedule:91")).toBe(
|
||||
"/api/private-room/moments/schedule%3A91/unlock",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from "./private_room_moment";
|
||||
export * from "./request";
|
||||
export * from "./response";
|
||||
@@ -0,0 +1,51 @@
|
||||
import {
|
||||
PrivateRoomMomentSchema,
|
||||
type PrivateRoomMomentData,
|
||||
type PrivateRoomMomentInput,
|
||||
} from "@/data/schemas/private-room";
|
||||
|
||||
export class PrivateRoomMoment {
|
||||
declare readonly momentId: string;
|
||||
declare readonly source: string;
|
||||
declare readonly sourceId: string;
|
||||
declare readonly characterId: string;
|
||||
declare readonly author: PrivateRoomMomentData["author"];
|
||||
declare readonly createdAt: string | null;
|
||||
declare readonly publishedAt: string | null;
|
||||
declare readonly timeText: string;
|
||||
declare readonly title: string;
|
||||
declare readonly content: string | null;
|
||||
declare readonly text: string | null;
|
||||
declare readonly textPreview: string;
|
||||
declare readonly mediaCount: number;
|
||||
declare readonly images: PrivateRoomMomentData["images"];
|
||||
declare readonly locked: boolean;
|
||||
declare readonly unlocked: boolean;
|
||||
declare readonly unlockCost: number;
|
||||
declare readonly unlockCostPerImage: number;
|
||||
declare readonly requiredCredits: number;
|
||||
declare readonly currency: string;
|
||||
declare readonly lockDetail: PrivateRoomMomentData["lockDetail"];
|
||||
|
||||
protected constructor(input: PrivateRoomMomentInput, freeze = true) {
|
||||
const data = PrivateRoomMomentSchema.parse(input);
|
||||
Object.assign(this, data);
|
||||
if (freeze) Object.freeze(this);
|
||||
}
|
||||
|
||||
static from(input: PrivateRoomMomentInput): PrivateRoomMoment {
|
||||
return new PrivateRoomMoment(input);
|
||||
}
|
||||
|
||||
static fromJson(json: unknown): PrivateRoomMoment {
|
||||
return PrivateRoomMoment.from(json as PrivateRoomMomentInput);
|
||||
}
|
||||
|
||||
toJson(): PrivateRoomMomentData {
|
||||
return PrivateRoomMomentSchema.parse(this);
|
||||
}
|
||||
}
|
||||
|
||||
export type PrivateRoomProfile = import("@/data/schemas/private-room").PrivateRoomProfileData;
|
||||
export type PrivateRoomImage = import("@/data/schemas/private-room").PrivateRoomImageData;
|
||||
export type PrivateRoomLockDetail = import("@/data/schemas/private-room").PrivateRoomLockDetailData;
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./unlock_private_room_moment_request";
|
||||
@@ -0,0 +1,31 @@
|
||||
import {
|
||||
UnlockPrivateRoomMomentRequestSchema,
|
||||
type UnlockPrivateRoomMomentRequestData,
|
||||
type UnlockPrivateRoomMomentRequestInput,
|
||||
} from "@/data/schemas/private-room";
|
||||
|
||||
export class UnlockPrivateRoomMomentRequest {
|
||||
declare readonly expectedCost: number;
|
||||
|
||||
private constructor(input: UnlockPrivateRoomMomentRequestInput) {
|
||||
const data = UnlockPrivateRoomMomentRequestSchema.parse(input);
|
||||
Object.assign(this, data);
|
||||
Object.freeze(this);
|
||||
}
|
||||
|
||||
static from(
|
||||
input: UnlockPrivateRoomMomentRequestInput,
|
||||
): UnlockPrivateRoomMomentRequest {
|
||||
return new UnlockPrivateRoomMomentRequest(input);
|
||||
}
|
||||
|
||||
static fromJson(json: unknown): UnlockPrivateRoomMomentRequest {
|
||||
return UnlockPrivateRoomMomentRequest.from(
|
||||
json as UnlockPrivateRoomMomentRequestInput,
|
||||
);
|
||||
}
|
||||
|
||||
toJson(): UnlockPrivateRoomMomentRequestData {
|
||||
return UnlockPrivateRoomMomentRequestSchema.parse(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./private_room_moments_response";
|
||||
export * from "./private_room_unlock_response";
|
||||
@@ -0,0 +1,54 @@
|
||||
import {
|
||||
PrivateRoomMomentsResponseSchema,
|
||||
type PrivateRoomMomentsResponseData,
|
||||
type PrivateRoomMomentsResponseInput,
|
||||
} from "@/data/schemas/private-room";
|
||||
|
||||
import { PrivateRoomMoment } from "../private_room_moment";
|
||||
|
||||
export class PrivateRoomMomentsResponse {
|
||||
declare readonly profile: PrivateRoomMomentsResponseData["profile"];
|
||||
declare readonly items: PrivateRoomMoment[];
|
||||
declare readonly nextCursor: string | null;
|
||||
declare readonly hasMore: boolean;
|
||||
declare readonly creditBalance: number;
|
||||
declare readonly unlockCostDefault: number;
|
||||
declare readonly unlockCostPerImage: number;
|
||||
declare readonly currency: string;
|
||||
declare readonly source: string;
|
||||
|
||||
private constructor(input: PrivateRoomMomentsResponseInput) {
|
||||
const data = PrivateRoomMomentsResponseSchema.parse(input);
|
||||
Object.assign(this, {
|
||||
...data,
|
||||
items: data.items.map((item) => PrivateRoomMoment.from(item)),
|
||||
});
|
||||
Object.freeze(this);
|
||||
}
|
||||
|
||||
static from(
|
||||
input: PrivateRoomMomentsResponseInput,
|
||||
): PrivateRoomMomentsResponse {
|
||||
return new PrivateRoomMomentsResponse(input);
|
||||
}
|
||||
|
||||
static fromJson(json: unknown): PrivateRoomMomentsResponse {
|
||||
return PrivateRoomMomentsResponse.from(
|
||||
json as PrivateRoomMomentsResponseInput,
|
||||
);
|
||||
}
|
||||
|
||||
toJson(): PrivateRoomMomentsResponseData {
|
||||
return {
|
||||
profile: this.profile,
|
||||
items: this.items.map((item) => item.toJson()),
|
||||
nextCursor: this.nextCursor,
|
||||
hasMore: this.hasMore,
|
||||
creditBalance: this.creditBalance,
|
||||
unlockCostDefault: this.unlockCostDefault,
|
||||
unlockCostPerImage: this.unlockCostPerImage,
|
||||
currency: this.currency,
|
||||
source: this.source,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import {
|
||||
PrivateRoomUnlockResponseSchema,
|
||||
type PrivateRoomUnlockReason,
|
||||
type PrivateRoomUnlockResponseData,
|
||||
type PrivateRoomUnlockResponseInput,
|
||||
} from "@/data/schemas/private-room";
|
||||
|
||||
import { PrivateRoomMoment } from "../private_room_moment";
|
||||
|
||||
export class PrivateRoomUnlockResponse extends PrivateRoomMoment {
|
||||
declare readonly reason: PrivateRoomUnlockReason | string;
|
||||
declare readonly creditsCharged: number;
|
||||
declare readonly creditBalance: number;
|
||||
declare readonly previousCreditBalance: number;
|
||||
declare readonly currentCredits: number;
|
||||
declare readonly shortfallCredits: number;
|
||||
declare readonly persisted: boolean;
|
||||
|
||||
private constructor(input: PrivateRoomUnlockResponseInput) {
|
||||
const data = PrivateRoomUnlockResponseSchema.parse(input);
|
||||
super(data, false);
|
||||
Object.assign(this, data);
|
||||
Object.freeze(this);
|
||||
}
|
||||
|
||||
static override from(
|
||||
input: PrivateRoomUnlockResponseInput,
|
||||
): PrivateRoomUnlockResponse {
|
||||
return new PrivateRoomUnlockResponse(input);
|
||||
}
|
||||
|
||||
static override fromJson(json: unknown): PrivateRoomUnlockResponse {
|
||||
return PrivateRoomUnlockResponse.from(
|
||||
json as PrivateRoomUnlockResponseInput,
|
||||
);
|
||||
}
|
||||
|
||||
override toJson(): PrivateRoomUnlockResponseData {
|
||||
return PrivateRoomUnlockResponseSchema.parse(this);
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,11 @@ export * from "./auth_repository";
|
||||
export * from "./chat_repository";
|
||||
export * from "./metrics_repository";
|
||||
export * from "./payment_repository";
|
||||
export * from "./private_room_repository";
|
||||
export * from "./user_repository";
|
||||
export * from "./interfaces/iauth_repository";
|
||||
export * from "./interfaces/ichat_repository";
|
||||
export * from "./interfaces/imetrics_repository";
|
||||
export * from "./interfaces/ipayment_repository";
|
||||
export * from "./interfaces/iprivate_room_repository";
|
||||
export * from "./interfaces/iuser_repository";
|
||||
|
||||
@@ -6,4 +6,5 @@ export * from "./iauth_repository";
|
||||
export * from "./ichat_repository";
|
||||
export * from "./imetrics_repository";
|
||||
export * from "./ipayment_repository";
|
||||
export * from "./iprivate_room_repository";
|
||||
export * from "./iuser_repository";
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import type {
|
||||
PrivateRoomMomentsResponse,
|
||||
PrivateRoomUnlockResponse,
|
||||
} from "@/data/dto/private-room";
|
||||
import type { Result } from "@/utils/result";
|
||||
|
||||
export interface GetPrivateRoomMomentsInput {
|
||||
character?: string;
|
||||
limit?: number;
|
||||
cursor?: string | null;
|
||||
}
|
||||
|
||||
export interface IPrivateRoomRepository {
|
||||
getMoments(
|
||||
input?: GetPrivateRoomMomentsInput,
|
||||
): Promise<Result<PrivateRoomMomentsResponse>>;
|
||||
|
||||
unlockMoment(
|
||||
momentId: string,
|
||||
expectedCost: number,
|
||||
): Promise<Result<PrivateRoomUnlockResponse>>;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
UnlockPrivateRoomMomentRequest,
|
||||
type PrivateRoomMomentsResponse,
|
||||
type PrivateRoomUnlockResponse,
|
||||
} from "@/data/dto/private-room";
|
||||
import {
|
||||
PrivateRoomApi,
|
||||
privateRoomApi,
|
||||
} from "@/data/services/api/private_room_api";
|
||||
import type {
|
||||
GetPrivateRoomMomentsInput,
|
||||
IPrivateRoomRepository,
|
||||
} from "@/data/repositories/interfaces";
|
||||
import { Result } from "@/utils/result";
|
||||
|
||||
import { createLazySingleton } from "./lazy_singleton";
|
||||
|
||||
export class PrivateRoomRepository implements IPrivateRoomRepository {
|
||||
constructor(private readonly api: PrivateRoomApi) {}
|
||||
|
||||
getMoments(
|
||||
input: GetPrivateRoomMomentsInput = {},
|
||||
): Promise<Result<PrivateRoomMomentsResponse>> {
|
||||
return Result.wrap(() => this.api.getMoments(input));
|
||||
}
|
||||
|
||||
unlockMoment(
|
||||
momentId: string,
|
||||
expectedCost: number,
|
||||
): Promise<Result<PrivateRoomUnlockResponse>> {
|
||||
return Result.wrap(() =>
|
||||
this.api.unlockMoment(
|
||||
momentId,
|
||||
UnlockPrivateRoomMomentRequest.from({ expectedCost }),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const getPrivateRoomRepository =
|
||||
createLazySingleton<IPrivateRoomRepository>(
|
||||
() => new PrivateRoomRepository(privateRoomApi),
|
||||
);
|
||||
@@ -0,0 +1,4 @@
|
||||
export * from "./private_room";
|
||||
export * from "./private_room_moments_response";
|
||||
export * from "./private_room_unlock_response";
|
||||
export * from "./unlock_private_room_moment_request";
|
||||
@@ -0,0 +1,102 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
arrayOrEmpty,
|
||||
booleanOrFalse,
|
||||
numberOrZero,
|
||||
schemaOr,
|
||||
stringOrEmpty,
|
||||
stringOrNull,
|
||||
} from "../nullable-defaults";
|
||||
|
||||
export const PrivateRoomProfileSchema = z.object({
|
||||
characterId: stringOrEmpty,
|
||||
displayName: stringOrEmpty,
|
||||
authorName: stringOrEmpty,
|
||||
avatarUrl: stringOrNull,
|
||||
coverUrl: stringOrNull,
|
||||
title: stringOrEmpty,
|
||||
subtitle: stringOrEmpty,
|
||||
});
|
||||
|
||||
export const PrivateRoomImageSchema = z.object({
|
||||
url: stringOrNull,
|
||||
type: stringOrEmpty,
|
||||
locked: booleanOrFalse,
|
||||
index: numberOrZero,
|
||||
});
|
||||
|
||||
export const PrivateRoomLockDetailSchema = z.object({
|
||||
locked: booleanOrFalse,
|
||||
showContent: booleanOrFalse,
|
||||
showUpgrade: booleanOrFalse,
|
||||
reason: stringOrNull,
|
||||
hint: stringOrNull,
|
||||
actionLabel: stringOrNull,
|
||||
type: stringOrNull,
|
||||
requiredCredits: numberOrZero,
|
||||
currentCredits: numberOrZero,
|
||||
shortfallCredits: numberOrZero,
|
||||
mediaCount: numberOrZero,
|
||||
unlockCostPerImage: numberOrZero,
|
||||
detail: z.unknown().nullable().default(null),
|
||||
});
|
||||
|
||||
export const PrivateRoomAuthorSchema = z.object({
|
||||
id: stringOrEmpty,
|
||||
name: stringOrEmpty,
|
||||
avatarUrl: stringOrNull,
|
||||
});
|
||||
|
||||
export const PrivateRoomMomentSchema = z.object({
|
||||
momentId: stringOrEmpty,
|
||||
source: stringOrEmpty,
|
||||
sourceId: stringOrEmpty,
|
||||
characterId: stringOrEmpty,
|
||||
author: schemaOr(PrivateRoomAuthorSchema, {
|
||||
id: "",
|
||||
name: "",
|
||||
avatarUrl: null,
|
||||
}),
|
||||
createdAt: stringOrNull,
|
||||
publishedAt: stringOrNull,
|
||||
timeText: stringOrEmpty,
|
||||
title: stringOrEmpty,
|
||||
content: stringOrNull,
|
||||
text: stringOrNull,
|
||||
textPreview: stringOrEmpty,
|
||||
mediaCount: numberOrZero,
|
||||
images: arrayOrEmpty(PrivateRoomImageSchema),
|
||||
locked: booleanOrFalse,
|
||||
unlocked: booleanOrFalse,
|
||||
unlockCost: numberOrZero,
|
||||
unlockCostPerImage: numberOrZero,
|
||||
requiredCredits: numberOrZero,
|
||||
currency: stringOrEmpty,
|
||||
lockDetail: schemaOr(PrivateRoomLockDetailSchema, {
|
||||
locked: false,
|
||||
showContent: false,
|
||||
showUpgrade: false,
|
||||
reason: null,
|
||||
hint: null,
|
||||
actionLabel: null,
|
||||
type: null,
|
||||
requiredCredits: 0,
|
||||
currentCredits: 0,
|
||||
shortfallCredits: 0,
|
||||
mediaCount: 0,
|
||||
unlockCostPerImage: 0,
|
||||
detail: null,
|
||||
}),
|
||||
});
|
||||
|
||||
export type PrivateRoomProfileData = z.output<
|
||||
typeof PrivateRoomProfileSchema
|
||||
>;
|
||||
export type PrivateRoomImageData = z.output<typeof PrivateRoomImageSchema>;
|
||||
export type PrivateRoomLockDetailData = z.output<
|
||||
typeof PrivateRoomLockDetailSchema
|
||||
>;
|
||||
export type PrivateRoomAuthorData = z.output<typeof PrivateRoomAuthorSchema>;
|
||||
export type PrivateRoomMomentInput = z.input<typeof PrivateRoomMomentSchema>;
|
||||
export type PrivateRoomMomentData = z.output<typeof PrivateRoomMomentSchema>;
|
||||
@@ -0,0 +1,41 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
arrayOrEmpty,
|
||||
booleanOrFalse,
|
||||
numberOrZero,
|
||||
schemaOr,
|
||||
stringOrEmpty,
|
||||
stringOrNull,
|
||||
} from "../nullable-defaults";
|
||||
import {
|
||||
PrivateRoomMomentSchema,
|
||||
PrivateRoomProfileSchema,
|
||||
} from "./private_room";
|
||||
|
||||
export const PrivateRoomMomentsResponseSchema = z.object({
|
||||
profile: schemaOr(PrivateRoomProfileSchema, {
|
||||
characterId: "elio",
|
||||
displayName: "Elio Silvestri",
|
||||
authorName: "Elio Silvestri",
|
||||
avatarUrl: null,
|
||||
coverUrl: null,
|
||||
title: "Elio Private room",
|
||||
subtitle: "Join me, unlock my private room",
|
||||
}),
|
||||
items: arrayOrEmpty(PrivateRoomMomentSchema),
|
||||
nextCursor: stringOrNull,
|
||||
hasMore: booleanOrFalse,
|
||||
creditBalance: numberOrZero,
|
||||
unlockCostDefault: numberOrZero,
|
||||
unlockCostPerImage: numberOrZero,
|
||||
currency: stringOrEmpty,
|
||||
source: stringOrEmpty,
|
||||
});
|
||||
|
||||
export type PrivateRoomMomentsResponseInput = z.input<
|
||||
typeof PrivateRoomMomentsResponseSchema
|
||||
>;
|
||||
export type PrivateRoomMomentsResponseData = z.output<
|
||||
typeof PrivateRoomMomentsResponseSchema
|
||||
>;
|
||||
@@ -0,0 +1,36 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { booleanOrFalse, numberOrZero, stringOrEmpty } from "../nullable-defaults";
|
||||
import { PrivateRoomMomentSchema } from "./private_room";
|
||||
|
||||
export const PrivateRoomUnlockReasonSchema = z.enum([
|
||||
"ok",
|
||||
"already_unlocked",
|
||||
"insufficient_credits",
|
||||
"cost_changed",
|
||||
"not_found",
|
||||
"no_media",
|
||||
"deduct_failed",
|
||||
"ok_persist_failed",
|
||||
]);
|
||||
|
||||
export const PrivateRoomUnlockResponseSchema =
|
||||
PrivateRoomMomentSchema.extend({
|
||||
reason: PrivateRoomUnlockReasonSchema.or(stringOrEmpty),
|
||||
creditsCharged: numberOrZero,
|
||||
creditBalance: numberOrZero,
|
||||
previousCreditBalance: numberOrZero,
|
||||
currentCredits: numberOrZero,
|
||||
shortfallCredits: numberOrZero,
|
||||
persisted: booleanOrFalse,
|
||||
});
|
||||
|
||||
export type PrivateRoomUnlockReason = z.output<
|
||||
typeof PrivateRoomUnlockReasonSchema
|
||||
>;
|
||||
export type PrivateRoomUnlockResponseInput = z.input<
|
||||
typeof PrivateRoomUnlockResponseSchema
|
||||
>;
|
||||
export type PrivateRoomUnlockResponseData = z.output<
|
||||
typeof PrivateRoomUnlockResponseSchema
|
||||
>;
|
||||
@@ -0,0 +1,14 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { numberOrZero } from "../nullable-defaults";
|
||||
|
||||
export const UnlockPrivateRoomMomentRequestSchema = z.object({
|
||||
expectedCost: numberOrZero,
|
||||
});
|
||||
|
||||
export type UnlockPrivateRoomMomentRequestInput = z.input<
|
||||
typeof UnlockPrivateRoomMomentRequestSchema
|
||||
>;
|
||||
export type UnlockPrivateRoomMomentRequestData = z.output<
|
||||
typeof UnlockPrivateRoomMomentRequestSchema
|
||||
>;
|
||||
@@ -14,6 +14,7 @@ export class ApiPath {
|
||||
private static readonly _user = `${ApiPath._baseUrl}/user`;
|
||||
private static readonly _payment = `${ApiPath._baseUrl}/payment`;
|
||||
private static readonly _chat = `${ApiPath._baseUrl}/chat`;
|
||||
private static readonly _privateRoom = `${ApiPath._baseUrl}/private-room`;
|
||||
|
||||
// ============ 认证相关 ============
|
||||
/** 邮箱密码登录 */
|
||||
@@ -73,6 +74,15 @@ export class ApiPath {
|
||||
/** 一键解锁历史锁定消息 */
|
||||
static readonly chatUnlockHistory = `${ApiPath._chat}/unlock-history`;
|
||||
|
||||
// ============ 私密空间相关 ============
|
||||
/** 获取私密空间动态列表 */
|
||||
static readonly privateRoomMoments = `${ApiPath._privateRoom}/moments`;
|
||||
|
||||
/** 解锁私密空间动态 */
|
||||
static privateRoomMomentUnlock(momentId: string): string {
|
||||
return `${ApiPath.privateRoomMoments}/${encodeURIComponent(momentId)}/unlock`;
|
||||
}
|
||||
|
||||
// ============ 数据看板相关 ============
|
||||
private static readonly _metrics = `${ApiPath._baseUrl}/metrics`;
|
||||
|
||||
|
||||
@@ -9,5 +9,6 @@ export * from "./chat_api";
|
||||
export * from "./http_client";
|
||||
export * from "./metrics_api";
|
||||
export * from "./payment_api";
|
||||
export * from "./private_room_api";
|
||||
export * from "./response_helper";
|
||||
export * from "./user_api";
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import {
|
||||
PrivateRoomMomentsResponse,
|
||||
PrivateRoomUnlockResponse,
|
||||
UnlockPrivateRoomMomentRequest,
|
||||
} from "@/data/dto/private-room";
|
||||
|
||||
import { ApiPath } from "./api_path";
|
||||
import { httpClient } from "./http_client";
|
||||
import { type ApiEnvelope, unwrap } from "./response_helper";
|
||||
|
||||
export interface GetPrivateRoomMomentsInput {
|
||||
character?: string;
|
||||
limit?: number;
|
||||
cursor?: string | null;
|
||||
}
|
||||
|
||||
export class PrivateRoomApi {
|
||||
async getMoments(
|
||||
input: GetPrivateRoomMomentsInput = {},
|
||||
): Promise<PrivateRoomMomentsResponse> {
|
||||
const env = await httpClient<ApiEnvelope<unknown>>(
|
||||
ApiPath.privateRoomMoments,
|
||||
{
|
||||
query: {
|
||||
character: input.character ?? "elio",
|
||||
limit: input.limit ?? 20,
|
||||
...(input.cursor ? { cursor: input.cursor } : {}),
|
||||
},
|
||||
},
|
||||
);
|
||||
return PrivateRoomMomentsResponse.fromJson(unwrap(env));
|
||||
}
|
||||
|
||||
async unlockMoment(
|
||||
momentId: string,
|
||||
body: UnlockPrivateRoomMomentRequest,
|
||||
): Promise<PrivateRoomUnlockResponse> {
|
||||
const env = await httpClient<ApiEnvelope<unknown>>(
|
||||
ApiPath.privateRoomMomentUnlock(momentId),
|
||||
{
|
||||
method: "POST",
|
||||
body: body.toJson(),
|
||||
},
|
||||
);
|
||||
return PrivateRoomUnlockResponse.fromJson(unwrap(env));
|
||||
}
|
||||
}
|
||||
|
||||
export const privateRoomApi = new PrivateRoomApi();
|
||||
@@ -0,0 +1,65 @@
|
||||
"use client";
|
||||
|
||||
import { type Dispatch, useEffect, useRef } from "react";
|
||||
|
||||
import type { LoginStatus } from "@/data/dto/auth";
|
||||
import type { AuthEvent } from "@/stores/auth/auth-events";
|
||||
|
||||
export interface GuestLoginBootstrapState {
|
||||
hasInitialized: boolean;
|
||||
isLoading: boolean;
|
||||
loginStatus: LoginStatus;
|
||||
}
|
||||
|
||||
export interface ShouldSubmitGuestLoginInput
|
||||
extends GuestLoginBootstrapState {
|
||||
alreadyRequested: boolean;
|
||||
}
|
||||
|
||||
export interface UseGuestLoginBootstrapInput
|
||||
extends GuestLoginBootstrapState {
|
||||
dispatch: Dispatch<AuthEvent>;
|
||||
}
|
||||
|
||||
export function shouldSubmitGuestLogin({
|
||||
alreadyRequested,
|
||||
hasInitialized,
|
||||
isLoading,
|
||||
loginStatus,
|
||||
}: ShouldSubmitGuestLoginInput): boolean {
|
||||
if (!hasInitialized || isLoading) return false;
|
||||
if (loginStatus !== "notLoggedIn") return false;
|
||||
return !alreadyRequested;
|
||||
}
|
||||
|
||||
export function useGuestLoginBootstrap({
|
||||
dispatch,
|
||||
hasInitialized,
|
||||
isLoading,
|
||||
loginStatus,
|
||||
}: UseGuestLoginBootstrapInput): void {
|
||||
const guestLoginRequestedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasInitialized || isLoading) return;
|
||||
|
||||
if (loginStatus !== "notLoggedIn") {
|
||||
guestLoginRequestedRef.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
!shouldSubmitGuestLogin({
|
||||
alreadyRequested: guestLoginRequestedRef.current,
|
||||
hasInitialized,
|
||||
isLoading,
|
||||
loginStatus,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
guestLoginRequestedRef.current = true;
|
||||
dispatch({ type: "AuthGuestLoginSubmitted" });
|
||||
}, [dispatch, hasInitialized, isLoading, loginStatus]);
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
* 根级 Client Providers 包装
|
||||
*
|
||||
* 把所有功能 Provider 串起来:
|
||||
* AuthProvider → UserProvider → PaymentProvider → ChatProvider
|
||||
* AuthProvider → UserProvider → PaymentProvider → ChatProvider → PrivateRoomProvider
|
||||
* + AuthStatusChecker(启动时一次:派发 AuthInit)
|
||||
* + OAuthSessionSync (持续监听 NextAuth session → auth machine)
|
||||
* + UserAuthSync (auth 登录态恢复后 hydrate user machine)
|
||||
@@ -23,6 +23,7 @@ import { AuthStatusChecker } from "@/stores/auth/auth-status-checker";
|
||||
import { OAuthSessionSync } from "@/stores/auth/oauth-session-sync";
|
||||
import { ChatProvider } from "@/stores/chat/chat-context";
|
||||
import { PaymentProvider } from "@/stores/payment";
|
||||
import { PrivateRoomProvider } from "@/stores/private-room";
|
||||
import {
|
||||
ChatAuthSync,
|
||||
PaymentSuccessSync,
|
||||
@@ -48,10 +49,12 @@ export function RootProviders({ children }: RootProvidersProps) {
|
||||
<UserAuthSync />
|
||||
<PaymentProvider>
|
||||
<ChatProvider>
|
||||
<ChatAuthSync />
|
||||
<PaymentSuccessSync />
|
||||
{children}
|
||||
<div id="toast-portal" />
|
||||
<PrivateRoomProvider>
|
||||
<ChatAuthSync />
|
||||
<PaymentSuccessSync />
|
||||
{children}
|
||||
<div id="toast-portal" />
|
||||
</PrivateRoomProvider>
|
||||
</ChatProvider>
|
||||
</PaymentProvider>
|
||||
</UserProvider>
|
||||
|
||||
@@ -8,7 +8,7 @@ describe("route meta", () => {
|
||||
expect(getRouteAccess(ROUTES.splash)).toBe("authOnly");
|
||||
expect(getRouteAccess(ROUTES.auth)).toBe("authOnly");
|
||||
expect(getRouteAccess(ROUTES.chat)).toBe("guestEntry");
|
||||
expect(getRouteAccess(ROUTES.profile)).toBe("public");
|
||||
expect(getRouteAccess(ROUTES.privateRoom)).toBe("guestEntry");
|
||||
expect(getRouteAccess(ROUTES.sidebar)).toBe("session");
|
||||
expect(getRouteAccess(ROUTES.subscription)).toBe("realUser");
|
||||
expect(getRouteAccess(ROUTES.coinsRules)).toBe("public");
|
||||
@@ -19,8 +19,8 @@ describe("route meta", () => {
|
||||
expect(getRouteAccess("/chat/deviceid/device_1")).toBe("public");
|
||||
});
|
||||
|
||||
it("includes profile in static routes", () => {
|
||||
expect(ALL_STATIC_ROUTES).toContain(ROUTES.profile);
|
||||
it("includes private room in static routes", () => {
|
||||
expect(ALL_STATIC_ROUTES).toContain(ROUTES.privateRoom);
|
||||
});
|
||||
|
||||
it("treats unknown routes as public by default", () => {
|
||||
|
||||
@@ -12,7 +12,7 @@ const STATIC_ROUTE_ACCESS: Partial<Record<string, RouteAccess>> = {
|
||||
[ROUTES.splash]: "authOnly",
|
||||
[ROUTES.auth]: "authOnly",
|
||||
[ROUTES.chat]: "guestEntry",
|
||||
[ROUTES.profile]: "public",
|
||||
[ROUTES.privateRoom]: "guestEntry",
|
||||
[ROUTES.sidebar]: "session",
|
||||
[ROUTES.subscription]: "realUser",
|
||||
[ROUTES.coinsRules]: "public",
|
||||
|
||||
@@ -21,7 +21,7 @@ export const ROUTES = {
|
||||
root: "/",
|
||||
splash: "/splash",
|
||||
chat: "/chat",
|
||||
profile: "/profile",
|
||||
privateRoom: "/private-room",
|
||||
auth: "/auth",
|
||||
sidebar: "/sidebar",
|
||||
subscription: "/subscription",
|
||||
@@ -53,7 +53,7 @@ export const ROUTE_BUILDERS = {
|
||||
export const ALL_STATIC_ROUTES: readonly StaticRoute[] = [
|
||||
ROUTES.splash,
|
||||
ROUTES.chat,
|
||||
ROUTES.profile,
|
||||
ROUTES.privateRoom,
|
||||
ROUTES.auth,
|
||||
ROUTES.sidebar,
|
||||
ROUTES.coinsRules,
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createActor, fromPromise, waitFor } from "xstate";
|
||||
|
||||
import {
|
||||
PrivateRoomMomentsResponse,
|
||||
PrivateRoomUnlockResponse,
|
||||
} from "@/data/dto/private-room";
|
||||
import { privateRoomMachine } from "@/stores/private-room/private-room-machine";
|
||||
|
||||
const baseMoment = {
|
||||
momentId: "schedule:91",
|
||||
source: "elio_schedules",
|
||||
sourceId: "91",
|
||||
characterId: "elio",
|
||||
author: {
|
||||
id: "elio",
|
||||
name: "Elio Silvestri",
|
||||
avatarUrl: null,
|
||||
},
|
||||
createdAt: "2026-07-01T08:11:35+00:00",
|
||||
publishedAt: "2026-07-01T08:11:35+00:00",
|
||||
timeText: "7 days ago",
|
||||
title: "Paris morning",
|
||||
content: null,
|
||||
text: null,
|
||||
textPreview: "Unlock to view private room photos",
|
||||
mediaCount: 1,
|
||||
images: [
|
||||
{
|
||||
url: null,
|
||||
type: "image",
|
||||
locked: true,
|
||||
index: 0,
|
||||
},
|
||||
],
|
||||
locked: true,
|
||||
unlocked: false,
|
||||
unlockCost: 40,
|
||||
unlockCostPerImage: 40,
|
||||
requiredCredits: 40,
|
||||
currency: "credits",
|
||||
lockDetail: {
|
||||
locked: true,
|
||||
showContent: false,
|
||||
showUpgrade: true,
|
||||
reason: "private_room_moment",
|
||||
hint: "40 credits · Unlock photo",
|
||||
actionLabel: "Unlock",
|
||||
type: "private_room_moment",
|
||||
requiredCredits: 40,
|
||||
currentCredits: 100,
|
||||
shortfallCredits: 0,
|
||||
mediaCount: 1,
|
||||
unlockCostPerImage: 40,
|
||||
},
|
||||
};
|
||||
|
||||
function makeMomentsResponse(
|
||||
overrides: Partial<Parameters<typeof PrivateRoomMomentsResponse.from>[0]> = {},
|
||||
): PrivateRoomMomentsResponse {
|
||||
return PrivateRoomMomentsResponse.from({
|
||||
profile: {
|
||||
characterId: "elio",
|
||||
displayName: "Elio Silvestri",
|
||||
authorName: "Elio Silvestri",
|
||||
avatarUrl: null,
|
||||
coverUrl: null,
|
||||
title: "Elio Private room",
|
||||
subtitle: "Join me, unlock my private room",
|
||||
},
|
||||
items: [baseMoment],
|
||||
nextCursor: null,
|
||||
hasMore: false,
|
||||
creditBalance: 100,
|
||||
unlockCostDefault: 40,
|
||||
unlockCostPerImage: 40,
|
||||
currency: "credits",
|
||||
source: "elio_schedules",
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
function makeUnlockResponse(
|
||||
overrides: Partial<Parameters<typeof PrivateRoomUnlockResponse.from>[0]> = {},
|
||||
): PrivateRoomUnlockResponse {
|
||||
return PrivateRoomUnlockResponse.from({
|
||||
...baseMoment,
|
||||
locked: false,
|
||||
unlocked: true,
|
||||
images: [
|
||||
{
|
||||
url: "https://example.supabase.co/storage/v1/object/public/elio-schedules/photo.jpg",
|
||||
type: "image",
|
||||
locked: false,
|
||||
index: 0,
|
||||
},
|
||||
],
|
||||
reason: "ok",
|
||||
creditsCharged: 40,
|
||||
creditBalance: 60,
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
function createTestMachine(
|
||||
options: {
|
||||
firstPage?: PrivateRoomMomentsResponse;
|
||||
morePage?: PrivateRoomMomentsResponse;
|
||||
unlockResponse?: PrivateRoomUnlockResponse;
|
||||
} = {},
|
||||
) {
|
||||
return privateRoomMachine.provide({
|
||||
actors: {
|
||||
loadMoments: fromPromise(async () => options.firstPage ?? makeMomentsResponse()),
|
||||
loadMoreMoments: fromPromise(async () =>
|
||||
options.morePage ??
|
||||
makeMomentsResponse({
|
||||
items: [
|
||||
{
|
||||
...baseMoment,
|
||||
momentId: "schedule:92",
|
||||
sourceId: "92",
|
||||
},
|
||||
],
|
||||
hasMore: false,
|
||||
nextCursor: null,
|
||||
}),
|
||||
),
|
||||
unlockMoment: fromPromise(async () =>
|
||||
options.unlockResponse ?? makeUnlockResponse(),
|
||||
),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe("privateRoomMachine", () => {
|
||||
it("loads the first page", async () => {
|
||||
const actor = createActor(createTestMachine()).start();
|
||||
|
||||
actor.send({ type: "PrivateRoomInit" });
|
||||
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
|
||||
|
||||
const context = actor.getSnapshot().context;
|
||||
expect(context.profile?.displayName).toBe("Elio Silvestri");
|
||||
expect(context.items).toHaveLength(1);
|
||||
expect(context.creditBalance).toBe(100);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("appends more moments without overwriting existing items", async () => {
|
||||
const actor = createActor(
|
||||
createTestMachine({
|
||||
firstPage: makeMomentsResponse({
|
||||
hasMore: true,
|
||||
nextCursor: "cursor-1",
|
||||
}),
|
||||
}),
|
||||
).start();
|
||||
|
||||
actor.send({ type: "PrivateRoomInit" });
|
||||
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
|
||||
|
||||
actor.send({ type: "PrivateRoomLoadMore" });
|
||||
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
|
||||
|
||||
expect(actor.getSnapshot().context.items.map((item) => item.momentId)).toEqual([
|
||||
"schedule:91",
|
||||
"schedule:92",
|
||||
]);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("replaces a locked moment after unlock success", async () => {
|
||||
const actor = createActor(createTestMachine()).start();
|
||||
|
||||
actor.send({ type: "PrivateRoomInit" });
|
||||
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
|
||||
|
||||
actor.send({
|
||||
type: "PrivateRoomUnlockRequested",
|
||||
momentId: "schedule:91",
|
||||
});
|
||||
actor.send({ type: "PrivateRoomUnlockConfirmed" });
|
||||
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
|
||||
|
||||
const context = actor.getSnapshot().context;
|
||||
expect(context.items[0]?.unlocked).toBe(true);
|
||||
expect(context.items[0]?.images[0]?.url).toContain("https://");
|
||||
expect(context.unlockSuccessNonce).toBe(1);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("exposes a paywall request for insufficient credits", async () => {
|
||||
const actor = createActor(
|
||||
createTestMachine({
|
||||
unlockResponse: makeUnlockResponse({
|
||||
...baseMoment,
|
||||
reason: "insufficient_credits",
|
||||
locked: true,
|
||||
unlocked: false,
|
||||
creditBalance: 10,
|
||||
currentCredits: 10,
|
||||
shortfallCredits: 30,
|
||||
}),
|
||||
}),
|
||||
).start();
|
||||
|
||||
actor.send({ type: "PrivateRoomInit" });
|
||||
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
|
||||
|
||||
actor.send({
|
||||
type: "PrivateRoomUnlockRequested",
|
||||
momentId: "schedule:91",
|
||||
});
|
||||
actor.send({ type: "PrivateRoomUnlockConfirmed" });
|
||||
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
|
||||
|
||||
const context = actor.getSnapshot().context;
|
||||
expect(context.items[0]?.unlocked).toBe(false);
|
||||
expect(context.unlockPaywallRequest).toMatchObject({
|
||||
momentId: "schedule:91",
|
||||
reason: "insufficient_credits",
|
||||
shortfallCredits: 30,
|
||||
});
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("refreshes and keeps an unlock error when the cost changes", async () => {
|
||||
const actor = createActor(
|
||||
createTestMachine({
|
||||
unlockResponse: makeUnlockResponse({
|
||||
...baseMoment,
|
||||
reason: "cost_changed",
|
||||
locked: true,
|
||||
unlocked: false,
|
||||
}),
|
||||
}),
|
||||
).start();
|
||||
|
||||
actor.send({ type: "PrivateRoomInit" });
|
||||
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
|
||||
|
||||
actor.send({
|
||||
type: "PrivateRoomUnlockRequested",
|
||||
momentId: "schedule:91",
|
||||
});
|
||||
actor.send({ type: "PrivateRoomUnlockConfirmed" });
|
||||
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
|
||||
|
||||
expect(actor.getSnapshot().context.unlockErrorMessage).toBe(
|
||||
"Unlock price changed. Please confirm again.",
|
||||
);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
export * from "./private-room-context";
|
||||
export * from "./private-room-events";
|
||||
export * from "./private-room-machine";
|
||||
export * from "./private-room-state";
|
||||
@@ -0,0 +1,96 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
type Dispatch,
|
||||
type ReactNode,
|
||||
createContext,
|
||||
useContext,
|
||||
useMemo,
|
||||
} from "react";
|
||||
import { useMachine } from "@xstate/react";
|
||||
|
||||
import { privateRoomMachine } from "./private-room-machine";
|
||||
import type {
|
||||
PrivateRoomEvent,
|
||||
PrivateRoomState as MachineContext,
|
||||
} from "./private-room-machine";
|
||||
|
||||
export interface PrivateRoomContextState {
|
||||
status: string;
|
||||
profile: MachineContext["profile"];
|
||||
items: MachineContext["items"];
|
||||
nextCursor: string | null;
|
||||
hasMore: boolean;
|
||||
creditBalance: number;
|
||||
errorMessage: string | null;
|
||||
unlockingMomentId: string | null;
|
||||
unlockErrorMessage: string | null;
|
||||
pendingConfirmMomentId: string | null;
|
||||
unlockPaywallRequest: MachineContext["unlockPaywallRequest"];
|
||||
unlockSuccessNonce: number;
|
||||
isLoading: boolean;
|
||||
isLoadingMore: boolean;
|
||||
isUnlocking: boolean;
|
||||
}
|
||||
|
||||
const PrivateRoomStateCtx = createContext<PrivateRoomContextState | null>(null);
|
||||
const PrivateRoomDispatchCtx = createContext<Dispatch<PrivateRoomEvent> | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
export interface PrivateRoomProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function PrivateRoomProvider({ children }: PrivateRoomProviderProps) {
|
||||
const [state, send] = useMachine(privateRoomMachine);
|
||||
|
||||
const privateRoomState = useMemo<PrivateRoomContextState>(
|
||||
() => ({
|
||||
status: String(state.value),
|
||||
profile: state.context.profile,
|
||||
items: state.context.items,
|
||||
nextCursor: state.context.nextCursor,
|
||||
hasMore: state.context.hasMore,
|
||||
creditBalance: state.context.creditBalance,
|
||||
errorMessage: state.context.errorMessage,
|
||||
unlockingMomentId: state.context.unlockingMomentId,
|
||||
unlockErrorMessage: state.context.unlockErrorMessage,
|
||||
pendingConfirmMomentId: state.context.pendingConfirmMomentId,
|
||||
unlockPaywallRequest: state.context.unlockPaywallRequest,
|
||||
unlockSuccessNonce: state.context.unlockSuccessNonce,
|
||||
isLoading: state.matches("loading"),
|
||||
isLoadingMore: state.matches("loadingMore"),
|
||||
isUnlocking: state.matches("unlocking"),
|
||||
}),
|
||||
[state],
|
||||
);
|
||||
|
||||
return (
|
||||
<PrivateRoomStateCtx.Provider value={privateRoomState}>
|
||||
<PrivateRoomDispatchCtx.Provider value={send}>
|
||||
{children}
|
||||
</PrivateRoomDispatchCtx.Provider>
|
||||
</PrivateRoomStateCtx.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function usePrivateRoomState(): PrivateRoomContextState {
|
||||
const ctx = useContext(PrivateRoomStateCtx);
|
||||
if (!ctx) {
|
||||
throw new Error(
|
||||
"usePrivateRoomState must be used inside <PrivateRoomProvider>",
|
||||
);
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
|
||||
export function usePrivateRoomDispatch(): Dispatch<PrivateRoomEvent> {
|
||||
const ctx = useContext(PrivateRoomDispatchCtx);
|
||||
if (!ctx) {
|
||||
throw new Error(
|
||||
"usePrivateRoomDispatch must be used inside <PrivateRoomProvider>",
|
||||
);
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export type PrivateRoomEvent =
|
||||
| { type: "PrivateRoomInit" }
|
||||
| { type: "PrivateRoomRefresh" }
|
||||
| { type: "PrivateRoomLoadMore" }
|
||||
| { type: "PrivateRoomUnlockRequested"; momentId: string }
|
||||
| { type: "PrivateRoomUnlockConfirmed" }
|
||||
| { type: "PrivateRoomUnlockCancelled" }
|
||||
| { type: "PrivateRoomUnlockPaywallConsumed" };
|
||||
@@ -0,0 +1,51 @@
|
||||
import { fromPromise } from "xstate";
|
||||
|
||||
import type {
|
||||
PrivateRoomMomentsResponse,
|
||||
PrivateRoomUnlockResponse,
|
||||
} from "@/data/dto/private-room";
|
||||
import { getPrivateRoomRepository } from "@/data/repositories/private_room_repository";
|
||||
import { Result } from "@/utils";
|
||||
|
||||
import {
|
||||
PRIVATE_ROOM_CHARACTER,
|
||||
PRIVATE_ROOM_PAGE_SIZE,
|
||||
} from "./private-room-machine.helpers";
|
||||
|
||||
export const loadPrivateRoomMomentsActor =
|
||||
fromPromise<PrivateRoomMomentsResponse>(async () => {
|
||||
const repo = getPrivateRoomRepository();
|
||||
const result = await repo.getMoments({
|
||||
character: PRIVATE_ROOM_CHARACTER,
|
||||
limit: PRIVATE_ROOM_PAGE_SIZE,
|
||||
});
|
||||
if (Result.isErr(result)) throw result.error;
|
||||
return result.data;
|
||||
});
|
||||
|
||||
export const loadMorePrivateRoomMomentsActor = fromPromise<
|
||||
PrivateRoomMomentsResponse,
|
||||
{ cursor: string | null }
|
||||
>(async ({ input }) => {
|
||||
const repo = getPrivateRoomRepository();
|
||||
const result = await repo.getMoments({
|
||||
character: PRIVATE_ROOM_CHARACTER,
|
||||
limit: PRIVATE_ROOM_PAGE_SIZE,
|
||||
cursor: input.cursor,
|
||||
});
|
||||
if (Result.isErr(result)) throw result.error;
|
||||
return result.data;
|
||||
});
|
||||
|
||||
export const unlockPrivateRoomMomentActor = fromPromise<
|
||||
PrivateRoomUnlockResponse,
|
||||
{ momentId: string; expectedCost: number }
|
||||
>(async ({ input }) => {
|
||||
const repo = getPrivateRoomRepository();
|
||||
const result = await repo.unlockMoment(
|
||||
input.momentId,
|
||||
input.expectedCost,
|
||||
);
|
||||
if (Result.isErr(result)) throw result.error;
|
||||
return result.data;
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import type {
|
||||
PrivateRoomMoment,
|
||||
PrivateRoomMomentsResponse,
|
||||
PrivateRoomUnlockResponse,
|
||||
} from "@/data/dto/private-room";
|
||||
|
||||
import type {
|
||||
PrivateRoomState,
|
||||
PrivateRoomUnlockPaywallRequest,
|
||||
} from "./private-room-state";
|
||||
|
||||
export const PRIVATE_ROOM_CHARACTER = "elio";
|
||||
export const PRIVATE_ROOM_PAGE_SIZE = 20;
|
||||
|
||||
export function applyMomentsResponse(
|
||||
response: PrivateRoomMomentsResponse,
|
||||
): Partial<PrivateRoomState> {
|
||||
return {
|
||||
profile: response.profile,
|
||||
items: response.items,
|
||||
nextCursor: response.nextCursor,
|
||||
hasMore: response.hasMore,
|
||||
creditBalance: response.creditBalance,
|
||||
errorMessage: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function appendMomentsResponse(
|
||||
context: PrivateRoomState,
|
||||
response: PrivateRoomMomentsResponse,
|
||||
): Partial<PrivateRoomState> {
|
||||
const knownIds = new Set(context.items.map((item) => item.momentId));
|
||||
const nextItems = [
|
||||
...context.items,
|
||||
...response.items.filter((item) => !knownIds.has(item.momentId)),
|
||||
];
|
||||
return {
|
||||
profile: response.profile,
|
||||
items: nextItems,
|
||||
nextCursor: response.nextCursor,
|
||||
hasMore: response.hasMore,
|
||||
creditBalance: response.creditBalance,
|
||||
errorMessage: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function replaceMoment(
|
||||
items: readonly PrivateRoomMoment[],
|
||||
nextMoment: PrivateRoomMoment,
|
||||
): PrivateRoomMoment[] {
|
||||
return items.map((item) =>
|
||||
item.momentId === nextMoment.momentId ? nextMoment : item,
|
||||
);
|
||||
}
|
||||
|
||||
export function toPrivateRoomErrorMessage(error: unknown): string {
|
||||
if (error instanceof Error && error.message) return error.message;
|
||||
return "Private room is temporarily unavailable. Please try again.";
|
||||
}
|
||||
|
||||
export function toUnlockErrorMessage(
|
||||
response: PrivateRoomUnlockResponse,
|
||||
): string | null {
|
||||
switch (response.reason) {
|
||||
case "cost_changed":
|
||||
return "Unlock price changed. Please confirm again.";
|
||||
case "not_found":
|
||||
return "This private room post is no longer available.";
|
||||
case "no_media":
|
||||
return "This private room post has no photos to unlock.";
|
||||
case "deduct_failed":
|
||||
return "Credit deduction failed. Please try again.";
|
||||
default:
|
||||
return response.unlocked ? null : "Unlock failed. Please try again.";
|
||||
}
|
||||
}
|
||||
|
||||
export function toPaywallRequest(
|
||||
response: PrivateRoomUnlockResponse,
|
||||
): PrivateRoomUnlockPaywallRequest {
|
||||
return {
|
||||
momentId: response.momentId,
|
||||
reason: response.reason,
|
||||
requiredCredits: response.requiredCredits,
|
||||
currentCredits: response.currentCredits || response.creditBalance,
|
||||
shortfallCredits: response.shortfallCredits,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import { assign, setup } from "xstate";
|
||||
|
||||
import type { PrivateRoomMoment } from "@/data/dto/private-room";
|
||||
|
||||
import type { PrivateRoomEvent } from "./private-room-events";
|
||||
import {
|
||||
appendMomentsResponse,
|
||||
applyMomentsResponse,
|
||||
replaceMoment,
|
||||
toPaywallRequest,
|
||||
toPrivateRoomErrorMessage,
|
||||
toUnlockErrorMessage,
|
||||
} from "./private-room-machine.helpers";
|
||||
import {
|
||||
loadMorePrivateRoomMomentsActor,
|
||||
loadPrivateRoomMomentsActor,
|
||||
unlockPrivateRoomMomentActor,
|
||||
} from "./private-room-machine.actors";
|
||||
import { initialState, type PrivateRoomState } from "./private-room-state";
|
||||
|
||||
export type { PrivateRoomEvent } from "./private-room-events";
|
||||
export type { PrivateRoomState } from "./private-room-state";
|
||||
export { initialState } from "./private-room-state";
|
||||
|
||||
function getPendingMoment(context: PrivateRoomState): PrivateRoomMoment | null {
|
||||
if (!context.pendingConfirmMomentId) return null;
|
||||
return (
|
||||
context.items.find(
|
||||
(item) => item.momentId === context.pendingConfirmMomentId,
|
||||
) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export const privateRoomMachine = setup({
|
||||
types: {
|
||||
context: {} as PrivateRoomState,
|
||||
events: {} as PrivateRoomEvent,
|
||||
},
|
||||
actors: {
|
||||
loadMoments: loadPrivateRoomMomentsActor,
|
||||
loadMoreMoments: loadMorePrivateRoomMomentsActor,
|
||||
unlockMoment: unlockPrivateRoomMomentActor,
|
||||
},
|
||||
}).createMachine({
|
||||
id: "privateRoom",
|
||||
initial: "idle",
|
||||
context: initialState,
|
||||
states: {
|
||||
idle: {
|
||||
on: {
|
||||
PrivateRoomInit: "loading",
|
||||
},
|
||||
},
|
||||
|
||||
loading: {
|
||||
entry: assign({
|
||||
errorMessage: null,
|
||||
unlockPaywallRequest: null,
|
||||
}),
|
||||
invoke: {
|
||||
src: "loadMoments",
|
||||
onDone: {
|
||||
target: "ready",
|
||||
actions: assign(({ event }) => applyMomentsResponse(event.output)),
|
||||
},
|
||||
onError: {
|
||||
target: "failed",
|
||||
actions: assign(({ event }) => ({
|
||||
errorMessage: toPrivateRoomErrorMessage(event.error),
|
||||
})),
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
failed: {
|
||||
on: {
|
||||
PrivateRoomInit: "loading",
|
||||
PrivateRoomRefresh: "loading",
|
||||
},
|
||||
},
|
||||
|
||||
ready: {
|
||||
on: {
|
||||
PrivateRoomInit: {
|
||||
target: "loading",
|
||||
},
|
||||
PrivateRoomRefresh: {
|
||||
target: "loading",
|
||||
},
|
||||
PrivateRoomLoadMore: [
|
||||
{
|
||||
guard: ({ context }) =>
|
||||
context.hasMore && context.nextCursor !== null,
|
||||
target: "loadingMore",
|
||||
},
|
||||
],
|
||||
PrivateRoomUnlockRequested: {
|
||||
actions: assign(({ event }) => ({
|
||||
pendingConfirmMomentId: event.momentId,
|
||||
unlockErrorMessage: null,
|
||||
unlockPaywallRequest: null,
|
||||
})),
|
||||
},
|
||||
PrivateRoomUnlockCancelled: {
|
||||
actions: assign({
|
||||
pendingConfirmMomentId: null,
|
||||
}),
|
||||
},
|
||||
PrivateRoomUnlockConfirmed: [
|
||||
{
|
||||
guard: ({ context }) => getPendingMoment(context) !== null,
|
||||
target: "unlocking",
|
||||
},
|
||||
],
|
||||
PrivateRoomUnlockPaywallConsumed: {
|
||||
actions: assign({
|
||||
unlockPaywallRequest: null,
|
||||
}),
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
loadingMore: {
|
||||
invoke: {
|
||||
src: "loadMoreMoments",
|
||||
input: ({ context }) => ({
|
||||
cursor: context.nextCursor,
|
||||
}),
|
||||
onDone: {
|
||||
target: "ready",
|
||||
actions: assign(({ context, event }) =>
|
||||
appendMomentsResponse(context, event.output),
|
||||
),
|
||||
},
|
||||
onError: {
|
||||
target: "ready",
|
||||
actions: assign(({ event }) => ({
|
||||
errorMessage: toPrivateRoomErrorMessage(event.error),
|
||||
})),
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
unlocking: {
|
||||
entry: assign(({ context }) => ({
|
||||
unlockingMomentId: context.pendingConfirmMomentId,
|
||||
unlockErrorMessage: null,
|
||||
unlockPaywallRequest: null,
|
||||
})),
|
||||
invoke: {
|
||||
src: "unlockMoment",
|
||||
input: ({ context }) => {
|
||||
const pendingMoment = getPendingMoment(context);
|
||||
return {
|
||||
momentId: pendingMoment?.momentId ?? "",
|
||||
expectedCost: pendingMoment?.unlockCost ?? 0,
|
||||
};
|
||||
},
|
||||
onDone: [
|
||||
{
|
||||
guard: ({ event }) => event.output.unlocked,
|
||||
target: "ready",
|
||||
actions: assign(({ context, event }) => ({
|
||||
items: replaceMoment(context.items, event.output),
|
||||
creditBalance: event.output.creditBalance || context.creditBalance,
|
||||
pendingConfirmMomentId: null,
|
||||
unlockingMomentId: null,
|
||||
unlockErrorMessage: null,
|
||||
unlockSuccessNonce: context.unlockSuccessNonce + 1,
|
||||
})),
|
||||
},
|
||||
{
|
||||
guard: ({ event }) =>
|
||||
event.output.reason === "insufficient_credits",
|
||||
target: "ready",
|
||||
actions: assign(({ context, event }) => ({
|
||||
items: replaceMoment(context.items, event.output),
|
||||
creditBalance: event.output.creditBalance || context.creditBalance,
|
||||
pendingConfirmMomentId: null,
|
||||
unlockingMomentId: null,
|
||||
unlockErrorMessage: null,
|
||||
unlockPaywallRequest: toPaywallRequest(event.output),
|
||||
})),
|
||||
},
|
||||
{
|
||||
guard: ({ event }) => event.output.reason === "cost_changed",
|
||||
target: "loading",
|
||||
actions: assign(({ event }) => ({
|
||||
pendingConfirmMomentId: null,
|
||||
unlockingMomentId: null,
|
||||
unlockErrorMessage: toUnlockErrorMessage(event.output),
|
||||
})),
|
||||
},
|
||||
{
|
||||
target: "ready",
|
||||
actions: assign(({ context, event }) => ({
|
||||
items: replaceMoment(context.items, event.output),
|
||||
pendingConfirmMomentId: null,
|
||||
unlockingMomentId: null,
|
||||
unlockErrorMessage: toUnlockErrorMessage(event.output),
|
||||
})),
|
||||
},
|
||||
],
|
||||
onError: {
|
||||
target: "ready",
|
||||
actions: assign(({ event }) => ({
|
||||
pendingConfirmMomentId: null,
|
||||
unlockingMomentId: null,
|
||||
unlockErrorMessage: toPrivateRoomErrorMessage(event.error),
|
||||
})),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export type PrivateRoomMachine = typeof privateRoomMachine;
|
||||
@@ -0,0 +1,40 @@
|
||||
import type {
|
||||
PrivateRoomMoment,
|
||||
PrivateRoomProfile,
|
||||
} from "@/data/dto/private-room";
|
||||
|
||||
export interface PrivateRoomUnlockPaywallRequest {
|
||||
momentId: string;
|
||||
reason: string;
|
||||
requiredCredits: number;
|
||||
currentCredits: number;
|
||||
shortfallCredits: number;
|
||||
}
|
||||
|
||||
export interface PrivateRoomState {
|
||||
profile: PrivateRoomProfile | null;
|
||||
items: PrivateRoomMoment[];
|
||||
nextCursor: string | null;
|
||||
hasMore: boolean;
|
||||
creditBalance: number;
|
||||
errorMessage: string | null;
|
||||
unlockingMomentId: string | null;
|
||||
unlockErrorMessage: string | null;
|
||||
pendingConfirmMomentId: string | null;
|
||||
unlockPaywallRequest: PrivateRoomUnlockPaywallRequest | null;
|
||||
unlockSuccessNonce: number;
|
||||
}
|
||||
|
||||
export const initialState: PrivateRoomState = {
|
||||
profile: null,
|
||||
items: [],
|
||||
nextCursor: null,
|
||||
hasMore: false,
|
||||
creditBalance: 0,
|
||||
errorMessage: null,
|
||||
unlockingMomentId: null,
|
||||
unlockErrorMessage: null,
|
||||
pendingConfirmMomentId: null,
|
||||
unlockPaywallRequest: null,
|
||||
unlockSuccessNonce: 0,
|
||||
};
|
||||
Reference in New Issue
Block a user