From 7949eb0d641156657e5a934a775fae2ba250648c Mon Sep 17 00:00:00 2001 From: Amiram_se Date: Wed, 7 Oct 2026 20:29:33 +0400 Subject: [PATCH] feat(market): channel, posts, composer, home feed and following The creator's channel and post pages, the post composer, the investor's home feed and the following tab, in bull and bear. - Channel and post page start from the server's read and re-read in the browser for the creator or a subscriber; locked posts show a gate only once the viewer and their standing are known, frozen for another creator. - Composer: text and up to four images uploaded as picked, free or premium, a device draft that keeps stored file URLs, 15-minute edit of a published post; on desktop a dialog over the page through bear's @modal intercept. - Owner actions: preview as a visitor or subscriber, edit, delete (dialogs locked while sending), close a prediction with the outcome the API recorded. - Follow and unfollow run in tap order; the home feed dates posts from its last read; paged lists read past pages with nothing to show. - Cache stays true after mutations: a delete re-reads the channel's offset pages, a new post resets them, and a post page delete navigates without a stale refresh. - Navigation: bottom nav, mobile top bar, desktop header and publish menu; the preview chrome only for the creator's own post. Co-Authored-By: Claude Opus 5.5 --- .../app/(flow)/compose/post/[id]/loading.tsx | 27 ++ .../src/app/(flow)/compose/post/[id]/page.tsx | 50 ++++ .../src/app/(flow)/compose/post/loading.tsx | 27 ++ .../bear/src/app/(flow)/compose/post/page.tsx | 43 +++ apps/bear/src/app/(main)/(home)/loading.tsx | 17 ++ apps/bear/src/app/(main)/(home)/page.tsx | 46 ++++ .../templates/home-template/HomeTemplate.tsx | 28 ++ .../(home)/templates/home-template/index.ts | 2 + .../(home)/templates/home-template/types.ts | 6 + .../app/(main)/@modal/(.)compose/layout.tsx | 3 + .../(main)/@modal/(.)compose/post/page.tsx | 19 ++ .../@modal/channels/[username]/page.tsx | 9 + apps/bear/src/app/(main)/@modal/default.tsx | 4 + apps/bear/src/app/(main)/@modal/page.tsx | 10 + .../(main)/channels/[username]/loading.tsx | 24 ++ .../(main)/channels/[username]/not-found.tsx | 18 ++ .../app/(main)/channels/[username]/page.tsx | 58 ++++ .../[username]/posts/[id]/loading.tsx | 41 +++ .../channels/[username]/posts/[id]/page.tsx | 78 ++++++ .../templates/post-template/PostTemplate.tsx | 64 +++++ .../[id]/templates/post-template/index.ts | 2 + .../[id]/templates/post-template/types.ts | 12 + .../channel-template/ChannelTemplate.tsx | 117 ++++++++ .../templates/channel-template/index.ts | 2 + .../templates/channel-template/types.ts | 9 + .../(investor)/following/loading.tsx | 15 ++ .../dashboard/(investor)/following/page.tsx | 43 +++ .../(main)/dashboard/(investor)/layout.tsx | 34 +++ .../(investor)/subscriptions}/.gitkeep | 0 .../(investor)/transactions}/.gitkeep | 0 .../(main)/dashboard/transactions/.gitkeep | 0 apps/bear/src/app/(main)/default.tsx | 16 ++ apps/bear/src/app/(main)/layout.tsx | 23 ++ apps/bear/src/configs/index.ts | 1 + apps/bear/src/configs/site.ts | 6 + .../bull/src/app/(flow)/compose/post/.gitkeep | 0 .../app/(flow)/compose/post/[id]/loading.tsx | 16 ++ .../src/app/(flow)/compose/post/[id]/page.tsx | 39 +++ .../src/app/(flow)/compose/post/loading.tsx | 16 ++ .../bull/src/app/(flow)/compose/post/page.tsx | 32 +++ apps/bull/src/app/(main)/(home)/loading.tsx | 17 ++ apps/bull/src/app/(main)/(home)/page.tsx | 45 ++++ .../templates/home-template/HomeTemplate.tsx | 31 +++ .../(home)/templates/home-template/index.ts | 2 + .../(home)/templates/home-template/types.ts | 6 + .../(main)/channels/[username]/loading.tsx | 26 ++ .../(main)/channels/[username]/not-found.tsx | 27 ++ .../app/(main)/channels/[username]/page.tsx | 58 ++++ .../channels/[username]/posts/[id]/.gitkeep | 0 .../[username]/posts/[id]/loading.tsx | 47 ++++ .../channels/[username]/posts/[id]/page.tsx | 78 ++++++ .../templates/post-template/PostTemplate.tsx | 69 +++++ .../[id]/templates/post-template/index.ts | 2 + .../[id]/templates/post-template/types.ts | 12 + .../channel-template/ChannelTemplate.tsx | 122 +++++++++ .../templates/channel-template/index.ts | 2 + .../templates/channel-template/types.ts | 9 + .../(investor)/following/loading.tsx | 15 ++ .../dashboard/(investor)/following/page.tsx | 43 +++ .../(main)/dashboard/(investor)/layout.tsx | 27 ++ .../(investor)/subscriptions}/.gitkeep | 0 .../(investor)/transactions}/.gitkeep | 0 .../app/(main)/dashboard/following/.gitkeep | 0 .../(main)/dashboard/subscriptions/.gitkeep | 0 .../(main)/dashboard/transactions/.gitkeep | 0 apps/bull/src/app/(main)/layout.tsx | 13 + apps/bull/src/configs/index.ts | 1 + apps/bull/src/configs/site.ts | 6 + .../market/src/app/app-shell/AppShell.tsx | 6 + .../src/app/app-shell/hooks/use-session.ts | 8 +- .../error-fallback/ErrorFallback.tsx | 23 +- .../error-boundaries/error-fallback/types.ts | 8 + .../part-boundary/PartBoundary.tsx | 5 +- .../error-boundaries/part-boundary/types.ts | 8 + .../market/src/app/navigation/active-tab.ts | 33 +++ .../src/app/navigation/components/.gitkeep | 0 .../components/bottom-nav/BottomNav.tsx | 75 ++++++ .../bottom-nav/components/NavTab.tsx | 35 +++ .../navigation/components/bottom-nav/index.ts | 1 + .../navigation/components/bottom-nav/types.ts | 8 + .../desktop-header/DesktopHeader.tsx | 117 ++++++++ .../components/HeaderNavLink.tsx | 23 ++ .../components/desktop-header/index.ts | 1 + .../components/desktop-header/types.ts | 5 + .../mobile-top-bar/MobileTopBar.tsx | 118 ++++++++ .../mobile-top-bar/components/BackButton.tsx | 27 ++ .../mobile-top-bar/components/Brand.tsx | 24 ++ .../components/mobile-top-bar/index.ts | 2 + .../components/mobile-top-bar/types.ts | 38 +++ .../components/publish-menu/PublishMenu.tsx | 70 +++++ .../components/BlockedPublishDialog.tsx | 84 ++++++ .../components/publish-menu/constants.ts | 16 ++ .../components/publish-menu/index.ts | 2 + .../components/publish-menu/types.ts | 19 ++ .../market/src/app/navigation/constants.ts | 9 + .../navigation/hooks/use-is-own-preview.ts | 22 ++ platforms/market/src/app/navigation/index.ts | 6 +- .../market/src/app/navigation/navigation.ts | 2 + platforms/market/src/app/navigation/types.ts | 3 + .../organisms/post-composer/PostComposer.tsx | 30 +++ .../post-composer/PostComposerDialog.tsx | 26 ++ .../PostComposerDialogSkeleton.tsx | 20 ++ .../post-composer/components/ComposerBody.tsx | 132 +++++++++ .../components/ComposerCount.tsx | 29 ++ .../components/ComposerDialog.tsx | 49 ++++ .../components/ComposerDialogFrame.tsx | 38 +++ .../components/ComposerDialogPlaceholder.tsx | 32 +++ .../post-composer/components/ComposerForm.tsx | 119 +++++++++ .../components/ComposerImages.tsx | 133 ++++++++++ .../components/ComposerLimit.tsx | 32 +++ .../components/ComposerPanel.tsx | 48 ++++ .../components/ComposerSubmit.tsx | 59 ++++ .../post-composer/components/EditComposer.tsx | 49 ++++ .../post-composer/components/ImageThumb.tsx | 100 +++++++ .../post-composer/components/LeaveConfirm.tsx | 52 ++++ .../post/organisms/post-composer/constants.ts | 2 + .../post-composer/hooks/use-caption-length.ts | 16 ++ .../post-composer/hooks/use-dialog-route.ts | 43 +++ .../post/organisms/post-composer/index.ts | 4 + .../post/organisms/post-composer/types.ts | 108 ++++++++ .../channel-actions/ChannelActions.tsx | 57 ++++ .../components/ActionsSkeleton.tsx | 16 ++ .../components/GuestActions.tsx | 55 ++++ .../components/GuestPrompt.tsx | 81 ++++++ .../components/InvestorActions.tsx | 110 ++++++++ .../components/PaymentFailedNote.tsx | 28 ++ .../components/PaymentPendingNote.tsx | 35 +++ .../components/PendingIndicator.tsx | 83 ++++++ .../components/WaitlistNote.tsx | 22 ++ .../organisms/channel-actions/index.ts | 2 + .../organisms/channel-actions/types.ts | 65 +++++ .../organisms/channel-feed/ChannelFeed.tsx | 21 ++ .../components/ChannelFeedEmpty.tsx | 75 ++++++ .../components/ChannelFeedList.tsx | 148 +++++++++++ .../components/NoSubscribersNote.tsx | 21 ++ .../organisms/channel-feed/server.ts | 4 + .../organisms/channel-feed/types.ts | 30 +++ .../channel-header/ChannelHeader.tsx | 124 +++++++++ .../channel-header/ChannelHeaderSkeleton.tsx | 24 ++ .../components/ChannelLinks.tsx | 56 ++++ .../organisms/channel-header/index.ts | 8 + .../organisms/channel-header/labels.ts | 29 ++ .../organisms/channel-header/types.ts | 55 ++++ .../channel-not-found/ChannelNotFound.tsx | 60 +++++ .../ChannelNotFoundTopBar.tsx | 21 ++ .../components/OwnPendingChannel.tsx | 114 ++++++++ .../hooks/use-own-address.ts | 45 ++++ .../organisms/channel-not-found/index.ts | 3 + .../organisms/channel-not-found/types.ts | 26 ++ .../organisms/channel-share/ChannelShare.tsx | 70 +++++ .../components/OwnerShareSheet.tsx | 103 +++++++ .../organisms/channel-share/index.ts | 2 + .../organisms/channel-share/types.ts | 19 ++ .../organisms/channel-stats/ChannelStats.tsx | 22 ++ .../organisms/channel-stats/server.ts | 4 + .../organisms/channel-stats/types.ts | 7 + .../ChannelUnavailable.tsx | 86 ++++++ .../components/OwnSuspendedChannel.tsx | 62 +++++ .../organisms/channel-unavailable/index.ts | 2 + .../organisms/channel-unavailable/types.ts | 17 ++ .../post-channel-bar/PostChannelBar.tsx | 64 +++++ .../[id]/organisms/post-channel-bar/index.ts | 2 + .../[id]/organisms/post-channel-bar/types.ts | 13 + .../organisms/post-missing/PostMissing.tsx | 34 +++ .../[id]/organisms/post-missing/index.ts | 2 + .../[id]/organisms/post-missing/types.ts | 4 + .../[id]/organisms/post-view/PostView.tsx | 139 ++++++++++ .../components/AccessEndedBanner.tsx | 25 ++ .../post-view/components/PreviewBanner.tsx | 53 ++++ .../[id]/organisms/post-view/constants.ts | 8 + .../posts/[id]/organisms/post-view/index.ts | 2 + .../posts/[id]/organisms/post-view/types.ts | 21 ++ .../following-list/FollowingList.tsx | 127 +++++++++ .../components/FollowingEmpty.tsx | 30 +++ .../components/FollowingRow.tsx | 134 ++++++++++ .../organisms/following-list/index.ts | 2 + .../organisms/following-list/types.ts | 25 ++ .../dashboard-tabs/DashboardTabs.tsx | 32 +++ .../organisms/dashboard-tabs/constants.ts | 8 + .../organisms/dashboard-tabs/index.ts | 2 + .../organisms/dashboard-tabs/types.ts | 4 + .../channel-post-card/ChannelPostCard.tsx | 233 ++++++++++++++++ .../organisms/channel-post-card/constants.ts | 5 + .../organisms/channel-post-card/index.ts | 3 + .../organisms/channel-post-card/preview.ts | 6 + .../organisms/channel-post-card/types.ts | 44 +++ .../organisms/channel-post-card/utils.ts | 40 +++ .../ClosePredictionSheet.tsx | 149 +++++++++++ .../components/PredictionSummary.tsx | 59 ++++ .../components/SummaryRow.tsx | 22 ++ .../close-prediction-sheet/constants.ts | 15 ++ .../organisms/close-prediction-sheet/index.ts | 2 + .../organisms/close-prediction-sheet/types.ts | 24 ++ .../delete-post-confirm/DeletePostConfirm.tsx | 66 +++++ .../organisms/delete-post-confirm/index.ts | 2 + .../organisms/delete-post-confirm/types.ts | 7 + .../(main)/organisms/home-feed/HomeFeed.tsx | 137 ++++++++++ .../organisms/home-feed/HomeFeedSkeleton.tsx | 34 +++ .../(main)/organisms/home-feed/HomeGuard.tsx | 38 +++ .../home-feed/components/HomeFeedEmpty.tsx | 43 +++ .../(main)/organisms/home-feed/constants.ts | 2 + .../(main)/organisms/home-feed/index.ts | 10 + .../(main)/organisms/home-feed/types.ts | 37 +++ .../organisms/post-lightbox/PostLightbox.tsx | 49 ++++ .../(main)/organisms/post-lightbox/index.ts | 2 + .../(main)/organisms/post-lightbox/types.ts | 18 ++ .../unfollow-confirm/UnfollowConfirm.tsx | 77 ++++++ .../organisms/unfollow-confirm/index.ts | 2 + .../organisms/unfollow-confirm/types.ts | 15 ++ .../organisms/support-entry/SupportEntry.tsx | 2 +- platforms/market/src/app/seo/constants.ts | 3 + platforms/market/src/app/seo/metadata.ts | 76 ++++++ platforms/market/src/app/seo/server.ts | 4 + platforms/market/src/app/seo/types.ts | 17 ++ .../src/features/channel/caches/channel.ts | 15 ++ .../src/features/channel/caches/server.ts | 1 + .../channel/entities/public-creator/types.ts | 2 + .../market/src/features/channel/index.ts | 29 ++ .../src/features/channel/models/.gitkeep | 0 .../features/channel/models/channel/index.ts | 14 + .../channel/models/channel/read-standing.ts | 36 +++ .../features/channel/models/channel/types.ts | 73 +++++ .../channel/use-channel-actions-part.ts | 117 ++++++++ .../models/channel/use-channel-viewer.ts | 82 ++++++ .../channel/models/follow-caches/index.ts | 1 + .../follow-caches/sync-follow-caches.ts | 23 ++ .../channel/models/following/index.ts | 2 + .../channel/models/following/types.ts | 30 +++ .../models/following/use-following-part.ts | 144 ++++++++++ .../channel/models/own-channel/index.ts | 2 + .../channel/models/own-channel/types.ts | 13 + .../models/own-channel/use-own-channel.ts | 44 +++ .../channel/models/share/constants.ts | 5 + .../features/channel/models/share/index.ts | 8 + .../features/channel/models/share/types.ts | 32 +++ .../models/share/use-channel-share-sheet.ts | 91 +++++++ .../channel/models/share/use-share-link.ts | 55 ++++ .../channel/repositories/channel/constants.ts | 3 + .../channel/repositories/channel/mappers.ts | 1 + .../channel/repositories/channel/types.ts | 2 + .../src/features/checkout/actions/.gitkeep | 0 .../actions/leave-waitlist/actions.ts | 17 ++ .../checkout/actions/leave-waitlist/index.ts | 1 + .../market/src/features/checkout/constants.ts | 4 + .../market/src/features/checkout/index.ts | 4 + .../checkout/repositories/checkout/mappers.ts | 14 + .../checkout/repositories/checkout/types.ts | 38 +++ .../market/src/features/checkout/types.ts | 7 + .../src/features/feed/entities/.gitkeep | 0 .../features/feed/entities/feed-item/index.ts | 1 + .../features/feed/entities/feed-item/types.ts | 20 ++ platforms/market/src/features/feed/index.ts | 9 +- .../market/src/features/feed/models/.gitkeep | 0 .../features/feed/models/home-feed/index.ts | 2 + .../features/feed/models/home-feed/types.ts | 16 ++ .../models/home-feed/use-home-feed-part.ts | 40 +++ .../feed/repositories/feed/constants.ts | 8 +- .../features/feed/repositories/feed/feed.ts | 7 +- .../features/feed/repositories/feed/index.ts | 7 +- .../feed/repositories/feed/mappers.ts | 29 +- .../features/feed/repositories/feed/types.ts | 42 ++- .../src/features/follow/actions/.gitkeep | 0 .../follow/actions/follow-creator/actions.ts | 23 ++ .../follow/actions/follow-creator/index.ts | 1 + .../actions/unfollow-creator/actions.ts | 23 ++ .../follow/actions/unfollow-creator/index.ts | 1 + .../market/src/features/follow/constants.ts | 5 + .../follow/entities/following/index.ts | 1 + .../follow/entities/following/types.ts | 28 ++ platforms/market/src/features/follow/index.ts | 15 +- .../follow/repositories/follow/constants.ts | 7 + .../follow/repositories/follow/follow.ts | 31 ++- .../follow/repositories/follow/index.ts | 6 +- .../follow/repositories/follow/mappers.ts | 41 +++ .../follow/repositories/follow/types.ts | 44 +++ platforms/market/src/features/follow/types.ts | 8 + .../market/src/features/overview/index.ts | 2 + .../src/features/overview/models/.gitkeep | 0 .../models/own-subscriber-count/index.ts | 2 + .../models/own-subscriber-count/types.ts | 4 + .../use-own-subscriber-count.ts | 29 ++ .../market/src/features/post/actions/.gitkeep | 0 .../post/actions/delete-post/actions.ts | 17 ++ .../post/actions/delete-post/index.ts | 1 + .../post/actions/edit-post/actions.ts | 24 ++ .../features/post/actions/edit-post/index.ts | 1 + .../post/actions/publish-post/actions.ts | 24 ++ .../post/actions/publish-post/index.ts | 1 + .../market/src/features/post/constants.ts | 18 ++ .../src/features/post/entities/post/index.ts | 1 - .../src/features/post/entities/post/types.ts | 23 +- platforms/market/src/features/post/index.ts | 44 ++- .../market/src/features/post/models/.gitkeep | 0 .../post/models/channel-feed/index.ts | 2 + .../post/models/channel-feed/types.ts | 13 + .../channel-feed/use-channel-feed-part.ts | 37 +++ .../features/post/models/composer/index.ts | 9 + .../post/models/composer/initial-images.ts | 28 ++ .../features/post/models/composer/types.ts | 83 ++++++ .../models/composer/use-composer-images.ts | 181 +++++++++++++ .../models/composer/use-post-composer-page.ts | 251 ++++++++++++++++++ .../post/models/editable-post/index.ts | 2 + .../post/models/editable-post/types.ts | 7 + .../models/editable-post/use-editable-post.ts | 33 +++ .../features/post/models/owner-post/index.ts | 2 + .../features/post/models/owner-post/types.ts | 23 ++ .../models/owner-post/use-owner-post-part.ts | 71 +++++ .../features/post/models/post-cache/index.ts | 6 + .../post/models/post-cache/post-cache.ts | 77 ++++++ .../features/post/models/post-list/index.ts | 7 + .../features/post/models/post-list/types.ts | 50 ++++ .../post/models/post-list/use-post-list.ts | 87 ++++++ .../src/features/post/models/post/index.ts | 6 + .../src/features/post/models/post/types.ts | 33 +++ .../post/models/post/use-post-part.ts | 62 +++++ .../post/repositories/post/constants.ts | 6 + .../features/post/repositories/post/index.ts | 8 +- .../post/repositories/post/mappers.ts | 9 +- .../features/post/repositories/post/post.ts | 3 +- .../features/post/repositories/post/types.ts | 32 +-- platforms/market/src/features/post/types.ts | 13 + .../src/features/prediction/actions/.gitkeep | 0 .../actions/close-prediction/actions.ts | 26 ++ .../actions/close-prediction/index.ts | 1 + .../src/features/prediction/constants.ts | 4 + .../market/src/features/prediction/index.ts | 14 + .../src/features/prediction/models/.gitkeep | 0 .../models/close-prediction/index.ts | 6 + .../models/close-prediction/outcome.ts | 29 ++ .../models/close-prediction/types.ts | 31 +++ .../use-close-prediction-part.ts | 96 +++++++ .../repositories/prediction/constants.ts | 6 + .../repositories/prediction/index.ts | 6 +- .../market/src/features/prediction/types.ts | 11 + .../profile/entities/creator-profile/types.ts | 5 + .../market/src/features/profile/index.ts | 5 + .../creator-standing/creator-standing-of.ts | 12 + .../profile/models/creator-standing/index.ts | 3 + .../profile/models/creator-standing/types.ts | 10 + .../creator-standing/use-creator-standing.ts | 20 ++ .../profile/repositories/profile/mappers.ts | 4 + .../profile/repositories/profile/types.ts | 2 + platforms/market/src/index.ts | 73 ++++- platforms/market/src/server.ts | 4 + .../src/shared/labels/content-labels.tsx | 186 +++++++++++++ platforms/market/src/shared/labels/index.ts | 7 + platforms/market/src/shared/labels/types.ts | 7 + .../market/src/shared/locales/fa/channel.json | 142 ++++++++++ .../market/src/shared/locales/fa/common.json | 37 +++ .../market/src/shared/locales/fa/content.json | 227 ++++++++++++++++ .../src/shared/locales/fa/dashboard.json | 23 ++ .../market/src/shared/locales/fa/home.json | 20 ++ .../market/src/shared/locales/resources.ts | 8 + .../src/shared/utils/apply-server-errors.ts | 4 +- .../src/shared/utils/channel-username.ts | 18 ++ .../market/src/shared/utils/first-of-each.ts | 16 ++ platforms/market/src/shared/utils/index.ts | 5 + .../src/shared/utils/load-more-error-kind.ts | 15 ++ .../market/src/shared/utils/price-input.ts | 13 + .../market/src/shared/utils/request-time.ts | 9 + .../shared/validations/content-validations.ts | 30 +++ .../market/src/shared/validations/index.ts | 7 + .../market/src/shared/validations/types.ts | 12 + .../market/src/stores/post-draft/index.ts | 2 + .../src/stores/post-draft/post-draft-store.ts | 34 +++ .../market/src/stores/post-draft/types.ts | 24 ++ 366 files changed, 11108 insertions(+), 83 deletions(-) create mode 100644 apps/bear/src/app/(flow)/compose/post/[id]/loading.tsx create mode 100644 apps/bear/src/app/(flow)/compose/post/[id]/page.tsx create mode 100644 apps/bear/src/app/(flow)/compose/post/loading.tsx create mode 100644 apps/bear/src/app/(flow)/compose/post/page.tsx create mode 100644 apps/bear/src/app/(main)/(home)/loading.tsx create mode 100644 apps/bear/src/app/(main)/(home)/page.tsx create mode 100644 apps/bear/src/app/(main)/(home)/templates/home-template/HomeTemplate.tsx create mode 100644 apps/bear/src/app/(main)/(home)/templates/home-template/index.ts create mode 100644 apps/bear/src/app/(main)/(home)/templates/home-template/types.ts create mode 100644 apps/bear/src/app/(main)/@modal/(.)compose/layout.tsx create mode 100644 apps/bear/src/app/(main)/@modal/(.)compose/post/page.tsx create mode 100644 apps/bear/src/app/(main)/@modal/channels/[username]/page.tsx create mode 100644 apps/bear/src/app/(main)/@modal/default.tsx create mode 100644 apps/bear/src/app/(main)/@modal/page.tsx create mode 100644 apps/bear/src/app/(main)/channels/[username]/loading.tsx create mode 100644 apps/bear/src/app/(main)/channels/[username]/not-found.tsx create mode 100644 apps/bear/src/app/(main)/channels/[username]/page.tsx create mode 100644 apps/bear/src/app/(main)/channels/[username]/posts/[id]/loading.tsx create mode 100644 apps/bear/src/app/(main)/channels/[username]/posts/[id]/page.tsx create mode 100644 apps/bear/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/PostTemplate.tsx create mode 100644 apps/bear/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/index.ts create mode 100644 apps/bear/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/types.ts create mode 100644 apps/bear/src/app/(main)/channels/[username]/templates/channel-template/ChannelTemplate.tsx create mode 100644 apps/bear/src/app/(main)/channels/[username]/templates/channel-template/index.ts create mode 100644 apps/bear/src/app/(main)/channels/[username]/templates/channel-template/types.ts create mode 100644 apps/bear/src/app/(main)/dashboard/(investor)/following/loading.tsx create mode 100644 apps/bear/src/app/(main)/dashboard/(investor)/following/page.tsx create mode 100644 apps/bear/src/app/(main)/dashboard/(investor)/layout.tsx rename apps/bear/src/app/{(flow)/compose/post => (main)/dashboard/(investor)/subscriptions}/.gitkeep (100%) rename apps/bear/src/app/(main)/{channels/[username]/posts/[id] => dashboard/(investor)/transactions}/.gitkeep (100%) delete mode 100644 apps/bear/src/app/(main)/dashboard/transactions/.gitkeep create mode 100644 apps/bear/src/app/(main)/default.tsx create mode 100644 apps/bear/src/app/(main)/layout.tsx create mode 100644 apps/bear/src/configs/site.ts delete mode 100644 apps/bull/src/app/(flow)/compose/post/.gitkeep create mode 100644 apps/bull/src/app/(flow)/compose/post/[id]/loading.tsx create mode 100644 apps/bull/src/app/(flow)/compose/post/[id]/page.tsx create mode 100644 apps/bull/src/app/(flow)/compose/post/loading.tsx create mode 100644 apps/bull/src/app/(flow)/compose/post/page.tsx create mode 100644 apps/bull/src/app/(main)/(home)/loading.tsx create mode 100644 apps/bull/src/app/(main)/(home)/page.tsx create mode 100644 apps/bull/src/app/(main)/(home)/templates/home-template/HomeTemplate.tsx create mode 100644 apps/bull/src/app/(main)/(home)/templates/home-template/index.ts create mode 100644 apps/bull/src/app/(main)/(home)/templates/home-template/types.ts create mode 100644 apps/bull/src/app/(main)/channels/[username]/loading.tsx create mode 100644 apps/bull/src/app/(main)/channels/[username]/not-found.tsx create mode 100644 apps/bull/src/app/(main)/channels/[username]/page.tsx delete mode 100644 apps/bull/src/app/(main)/channels/[username]/posts/[id]/.gitkeep create mode 100644 apps/bull/src/app/(main)/channels/[username]/posts/[id]/loading.tsx create mode 100644 apps/bull/src/app/(main)/channels/[username]/posts/[id]/page.tsx create mode 100644 apps/bull/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/PostTemplate.tsx create mode 100644 apps/bull/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/index.ts create mode 100644 apps/bull/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/types.ts create mode 100644 apps/bull/src/app/(main)/channels/[username]/templates/channel-template/ChannelTemplate.tsx create mode 100644 apps/bull/src/app/(main)/channels/[username]/templates/channel-template/index.ts create mode 100644 apps/bull/src/app/(main)/channels/[username]/templates/channel-template/types.ts create mode 100644 apps/bull/src/app/(main)/dashboard/(investor)/following/loading.tsx create mode 100644 apps/bull/src/app/(main)/dashboard/(investor)/following/page.tsx create mode 100644 apps/bull/src/app/(main)/dashboard/(investor)/layout.tsx rename apps/{bear/src/app/(main)/dashboard/following => bull/src/app/(main)/dashboard/(investor)/subscriptions}/.gitkeep (100%) rename apps/{bear/src/app/(main)/dashboard/subscriptions => bull/src/app/(main)/dashboard/(investor)/transactions}/.gitkeep (100%) delete mode 100644 apps/bull/src/app/(main)/dashboard/following/.gitkeep delete mode 100644 apps/bull/src/app/(main)/dashboard/subscriptions/.gitkeep delete mode 100644 apps/bull/src/app/(main)/dashboard/transactions/.gitkeep create mode 100644 apps/bull/src/app/(main)/layout.tsx create mode 100644 apps/bull/src/configs/site.ts create mode 100644 platforms/market/src/app/navigation/active-tab.ts delete mode 100644 platforms/market/src/app/navigation/components/.gitkeep create mode 100644 platforms/market/src/app/navigation/components/bottom-nav/BottomNav.tsx create mode 100644 platforms/market/src/app/navigation/components/bottom-nav/components/NavTab.tsx create mode 100644 platforms/market/src/app/navigation/components/bottom-nav/index.ts create mode 100644 platforms/market/src/app/navigation/components/bottom-nav/types.ts create mode 100644 platforms/market/src/app/navigation/components/desktop-header/DesktopHeader.tsx create mode 100644 platforms/market/src/app/navigation/components/desktop-header/components/HeaderNavLink.tsx create mode 100644 platforms/market/src/app/navigation/components/desktop-header/index.ts create mode 100644 platforms/market/src/app/navigation/components/desktop-header/types.ts create mode 100644 platforms/market/src/app/navigation/components/mobile-top-bar/MobileTopBar.tsx create mode 100644 platforms/market/src/app/navigation/components/mobile-top-bar/components/BackButton.tsx create mode 100644 platforms/market/src/app/navigation/components/mobile-top-bar/components/Brand.tsx create mode 100644 platforms/market/src/app/navigation/components/mobile-top-bar/index.ts create mode 100644 platforms/market/src/app/navigation/components/mobile-top-bar/types.ts create mode 100644 platforms/market/src/app/navigation/components/publish-menu/PublishMenu.tsx create mode 100644 platforms/market/src/app/navigation/components/publish-menu/components/BlockedPublishDialog.tsx create mode 100644 platforms/market/src/app/navigation/components/publish-menu/constants.ts create mode 100644 platforms/market/src/app/navigation/components/publish-menu/index.ts create mode 100644 platforms/market/src/app/navigation/components/publish-menu/types.ts create mode 100644 platforms/market/src/app/navigation/hooks/use-is-own-preview.ts create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/PostComposer.tsx create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/PostComposerDialog.tsx create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/PostComposerDialogSkeleton.tsx create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerBody.tsx create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerCount.tsx create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerDialog.tsx create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerDialogFrame.tsx create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerDialogPlaceholder.tsx create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerForm.tsx create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerImages.tsx create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerLimit.tsx create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerPanel.tsx create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerSubmit.tsx create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/EditComposer.tsx create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ImageThumb.tsx create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/LeaveConfirm.tsx create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/constants.ts create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/hooks/use-caption-length.ts create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/hooks/use-dialog-route.ts create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/index.ts create mode 100644 platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/types.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/ChannelActions.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/ActionsSkeleton.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/GuestActions.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/GuestPrompt.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/InvestorActions.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/PaymentFailedNote.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/PaymentPendingNote.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/PendingIndicator.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/WaitlistNote.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/index.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/types.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/ChannelFeed.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/components/ChannelFeedEmpty.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/components/ChannelFeedList.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/components/NoSubscribersNote.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/server.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/types.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/ChannelHeader.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/ChannelHeaderSkeleton.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/components/ChannelLinks.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/index.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/labels.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/types.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/ChannelNotFound.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/ChannelNotFoundTopBar.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/components/OwnPendingChannel.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/hooks/use-own-address.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/index.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/types.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-share/ChannelShare.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-share/components/OwnerShareSheet.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-share/index.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-share/types.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-stats/ChannelStats.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-stats/server.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-stats/types.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-unavailable/ChannelUnavailable.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-unavailable/components/OwnSuspendedChannel.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-unavailable/index.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-unavailable/types.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/PostChannelBar.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/index.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/types.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-missing/PostMissing.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-missing/index.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-missing/types.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/PostView.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/components/AccessEndedBanner.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/components/PreviewBanner.tsx create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/constants.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/index.ts create mode 100644 platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/types.ts create mode 100644 platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/FollowingList.tsx create mode 100644 platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/components/FollowingEmpty.tsx create mode 100644 platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/components/FollowingRow.tsx create mode 100644 platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/index.ts create mode 100644 platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/types.ts create mode 100644 platforms/market/src/app/screens/(main)/dashboard/organisms/dashboard-tabs/DashboardTabs.tsx create mode 100644 platforms/market/src/app/screens/(main)/dashboard/organisms/dashboard-tabs/constants.ts create mode 100644 platforms/market/src/app/screens/(main)/dashboard/organisms/dashboard-tabs/index.ts create mode 100644 platforms/market/src/app/screens/(main)/dashboard/organisms/dashboard-tabs/types.ts create mode 100644 platforms/market/src/app/screens/(main)/organisms/channel-post-card/ChannelPostCard.tsx create mode 100644 platforms/market/src/app/screens/(main)/organisms/channel-post-card/constants.ts create mode 100644 platforms/market/src/app/screens/(main)/organisms/channel-post-card/index.ts create mode 100644 platforms/market/src/app/screens/(main)/organisms/channel-post-card/preview.ts create mode 100644 platforms/market/src/app/screens/(main)/organisms/channel-post-card/types.ts create mode 100644 platforms/market/src/app/screens/(main)/organisms/channel-post-card/utils.ts create mode 100644 platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/ClosePredictionSheet.tsx create mode 100644 platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/components/PredictionSummary.tsx create mode 100644 platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/components/SummaryRow.tsx create mode 100644 platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/constants.ts create mode 100644 platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/index.ts create mode 100644 platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/types.ts create mode 100644 platforms/market/src/app/screens/(main)/organisms/delete-post-confirm/DeletePostConfirm.tsx create mode 100644 platforms/market/src/app/screens/(main)/organisms/delete-post-confirm/index.ts create mode 100644 platforms/market/src/app/screens/(main)/organisms/delete-post-confirm/types.ts create mode 100644 platforms/market/src/app/screens/(main)/organisms/home-feed/HomeFeed.tsx create mode 100644 platforms/market/src/app/screens/(main)/organisms/home-feed/HomeFeedSkeleton.tsx create mode 100644 platforms/market/src/app/screens/(main)/organisms/home-feed/HomeGuard.tsx create mode 100644 platforms/market/src/app/screens/(main)/organisms/home-feed/components/HomeFeedEmpty.tsx create mode 100644 platforms/market/src/app/screens/(main)/organisms/home-feed/constants.ts create mode 100644 platforms/market/src/app/screens/(main)/organisms/home-feed/index.ts create mode 100644 platforms/market/src/app/screens/(main)/organisms/home-feed/types.ts create mode 100644 platforms/market/src/app/screens/(main)/organisms/post-lightbox/PostLightbox.tsx create mode 100644 platforms/market/src/app/screens/(main)/organisms/post-lightbox/index.ts create mode 100644 platforms/market/src/app/screens/(main)/organisms/post-lightbox/types.ts create mode 100644 platforms/market/src/app/screens/(main)/organisms/unfollow-confirm/UnfollowConfirm.tsx create mode 100644 platforms/market/src/app/screens/(main)/organisms/unfollow-confirm/index.ts create mode 100644 platforms/market/src/app/screens/(main)/organisms/unfollow-confirm/types.ts create mode 100644 platforms/market/src/app/seo/constants.ts create mode 100644 platforms/market/src/app/seo/metadata.ts create mode 100644 platforms/market/src/app/seo/server.ts create mode 100644 platforms/market/src/app/seo/types.ts create mode 100644 platforms/market/src/features/channel/caches/channel.ts delete mode 100644 platforms/market/src/features/channel/models/.gitkeep create mode 100644 platforms/market/src/features/channel/models/channel/index.ts create mode 100644 platforms/market/src/features/channel/models/channel/read-standing.ts create mode 100644 platforms/market/src/features/channel/models/channel/types.ts create mode 100644 platforms/market/src/features/channel/models/channel/use-channel-actions-part.ts create mode 100644 platforms/market/src/features/channel/models/channel/use-channel-viewer.ts create mode 100644 platforms/market/src/features/channel/models/follow-caches/index.ts create mode 100644 platforms/market/src/features/channel/models/follow-caches/sync-follow-caches.ts create mode 100644 platforms/market/src/features/channel/models/following/index.ts create mode 100644 platforms/market/src/features/channel/models/following/types.ts create mode 100644 platforms/market/src/features/channel/models/following/use-following-part.ts create mode 100644 platforms/market/src/features/channel/models/own-channel/index.ts create mode 100644 platforms/market/src/features/channel/models/own-channel/types.ts create mode 100644 platforms/market/src/features/channel/models/own-channel/use-own-channel.ts create mode 100644 platforms/market/src/features/channel/models/share/constants.ts create mode 100644 platforms/market/src/features/channel/models/share/index.ts create mode 100644 platforms/market/src/features/channel/models/share/types.ts create mode 100644 platforms/market/src/features/channel/models/share/use-channel-share-sheet.ts create mode 100644 platforms/market/src/features/channel/models/share/use-share-link.ts delete mode 100644 platforms/market/src/features/checkout/actions/.gitkeep create mode 100644 platforms/market/src/features/checkout/actions/leave-waitlist/actions.ts create mode 100644 platforms/market/src/features/checkout/actions/leave-waitlist/index.ts create mode 100644 platforms/market/src/features/checkout/constants.ts create mode 100644 platforms/market/src/features/checkout/types.ts delete mode 100644 platforms/market/src/features/feed/entities/.gitkeep create mode 100644 platforms/market/src/features/feed/entities/feed-item/index.ts create mode 100644 platforms/market/src/features/feed/entities/feed-item/types.ts delete mode 100644 platforms/market/src/features/feed/models/.gitkeep create mode 100644 platforms/market/src/features/feed/models/home-feed/index.ts create mode 100644 platforms/market/src/features/feed/models/home-feed/types.ts create mode 100644 platforms/market/src/features/feed/models/home-feed/use-home-feed-part.ts delete mode 100644 platforms/market/src/features/follow/actions/.gitkeep create mode 100644 platforms/market/src/features/follow/actions/follow-creator/actions.ts create mode 100644 platforms/market/src/features/follow/actions/follow-creator/index.ts create mode 100644 platforms/market/src/features/follow/actions/unfollow-creator/actions.ts create mode 100644 platforms/market/src/features/follow/actions/unfollow-creator/index.ts create mode 100644 platforms/market/src/features/follow/constants.ts create mode 100644 platforms/market/src/features/follow/entities/following/index.ts create mode 100644 platforms/market/src/features/follow/entities/following/types.ts create mode 100644 platforms/market/src/features/follow/types.ts delete mode 100644 platforms/market/src/features/overview/models/.gitkeep create mode 100644 platforms/market/src/features/overview/models/own-subscriber-count/index.ts create mode 100644 platforms/market/src/features/overview/models/own-subscriber-count/types.ts create mode 100644 platforms/market/src/features/overview/models/own-subscriber-count/use-own-subscriber-count.ts delete mode 100644 platforms/market/src/features/post/actions/.gitkeep create mode 100644 platforms/market/src/features/post/actions/delete-post/actions.ts create mode 100644 platforms/market/src/features/post/actions/delete-post/index.ts create mode 100644 platforms/market/src/features/post/actions/edit-post/actions.ts create mode 100644 platforms/market/src/features/post/actions/edit-post/index.ts create mode 100644 platforms/market/src/features/post/actions/publish-post/actions.ts create mode 100644 platforms/market/src/features/post/actions/publish-post/index.ts create mode 100644 platforms/market/src/features/post/constants.ts delete mode 100644 platforms/market/src/features/post/models/.gitkeep create mode 100644 platforms/market/src/features/post/models/channel-feed/index.ts create mode 100644 platforms/market/src/features/post/models/channel-feed/types.ts create mode 100644 platforms/market/src/features/post/models/channel-feed/use-channel-feed-part.ts create mode 100644 platforms/market/src/features/post/models/composer/index.ts create mode 100644 platforms/market/src/features/post/models/composer/initial-images.ts create mode 100644 platforms/market/src/features/post/models/composer/types.ts create mode 100644 platforms/market/src/features/post/models/composer/use-composer-images.ts create mode 100644 platforms/market/src/features/post/models/composer/use-post-composer-page.ts create mode 100644 platforms/market/src/features/post/models/editable-post/index.ts create mode 100644 platforms/market/src/features/post/models/editable-post/types.ts create mode 100644 platforms/market/src/features/post/models/editable-post/use-editable-post.ts create mode 100644 platforms/market/src/features/post/models/owner-post/index.ts create mode 100644 platforms/market/src/features/post/models/owner-post/types.ts create mode 100644 platforms/market/src/features/post/models/owner-post/use-owner-post-part.ts create mode 100644 platforms/market/src/features/post/models/post-cache/index.ts create mode 100644 platforms/market/src/features/post/models/post-cache/post-cache.ts create mode 100644 platforms/market/src/features/post/models/post-list/index.ts create mode 100644 platforms/market/src/features/post/models/post-list/types.ts create mode 100644 platforms/market/src/features/post/models/post-list/use-post-list.ts create mode 100644 platforms/market/src/features/post/models/post/index.ts create mode 100644 platforms/market/src/features/post/models/post/types.ts create mode 100644 platforms/market/src/features/post/models/post/use-post-part.ts create mode 100644 platforms/market/src/features/post/types.ts delete mode 100644 platforms/market/src/features/prediction/actions/.gitkeep create mode 100644 platforms/market/src/features/prediction/actions/close-prediction/actions.ts create mode 100644 platforms/market/src/features/prediction/actions/close-prediction/index.ts create mode 100644 platforms/market/src/features/prediction/constants.ts delete mode 100644 platforms/market/src/features/prediction/models/.gitkeep create mode 100644 platforms/market/src/features/prediction/models/close-prediction/index.ts create mode 100644 platforms/market/src/features/prediction/models/close-prediction/outcome.ts create mode 100644 platforms/market/src/features/prediction/models/close-prediction/types.ts create mode 100644 platforms/market/src/features/prediction/models/close-prediction/use-close-prediction-part.ts create mode 100644 platforms/market/src/features/prediction/types.ts create mode 100644 platforms/market/src/features/profile/models/creator-standing/creator-standing-of.ts create mode 100644 platforms/market/src/features/profile/models/creator-standing/index.ts create mode 100644 platforms/market/src/features/profile/models/creator-standing/types.ts create mode 100644 platforms/market/src/features/profile/models/creator-standing/use-creator-standing.ts create mode 100644 platforms/market/src/shared/labels/content-labels.tsx create mode 100644 platforms/market/src/shared/labels/index.ts create mode 100644 platforms/market/src/shared/labels/types.ts create mode 100644 platforms/market/src/shared/locales/fa/channel.json create mode 100644 platforms/market/src/shared/locales/fa/content.json create mode 100644 platforms/market/src/shared/locales/fa/dashboard.json create mode 100644 platforms/market/src/shared/locales/fa/home.json create mode 100644 platforms/market/src/shared/utils/channel-username.ts create mode 100644 platforms/market/src/shared/utils/first-of-each.ts create mode 100644 platforms/market/src/shared/utils/load-more-error-kind.ts create mode 100644 platforms/market/src/shared/utils/price-input.ts create mode 100644 platforms/market/src/shared/utils/request-time.ts create mode 100644 platforms/market/src/shared/validations/content-validations.ts create mode 100644 platforms/market/src/stores/post-draft/index.ts create mode 100644 platforms/market/src/stores/post-draft/post-draft-store.ts create mode 100644 platforms/market/src/stores/post-draft/types.ts diff --git a/apps/bear/src/app/(flow)/compose/post/[id]/loading.tsx b/apps/bear/src/app/(flow)/compose/post/[id]/loading.tsx new file mode 100644 index 0000000..27ca44d --- /dev/null +++ b/apps/bear/src/app/(flow)/compose/post/[id]/loading.tsx @@ -0,0 +1,27 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; +import { DesktopHeader } from '@lumina/market/app/navigation'; + +import { i18n } from '../../../../../i18n'; + +/** The composer before it arrives, under the real header. */ +export default function Loading() { + return ( + + + + + + + ); +} diff --git a/apps/bear/src/app/(flow)/compose/post/[id]/page.tsx b/apps/bear/src/app/(flow)/compose/post/[id]/page.tsx new file mode 100644 index 0000000..c85ea82 --- /dev/null +++ b/apps/bear/src/app/(flow)/compose/post/[id]/page.tsx @@ -0,0 +1,50 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; +import { AuthGuard } from '@lumina/market/app/guards/auth-guard'; +import { DesktopHeader } from '@lumina/market/app/navigation'; +import { PostComposer } from '@lumina/market/app/screens/(flow)/compose/post/organisms/post-composer'; +import { POST_ID_PATTERN } from '@lumina/market/features/post'; +import type { Metadata } from 'next'; +import { notFound } from 'next/navigation'; + +import { i18n } from '../../../../../i18n'; + +type EditPostPageProps = { params: Promise<{ id: string }> }; + +export function generateMetadata(): Metadata { + return { + title: i18n.t('content:composer.edit-title'), + robots: { index: false }, + }; +} + +/** Editing a published post, in its first 15 minutes; in the browser only. */ +export default async function EditPostPage({ params }: EditPostPageProps) { + const { id } = await params; + // The API answers a malformed id with a 500, not a 404. + if (!POST_ID_PATTERN.test(id)) notFound(); + return ( + + + + + } + > + + + + + ); +} diff --git a/apps/bear/src/app/(flow)/compose/post/loading.tsx b/apps/bear/src/app/(flow)/compose/post/loading.tsx new file mode 100644 index 0000000..e66a4b1 --- /dev/null +++ b/apps/bear/src/app/(flow)/compose/post/loading.tsx @@ -0,0 +1,27 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; +import { DesktopHeader } from '@lumina/market/app/navigation'; + +import { i18n } from '../../../../i18n'; + +/** The composer before it arrives, under the real header. */ +export default function Loading() { + return ( + + + + + + + ); +} diff --git a/apps/bear/src/app/(flow)/compose/post/page.tsx b/apps/bear/src/app/(flow)/compose/post/page.tsx new file mode 100644 index 0000000..8d7711f --- /dev/null +++ b/apps/bear/src/app/(flow)/compose/post/page.tsx @@ -0,0 +1,43 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; +import { AuthGuard } from '@lumina/market/app/guards/auth-guard'; +import { DesktopHeader } from '@lumina/market/app/navigation'; +import { PostComposer } from '@lumina/market/app/screens/(flow)/compose/post/organisms/post-composer'; +import type { Metadata } from 'next'; + +import { i18n } from '../../../../i18n'; + +export function generateMetadata(): Metadata { + return { + title: i18n.t('content:composer.new-title'), + robots: { index: false }, + }; +} + +/** A new post (C4 ۷.۳): the 640px composer under the header, in the browser only. */ +export default function ComposePostPage() { + return ( + + + + + } + > + + + + + ); +} diff --git a/apps/bear/src/app/(main)/(home)/loading.tsx b/apps/bear/src/app/(main)/(home)/loading.tsx new file mode 100644 index 0000000..091eeba --- /dev/null +++ b/apps/bear/src/app/(main)/(home)/loading.tsx @@ -0,0 +1,17 @@ +import { HomeFeedSkeleton } from '@lumina/market/app/screens/(main)/organisms/home-feed'; + +import { i18n } from '../../../i18n'; +import { HomeTemplate } from './templates/home-template'; + +/** خانه before it arrives: the heading, then three post skeletons in the 640 column (S1-03). */ +export default function Loading() { + return ( + + + + ); +} diff --git a/apps/bear/src/app/(main)/(home)/page.tsx b/apps/bear/src/app/(main)/(home)/page.tsx new file mode 100644 index 0000000..7d6732c --- /dev/null +++ b/apps/bear/src/app/(main)/(home)/page.tsx @@ -0,0 +1,46 @@ +import { PartBoundary } from '@lumina/market/app/error-boundaries'; +import { ROUTES } from '@lumina/market/app/navigation'; +import { + EXAMPLE_CHANNEL_USERNAME, + HomeFeed, + HomeFeedSkeleton, + HomeGuard, +} from '@lumina/market/app/screens/(main)/organisms/home-feed'; +import type { Metadata } from 'next'; +import { Suspense } from 'react'; + +import { displayUrl } from '../../../configs'; +import { i18n } from '../../../i18n'; +import { HomeTemplate } from './templates/home-template'; + +export function generateMetadata(): Metadata { + return { title: i18n.t('home:meta.title'), robots: { index: false } }; +} + +/** + * خانه, `/`: the investor's feed of the creators they follow. The server sends only the frame and + * the feed's skeleton, the same for every visitor; the feed loads in the browser with the session. + * A guest goes to login, which returns here, and a creator to their own channel. A failed feed + * shows in a card in the column, as the desktop boards draw a state there (S3, S2-Desktop). + */ +export default function HomePage() { + const skeleton = ( + + ); + return ( + + + + + + + + + + ); +} diff --git a/apps/bear/src/app/(main)/(home)/templates/home-template/HomeTemplate.tsx b/apps/bear/src/app/(main)/(home)/templates/home-template/HomeTemplate.tsx new file mode 100644 index 0000000..f69d073 --- /dev/null +++ b/apps/bear/src/app/(main)/(home)/templates/home-template/HomeTemplate.tsx @@ -0,0 +1,28 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; + +import { i18n } from '../../../../../i18n'; +import type { HomeTemplateProps } from './types'; + +/** + * خانه's frame on desktop, shared by the page and its loading: one 640 column under the header, + * with no side content (U7 ۶.۱, Main C), the h2 «خانه» at its top as on mobile, then the feed. + * The header comes from the main layout, خانه on. + */ +export function HomeTemplate({ children }: HomeTemplateProps) { + const t = i18n.getFixedT(null, 'home'); + return ( + + + + {t('heading')} + + {children} + + + ); +} diff --git a/apps/bear/src/app/(main)/(home)/templates/home-template/index.ts b/apps/bear/src/app/(main)/(home)/templates/home-template/index.ts new file mode 100644 index 0000000..79f22a8 --- /dev/null +++ b/apps/bear/src/app/(main)/(home)/templates/home-template/index.ts @@ -0,0 +1,2 @@ +export { HomeTemplate } from './HomeTemplate'; +export type { HomeTemplateProps } from './types'; diff --git a/apps/bear/src/app/(main)/(home)/templates/home-template/types.ts b/apps/bear/src/app/(main)/(home)/templates/home-template/types.ts new file mode 100644 index 0000000..973ad2f --- /dev/null +++ b/apps/bear/src/app/(main)/(home)/templates/home-template/types.ts @@ -0,0 +1,6 @@ +import type { ReactNode } from 'react'; + +export type HomeTemplateProps = { + /** The feed, or its skeleton. */ + children: ReactNode; +}; diff --git a/apps/bear/src/app/(main)/@modal/(.)compose/layout.tsx b/apps/bear/src/app/(main)/@modal/(.)compose/layout.tsx new file mode 100644 index 0000000..c01906c --- /dev/null +++ b/apps/bear/src/app/(main)/@modal/(.)compose/layout.tsx @@ -0,0 +1,3 @@ +// Locked until a creator finishes registration step 5 (0016), as on the full page; the guard +// renders the dialog as is. +export { OnboardingGuard as default } from '@lumina/market/app/guards/onboarding-guard'; diff --git a/apps/bear/src/app/(main)/@modal/(.)compose/post/page.tsx b/apps/bear/src/app/(main)/@modal/(.)compose/post/page.tsx new file mode 100644 index 0000000..f155bc4 --- /dev/null +++ b/apps/bear/src/app/(main)/@modal/(.)compose/post/page.tsx @@ -0,0 +1,19 @@ +import { AuthGuard } from '@lumina/market/app/guards/auth-guard'; +import { + PostComposerDialog, + PostComposerDialogSkeleton, +} from '@lumina/market/app/screens/(flow)/compose/post/organisms/post-composer'; + +/** + * A new post opened from a main page (C4 ۷.۳): the 640px composer dialog over that page, the URL + * /compose/post; a direct load of that URL gets the full page instead. In the browser only: the + * dialog's skeleton until the viewer is known, then the composer for a creator, or the no-access + * state in the dialog for anyone else. + */ +export default function ComposePostDialog() { + return ( + }> + + + ); +} diff --git a/apps/bear/src/app/(main)/@modal/channels/[username]/page.tsx b/apps/bear/src/app/(main)/@modal/channels/[username]/page.tsx new file mode 100644 index 0000000..d2903df --- /dev/null +++ b/apps/bear/src/app/(main)/@modal/channels/[username]/page.tsx @@ -0,0 +1,9 @@ +/** + * Empties the `@modal` slot on the channel. A slot keeps its last page through a soft navigation + * to a route it has none for, so without this the «پست جدید» dialog would stay open over the + * channel it lands on after publishing. Only this route: a catch-all here would also match every + * path without a page, and a soft navigation there would keep the old page under the new URL. + */ +export default function ChannelModal() { + return null; +} diff --git a/apps/bear/src/app/(main)/@modal/default.tsx b/apps/bear/src/app/(main)/@modal/default.tsx new file mode 100644 index 0000000..aedfadb --- /dev/null +++ b/apps/bear/src/app/(main)/@modal/default.tsx @@ -0,0 +1,4 @@ +/** No dialog: what the `@modal` slot shows on a direct load and on every page that opens none. */ +export default function ModalDefault() { + return null; +} diff --git a/apps/bear/src/app/(main)/@modal/page.tsx b/apps/bear/src/app/(main)/@modal/page.tsx new file mode 100644 index 0000000..f922055 --- /dev/null +++ b/apps/bear/src/app/(main)/@modal/page.tsx @@ -0,0 +1,10 @@ +/** + * Empties the `@modal` slot on خانه. A slot keeps its last page through a soft navigation to a + * route it has none for, so without this the «پست جدید» dialog would stay open over خانه when it + * closes there (the composer's fallback with no history behind it) or when a link leads home while + * it is open. Only this route: a catch-all here would also match every path without a page, and a + * soft navigation there would keep the old page under the new URL. + */ +export default function HomeModal() { + return null; +} diff --git a/apps/bear/src/app/(main)/channels/[username]/loading.tsx b/apps/bear/src/app/(main)/channels/[username]/loading.tsx new file mode 100644 index 0000000..5b0b37f --- /dev/null +++ b/apps/bear/src/app/(main)/channels/[username]/loading.tsx @@ -0,0 +1,24 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Card } from '@lumina/island/molecules/card'; +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; + +import { i18n } from '../../../../i18n'; + +/** The channel before it arrives: the header panel, then a post, in the 640 column. */ +export default function Loading() { + const t = i18n.getFixedT(null, 'channel'); + return ( + + + + + + + + + ); +} diff --git a/apps/bear/src/app/(main)/channels/[username]/not-found.tsx b/apps/bear/src/app/(main)/channels/[username]/not-found.tsx new file mode 100644 index 0000000..768d041 --- /dev/null +++ b/apps/bear/src/app/(main)/channels/[username]/not-found.tsx @@ -0,0 +1,18 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { ChannelNotFound } from '@lumina/market/app/screens/(main)/channels/[username]/organisms/channel-not-found'; +import type { Metadata } from 'next'; + +import { displayUrl } from '../../../../configs'; + +export const metadata: Metadata = { robots: { index: false } }; + +/** No channel at this address, or not any more. */ +export default function ChannelNotFoundPage() { + return ( + + + + + + ); +} diff --git a/apps/bear/src/app/(main)/channels/[username]/page.tsx b/apps/bear/src/app/(main)/channels/[username]/page.tsx new file mode 100644 index 0000000..795bee3 --- /dev/null +++ b/apps/bear/src/app/(main)/channels/[username]/page.tsx @@ -0,0 +1,58 @@ +import { ROUTES } from '@lumina/market/app/navigation'; +import { + channelMetadata, + getChannel, + getRequestTime, + readOnServer, +} from '@lumina/market/server'; +import { toChannelUsername } from '@lumina/market/shared/utils'; +import type { Metadata } from 'next'; +import { notFound, permanentRedirect } from 'next/navigation'; + +import { displayUrl } from '../../../../configs'; +import { i18n } from '../../../../i18n'; +import { ChannelTemplate } from './templates/channel-template'; + +type ChannelPageProps = { params: Promise<{ username: string }> }; + +export async function generateMetadata({ + params, +}: ChannelPageProps): Promise { + const username = toChannelUsername((await params).username); + if (!username) return { robots: { index: false } }; + const channel = await readOnServer(() => getChannel(username)); + if (channel.status !== 'ok') return { robots: { index: false } }; + if (channel.data.suspended) { + return { + title: i18n.t('channel:meta.unavailable-title'), + robots: { index: false }, + }; + } + return channelMetadata({ + channel: channel.data, + title: i18n.t('channel:meta.title', { username }), + description: i18n.t('channel:meta.description', { username }), + }); +} + +/** + * A creator's channel, `/@username`. The same server render for every visitor: the header, the + * track record and the first posts; subscribe, follow and the locked posts' gates load in the + * browser. Any other spelling of the username redirects to the one the API stores. + */ +export default async function ChannelPage({ params }: ChannelPageProps) { + const segment = (await params).username; + const username = toChannelUsername(segment); + if (!username) notFound(); + if (username !== segment) permanentRedirect(ROUTES.channel(username)); + const channel = await readOnServer(() => getChannel(username)); + if (channel.status !== 'ok') notFound(); + + return ( + + ); +} diff --git a/apps/bear/src/app/(main)/channels/[username]/posts/[id]/loading.tsx b/apps/bear/src/app/(main)/channels/[username]/posts/[id]/loading.tsx new file mode 100644 index 0000000..bebb6f1 --- /dev/null +++ b/apps/bear/src/app/(main)/channels/[username]/posts/[id]/loading.tsx @@ -0,0 +1,41 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton'; +import { Card } from '@lumina/island/molecules/card'; +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; + +import { i18n } from '../../../../../../i18n'; + +/** + * The post before it arrives, in the 640 column (C4b ۱.۵): the channel bar's panel with the author + * row and the subscribe and follow row, then the post with its media. No lock is guessed meanwhile. + */ +export default function Loading() { + const t = i18n.getFixedT(null, 'channel'); + return ( + + + + + + + + + + + + + + + + + + ); +} diff --git a/apps/bear/src/app/(main)/channels/[username]/posts/[id]/page.tsx b/apps/bear/src/app/(main)/channels/[username]/posts/[id]/page.tsx new file mode 100644 index 0000000..27c5955 --- /dev/null +++ b/apps/bear/src/app/(main)/channels/[username]/posts/[id]/page.tsx @@ -0,0 +1,78 @@ +import { ROUTES } from '@lumina/market/app/navigation'; +import { POST_ID_PATTERN } from '@lumina/market/features/post'; +import { + getChannel, + getRequestTime, + getPost, + postMetadata, + readOnServer, +} from '@lumina/market/server'; +import { toChannelUsername } from '@lumina/market/shared/utils'; +import type { Metadata } from 'next'; +import { notFound, permanentRedirect } from 'next/navigation'; + +import { displayUrl } from '../../../../../../configs'; +import { i18n } from '../../../../../../i18n'; +import { PostTemplate } from './templates/post-template'; + +type PostPageProps = { params: Promise<{ username: string; id: string }> }; + +/** The channel and the post, read together; a post that isn't this channel's is missing. */ +async function readPostPage(username: string, id: string) { + const [channel, post] = await Promise.all([ + readOnServer(() => getChannel(username)), + POST_ID_PATTERN.test(id) + ? readOnServer(() => getPost(id)) + : ({ status: 'not-found' } as const), + ]); + if (channel.status !== 'ok') return null; + const found = + post.status === 'ok' && post.data.creatorId === channel.data.creatorId + ? post.data + : null; + return { channel: channel.data, post: found }; +} + +export async function generateMetadata({ + params, +}: PostPageProps): Promise { + const { username: segment, id } = await params; + const username = toChannelUsername(segment); + const page = username ? await readPostPage(username, id) : null; + if (!page?.post || page.channel.suspended) { + return { + title: i18n.t('channel:meta.post-missing-title'), + robots: { index: false }, + }; + } + return postMetadata({ + channel: page.channel, + post: page.post, + fallbackTitle: i18n.t('channel:meta.post-title', { + username: page.channel.username, + }), + }); +} + +/** + * One post, `/@username/posts/[id]`: where every shared link lands. The server renders it as every + * visitor sees it; a subscriber's or the creator's premium post opens in the browser. A deleted + * or unknown post keeps the channel's frame and leads back to the channel. + */ +export default async function PostPage({ params }: PostPageProps) { + const { username: segment, id } = await params; + const username = toChannelUsername(segment); + if (!username) notFound(); + if (username !== segment) permanentRedirect(ROUTES.post(username, id)); + const page = await readPostPage(username, id); + if (!page) notFound(); + + return ( + + ); +} diff --git a/apps/bear/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/PostTemplate.tsx b/apps/bear/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/PostTemplate.tsx new file mode 100644 index 0000000..9b5fe8b --- /dev/null +++ b/apps/bear/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/PostTemplate.tsx @@ -0,0 +1,64 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { PartBoundary } from '@lumina/market/app/error-boundaries'; +import { ChannelActions } from '@lumina/market/app/screens/(main)/channels/[username]/organisms/channel-actions'; +import { ChannelUnavailable } from '@lumina/market/app/screens/(main)/channels/[username]/organisms/channel-unavailable'; +import { PostChannelBar } from '@lumina/market/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar'; +import { PostMissing } from '@lumina/market/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-missing'; +import { PostView } from '@lumina/market/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view'; + +import { i18n } from '../../../../../../../../i18n'; +import type { PostTemplateProps } from './types'; + +/** + * The post on desktop, in the 640 column: the creator with subscribe and follow, then the post in + * full. The action area loads in the browser. + */ +export function PostTemplate({ + channel, + post, + channelUrl, + now, +}: PostTemplateProps) { + const t = i18n.getFixedT(null, 'channel'); + + return ( + + + {channel.suspended ? ( + + ) : post ? ( + <> + + + + } + /> + + + ) : ( + + )} + + + ); +} diff --git a/apps/bear/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/index.ts b/apps/bear/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/index.ts new file mode 100644 index 0000000..cde4663 --- /dev/null +++ b/apps/bear/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/index.ts @@ -0,0 +1,2 @@ +export { PostTemplate } from './PostTemplate'; +export type { PostTemplateProps } from './types'; diff --git a/apps/bear/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/types.ts b/apps/bear/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/types.ts new file mode 100644 index 0000000..8db8fb8 --- /dev/null +++ b/apps/bear/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/types.ts @@ -0,0 +1,12 @@ +import type { PublicCreatorPayload } from '@lumina/market/features/channel'; +import type { PostPayload } from '@lumina/market/features/post'; + +export type PostTemplateProps = { + channel: PublicCreatorPayload; + /** `null`: deleted, unknown, or another channel's. */ + post: PostPayload | null; + /** «lumina.ir/@sara_gold», for the guest's login prompt. */ + channelUrl: string; + /** The render's time: the post's time counts from it. */ + now: string; +}; diff --git a/apps/bear/src/app/(main)/channels/[username]/templates/channel-template/ChannelTemplate.tsx b/apps/bear/src/app/(main)/channels/[username]/templates/channel-template/ChannelTemplate.tsx new file mode 100644 index 0000000..b6fe871 --- /dev/null +++ b/apps/bear/src/app/(main)/channels/[username]/templates/channel-template/ChannelTemplate.tsx @@ -0,0 +1,117 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; +import { PartBoundary } from '@lumina/market/app/error-boundaries'; +import { ChannelActions } from '@lumina/market/app/screens/(main)/channels/[username]/organisms/channel-actions'; +import { ChannelFeed } from '@lumina/market/app/screens/(main)/channels/[username]/organisms/channel-feed/server'; +import { + ChannelHeader, + channelHeaderLabels, +} from '@lumina/market/app/screens/(main)/channels/[username]/organisms/channel-header'; +import { ChannelShare } from '@lumina/market/app/screens/(main)/channels/[username]/organisms/channel-share'; +import { ChannelStats } from '@lumina/market/app/screens/(main)/channels/[username]/organisms/channel-stats/server'; +import { ChannelUnavailable } from '@lumina/market/app/screens/(main)/channels/[username]/organisms/channel-unavailable'; +import { creatorStatsLabels } from '@lumina/market/shared/labels'; +import { Suspense } from 'react'; + +import { i18n } from '../../../../../../i18n'; +import type { ChannelTemplateProps } from './types'; + +/** + * The channel on desktop: one 640px column, no side rail. The header panel renders at once; the + * track record and the feed stream in reading order, each in its own boundary, and the action + * area loads in the browser. + */ +export function ChannelTemplate({ + channel, + channelUrl, + now, +}: ChannelTemplateProps) { + const t = i18n.getFixedT(null, 'channel'); + + // Suspension outranks everything: no header, posts or actions, for anyone (U6 ۵.۳). + if (channel.suspended) { + return ( + + + + + + ); + } + + return ( + + + + } + stats={ + + + } + > + + + + } + actions={ + + + + } + labels={channelHeaderLabels(t, i18n.getFixedT(null, 'common'))} + /> + + + } + > + + + + + + ); +} diff --git a/apps/bear/src/app/(main)/channels/[username]/templates/channel-template/index.ts b/apps/bear/src/app/(main)/channels/[username]/templates/channel-template/index.ts new file mode 100644 index 0000000..2c54681 --- /dev/null +++ b/apps/bear/src/app/(main)/channels/[username]/templates/channel-template/index.ts @@ -0,0 +1,2 @@ +export { ChannelTemplate } from './ChannelTemplate'; +export type { ChannelTemplateProps } from './types'; diff --git a/apps/bear/src/app/(main)/channels/[username]/templates/channel-template/types.ts b/apps/bear/src/app/(main)/channels/[username]/templates/channel-template/types.ts new file mode 100644 index 0000000..8f8764a --- /dev/null +++ b/apps/bear/src/app/(main)/channels/[username]/templates/channel-template/types.ts @@ -0,0 +1,9 @@ +import type { PublicCreatorPayload } from '@lumina/market/features/channel'; + +export type ChannelTemplateProps = { + channel: PublicCreatorPayload; + /** «lumina.ir/@sara_gold». */ + channelUrl: string; + /** The render's time: the posts' relative times count from it. */ + now: string; +}; diff --git a/apps/bear/src/app/(main)/dashboard/(investor)/following/loading.tsx b/apps/bear/src/app/(main)/dashboard/(investor)/following/loading.tsx new file mode 100644 index 0000000..de98471 --- /dev/null +++ b/apps/bear/src/app/(main)/dashboard/(investor)/following/loading.tsx @@ -0,0 +1,15 @@ +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; + +import { i18n } from '../../../../../i18n'; + +/** The list before it arrives, row for row; the layout keeps the heading and the tabs. */ +export default function Loading() { + return ( + + ); +} diff --git a/apps/bear/src/app/(main)/dashboard/(investor)/following/page.tsx b/apps/bear/src/app/(main)/dashboard/(investor)/following/page.tsx new file mode 100644 index 0000000..d18627e --- /dev/null +++ b/apps/bear/src/app/(main)/dashboard/(investor)/following/page.tsx @@ -0,0 +1,43 @@ +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; +import { PartBoundary } from '@lumina/market/app/error-boundaries'; +import { AuthGuard } from '@lumina/market/app/guards/auth-guard'; +import { FollowingList } from '@lumina/market/app/screens/(main)/dashboard/following/organisms/following-list'; +import type { Metadata } from 'next'; +import { Suspense } from 'react'; + +import { i18n } from '../../../../../i18n'; + +export function generateMetadata(): Metadata { + return { + title: i18n.t('dashboard:following.meta-title'), + robots: { index: false }, + }; +} + +/** + * داشبورد › دنبال‌شده‌ها (U8 ۶.۱): the investor's own list, in the browser only, behind rows of the + * same size. A failed read shows in place of the list; the heading and the tabs stay (U8 ۴.۵). + */ +export default function FollowingPage() { + const skeleton = ( + + ); + + return ( + + + + + + + + ); +} diff --git a/apps/bear/src/app/(main)/dashboard/(investor)/layout.tsx b/apps/bear/src/app/(main)/dashboard/(investor)/layout.tsx new file mode 100644 index 0000000..b162e78 --- /dev/null +++ b/apps/bear/src/app/(main)/dashboard/(investor)/layout.tsx @@ -0,0 +1,34 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { DashboardTabs } from '@lumina/market/app/screens/(main)/dashboard/organisms/dashboard-tabs'; +import type { ReactNode } from 'react'; + +import { i18n } from '../../../../i18n'; + +/** + * The investor's داشبورد on desktop (U8 ۶.۱; U2): the 640 column under the header, with the + * «داشبورد» heading, the section row «اشتراک‌ها» · «تراکنش‌ها» · «دنبال‌شده‌ها», then the section. + * Each section is its own route with its own loading, so the heading and the row stay while one + * loads. + */ +export default function InvestorDashboardLayout({ + children, +}: { + children: ReactNode; +}) { + return ( + + + + {i18n.t('common:nav.dashboard')} + + + {children} + + + ); +} diff --git a/apps/bear/src/app/(flow)/compose/post/.gitkeep b/apps/bear/src/app/(main)/dashboard/(investor)/subscriptions/.gitkeep similarity index 100% rename from apps/bear/src/app/(flow)/compose/post/.gitkeep rename to apps/bear/src/app/(main)/dashboard/(investor)/subscriptions/.gitkeep diff --git a/apps/bear/src/app/(main)/channels/[username]/posts/[id]/.gitkeep b/apps/bear/src/app/(main)/dashboard/(investor)/transactions/.gitkeep similarity index 100% rename from apps/bear/src/app/(main)/channels/[username]/posts/[id]/.gitkeep rename to apps/bear/src/app/(main)/dashboard/(investor)/transactions/.gitkeep diff --git a/apps/bear/src/app/(main)/dashboard/transactions/.gitkeep b/apps/bear/src/app/(main)/dashboard/transactions/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/apps/bear/src/app/(main)/default.tsx b/apps/bear/src/app/(main)/default.tsx new file mode 100644 index 0000000..cad5e2b --- /dev/null +++ b/apps/bear/src/app/(main)/default.tsx @@ -0,0 +1,16 @@ +'use client'; + +import { useEffect } from 'react'; + +/** + * The main page under the «پست جدید» dialog when there is none. A soft navigation to /compose/post + * from outside the main pages (the full composer's own header, a login that returns there) still + * lands on the `@modal` intercept, with no main page for it to cover. Load the URL again, so the + * full composer page takes over. + */ +export default function MainDefault() { + useEffect(() => { + window.location.replace(window.location.href); + }, []); + return null; +} diff --git a/apps/bear/src/app/(main)/layout.tsx b/apps/bear/src/app/(main)/layout.tsx new file mode 100644 index 0000000..3c2f305 --- /dev/null +++ b/apps/bear/src/app/(main)/layout.tsx @@ -0,0 +1,23 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { DesktopHeader } from '@lumina/market/app/navigation'; +import type { ReactNode } from 'react'; + +type MainLayoutProps = { + children: ReactNode; + /** The `@modal` slot: «پست جدید» over the page (C4 ۷.۳), or nothing. */ + modal: ReactNode; +}; + +/** + * The main pages on desktop: the header over each page's column. «انتشار» › «پست جدید» opens the + * composer as a dialog over the page in the `@modal` slot, which intercepts /compose/post. + */ +export default function MainLayout({ children, modal }: MainLayoutProps) { + return ( + + + {children} + {modal} + + ); +} diff --git a/apps/bear/src/configs/index.ts b/apps/bear/src/configs/index.ts index bc4704f..fe4fde0 100644 --- a/apps/bear/src/configs/index.ts +++ b/apps/bear/src/configs/index.ts @@ -1,2 +1,3 @@ export { getQueryClient } from './react-query'; export { rootMetadata } from './seo'; +export { displayUrl } from './site'; diff --git a/apps/bear/src/configs/site.ts b/apps/bear/src/configs/site.ts new file mode 100644 index 0000000..44db08e --- /dev/null +++ b/apps/bear/src/configs/site.ts @@ -0,0 +1,6 @@ +import { clientEnv } from '../env'; + +/** A path on this site as people read and type it, without the scheme: «lumina.ir/@sara_gold». */ +export function displayUrl(path: string): string { + return `${new URL(clientEnv.NEXT_PUBLIC_SITE_URL).host}${path}`; +} diff --git a/apps/bull/src/app/(flow)/compose/post/.gitkeep b/apps/bull/src/app/(flow)/compose/post/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/apps/bull/src/app/(flow)/compose/post/[id]/loading.tsx b/apps/bull/src/app/(flow)/compose/post/[id]/loading.tsx new file mode 100644 index 0000000..3e3007c --- /dev/null +++ b/apps/bull/src/app/(flow)/compose/post/[id]/loading.tsx @@ -0,0 +1,16 @@ +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; + +import { i18n } from '../../../../../i18n'; + +/** The composer before it arrives. */ +export default function Loading() { + return ( + + ); +} diff --git a/apps/bull/src/app/(flow)/compose/post/[id]/page.tsx b/apps/bull/src/app/(flow)/compose/post/[id]/page.tsx new file mode 100644 index 0000000..66ce2cc --- /dev/null +++ b/apps/bull/src/app/(flow)/compose/post/[id]/page.tsx @@ -0,0 +1,39 @@ +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; +import { AuthGuard } from '@lumina/market/app/guards/auth-guard'; +import { PostComposer } from '@lumina/market/app/screens/(flow)/compose/post/organisms/post-composer'; +import { POST_ID_PATTERN } from '@lumina/market/features/post'; +import type { Metadata } from 'next'; +import { notFound } from 'next/navigation'; + +import { i18n } from '../../../../../i18n'; + +type EditPostPageProps = { params: Promise<{ id: string }> }; + +export function generateMetadata(): Metadata { + return { + title: i18n.t('content:composer.edit-title'), + robots: { index: false }, + }; +} + +/** Editing a published post (C4 ۵.۲), in its first 15 minutes; in the browser only. */ +export default async function EditPostPage({ params }: EditPostPageProps) { + const { id } = await params; + // The API answers a malformed id with a 500, not a 404. + if (!POST_ID_PATTERN.test(id)) notFound(); + return ( + + } + > + + + ); +} diff --git a/apps/bull/src/app/(flow)/compose/post/loading.tsx b/apps/bull/src/app/(flow)/compose/post/loading.tsx new file mode 100644 index 0000000..19154de --- /dev/null +++ b/apps/bull/src/app/(flow)/compose/post/loading.tsx @@ -0,0 +1,16 @@ +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; + +import { i18n } from '../../../../i18n'; + +/** The composer before it arrives. */ +export default function Loading() { + return ( + + ); +} diff --git a/apps/bull/src/app/(flow)/compose/post/page.tsx b/apps/bull/src/app/(flow)/compose/post/page.tsx new file mode 100644 index 0000000..446cffb --- /dev/null +++ b/apps/bull/src/app/(flow)/compose/post/page.tsx @@ -0,0 +1,32 @@ +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; +import { AuthGuard } from '@lumina/market/app/guards/auth-guard'; +import { PostComposer } from '@lumina/market/app/screens/(flow)/compose/post/organisms/post-composer'; +import type { Metadata } from 'next'; + +import { i18n } from '../../../../i18n'; + +export function generateMetadata(): Metadata { + return { + title: i18n.t('content:composer.new-title'), + robots: { index: false }, + }; +} + +/** A new post (C4): the creator's own task flow, in the browser only, with no bottom nav. */ +export default function ComposePostPage() { + return ( + + } + > + + + ); +} diff --git a/apps/bull/src/app/(main)/(home)/loading.tsx b/apps/bull/src/app/(main)/(home)/loading.tsx new file mode 100644 index 0000000..68330fe --- /dev/null +++ b/apps/bull/src/app/(main)/(home)/loading.tsx @@ -0,0 +1,17 @@ +import { HomeFeedSkeleton } from '@lumina/market/app/screens/(main)/organisms/home-feed'; + +import { i18n } from '../../../i18n'; +import { HomeTemplate } from './templates/home-template'; + +/** خانه before it arrives (S1-03): the real top bar and heading, then three post skeletons. */ +export default function Loading() { + return ( + + + + ); +} diff --git a/apps/bull/src/app/(main)/(home)/page.tsx b/apps/bull/src/app/(main)/(home)/page.tsx new file mode 100644 index 0000000..304cf69 --- /dev/null +++ b/apps/bull/src/app/(main)/(home)/page.tsx @@ -0,0 +1,45 @@ +import { PartBoundary } from '@lumina/market/app/error-boundaries'; +import { ROUTES } from '@lumina/market/app/navigation'; +import { + EXAMPLE_CHANNEL_USERNAME, + HomeFeed, + HomeFeedSkeleton, + HomeGuard, +} from '@lumina/market/app/screens/(main)/organisms/home-feed'; +import type { Metadata } from 'next'; +import { Suspense } from 'react'; + +import { displayUrl } from '../../../configs'; +import { i18n } from '../../../i18n'; +import { HomeTemplate } from './templates/home-template'; + +export function generateMetadata(): Metadata { + return { title: i18n.t('home:meta.title'), robots: { index: false } }; +} + +/** + * خانه, `/`: the investor's feed of the creators they follow. The server sends only the frame and + * the feed's skeleton, the same for every visitor; the feed loads in the browser with the session. + * A guest goes to login, which returns here, and a creator to their own channel. + */ +export default function HomePage() { + const skeleton = ( + + ); + return ( + + + + + + + + + + ); +} diff --git a/apps/bull/src/app/(main)/(home)/templates/home-template/HomeTemplate.tsx b/apps/bull/src/app/(main)/(home)/templates/home-template/HomeTemplate.tsx new file mode 100644 index 0000000..9064707 --- /dev/null +++ b/apps/bull/src/app/(main)/(home)/templates/home-template/HomeTemplate.tsx @@ -0,0 +1,31 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { MobileTopBar } from '@lumina/market/app/navigation'; + +import { i18n } from '../../../../../i18n'; +import type { HomeTemplateProps } from './types'; + +/** + * خانه's frame on mobile, shared by the page and its loading: the tab's top bar (the brand, + * support and the account, no title), then «خانه» over the feed, the h2 the boards draw + * (Home--relocked, Home--confirmed-banner). The bottom nav comes from the main layout, خانه on. + */ +export function HomeTemplate({ children }: HomeTemplateProps) { + const t = i18n.getFixedT(null, 'home'); + return ( + <> + + + + {t('heading')} + + {children} + + + ); +} diff --git a/apps/bull/src/app/(main)/(home)/templates/home-template/index.ts b/apps/bull/src/app/(main)/(home)/templates/home-template/index.ts new file mode 100644 index 0000000..79f22a8 --- /dev/null +++ b/apps/bull/src/app/(main)/(home)/templates/home-template/index.ts @@ -0,0 +1,2 @@ +export { HomeTemplate } from './HomeTemplate'; +export type { HomeTemplateProps } from './types'; diff --git a/apps/bull/src/app/(main)/(home)/templates/home-template/types.ts b/apps/bull/src/app/(main)/(home)/templates/home-template/types.ts new file mode 100644 index 0000000..02ec0b2 --- /dev/null +++ b/apps/bull/src/app/(main)/(home)/templates/home-template/types.ts @@ -0,0 +1,6 @@ +import type { ReactNode } from 'react'; + +export type HomeTemplateProps = { + /** The feed, or its skeleton; it fills the height, so an empty feed centres in it. */ + children: ReactNode; +}; diff --git a/apps/bull/src/app/(main)/channels/[username]/loading.tsx b/apps/bull/src/app/(main)/channels/[username]/loading.tsx new file mode 100644 index 0000000..af25592 --- /dev/null +++ b/apps/bull/src/app/(main)/channels/[username]/loading.tsx @@ -0,0 +1,26 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; +import { MobileTopBar } from '@lumina/market/app/navigation'; + +import { i18n } from '../../../../i18n'; + +/** The channel before it arrives: the real top bar, then the header, track record and a post. */ +export default function Loading() { + const t = i18n.getFixedT(null, 'channel'); + return ( + <> + + + {/* The skeleton draws the header's flush band itself. */} + + + + + + + ); +} diff --git a/apps/bull/src/app/(main)/channels/[username]/not-found.tsx b/apps/bull/src/app/(main)/channels/[username]/not-found.tsx new file mode 100644 index 0000000..c96d8d1 --- /dev/null +++ b/apps/bull/src/app/(main)/channels/[username]/not-found.tsx @@ -0,0 +1,27 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { + ChannelNotFound, + ChannelNotFoundTopBar, +} from '@lumina/market/app/screens/(main)/channels/[username]/organisms/channel-not-found'; +import type { Metadata } from 'next'; + +import { displayUrl } from '../../../../configs'; +import { i18n } from '../../../../i18n'; + +export const metadata: Metadata = { robots: { index: false } }; + +/** + * No channel at this address, or not any more. Its creator, before approval, sees their own tab + * here instead (C6 ۱.۲), under their tab bar; both are decided in the browser. The main is flush + * for that tab's banner strip and header; the message keeps its own inset. + */ +export default function ChannelNotFoundPage() { + return ( + <> + + + + + + ); +} diff --git a/apps/bull/src/app/(main)/channels/[username]/page.tsx b/apps/bull/src/app/(main)/channels/[username]/page.tsx new file mode 100644 index 0000000..795bee3 --- /dev/null +++ b/apps/bull/src/app/(main)/channels/[username]/page.tsx @@ -0,0 +1,58 @@ +import { ROUTES } from '@lumina/market/app/navigation'; +import { + channelMetadata, + getChannel, + getRequestTime, + readOnServer, +} from '@lumina/market/server'; +import { toChannelUsername } from '@lumina/market/shared/utils'; +import type { Metadata } from 'next'; +import { notFound, permanentRedirect } from 'next/navigation'; + +import { displayUrl } from '../../../../configs'; +import { i18n } from '../../../../i18n'; +import { ChannelTemplate } from './templates/channel-template'; + +type ChannelPageProps = { params: Promise<{ username: string }> }; + +export async function generateMetadata({ + params, +}: ChannelPageProps): Promise { + const username = toChannelUsername((await params).username); + if (!username) return { robots: { index: false } }; + const channel = await readOnServer(() => getChannel(username)); + if (channel.status !== 'ok') return { robots: { index: false } }; + if (channel.data.suspended) { + return { + title: i18n.t('channel:meta.unavailable-title'), + robots: { index: false }, + }; + } + return channelMetadata({ + channel: channel.data, + title: i18n.t('channel:meta.title', { username }), + description: i18n.t('channel:meta.description', { username }), + }); +} + +/** + * A creator's channel, `/@username`. The same server render for every visitor: the header, the + * track record and the first posts; subscribe, follow and the locked posts' gates load in the + * browser. Any other spelling of the username redirects to the one the API stores. + */ +export default async function ChannelPage({ params }: ChannelPageProps) { + const segment = (await params).username; + const username = toChannelUsername(segment); + if (!username) notFound(); + if (username !== segment) permanentRedirect(ROUTES.channel(username)); + const channel = await readOnServer(() => getChannel(username)); + if (channel.status !== 'ok') notFound(); + + return ( + + ); +} diff --git a/apps/bull/src/app/(main)/channels/[username]/posts/[id]/.gitkeep b/apps/bull/src/app/(main)/channels/[username]/posts/[id]/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/apps/bull/src/app/(main)/channels/[username]/posts/[id]/loading.tsx b/apps/bull/src/app/(main)/channels/[username]/posts/[id]/loading.tsx new file mode 100644 index 0000000..f8fe67d --- /dev/null +++ b/apps/bull/src/app/(main)/channels/[username]/posts/[id]/loading.tsx @@ -0,0 +1,47 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton'; +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; +import { MobileTopBar } from '@lumina/market/app/navigation'; + +import { i18n } from '../../../../../../i18n'; + +/** + * The post before it arrives, in the real layout (C4b ۱.۵): the live top bar, the channel bar's + * band with the author row and the subscribe and follow row, then the post with its media. No lock + * is guessed meanwhile. + */ +export default function Loading() { + const t = i18n.getFixedT(null, 'channel'); + return ( + <> + + + + + + + + + + + + + + + + + + ); +} diff --git a/apps/bull/src/app/(main)/channels/[username]/posts/[id]/page.tsx b/apps/bull/src/app/(main)/channels/[username]/posts/[id]/page.tsx new file mode 100644 index 0000000..27c5955 --- /dev/null +++ b/apps/bull/src/app/(main)/channels/[username]/posts/[id]/page.tsx @@ -0,0 +1,78 @@ +import { ROUTES } from '@lumina/market/app/navigation'; +import { POST_ID_PATTERN } from '@lumina/market/features/post'; +import { + getChannel, + getRequestTime, + getPost, + postMetadata, + readOnServer, +} from '@lumina/market/server'; +import { toChannelUsername } from '@lumina/market/shared/utils'; +import type { Metadata } from 'next'; +import { notFound, permanentRedirect } from 'next/navigation'; + +import { displayUrl } from '../../../../../../configs'; +import { i18n } from '../../../../../../i18n'; +import { PostTemplate } from './templates/post-template'; + +type PostPageProps = { params: Promise<{ username: string; id: string }> }; + +/** The channel and the post, read together; a post that isn't this channel's is missing. */ +async function readPostPage(username: string, id: string) { + const [channel, post] = await Promise.all([ + readOnServer(() => getChannel(username)), + POST_ID_PATTERN.test(id) + ? readOnServer(() => getPost(id)) + : ({ status: 'not-found' } as const), + ]); + if (channel.status !== 'ok') return null; + const found = + post.status === 'ok' && post.data.creatorId === channel.data.creatorId + ? post.data + : null; + return { channel: channel.data, post: found }; +} + +export async function generateMetadata({ + params, +}: PostPageProps): Promise { + const { username: segment, id } = await params; + const username = toChannelUsername(segment); + const page = username ? await readPostPage(username, id) : null; + if (!page?.post || page.channel.suspended) { + return { + title: i18n.t('channel:meta.post-missing-title'), + robots: { index: false }, + }; + } + return postMetadata({ + channel: page.channel, + post: page.post, + fallbackTitle: i18n.t('channel:meta.post-title', { + username: page.channel.username, + }), + }); +} + +/** + * One post, `/@username/posts/[id]`: where every shared link lands. The server renders it as every + * visitor sees it; a subscriber's or the creator's premium post opens in the browser. A deleted + * or unknown post keeps the channel's frame and leads back to the channel. + */ +export default async function PostPage({ params }: PostPageProps) { + const { username: segment, id } = await params; + const username = toChannelUsername(segment); + if (!username) notFound(); + if (username !== segment) permanentRedirect(ROUTES.post(username, id)); + const page = await readPostPage(username, id); + if (!page) notFound(); + + return ( + + ); +} diff --git a/apps/bull/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/PostTemplate.tsx b/apps/bull/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/PostTemplate.tsx new file mode 100644 index 0000000..6fe221b --- /dev/null +++ b/apps/bull/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/PostTemplate.tsx @@ -0,0 +1,69 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { PartBoundary } from '@lumina/market/app/error-boundaries'; +import { MobileTopBar } from '@lumina/market/app/navigation'; +import { ChannelActions } from '@lumina/market/app/screens/(main)/channels/[username]/organisms/channel-actions'; +import { ChannelUnavailable } from '@lumina/market/app/screens/(main)/channels/[username]/organisms/channel-unavailable'; +import { PostChannelBar } from '@lumina/market/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar'; +import { PostMissing } from '@lumina/market/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-missing'; +import { PostView } from '@lumina/market/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view'; + +import { i18n } from '../../../../../../../../i18n'; +import type { PostTemplateProps } from './types'; + +/** + * The post on mobile, pushed from خانه or the channel: the creator with subscribe and follow, + * then the post in full. The action area loads in the browser. + */ +export function PostTemplate({ + channel, + post, + channelUrl, + now, +}: PostTemplateProps) { + const t = i18n.getFixedT(null, 'channel'); + + return ( + <> + + + {channel.suspended ? ( + + ) : post ? ( + <> + + + + } + /> + + + + + ) : ( + + + + )} + + + ); +} diff --git a/apps/bull/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/index.ts b/apps/bull/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/index.ts new file mode 100644 index 0000000..cde4663 --- /dev/null +++ b/apps/bull/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/index.ts @@ -0,0 +1,2 @@ +export { PostTemplate } from './PostTemplate'; +export type { PostTemplateProps } from './types'; diff --git a/apps/bull/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/types.ts b/apps/bull/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/types.ts new file mode 100644 index 0000000..8db8fb8 --- /dev/null +++ b/apps/bull/src/app/(main)/channels/[username]/posts/[id]/templates/post-template/types.ts @@ -0,0 +1,12 @@ +import type { PublicCreatorPayload } from '@lumina/market/features/channel'; +import type { PostPayload } from '@lumina/market/features/post'; + +export type PostTemplateProps = { + channel: PublicCreatorPayload; + /** `null`: deleted, unknown, or another channel's. */ + post: PostPayload | null; + /** «lumina.ir/@sara_gold», for the guest's login prompt. */ + channelUrl: string; + /** The render's time: the post's time counts from it. */ + now: string; +}; diff --git a/apps/bull/src/app/(main)/channels/[username]/templates/channel-template/ChannelTemplate.tsx b/apps/bull/src/app/(main)/channels/[username]/templates/channel-template/ChannelTemplate.tsx new file mode 100644 index 0000000..16af2a3 --- /dev/null +++ b/apps/bull/src/app/(main)/channels/[username]/templates/channel-template/ChannelTemplate.tsx @@ -0,0 +1,122 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; +import { PartBoundary } from '@lumina/market/app/error-boundaries'; +import { MobileTopBar } from '@lumina/market/app/navigation'; +import { ChannelActions } from '@lumina/market/app/screens/(main)/channels/[username]/organisms/channel-actions'; +import { ChannelFeed } from '@lumina/market/app/screens/(main)/channels/[username]/organisms/channel-feed/server'; +import { + ChannelHeader, + channelHeaderLabels, +} from '@lumina/market/app/screens/(main)/channels/[username]/organisms/channel-header'; +import { ChannelShare } from '@lumina/market/app/screens/(main)/channels/[username]/organisms/channel-share'; +import { ChannelStats } from '@lumina/market/app/screens/(main)/channels/[username]/organisms/channel-stats/server'; +import { ChannelUnavailable } from '@lumina/market/app/screens/(main)/channels/[username]/organisms/channel-unavailable'; +import { creatorStatsLabels } from '@lumina/market/shared/labels'; +import { Suspense } from 'react'; + +import { i18n } from '../../../../../../i18n'; +import type { ChannelTemplateProps } from './types'; + +/** + * The channel on mobile: a page pushed from خانه (the creator's own کانال tab). The header renders + * at once; the track record and the feed stream in reading order, each in its own boundary, and + * the action area loads in the browser. + */ +export function ChannelTemplate({ + channel, + channelUrl, + now, +}: ChannelTemplateProps) { + const t = i18n.getFixedT(null, 'channel'); + + // Suspension outranks everything: no header, posts or actions, for anyone (U6 ۱.۳). Its creator + // sees their suspended tab under their tab bar (C6 ۱.۳); the browser decides. The main is flush + // for that tab's banner strip and header; the message keeps its own inset. + if (channel.suspended) { + return ( + <> + + + + + + ); + } + + return ( + <> + + + + } + stats={ + + + } + > + + + + } + actions={ + + + + } + labels={channelHeaderLabels(t, i18n.getFixedT(null, 'common'))} + /> + + + + } + > + + + + + + + ); +} diff --git a/apps/bull/src/app/(main)/channels/[username]/templates/channel-template/index.ts b/apps/bull/src/app/(main)/channels/[username]/templates/channel-template/index.ts new file mode 100644 index 0000000..2c54681 --- /dev/null +++ b/apps/bull/src/app/(main)/channels/[username]/templates/channel-template/index.ts @@ -0,0 +1,2 @@ +export { ChannelTemplate } from './ChannelTemplate'; +export type { ChannelTemplateProps } from './types'; diff --git a/apps/bull/src/app/(main)/channels/[username]/templates/channel-template/types.ts b/apps/bull/src/app/(main)/channels/[username]/templates/channel-template/types.ts new file mode 100644 index 0000000..8f8764a --- /dev/null +++ b/apps/bull/src/app/(main)/channels/[username]/templates/channel-template/types.ts @@ -0,0 +1,9 @@ +import type { PublicCreatorPayload } from '@lumina/market/features/channel'; + +export type ChannelTemplateProps = { + channel: PublicCreatorPayload; + /** «lumina.ir/@sara_gold». */ + channelUrl: string; + /** The render's time: the posts' relative times count from it. */ + now: string; +}; diff --git a/apps/bull/src/app/(main)/dashboard/(investor)/following/loading.tsx b/apps/bull/src/app/(main)/dashboard/(investor)/following/loading.tsx new file mode 100644 index 0000000..71ebc25 --- /dev/null +++ b/apps/bull/src/app/(main)/dashboard/(investor)/following/loading.tsx @@ -0,0 +1,15 @@ +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; + +import { i18n } from '../../../../../i18n'; + +/** The list before it arrives, row for row; the layout keeps the bar and the tabs. */ +export default function Loading() { + return ( + + ); +} diff --git a/apps/bull/src/app/(main)/dashboard/(investor)/following/page.tsx b/apps/bull/src/app/(main)/dashboard/(investor)/following/page.tsx new file mode 100644 index 0000000..b34f752 --- /dev/null +++ b/apps/bull/src/app/(main)/dashboard/(investor)/following/page.tsx @@ -0,0 +1,43 @@ +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; +import { PartBoundary } from '@lumina/market/app/error-boundaries'; +import { AuthGuard } from '@lumina/market/app/guards/auth-guard'; +import { FollowingList } from '@lumina/market/app/screens/(main)/dashboard/following/organisms/following-list'; +import type { Metadata } from 'next'; +import { Suspense } from 'react'; + +import { i18n } from '../../../../../i18n'; + +export function generateMetadata(): Metadata { + return { + title: i18n.t('dashboard:following.meta-title'), + robots: { index: false }, + }; +} + +/** + * داشبورد › دنبال‌شده‌ها (U8 §۴): the investor's own list, in the browser only, behind rows of the + * same size. A failed read shows in place of the list; the bar and the tabs stay (U8 ۴.۵). + */ +export default function FollowingPage() { + const skeleton = ( + + ); + + return ( + + + + + + + + ); +} diff --git a/apps/bull/src/app/(main)/dashboard/(investor)/layout.tsx b/apps/bull/src/app/(main)/dashboard/(investor)/layout.tsx new file mode 100644 index 0000000..d69e698 --- /dev/null +++ b/apps/bull/src/app/(main)/dashboard/(investor)/layout.tsx @@ -0,0 +1,27 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { MobileTopBar } from '@lumina/market/app/navigation'; +import { DashboardTabs } from '@lumina/market/app/screens/(main)/dashboard/organisms/dashboard-tabs'; +import type { ReactNode } from 'react'; + +import { i18n } from '../../../../i18n'; + +/** + * The investor's داشبورد on mobile (U8 ۴.۱; U2): the tab bar «داشبورد», the section row + * «اشتراک‌ها» · «تراکنش‌ها» · «دنبال‌شده‌ها», then the section. Each section is its own route with + * its own loading, so the bar and the row stay while one loads. + */ +export default function InvestorDashboardLayout({ + children, +}: { + children: ReactNode; +}) { + return ( + <> + + + + {children} + + + ); +} diff --git a/apps/bear/src/app/(main)/dashboard/following/.gitkeep b/apps/bull/src/app/(main)/dashboard/(investor)/subscriptions/.gitkeep similarity index 100% rename from apps/bear/src/app/(main)/dashboard/following/.gitkeep rename to apps/bull/src/app/(main)/dashboard/(investor)/subscriptions/.gitkeep diff --git a/apps/bear/src/app/(main)/dashboard/subscriptions/.gitkeep b/apps/bull/src/app/(main)/dashboard/(investor)/transactions/.gitkeep similarity index 100% rename from apps/bear/src/app/(main)/dashboard/subscriptions/.gitkeep rename to apps/bull/src/app/(main)/dashboard/(investor)/transactions/.gitkeep diff --git a/apps/bull/src/app/(main)/dashboard/following/.gitkeep b/apps/bull/src/app/(main)/dashboard/following/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/apps/bull/src/app/(main)/dashboard/subscriptions/.gitkeep b/apps/bull/src/app/(main)/dashboard/subscriptions/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/apps/bull/src/app/(main)/dashboard/transactions/.gitkeep b/apps/bull/src/app/(main)/dashboard/transactions/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/apps/bull/src/app/(main)/layout.tsx b/apps/bull/src/app/(main)/layout.tsx new file mode 100644 index 0000000..04d8392 --- /dev/null +++ b/apps/bull/src/app/(main)/layout.tsx @@ -0,0 +1,13 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { BottomNav } from '@lumina/market/app/navigation'; +import type { ReactNode } from 'react'; + +/** The main pages on mobile: each page brings its top bar; the bottom nav is shared. */ +export default function MainLayout({ children }: { children: ReactNode }) { + return ( + + {children} + + + ); +} diff --git a/apps/bull/src/configs/index.ts b/apps/bull/src/configs/index.ts index bc4704f..fe4fde0 100644 --- a/apps/bull/src/configs/index.ts +++ b/apps/bull/src/configs/index.ts @@ -1,2 +1,3 @@ export { getQueryClient } from './react-query'; export { rootMetadata } from './seo'; +export { displayUrl } from './site'; diff --git a/apps/bull/src/configs/site.ts b/apps/bull/src/configs/site.ts new file mode 100644 index 0000000..44db08e --- /dev/null +++ b/apps/bull/src/configs/site.ts @@ -0,0 +1,6 @@ +import { clientEnv } from '../env'; + +/** A path on this site as people read and type it, without the scheme: «lumina.ir/@sara_gold». */ +export function displayUrl(path: string): string { + return `${new URL(clientEnv.NEXT_PUBLIC_SITE_URL).host}${path}`; +} diff --git a/platforms/market/src/app/app-shell/AppShell.tsx b/platforms/market/src/app/app-shell/AppShell.tsx index fae378f..21b038f 100644 --- a/platforms/market/src/app/app-shell/AppShell.tsx +++ b/platforms/market/src/app/app-shell/AppShell.tsx @@ -2,8 +2,10 @@ import { Toaster } from '@lumina/island/molecules/toast'; import { QueryClientProvider } from '@tanstack/react-query'; +import { useEffect } from 'react'; import { I18nextProvider } from 'react-i18next'; +import { usePostDraftStore } from '../../stores/post-draft'; import { NetworkBoundary } from './components/NetworkBoundary'; import { useSession } from './hooks/use-session'; import type { AppShellProps } from './types'; @@ -15,6 +17,10 @@ import type { AppShellProps } from './types'; */ export function AppShell({ queryClient, i18n, children }: AppShellProps) { useSession(queryClient); + // Persisted stores wait for the first browser render, so it matches the server's. + useEffect(() => { + void usePostDraftStore.persist.rehydrate(); + }, []); return ( diff --git a/platforms/market/src/app/app-shell/hooks/use-session.ts b/platforms/market/src/app/app-shell/hooks/use-session.ts index b936c01..98b09f9 100644 --- a/platforms/market/src/app/app-shell/hooks/use-session.ts +++ b/platforms/market/src/app/app-shell/hooks/use-session.ts @@ -1,17 +1,19 @@ import { handleError } from '@lumina/libs/error-handler'; import { eventEmitter } from '@lumina/libs/event-emitter'; +import { storage } from '@lumina/libs/local-storage'; import type { QueryClient } from '@tanstack/react-query'; import { useEffect } from 'react'; import { AUTH_EVENTS, restoreSession } from '../../../features/auth'; import { useAuthStore } from '../../../stores/auth'; +import { usePostDraftStore } from '../../../stores/post-draft'; /** * The browser learns who the viewer is once per page load; auth-dependent parts wait in their * skeleton until then. A read that failed offline or on a gateway error leaves the viewer unknown, * so it runs again when the connection comes back. When the session ends (sign-out, or a refresh * that failed), the store goes back to guest and every cached query is dropped: it belonged to the - * old account. + * old account, and so is what it kept on the device (`session.` keys). */ export function useSession(queryClient: QueryClient): void { useEffect(() => { @@ -27,6 +29,10 @@ export function useSession(queryClient: QueryClient): void { const offLogout = eventEmitter.on(AUTH_EVENTS.logout, () => { useAuthStore.getState().clearSession(); queryClient.clear(); + // The account's own drafts and choices stay with it, not with the device. The stores go + // first: a persisted store writes its key again on every change. + usePostDraftStore.getState().clearDraft(); + storage.clearByPrefix('session.'); }); return () => { window.removeEventListener('online', restoreIfUnknown); diff --git a/platforms/market/src/app/error-boundaries/error-fallback/ErrorFallback.tsx b/platforms/market/src/app/error-boundaries/error-fallback/ErrorFallback.tsx index 64f44ef..e66fbce 100644 --- a/platforms/market/src/app/error-boundaries/error-fallback/ErrorFallback.tsx +++ b/platforms/market/src/app/error-boundaries/error-fallback/ErrorFallback.tsx @@ -1,5 +1,6 @@ 'use client'; +import { Card } from '@lumina/island/molecules/card'; import { ErrorState } from '@lumina/island/molecules/error-state'; import { classifyError, @@ -7,6 +8,7 @@ import { handleError, } from '@lumina/libs/error-handler'; import { useEffect, useRef } from 'react'; +import type { ReactNode } from 'react'; import { useTranslation } from 'react-i18next'; import { StatusEmptyState } from '../status-empty-state'; @@ -17,13 +19,17 @@ import { errorKind } from './utils'; * What every boundary renders. A silent error (aborted, or a 401 already redirecting) shows * nothing; a 404 or 403 read shows its empty state; anything else shows ErrorState with Try again * for a network cause or Reload page for a bug, and the reference ID. It reports the error once, - * and a page or app fallback moves focus to its heading. + * and a page or app fallback moves focus to its heading. A framed part sits in a Card, as the + * boards draw a section's error (S3-03, U8 ۴.۵). */ export function ErrorFallback({ error, size, name, onRetry, + title, + description, + framed = false, }: ErrorFallbackProps) { const { t } = useTranslation('errors'); const headingRef = useRef(null); @@ -35,13 +41,14 @@ export function ErrorFallback({ }, [error, size, name]); if (read === 'silent') return null; + const frame = (state: ReactNode) => (framed ? {state} : state); if (read !== 'boundary') { - return ( + return frame( + />, ); } @@ -49,19 +56,21 @@ export function ErrorFallback({ // Only the reference ID is read here, so no copy goes through a translator. const { referenceId } = describeError(error, (key) => key); const isBug = cause === 'logic'; + // Offline keeps its own copy: it says the page updates by itself once the device is back. + const ownDescription = kind === 'offline' ? undefined : description; - return ( + return frame( window.location.reload() : onRetry} retryLabel={isBug ? t('fallback.reload') : t('fallback.retry')} digest={referenceId} digestLabel={t('fallback.reference')} - /> + />, ); } diff --git a/platforms/market/src/app/error-boundaries/error-fallback/types.ts b/platforms/market/src/app/error-boundaries/error-fallback/types.ts index 7e018ea..031aac4 100644 --- a/platforms/market/src/app/error-boundaries/error-fallback/types.ts +++ b/platforms/market/src/app/error-boundaries/error-fallback/types.ts @@ -16,4 +16,12 @@ export type ErrorFallbackProps = { name?: string; /** Try again: resets the failed queries, then the boundary. */ onRetry?: () => void; + /** + * A part's own copy for a failure it can be retried from; empty states keep theirs, and offline + * keeps its description. + */ + title?: string; + description?: string; + /** Sits in a Card, where the board draws the part's error as a card (S3-03, U8 ۴.۵). */ + framed?: boolean; }; diff --git a/platforms/market/src/app/error-boundaries/part-boundary/PartBoundary.tsx b/platforms/market/src/app/error-boundaries/part-boundary/PartBoundary.tsx index 0c95125..e85cc97 100644 --- a/platforms/market/src/app/error-boundaries/part-boundary/PartBoundary.tsx +++ b/platforms/market/src/app/error-boundaries/part-boundary/PartBoundary.tsx @@ -8,7 +8,7 @@ import { ErrorFallback } from '../error-fallback'; import type { PartBoundaryProps } from './types'; function PartFallback( - { name }: PartBoundaryProps, + { name, title, description, framed }: PartBoundaryProps, { error, retry, reset }: ErrorInfo, ) { const queryErrors = useQueryErrorResetBoundary(); @@ -21,6 +21,9 @@ function PartFallback( error={error} size="part" name={name} + title={title} + description={description} + framed={framed} onRetry={() => { queryErrors.reset(); if (isServerError) retry(); diff --git a/platforms/market/src/app/error-boundaries/part-boundary/types.ts b/platforms/market/src/app/error-boundaries/part-boundary/types.ts index 15b640e..a3c4d12 100644 --- a/platforms/market/src/app/error-boundaries/part-boundary/types.ts +++ b/platforms/market/src/app/error-boundaries/part-boundary/types.ts @@ -1,4 +1,12 @@ export type PartBoundaryProps = { /** The part, for the error report: «creator-stats», «feed». Never personal data. */ name: string; + /** + * The part's own failure copy, such as «عملکرد پیش‌بینی‌ها بارگذاری نشد» / «بقیه کانال در دسترس + * است…» (S3); without it the fallback says what every part says. + */ + title?: string; + description?: string; + /** The fallback sits in a Card, where the board draws the part's error as a card (S3-03). */ + framed?: boolean; }; diff --git a/platforms/market/src/app/navigation/active-tab.ts b/platforms/market/src/app/navigation/active-tab.ts new file mode 100644 index 0000000..c1874c0 --- /dev/null +++ b/platforms/market/src/app/navigation/active-tab.ts @@ -0,0 +1,33 @@ +import { + CHANNEL_PREFIX, + CHANNEL_ROUTE_PREFIX, + DASHBOARD_PATH, +} from './constants'; +import type { NavTabName } from './types'; + +/** + * The creator's own channel or a page under it, by its public path or the route it is rewritten + * onto, depending on who reads it. + */ +export function isOwnChannelPath( + pathname: string, + ownUsername: string, +): boolean { + return [CHANNEL_PREFIX, CHANNEL_ROUTE_PREFIX].some((prefix) => { + const channel = `${prefix}${ownUsername}`; + return pathname === channel || pathname.startsWith(`${channel}/`); + }); +} + +/** + * The tab a page belongs to: the one it was pushed from. داشبورد for its own pages, کانال for the + * creator's own channel and its posts, and خانه for everything else (a channel, a post). + */ +export function activeTab( + pathname: string, + ownUsername: string | null, +): NavTabName { + if (pathname.startsWith(DASHBOARD_PATH)) return 'dashboard'; + if (ownUsername && isOwnChannelPath(pathname, ownUsername)) return 'channel'; + return 'home'; +} diff --git a/platforms/market/src/app/navigation/components/.gitkeep b/platforms/market/src/app/navigation/components/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/app/navigation/components/bottom-nav/BottomNav.tsx b/platforms/market/src/app/navigation/components/bottom-nav/BottomNav.tsx new file mode 100644 index 0000000..beec0e5 --- /dev/null +++ b/platforms/market/src/app/navigation/components/bottom-nav/BottomNav.tsx @@ -0,0 +1,75 @@ +'use client'; + +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Element } from '@lumina/island/primitives/element'; +import { usePathname } from 'next/navigation'; +import { useTranslation } from 'react-i18next'; + +import { useCurrentAccount, useViewerStatus } from '../../../../stores/auth'; +import { activeTab } from '../../active-tab'; +import { useIsOwnPreview } from '../../hooks/use-is-own-preview'; +import { ROUTES } from '../../navigation'; +import { PublishMenu } from '../publish-menu'; +import { NavTab } from './components/NavTab'; + +/** + * The mobile bottom nav of a signed-in person, on tab screens and the pages pushed from them, with + * the tab they came from active. An investor: خانه · داشبورد. A creator: کانال · «انتشار» · + * داشبورد. A guest gets none; until the viewer is known nothing renders, and the bar is fixed, so + * the page doesn't move when it appears. + */ +export function BottomNav() { + const { t } = useTranslation(); + const status = useViewerStatus(); + const account = useCurrentAccount(); + const pathname = usePathname(); + const isPreview = useIsOwnPreview(); + + if (status !== 'member' || !account || isPreview) return null; + const isCreator = account.role === 'creator'; + const active = activeTab(pathname, isCreator ? account.username : null); + + return ( + <> + {/* Keeps the page's end clear of the fixed bar. */} + + + {isCreator ? ( + + ) : ( + + )} + {isCreator && ( + + + + )} + + + + ); +} diff --git a/platforms/market/src/app/navigation/components/bottom-nav/components/NavTab.tsx b/platforms/market/src/app/navigation/components/bottom-nav/components/NavTab.tsx new file mode 100644 index 0000000..c3fa055 --- /dev/null +++ b/platforms/market/src/app/navigation/components/bottom-nav/components/NavTab.tsx @@ -0,0 +1,35 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Typography } from '@lumina/island/atoms/typography'; +import { cn } from '@lumina/island/tools/cn'; +import NextLink from 'next/link'; + +import type { NavTabProps } from '../types'; + +/** One tab: its icon over its name, the active one in the brand colour. */ +export function NavTab({ href, icon, label, isActive }: NavTabProps) { + return ( + + + + {label} + + + ); +} diff --git a/platforms/market/src/app/navigation/components/bottom-nav/index.ts b/platforms/market/src/app/navigation/components/bottom-nav/index.ts new file mode 100644 index 0000000..e14162a --- /dev/null +++ b/platforms/market/src/app/navigation/components/bottom-nav/index.ts @@ -0,0 +1 @@ +export { BottomNav } from './BottomNav'; diff --git a/platforms/market/src/app/navigation/components/bottom-nav/types.ts b/platforms/market/src/app/navigation/components/bottom-nav/types.ts new file mode 100644 index 0000000..84f050e --- /dev/null +++ b/platforms/market/src/app/navigation/components/bottom-nav/types.ts @@ -0,0 +1,8 @@ +import type { IconName } from '@lumina/island/atoms/icon'; + +export type NavTabProps = { + href: string; + icon: IconName; + label: string; + isActive: boolean; +}; diff --git a/platforms/market/src/app/navigation/components/desktop-header/DesktopHeader.tsx b/platforms/market/src/app/navigation/components/desktop-header/DesktopHeader.tsx new file mode 100644 index 0000000..5eee537 --- /dev/null +++ b/platforms/market/src/app/navigation/components/desktop-header/DesktopHeader.tsx @@ -0,0 +1,117 @@ +'use client'; + +import { Avatar } from '@lumina/island/atoms/avatar'; +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { GridBox } from '@lumina/island/atoms/grid-box'; +import { Skeleton } from '@lumina/island/atoms/skeleton'; +import { Typography } from '@lumina/island/atoms/typography'; +import NextLink from 'next/link'; +import { usePathname } from 'next/navigation'; +import { useTranslation } from 'react-i18next'; + +import { useCurrentAccount, useViewerStatus } from '../../../../stores/auth'; +import { SupportEntry } from '../../../screens/organisms/support-entry'; +import { activeTab } from '../../active-tab'; +import { loginRoute, ROUTES } from '../../navigation'; +import { PublishMenu } from '../publish-menu'; +import { HeaderNavLink } from './components/HeaderNavLink'; + +/** + * The desktop header on every main page: the brand, the nav, then support and the account at the + * end. An investor's nav is خانه · داشبورد; a creator's is کانال · داشبورد, with «انتشار» before + * support. A guest sees only the brand, support and «ورود/ثبت‌نام», which returns here. The brand + * goes home, or to a creator's own channel. Who is looking is known only in the browser; until then + * the account's place is a skeleton. + */ +export function DesktopHeader() { + const { t } = useTranslation(); + const status = useViewerStatus(); + const account = useCurrentAccount(); + const pathname = usePathname(); + const isCreator = account?.role === 'creator'; + const active = activeTab(pathname, isCreator ? account.username : null); + + return ( + + + {t('nav.brand')} + + {status === 'member' && account && ( + + {isCreator ? ( + + ) : ( + + )} + + + )} + + {isCreator && } + + {status === 'unknown' && ( + // The account link's size, so the end doesn't move when the session arrives. + + + + )} + {status === 'guest' && ( + + )} + {status === 'member' && account && ( + + + + )} + + + ); +} diff --git a/platforms/market/src/app/navigation/components/desktop-header/components/HeaderNavLink.tsx b/platforms/market/src/app/navigation/components/desktop-header/components/HeaderNavLink.tsx new file mode 100644 index 0000000..da3be95 --- /dev/null +++ b/platforms/market/src/app/navigation/components/desktop-header/components/HeaderNavLink.tsx @@ -0,0 +1,23 @@ +import { Typography } from '@lumina/island/atoms/typography'; +import { cn } from '@lumina/island/tools/cn'; +import NextLink from 'next/link'; + +import type { HeaderNavLinkProps } from '../types'; + +/** A 40px pill in the header nav; the active one on the brand's subtle fill. */ +export function HeaderNavLink({ href, label, isActive }: HeaderNavLinkProps) { + return ( + + {label} + + ); +} diff --git a/platforms/market/src/app/navigation/components/desktop-header/index.ts b/platforms/market/src/app/navigation/components/desktop-header/index.ts new file mode 100644 index 0000000..38143d5 --- /dev/null +++ b/platforms/market/src/app/navigation/components/desktop-header/index.ts @@ -0,0 +1 @@ +export { DesktopHeader } from './DesktopHeader'; diff --git a/platforms/market/src/app/navigation/components/desktop-header/types.ts b/platforms/market/src/app/navigation/components/desktop-header/types.ts new file mode 100644 index 0000000..0de7078 --- /dev/null +++ b/platforms/market/src/app/navigation/components/desktop-header/types.ts @@ -0,0 +1,5 @@ +export type HeaderNavLinkProps = { + href: string; + label: string; + isActive: boolean; +}; diff --git a/platforms/market/src/app/navigation/components/mobile-top-bar/MobileTopBar.tsx b/platforms/market/src/app/navigation/components/mobile-top-bar/MobileTopBar.tsx new file mode 100644 index 0000000..b0a7a6d --- /dev/null +++ b/platforms/market/src/app/navigation/components/mobile-top-bar/MobileTopBar.tsx @@ -0,0 +1,118 @@ +'use client'; + +import { Avatar } from '@lumina/island/atoms/avatar'; +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { GridBox } from '@lumina/island/atoms/grid-box'; +import { Skeleton } from '@lumina/island/atoms/skeleton'; +import { Typography } from '@lumina/island/atoms/typography'; +import NextLink from 'next/link'; +import { usePathname } from 'next/navigation'; +import { useTranslation } from 'react-i18next'; + +import { useCurrentAccount, useViewerStatus } from '../../../../stores/auth'; +import { SupportEntry } from '../../../screens/organisms/support-entry'; +import { useIsOwnPreview } from '../../hooks/use-is-own-preview'; +import { loginRoute, ROUTES } from '../../navigation'; +import { BackButton } from './components/BackButton'; +import { Brand } from './components/Brand'; +import type { MobileTopBarProps } from './types'; + +/** + * The mobile top bar of a page pushed from a tab: back, the page's name and support. A guest sees + * the logged-out bar instead (the brand, support and «ورود/ثبت‌نام», which returns here). A tab's + * main screen, and a creator on their own tab, get the tab bar: the brand, the tab's name centred + * when it has one («داشبورد»; خانه has none), support and the member's account (Main A, U8 ۴.۱). + * Who is looking is known only in the browser, so the server and the first browser render show a + * tab's bar with its brand and name and a placeholder where the account goes, and a pushed page's + * bar without its start. A creator's brand goes to their own channel, their home tab. + */ +export function MobileTopBar({ + title, + isTab = false, + tabOwnerId, + onBack, + previewTitle, +}: MobileTopBarProps) { + const { t } = useTranslation(); + const status = useViewerStatus(); + const account = useCurrentAccount(); + const pathname = usePathname(); + const isPreview = useIsOwnPreview(); + // While the viewer is unknown, account is null, so only a tab's main screen gets the tab bar. + const isTabBar = isTab || (account != null && account.id === tabOwnerId); + + return ( + + {status === 'unknown' && !isTabBar && ( + + + + )} + {(status === 'guest' || isTabBar) && ( + + )} + {status !== 'guest' && isTab && title && ( + + {title} + + )} + {status === 'member' && !isTabBar && ( + <> + + + {isPreview && previewTitle ? previewTitle : title} + + + )} + + {status === 'guest' && ( + + )} + {status === 'unknown' && isTabBar && ( + + + + )} + {status === 'member' && isTabBar && account && ( + + + + )} + + ); +} diff --git a/platforms/market/src/app/navigation/components/mobile-top-bar/components/BackButton.tsx b/platforms/market/src/app/navigation/components/mobile-top-bar/components/BackButton.tsx new file mode 100644 index 0000000..ad55588 --- /dev/null +++ b/platforms/market/src/app/navigation/components/mobile-top-bar/components/BackButton.tsx @@ -0,0 +1,27 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { useRouter } from 'next/navigation'; + +import { ROUTES } from '../../../navigation'; +import type { BackButtonProps } from '../types'; + +/** + * Back to where the person came from; a page opened on its own (a shared link) goes home. A page + * that may lose work passes `onBack` and asks first. + */ +export function BackButton({ label, onBack }: BackButtonProps) { + const router = useRouter(); + return ( + + setIsOpen(false)} + label={t('publish.menu')} + placement={placement === 'nav' ? 'above' : 'below'} + items={[ + { href: ROUTES.composePost, icon: 'edit', label: t('publish.post') }, + { + href: ROUTES.composePrediction, + icon: 'trend-up', + label: t('publish.prediction'), + }, + ]} + /> + {blocked && ( + setIsExplaining(false)} + layout={placement === 'nav' ? 'mobile' : 'desktop'} + /> + )} + + ); +} diff --git a/platforms/market/src/app/navigation/components/publish-menu/components/BlockedPublishDialog.tsx b/platforms/market/src/app/navigation/components/publish-menu/components/BlockedPublishDialog.tsx new file mode 100644 index 0000000..eb547e0 --- /dev/null +++ b/platforms/market/src/app/navigation/components/publish-menu/components/BlockedPublishDialog.tsx @@ -0,0 +1,84 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { GridBox } from '@lumina/island/atoms/grid-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Modal } from '@lumina/island/molecules/modal'; +import { Sheet } from '@lumina/island/molecules/sheet'; +import { cn } from '@lumina/island/tools/cn'; +import { useTranslation } from 'react-i18next'; + +import { SupportEntry } from '../../../../screens/organisms/support-entry'; +import { ROUTES } from '../../../navigation'; +import { BLOCKED_ART } from '../constants'; +import type { BlockedPublishDialogProps } from '../types'; + +/** + * Why «انتشار» can't publish (C4 ۲.۱–۲.۳), with the one way forward: the identity review's status, + * resubmitting it, or support for a suspended account. «بستن» under it; no ✕. + */ +export function BlockedPublishDialog({ + standing, + open, + onClose, + layout, +}: BlockedPublishDialogProps) { + const { t } = useTranslation(); + const size = layout === 'mobile' ? 'lg' : undefined; + const art = BLOCKED_ART[standing]; + const icon = ( + + + + ); + const next = + standing === 'suspended' ? ( + + ) : ( + + ); + const buttons = ( + <> + {next} + + + ); + const body = ( + {t(`publish.${standing}.reason`)} + ); + + return layout === 'mobile' ? ( + + {body} + + ) : ( + + {body} + + ); +} diff --git a/platforms/market/src/app/navigation/components/publish-menu/constants.ts b/platforms/market/src/app/navigation/components/publish-menu/constants.ts new file mode 100644 index 0000000..abb283c --- /dev/null +++ b/platforms/market/src/app/navigation/components/publish-menu/constants.ts @@ -0,0 +1,16 @@ +import type { IconName } from '@lumina/island/atoms/icon'; + +import type { BlockedStanding } from './types'; + +/** Each blocked standing's art: its icon and its tile's tone. */ +export const BLOCKED_ART: Record< + BlockedStanding, + { icon: IconName; className: string } +> = { + pending: { + icon: 'clock', + className: 'bg-surface-sunken text-text-secondary', + }, + rejected: { icon: 'alert', className: 'bg-danger-subtle text-danger-text' }, + suspended: { icon: 'lock', className: 'bg-surface-sunken text-text-primary' }, +}; diff --git a/platforms/market/src/app/navigation/components/publish-menu/index.ts b/platforms/market/src/app/navigation/components/publish-menu/index.ts new file mode 100644 index 0000000..61b8637 --- /dev/null +++ b/platforms/market/src/app/navigation/components/publish-menu/index.ts @@ -0,0 +1,2 @@ +export { PublishMenu } from './PublishMenu'; +export type { PublishMenuProps } from './types'; diff --git a/platforms/market/src/app/navigation/components/publish-menu/types.ts b/platforms/market/src/app/navigation/components/publish-menu/types.ts new file mode 100644 index 0000000..3c80c2a --- /dev/null +++ b/platforms/market/src/app/navigation/components/publish-menu/types.ts @@ -0,0 +1,19 @@ +import type { CreatorStanding } from '../../../../features/profile'; + +export type PublishMenuProps = { + /** nav: the mobile FAB, its menu above it. header: the desktop button, its menu below. */ + placement: 'nav' | 'header'; +}; + +/** A creator who may not publish yet, or at all. */ +export type BlockedStanding = Extract< + CreatorStanding, + 'pending' | 'rejected' | 'suspended' +>; + +export type BlockedPublishDialogProps = { + standing: BlockedStanding; + open: boolean; + onClose: () => void; + layout: 'mobile' | 'desktop'; +}; diff --git a/platforms/market/src/app/navigation/constants.ts b/platforms/market/src/app/navigation/constants.ts index 1a53078..f60415e 100644 --- a/platforms/market/src/app/navigation/constants.ts +++ b/platforms/market/src/app/navigation/constants.ts @@ -1,5 +1,14 @@ /** The public channel URL prefix; next.config rewrites `/@username` onto `channels/[username]`. */ export const CHANNEL_PREFIX = '/@'; +/** The App Router's own path for a channel, which `/@username` is rewritten onto. */ +export const CHANNEL_ROUTE_PREFIX = '/channels/'; + +/** `?preview=visitor|subscriber`: the creator's preview of their own post as others see it (C5 §6). */ +export const PREVIEW_PARAM = 'preview'; + /** Login's query parameter naming the channel a guest wants to subscribe to. */ export const SUBSCRIBE_PARAM = 'subscribe'; + +/** The investor's dashboard and the creator's live under one path; it marks داشبورد active. */ +export const DASHBOARD_PATH = '/dashboard'; diff --git a/platforms/market/src/app/navigation/hooks/use-is-own-preview.ts b/platforms/market/src/app/navigation/hooks/use-is-own-preview.ts new file mode 100644 index 0000000..56f36a7 --- /dev/null +++ b/platforms/market/src/app/navigation/hooks/use-is-own-preview.ts @@ -0,0 +1,22 @@ +import { usePathname, useSearchParams } from 'next/navigation'; + +import { useCurrentAccount } from '../../../stores/auth'; +import { isOwnChannelPath } from '../active-tab'; +import { PREVIEW_PARAM } from '../constants'; + +/** + * The creator previewing a post of their own channel (`?preview`): a task flow, so the nav steps + * aside and the top bar says so (R8). Anyone else opening the same link gets the usual chrome, + * as the post page shows them no preview. + */ +export function useIsOwnPreview(): boolean { + const account = useCurrentAccount(); + const pathname = usePathname(); + const hasPreview = useSearchParams().has(PREVIEW_PARAM); + return ( + hasPreview && + account?.role === 'creator' && + isOwnChannelPath(pathname, account.username) && + pathname.includes('/posts/') + ); +} diff --git a/platforms/market/src/app/navigation/index.ts b/platforms/market/src/app/navigation/index.ts index 5d8c640..71ea435 100644 --- a/platforms/market/src/app/navigation/index.ts +++ b/platforms/market/src/app/navigation/index.ts @@ -1,4 +1,8 @@ -export { CHANNEL_PREFIX } from './constants'; +export { BottomNav } from './components/bottom-nav'; +export { DesktopHeader } from './components/desktop-header'; +export { MobileTopBar } from './components/mobile-top-bar'; +export type { MobileTopBarProps } from './components/mobile-top-bar'; +export { CHANNEL_PREFIX, PREVIEW_PARAM } from './constants'; export { useAuthRoutes } from './hooks/use-auth-routes'; export { loginRoute, diff --git a/platforms/market/src/app/navigation/navigation.ts b/platforms/market/src/app/navigation/navigation.ts index 3cada10..5890822 100644 --- a/platforms/market/src/app/navigation/navigation.ts +++ b/platforms/market/src/app/navigation/navigation.ts @@ -24,6 +24,8 @@ export const ROUTES = { checkout: (username: string) => `/checkout/${encodeURIComponent(username)}`, paymentReturn: '/payment/return', composePost: '/compose/post', + /** The composer on a published post of the creator's own, for its first 15 minutes. */ + editPost: (id: string) => `/compose/post/${encodeURIComponent(id)}`, composePrediction: '/compose/prediction', dashboard: { subscriptions: '/dashboard/subscriptions', diff --git a/platforms/market/src/app/navigation/types.ts b/platforms/market/src/app/navigation/types.ts index 5f9dac4..2017643 100644 --- a/platforms/market/src/app/navigation/types.ts +++ b/platforms/market/src/app/navigation/types.ts @@ -17,3 +17,6 @@ export type AuthRoutes = { /** The channel's username when a guest came to log in from «اشتراک», else `null`. */ subscribeTo: string | null; }; + +/** The bottom nav's and the desktop header's tabs; a page belongs to the one it was pushed from. */ +export type NavTabName = 'home' | 'dashboard' | 'channel'; diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/PostComposer.tsx b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/PostComposer.tsx new file mode 100644 index 0000000..5337d8d --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/PostComposer.tsx @@ -0,0 +1,30 @@ +'use client'; + +import { useCurrentAccount } from '../../../../../../../stores/auth'; +import { ComposerForm } from './components/ComposerForm'; +import { EditComposer } from './components/EditComposer'; +import type { PostComposerProps } from './types'; + +/** + * The creator's post composer, new or editing, in the browser only: the page wraps it in the + * creator-only guard, which shows the skeleton until the session is known. + */ +export function PostComposer({ layout, postId }: PostComposerProps) { + const account = useCurrentAccount(); + if (!account) return null; + + return postId ? ( + + ) : ( + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/PostComposerDialog.tsx b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/PostComposerDialog.tsx new file mode 100644 index 0000000..8e8bbcd --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/PostComposerDialog.tsx @@ -0,0 +1,26 @@ +'use client'; + +import { useCurrentAccount } from '../../../../../../../stores/auth'; +import { StatusEmptyState } from '../../../../../../error-boundaries'; +import { ComposerDialog } from './components/ComposerDialog'; +import { ComposerDialogPlaceholder } from './components/ComposerDialogPlaceholder'; + +/** + * «پست جدید» over the current page on desktop (C4 ۷.۳), for the route that intercepts + * /compose/post. The app wraps it in AuthGuard with `PostComposerDialogSkeleton`, so it renders + * once the browser knows a signed-in viewer. Only a creator gets the composer; anyone else gets the + * no-access state inside the same dialog, not AuthGuard's page-size one under the page. + */ +export function PostComposerDialog() { + const account = useCurrentAccount(); + if (!account) return null; + + if (account.role !== 'creator') { + return ( + + + + ); + } + return ; +} diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/PostComposerDialogSkeleton.tsx b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/PostComposerDialogSkeleton.tsx new file mode 100644 index 0000000..e061d36 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/PostComposerDialogSkeleton.tsx @@ -0,0 +1,20 @@ +'use client'; + +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; +import { useTranslation } from 'react-i18next'; + +import { ComposerDialogPlaceholder } from './components/ComposerDialogPlaceholder'; + +/** + * The «پست جدید» dialog until the browser knows the viewer: the same 640px frame with the form + * skeleton in its body, AuthGuard's fallback on the intercepted route. «انصراف» still closes it. + */ +export function PostComposerDialogSkeleton() { + const { t } = useTranslation('content'); + + return ( + + + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerBody.tsx b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerBody.tsx new file mode 100644 index 0000000..5a5e349 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerBody.tsx @@ -0,0 +1,132 @@ +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Banner } from '@lumina/island/molecules/banner'; +import { SegmentedChoice } from '@lumina/island/molecules/segmented-choice'; +import { TextInput } from '@lumina/island/molecules/text-input'; +import { number as formatNumber } from '@lumina/tools/format'; +import { useController } from 'react-hook-form'; +import { useTranslation } from 'react-i18next'; + +import { POST_LIMITS } from '../../../../../../../../features/post'; +import { translateMessage } from '../../../../../../../../shared/utils'; +import type { ComposerBodyProps } from '../types'; +import { ComposerImages } from './ComposerImages'; +import { ComposerLimit } from './ComposerLimit'; + +/** + * What a post holds, top to bottom: who sees it, the text, and the images. A failed save and a + * restored draft say so above them; while saving, everything holds still. On mobile the text + * counts itself under the field; on desktop (C4 ۷.۳) it is six rows, its count sits in the + * toolbar, and only the limit message stays under it (۳.۲). + */ +export function ComposerBody({ model, layout, picker }: ComposerBodyProps) { + const { t } = useTranslation('content'); + const { form, images, phase, mode } = model; + const isSaving = phase === 'saving'; + const isMobile = layout === 'mobile'; + const rows = layout === 'desktop' ? 6 : images.images.length > 0 ? 8 : 12; + const { field: access } = useController({ + control: form.control, + name: 'accessLevel', + }); + const captionError = form.formState.errors.caption?.message; + + return ( + + {model.restored && ( + + )} + {model.isEditExpired && ( + + )} + {model.submitError && ( + + {t('composer.retry')} + + } + > + {model.submitError} + + )} + + + + {mode === 'edit' && + model.minutesLeft !== null && + !model.isEditExpired && ( + + {t('composer.minutes-left', { + n: formatNumber(model.minutesLeft), + })} + + )} + + {access.value === 'premium' && ( + + + + {t('composer.premium-hint')} + + + )} + + + { + if (form.formState.errors.caption) form.clearErrors('caption'); + }, + })} + /> + {!isMobile && } + + + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerCount.tsx b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerCount.tsx new file mode 100644 index 0000000..9dab785 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerCount.tsx @@ -0,0 +1,29 @@ +import { Typography } from '@lumina/island/atoms/typography'; +import { cn } from '@lumina/island/tools/cn'; +import { number as formatNumber } from '@lumina/tools/format'; + +import { POST_LIMITS } from '../../../../../../../../features/post'; +import { useCaptionLength } from '../hooks/use-caption-length'; +import type { CaptionWatchProps } from '../types'; + +/** + * The caption's count in the desktop toolbar (C4 ۷.۳), «۱۷۸/۲۰۰۰» left to right, as TextInput + * draws its own: ruby at the limit (۳.۲). It pushes «انتشار» to the toolbar's end. + */ +export function ComposerCount({ control }: CaptionWatchProps) { + const length = useCaptionLength(control); + const atLimit = length >= POST_LIMITS.captionMaxLength; + + return ( + + {formatNumber(length)}/{formatNumber(POST_LIMITS.captionMaxLength)} + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerDialog.tsx b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerDialog.tsx new file mode 100644 index 0000000..46d5759 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerDialog.tsx @@ -0,0 +1,49 @@ +import { useQueryClient } from '@tanstack/react-query'; +import { useRef } from 'react'; + +import { + isChannelOnScreen, + usePostComposerPage, +} from '../../../../../../../../features/post'; +import { ROUTES } from '../../../../../../../navigation/navigation'; +import { useDialogRoute } from '../hooks/use-dialog-route'; +import type { ComposerDialogProps } from '../types'; +import { ComposerDialogFrame } from './ComposerDialogFrame'; +import { ComposerPanel } from './ComposerPanel'; +import { LeaveConfirm } from './LeaveConfirm'; + +/** + * A new post in the dialog over the current page (C4 ۷.۳). Escape, the scrim and «انصراف» close an + * empty one, and ask first about one with something to lose: the 420px question opens over it as + * its sibling (۷.۴), and «خروج» closes both and drops the draft. Published, it closes onto the + * creator's channel, the new post on top, with the success toast. + */ +export function ComposerDialog({ creatorId, username }: ComposerDialogProps) { + const picker = useRef(null); + const queryClient = useQueryClient(); + const channel = ROUTES.channel(username); + const route = useDialogRoute(channel); + const model = usePostComposerPage({ + creatorId, + // Opened over the creator's own channel: the dialog goes back to it. + onDone: () => + route.finish(channel, { + isUnder: isChannelOnScreen(queryClient, creatorId), + }), + onLeave: route.close, + }); + + return ( + <> + + + + + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerDialogFrame.tsx b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerDialogFrame.tsx new file mode 100644 index 0000000..7ac869b --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerDialogFrame.tsx @@ -0,0 +1,38 @@ +import { Button } from '@lumina/island/atoms/button'; +import { Modal } from '@lumina/island/molecules/modal'; +import { useTranslation } from 'react-i18next'; + +import type { ComposerDialogFrameProps } from '../types'; + +/** + * The new-post dialog's frame (C4 ۷.۳): 640px over the page, «پست جدید» with a ghost «انصراف» at + * the end of its header row, and the content edge to edge under the hairline. While publishing, + * Escape, the scrim and «انصراف» do nothing. + */ +export function ComposerDialogFrame({ + open, + onCancel, + onExited, + dismissible = true, + children, +}: ComposerDialogFrameProps) { + const { t } = useTranslation('content'); + + return ( + + {t('composer.cancel')} + + } + onClose={onCancel} + onExited={onExited} + dismissible={dismissible} + > + {children} + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerDialogPlaceholder.tsx b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerDialogPlaceholder.tsx new file mode 100644 index 0000000..4b75fd8 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerDialogPlaceholder.tsx @@ -0,0 +1,32 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; + +import { ROUTES } from '../../../../../../../navigation/navigation'; +import { useDialogRoute } from '../hooks/use-dialog-route'; +import type { ComposerDialogPlaceholderProps } from '../types'; +import { ComposerDialogFrame } from './ComposerDialogFrame'; + +/** + * The dialog while it can't hold the composer yet or at all: the skeleton until the browser knows + * the viewer, or the no-access state for anyone who isn't a creator. «انصراف», Escape and the + * scrim close it back to the page under it. + */ +export function ComposerDialogPlaceholder({ + children, +}: ComposerDialogPlaceholderProps) { + const route = useDialogRoute(ROUTES.home); + + return ( + + + {children} + + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerForm.tsx b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerForm.tsx new file mode 100644 index 0000000..cd1a7d8 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerForm.tsx @@ -0,0 +1,119 @@ +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Card } from '@lumina/island/molecules/card'; +import { useRouter } from 'next/navigation'; +import { useRef } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { usePostComposerPage } from '../../../../../../../../features/post'; +import { MobileTopBar } from '../../../../../../../navigation/components/mobile-top-bar'; +import { ROUTES } from '../../../../../../../navigation/navigation'; +import type { ComposerFormProps } from '../types'; +import { ComposerBody } from './ComposerBody'; +import { ComposerPanel } from './ComposerPanel'; +import { ComposerSubmit } from './ComposerSubmit'; +import { LeaveConfirm } from './LeaveConfirm'; + +/** + * The composer's frame on its own page. Mobile: a pushed page, back · title · support, a new post's + * ghost «انصراف» row under it (C4 ۱.۳), and «انتشار» pinned to the bottom; back and «انصراف» both + * ask first about something to lose (۳.۸). Desktop: a 640px card drawn as the «پست جدید» dialog + * (C4 ۷.۳), its title and «انصراف» in the header row over the same panel. Published, it lands on + * the creator's channel in the composer's place, the new post on top (۱.۷); saved, it goes back to + * where the edit was opened, showing the edit (۵.۳); left, it goes back. + */ +export function ComposerForm({ + layout, + creatorId, + username, + post, +}: ComposerFormProps) { + const { t } = useTranslation('content'); + const router = useRouter(); + const picker = useRef(null); + const model = usePostComposerPage({ + creatorId, + post, + onDone: (saved) => { + // Replaced, so back never reopens an empty composer. + if (!post) { + router.replace(ROUTES.channel(username)); + return; + } + // Back restores the page as the router kept it, from before the edit. The refresh drops + // those copies at once (the navigation then takes over from it), so that page is read again. + router.refresh(); + if (window.history.length > 1) router.back(); + else router.replace(ROUTES.post(username, saved.id)); + }, + onLeave: () => { + if (window.history.length > 1) router.back(); + else router.push(ROUTES.channel(username)); + }, + }); + const title = t(post ? 'composer.edit-title' : 'composer.new-title'); + + if (layout === 'mobile') { + return ( + + + + {/* Editing has its «انصراف» beside «ذخیره تغییرات» (C5 ۱.۵). */} + {!post && ( + + + + )} + + + + + + + + + + ); + } + + return ( + + + + {title} + + {!post && ( + + )} + + + + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerImages.tsx b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerImages.tsx new file mode 100644 index 0000000..91f9b36 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerImages.tsx @@ -0,0 +1,133 @@ +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { GridBox } from '@lumina/island/atoms/grid-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Element } from '@lumina/island/primitives/element'; +import { cn } from '@lumina/island/tools/cn'; +import { number as formatNumber } from '@lumina/tools/format'; +import type { ChangeEvent } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { IMAGE_ACCEPT } from '../constants'; +import type { ComposerImagesProps } from '../types'; +import { ImageThumb } from './ImageThumb'; + +/** + * The images: the thumbnails in the order they were picked with an add tile, and one line under + * them: the format rule, why a file was refused, a failed upload, or that four is the most. On + * mobile «افزودن تصویر» stands in for an empty strip; on desktop it lives in the toolbar and the + * thumbnails are 96px (C4 ۷.۳). The file input is the frame's `picker`, which both press. + */ +export function ComposerImages({ + images, + disabled, + layout, + picker, +}: ComposerImagesProps) { + const { t } = useTranslation('content'); + const isMobile = layout === 'mobile'; + const failed = images.images.findIndex((image) => image.status === 'failed'); + const pick = () => picker.current?.click(); + + const onPicked = (event: ChangeEvent) => { + if (event.target.files) images.add(Array.from(event.target.files)); + // The same file can be picked again after it was removed. + event.target.value = ''; + }; + + const line = + failed >= 0 ? ( + + {t('composer.images.failed', { n: formatNumber(failed + 1) })} + + ) : images.error === 'type' || images.error === 'size' ? ( + + {t(`composer.images.${images.error}`)} + + ) : !images.canAdd || images.error === 'count' ? ( + + + + {t('composer.images.count')} + + + ) : ( + + {t('composer.images.hint')} + + ); + + return ( + + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerLimit.tsx b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerLimit.tsx new file mode 100644 index 0000000..09692c0 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerLimit.tsx @@ -0,0 +1,32 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Typography } from '@lumina/island/atoms/typography'; +import { useTranslation } from 'react-i18next'; + +import { POST_LIMITS } from '../../../../../../../../features/post'; +import { useCaptionLength } from '../hooks/use-caption-length'; +import type { CaptionWatchProps } from '../types'; + +/** + * The desktop field at 2000 characters (C4 ۳.۲): «به حداکثر تعداد کاراکتر رسیدید.» under it, not a + * field error, while the toolbar count turns ruby. Mobile's TextInput says it with its own count. + */ +export function ComposerLimit({ control }: CaptionWatchProps) { + const { t } = useTranslation('content'); + const length = useCaptionLength(control); + if (length < POST_LIMITS.captionMaxLength) return null; + + return ( + + + + {t('composer.limit')} + + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerPanel.tsx b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerPanel.tsx new file mode 100644 index 0000000..78929fd --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerPanel.tsx @@ -0,0 +1,48 @@ +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { useTranslation } from 'react-i18next'; + +import type { ComposerPanelProps } from '../types'; +import { ComposerBody } from './ComposerBody'; +import { ComposerCount } from './ComposerCount'; +import { ComposerSubmit } from './ComposerSubmit'; + +/** + * The desktop composer under its header row (C4 ۷.۳), the same in the dialog and on the full page: + * the body scrolls, and the toolbar under it holds «افزودن تصویر», the count and «انتشار» (or + * «ذخیره تغییرات» with «انصراف»). At four images «افزودن تصویر» freezes and says why (۳.۵). + */ +export function ComposerPanel({ model, picker }: ComposerPanelProps) { + const { t } = useTranslation('content'); + const { images } = model; + + return ( + + + + + + + + + + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerSubmit.tsx b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerSubmit.tsx new file mode 100644 index 0000000..2282037 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ComposerSubmit.tsx @@ -0,0 +1,59 @@ +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { number as formatNumber } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { ComposerSubmitProps } from '../types'; + +/** + * «انتشار» (or «ذخیره تغییرات» beside «انصراف» when editing). It waits, frozen and saying why, for + * an upload in flight or a failed one. With no text and no image it is frozen too (C4 ۱.۳), yet a + * tap still checks the post and the field says what's missing (۳.۱); it goes live with either. + */ +export function ComposerSubmit({ model, layout }: ComposerSubmitProps) { + const { t } = useTranslation('content'); + const isEdit = model.mode === 'edit'; + const size = layout === 'mobile' ? 'lg' : undefined; + const frozenReason = + model.blocker?.kind === 'uploading' + ? t('composer.uploading-reason') + : model.blocker?.kind === 'failed' + ? t('composer.images.failed', { n: formatNumber(model.blocker.number) }) + : model.isEditExpired + ? t('composer.edit-expired') + : undefined; + + const submit = ( + + ); + + if (!isEdit) return submit; + return ( + + {submit} + + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/EditComposer.tsx b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/EditComposer.tsx new file mode 100644 index 0000000..d23f1a3 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/EditComposer.tsx @@ -0,0 +1,49 @@ +import { Button } from '@lumina/island/atoms/button'; +import { EmptyState } from '@lumina/island/molecules/empty-state'; +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; +import { useTranslation } from 'react-i18next'; + +import { useEditablePost } from '../../../../../../../../features/post'; +import { ROUTES } from '../../../../../../../navigation/navigation'; +import type { ComposerFormProps } from '../types'; +import { ComposerForm } from './ComposerForm'; + +/** Editing: the post loads first, then opens in the composer, or says why it can't be edited. */ +export function EditComposer({ + layout, + creatorId, + username, + postId, +}: Omit & { postId: string }) { + const { t } = useTranslation('content'); + const editable = useEditablePost(postId, creatorId); + + if (editable.status === 'pending') { + return ( + + ); + } + if (editable.status === 'not-editable') { + return ( + + + + ); + } + return ( + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ImageThumb.tsx b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ImageThumb.tsx new file mode 100644 index 0000000..affdfda --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/components/ImageThumb.tsx @@ -0,0 +1,100 @@ +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { GridBox } from '@lumina/island/atoms/grid-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Element } from '@lumina/island/primitives/element'; +import { cn } from '@lumina/island/tools/cn'; +import { number as formatNumber, percent } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { ImageThumbProps } from '../types'; + +/** + * One picked image: its preview, its upload progress as a bar and a percentage, or, failed, a + * danger frame that sends it again on tap. ✕ removes it, and cancels its upload. 76px on mobile, + * 96px in the desktop composer (C4 ۷.۳). + */ +export function ImageThumb({ + image, + number, + onRemove, + onRetry, + disabled, + layout, +}: ImageThumbProps) { + const { t } = useTranslation('content'); + const n = formatNumber(number); + const isFailed = image.status === 'failed'; + + return ( + + {isFailed ? ( + + + + {t('composer.images.thumb', { n })} + + + ) : ( + + )} + {image.status === 'uploading' && ( + + + {percent(image.progress, 0)} + + + + )} + + + + ); + + return layout === 'mobile' ? ( + + ) : ( + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/constants.ts b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/constants.ts new file mode 100644 index 0000000..1a033b2 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/constants.ts @@ -0,0 +1,2 @@ +/** What the file picker offers: the image types the API takes. */ +export const IMAGE_ACCEPT = 'image/jpeg,image/png,image/webp'; diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/hooks/use-caption-length.ts b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/hooks/use-caption-length.ts new file mode 100644 index 0000000..64271b4 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/hooks/use-caption-length.ts @@ -0,0 +1,16 @@ +import { useWatch } from 'react-hook-form'; +import type { Control } from 'react-hook-form'; + +import type { PostComposerFormValues } from '../../../../../../../../shared/validations'; + +/** + * The caption's length as it is typed, in UTF-16 units as the textarea's `maxLength`, the schema + * and TextInput's own count have it; only the component that calls it renders again on a + * keystroke. + */ +export function useCaptionLength( + control: Control, +): number { + const caption = useWatch({ control, name: 'caption' }); + return caption.length; +} diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/hooks/use-dialog-route.ts b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/hooks/use-dialog-route.ts new file mode 100644 index 0000000..e7113fb --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/hooks/use-dialog-route.ts @@ -0,0 +1,43 @@ +import { useRouter } from 'next/navigation'; +import { useState } from 'react'; + +import type { DialogRoute } from '../types'; + +/** + * The dialog that intercepts /compose/post plays its exit before its route changes. Closed, it goes + * back to the page under it, or to `fallback` when there is no history to go back to. Finished, it + * goes to `href` so back never reopens an empty composer, the `@modal` slot empties there, and + * `href` is read again from the server: back when `href` is the page under it, else in place of + * its own history entry. + */ +export function useDialogRoute(fallback: string): DialogRoute { + const router = useRouter(); + const [exit, setExit] = useState<'back' | 'done' | null>(null); + + return { + open: exit === null, + close: () => setExit('back'), + finish: (href, { isUnder = false } = {}) => { + setExit('done'); + if (isUnder) { + // Replacing would leave that page in history twice, and the next back would seem to do + // nothing. The refresh waits for the back to land, or it would read /compose/post again. + window.addEventListener('popstate', () => router.refresh(), { + once: true, + }); + router.back(); + return; + } + router.replace(href); + // Over the creator's own channel, `href` is the page already under the dialog: a navigation + // keeps a segment it already holds as rendered, so its first page would miss the new post. + // The refresh, queued after the replace, renders it again (as deleting a post does). + router.refresh(); + }, + onExited: () => { + if (exit !== 'back') return; + if (window.history.length > 1) router.back(); + else router.push(fallback); + }, + }; +} diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/index.ts b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/index.ts new file mode 100644 index 0000000..b476033 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/index.ts @@ -0,0 +1,4 @@ +export { PostComposer } from './PostComposer'; +export { PostComposerDialog } from './PostComposerDialog'; +export { PostComposerDialogSkeleton } from './PostComposerDialogSkeleton'; +export type { ComposerLayout, PostComposerProps } from './types'; diff --git a/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/types.ts b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/types.ts new file mode 100644 index 0000000..e03431d --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/compose/post/organisms/post-composer/types.ts @@ -0,0 +1,108 @@ +import type { ReactNode, RefObject } from 'react'; +import type { Control } from 'react-hook-form'; + +import type { + ComposerImage, + ComposerImagesModel, + PostComposerPageModel, + UnlockedPostPayload, +} from '../../../../../../../features/post'; +import type { PostComposerFormValues } from '../../../../../../../shared/validations'; + +export type ComposerLayout = 'mobile' | 'desktop'; + +export type PostComposerProps = { + /** + * mobile: a pushed page with a pinned footer. desktop: the 640px card under the header, with the + * same panel as the dialog (C4 ۷.۳). + */ + layout: ComposerLayout; + /** Edit this post (the creator's own, published); omitted for a new one. */ + postId?: string; +}; + +/** The file input behind every «افزودن تصویر»: the frame owns it, the body and toolbar press it. */ +export type ImagePickerRef = RefObject; + +export type ComposerFormProps = { + layout: ComposerLayout; + creatorId: string; + username: string; + post?: UnlockedPostPayload; +}; + +export type ComposerDialogProps = { + creatorId: string; + username: string; +}; + +export type ComposerDialogFrameProps = { + /** Until it starts closing. */ + open: boolean; + /** Escape, the scrim and «انصراف». */ + onCancel: () => void; + /** Closed: the route leaves the dialog. */ + onExited: () => void; + /** false while publishing: nothing closes it, and «انصراف» is disabled. */ + dismissible?: boolean; + /** Edge to edge under the header row: a `min-h-0` flex column, so its body scrolls. */ + children: ReactNode; +}; + +export type ComposerDialogPlaceholderProps = { children: ReactNode }; + +export type ComposerPanelProps = { + model: PostComposerPageModel; + picker: ImagePickerRef; +}; + +export type ComposerBodyProps = { + model: PostComposerPageModel; + layout: ComposerLayout; + picker: ImagePickerRef; +}; + +export type ComposerImagesProps = { + images: ComposerImagesModel; + disabled: boolean; + layout: ComposerLayout; + picker: ImagePickerRef; +}; + +export type ImageThumbProps = { + image: ComposerImage; + /** Its place, from 1, as the labels name it. */ + number: number; + onRemove: () => void; + onRetry: () => void; + disabled: boolean; + layout: ComposerLayout; +}; + +/** ComposerCount and ComposerLimit: both follow the caption as it is typed. */ +export type CaptionWatchProps = { control: Control }; + +export type ComposerSubmitProps = { + model: PostComposerPageModel; + layout: ComposerLayout; +}; + +export type LeaveConfirmProps = { + model: PostComposerPageModel; + layout: ComposerLayout; +}; + +/** How the intercepted dialog leaves its route (C4 ۷.۳). */ +export type DialogRoute = { + /** Until it starts closing. */ + open: boolean; + /** Closes it, then goes back to the page under it. */ + close: () => void; + /** + * Closes it and goes to `href`, read again: back, when `href` is the page under it (`isUnder`), + * else in place of the dialog's history entry. + */ + finish: (href: string, options?: { isUnder?: boolean }) => void; + /** The Modal's `onExited`. */ + onExited: () => void; +}; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/ChannelActions.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/ChannelActions.tsx new file mode 100644 index 0000000..4a20864 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/ChannelActions.tsx @@ -0,0 +1,57 @@ +'use client'; + +import { useTranslation } from 'react-i18next'; + +import { useChannelActionsPart } from '../../../../../../../features/channel'; +import { ActionsSkeleton } from './components/ActionsSkeleton'; +import { GuestActions } from './components/GuestActions'; +import { InvestorActions } from './components/InvestorActions'; +import type { ChannelActionsProps } from './types'; + +/** + * The channel's action area, the one part of the header that depends on the viewer, so it renders + * only in the browser: a same-size skeleton until the viewer is known. Guests and investors get + * subscribe and follow; the creator on their own channel, and other creators, get none. + */ +export function ChannelActions({ + creatorId, + username, + channelUrl, + layout, +}: ChannelActionsProps) { + const { t } = useTranslation('channel'); + const { viewer, ...model } = useChannelActionsPart({ creatorId, username }); + + switch (viewer.kind) { + case 'pending': + return ; + case 'guest': + return ( + + ); + case 'investor': + return ( + + ); + default: + return null; + } +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/ActionsSkeleton.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/ActionsSkeleton.tsx new file mode 100644 index 0000000..e489c28 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/ActionsSkeleton.tsx @@ -0,0 +1,16 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton'; + +import type { ActionsSkeletonProps } from '../types'; + +/** The action row's size until the viewer is known: two 44px pills, the first filling the row. */ +export function ActionsSkeleton({ label }: ActionsSkeletonProps) { + return ( + + + + + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/GuestActions.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/GuestActions.tsx new file mode 100644 index 0000000..a5f2941 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/GuestActions.tsx @@ -0,0 +1,55 @@ +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { useTranslation } from 'react-i18next'; + +import { + loginRoute, + ROUTES, + subscribeLoginRoute, +} from '../../../../../../../navigation/navigation'; +import type { GuestActionsProps } from '../types'; +import { GuestPrompt } from './GuestPrompt'; + +/** + * A guest sees both actions. «اشتراک» goes straight to login, which says why and comes back here; + * «دنبال کردن» opens the login prompt. + */ +export function GuestActions({ + username, + channelUrl, + layout, + isGuestPromptOpen, + openGuestPrompt, + closeGuestPrompt, +}: GuestActionsProps) { + const { t } = useTranslation('channel'); + const isMobile = layout === 'mobile'; + + return ( + <> + + + + + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/GuestPrompt.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/GuestPrompt.tsx new file mode 100644 index 0000000..0d2ecf4 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/GuestPrompt.tsx @@ -0,0 +1,81 @@ +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Modal } from '@lumina/island/molecules/modal'; +import { Sheet } from '@lumina/island/molecules/sheet'; +import { Element } from '@lumina/island/primitives/element'; +import { useTranslation } from 'react-i18next'; + +import type { GuestPromptProps } from '../types'; + +/** + * A guest tapped «دنبال کردن»: one way in, «ورود/ثبت‌نام», and back to this channel afterwards. + * The follow isn't applied on return; the person taps it again. A bottom sheet on mobile, a modal + * on desktop; ✕ closes it, as it has no cancel button. + */ +export function GuestPrompt({ + open, + onClose, + channelUrl, + loginHref, + layout, +}: GuestPromptProps) { + const { t } = useTranslation('channel'); + const isMobile = layout === 'mobile'; + + const body = ( + + {t('guest.description')} + + + + + {channelUrl} + + + + + ); + const login = ( + + ); + + return isMobile ? ( + + {body} + + ) : ( + + {body} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/InvestorActions.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/InvestorActions.tsx new file mode 100644 index 0000000..645907e --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/InvestorActions.tsx @@ -0,0 +1,110 @@ +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Typography } from '@lumina/island/atoms/typography'; +import { cn } from '@lumina/island/tools/cn'; +import { useId } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { ROUTES } from '../../../../../../../navigation/navigation'; +import { UnfollowConfirm } from '../../../../../organisms/unfollow-confirm'; +import type { InvestorActionsProps } from '../types'; +import { PaymentFailedNote } from './PaymentFailedNote'; +import { PaymentPendingNote } from './PaymentPendingNote'; +import { PendingIndicator } from './PendingIndicator'; +import { WaitlistNote } from './WaitlistNote'; + +/** + * A signed-in investor's actions. Subscribe is the dominant one: «اشتراک» into checkout, «مشترک + * هستید» once subscribed, or frozen while a payment waits for the bank; live again once the bank + * turns it down, with why under the row (U10 ۵.۴). Follow sits beside it; while the subscription + * is active unfollow is frozen and says why. + */ +export function InvestorActions({ + username, + layout, + standing, + follow, + askUnfollow, + isConfirmingUnfollow, + confirmUnfollow, + cancelUnfollow, + leaveWaitlist, + isLeavingWaitlist, +}: InvestorActionsProps) { + const { t } = useTranslation('channel'); + const pendingNoteId = useId(); + const isMobile = layout === 'mobile'; + const fill = isMobile ? 'flex-1' : undefined; + + const subscribe = standing.subscribed ? ( + + + + {t('actions.subscribed')} + + + ) : standing.paymentPending ? ( + + ) : ( + + ); + + const followControl = standing.subscribed ? ( + + ) : standing.following ? ( + + ) : ( + + ); + + return ( + <> + + + {subscribe} + {followControl} + + {standing.paymentPending && ( + + )} + {standing.paymentFailed && + !standing.paymentPending && + !standing.subscribed && } + {standing.waitlisted && !standing.subscribed && ( + + )} + + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/PaymentFailedNote.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/PaymentFailedNote.tsx new file mode 100644 index 0000000..a323f5a --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/PaymentFailedNote.tsx @@ -0,0 +1,28 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Banner } from '@lumina/island/molecules/banner'; +import { useTranslation } from 'react-i18next'; + +import { SupportEntry } from '../../../../../../organisms/support-entry'; +import type { PaymentFailedNoteProps } from '../types'; + +/** + * The bank turned the last payment down (U10 ۵.۴ pending-reverted): «اشتراک» is live again, and + * under the row the alert, when a deducted amount comes back, and the way to support. + */ +export function PaymentFailedNote({ layout }: PaymentFailedNoteProps) { + const { t } = useTranslation('channel'); + + return ( + + + + {t('actions.payment-failed-description')} + + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/PaymentPendingNote.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/PaymentPendingNote.tsx new file mode 100644 index 0000000..b98b1a1 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/PaymentPendingNote.tsx @@ -0,0 +1,35 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Typography } from '@lumina/island/atoms/typography'; +import { useTranslation } from 'react-i18next'; + +import { SupportEntry } from '../../../../../../organisms/support-entry'; +import type { PaymentPendingNoteProps } from '../types'; + +/** Why subscribe is frozen while a payment waits for the bank, and the way to support. */ +export function PaymentPendingNote({ id, layout }: PaymentPendingNoteProps) { + const { t } = useTranslation('channel'); + + return ( + + + + {t('actions.pending-description')} + + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/PendingIndicator.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/PendingIndicator.tsx new file mode 100644 index 0000000..b57181f --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/PendingIndicator.tsx @@ -0,0 +1,83 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Typography } from '@lumina/island/atoms/typography'; +import { cn } from '@lumina/island/tools/cn'; +import { useEffect, useId, useRef, useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { SupportEntry } from '../../../../../../organisms/support-entry'; +import type { PendingIndicatorProps } from '../types'; + +/** + * «پرداخت در حال بررسی» in the subscribe slot (U9 ۱.۴, U10 ۵.۵): frozen, since a second payment + * can't start, but a press opens why above it, with «تماس با پشتیبانی» (U10 ۵.۶). Escape or a + * press elsewhere closes it. + */ +export function PendingIndicator({ + describedBy, + layout, + className, +}: PendingIndicatorProps) { + const { t } = useTranslation('channel'); + const tipId = useId(); + const area = useRef(null); + const [isOpen, setIsOpen] = useState(false); + + useEffect(() => { + if (!isOpen) return undefined; + const close = () => setIsOpen(false); + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape') close(); + }; + const onPointerDown = (event: PointerEvent) => { + if (!area.current?.contains(event.target as Node)) close(); + }; + document.addEventListener('keydown', onKeyDown); + document.addEventListener('pointerdown', onPointerDown); + return () => { + document.removeEventListener('keydown', onKeyDown); + document.removeEventListener('pointerdown', onPointerDown); + }; + }, [isOpen]); + + return ( + + setIsOpen((open) => !open)} + alignItems="items-center" + justifyContent="justify-center" + gap="gap-2" + className="min-h-control-md w-full cursor-pointer rounded-full border border-border-default bg-surface px-5 text-text-secondary opacity-(--opacity-frozen) focus-visible:focus-ring" + > + + + {t('actions.pending')} + + + {isOpen && ( + + + {t('actions.pending-description')} + + + + )} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/WaitlistNote.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/WaitlistNote.tsx new file mode 100644 index 0000000..14e629a --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/components/WaitlistNote.tsx @@ -0,0 +1,22 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { LinkButton } from '@lumina/island/atoms/link-button'; +import { Typography } from '@lumina/island/atoms/typography'; +import { useTranslation } from 'react-i18next'; + +import type { WaitlistNoteProps } from '../types'; + +/** On a full channel's waitlist: the promise of a notice, and the way off the list. */ +export function WaitlistNote({ onLeave, isLeaving }: WaitlistNoteProps) { + const { t } = useTranslation('channel'); + + return ( + + + {t('waitlist.note')} + + + {t('waitlist.leave')} + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/index.ts b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/index.ts new file mode 100644 index 0000000..d425cc5 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/index.ts @@ -0,0 +1,2 @@ +export { ChannelActions } from './ChannelActions'; +export type { ChannelActionsLayout, ChannelActionsProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/types.ts b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/types.ts new file mode 100644 index 0000000..bf6b976 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-actions/types.ts @@ -0,0 +1,65 @@ +import type { + ChannelActionsPartModel, + ChannelStanding, +} from '../../../../../../../features/channel'; + +export type ChannelActionsLayout = 'mobile' | 'desktop'; + +export type ChannelActionsProps = { + /** The creator's account id. */ + creatorId: string; + username: string; + /** The channel's address without the scheme, shown in the guest's login prompt. */ + channelUrl: string; + /** mobile: «اشتراک» fills the row; dialogs are bottom sheets. desktop: content width, modals. */ + layout: ChannelActionsLayout; +}; + +export type ActionsSkeletonProps = { label: string }; + +export type GuestActionsProps = Pick< + ChannelActionsProps, + 'username' | 'channelUrl' | 'layout' +> & + Pick< + ChannelActionsPartModel, + 'isGuestPromptOpen' | 'openGuestPrompt' | 'closeGuestPrompt' + >; + +export type InvestorActionsProps = Pick< + ChannelActionsProps, + 'username' | 'layout' +> & + Omit< + ChannelActionsPartModel, + 'viewer' | 'isGuestPromptOpen' | 'openGuestPrompt' | 'closeGuestPrompt' + > & { standing: ChannelStanding }; + +export type GuestPromptProps = { + open: boolean; + onClose: () => void; + channelUrl: string; + loginHref: string; + layout: ChannelActionsLayout; +}; + +export type PaymentPendingNoteProps = { + id: string; + layout: ChannelActionsLayout; +}; + +export type PaymentFailedNoteProps = { + layout: ChannelActionsLayout; +}; + +export type WaitlistNoteProps = { + onLeave: () => void; + isLeaving: boolean; +}; + +export type PendingIndicatorProps = { + /** The always-visible explanation under the row, which the indicator points to. */ + describedBy: string; + layout: ChannelActionsLayout; + className?: string; +}; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/ChannelFeed.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/ChannelFeed.tsx new file mode 100644 index 0000000..c563efd --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/ChannelFeed.tsx @@ -0,0 +1,21 @@ +import { getCreatorPosts } from '../../../../../../../features/post/caches/server'; +import { ChannelFeedList } from './components/ChannelFeedList'; +import type { ChannelFeedProps } from './types'; + +/** + * The channel's feed part: the first page read on the server, so search engines and the first + * paint have the posts, handed to the list that keeps it live in the browser. + */ +export async function ChannelFeed({ channel, now, layout }: ChannelFeedProps) { + const firstPage = await getCreatorPosts(channel.creatorId); + return ( + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/components/ChannelFeedEmpty.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/components/ChannelFeedEmpty.tsx new file mode 100644 index 0000000..c8bb7f9 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/components/ChannelFeedEmpty.tsx @@ -0,0 +1,75 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton'; +import { Card } from '@lumina/island/molecules/card'; +import { EmptyState } from '@lumina/island/molecules/empty-state'; +import { useTranslation } from 'react-i18next'; + +import { + useCurrentAccount, + useViewerStatus, +} from '../../../../../../../../stores/auth'; +import { ROUTES } from '../../../../../../../navigation/navigation'; +import type { ChannelFeedEmptyProps } from '../types'; + +/** + * A channel with no posts yet. Visitors are told following brings the first ones; the creator is + * asked to publish. Which of the two depends on the viewer, so until then it is a skeleton. + */ +export function ChannelFeedEmpty({ creatorId }: ChannelFeedEmptyProps) { + const { t } = useTranslation('channel'); + const status = useViewerStatus(); + const account = useCurrentAccount(); + + if (status === 'unknown') { + return ( + + + + + + + + + + ); + } + + if (account?.id === creatorId) { + return ( + + + + + + + ); + } + + return ( + + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/components/ChannelFeedList.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/components/ChannelFeedList.tsx new file mode 100644 index 0000000..1b0aee3 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/components/ChannelFeedList.tsx @@ -0,0 +1,148 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { ErrorState } from '@lumina/island/molecules/error-state'; +import dynamic from 'next/dynamic'; +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { + useChannelEntitled, + useChannelGate, + useChannelStanding, +} from '../../../../../../../../features/channel'; +import { useChannelFeedPart } from '../../../../../../../../features/post'; +import { useCurrentAccount } from '../../../../../../../../stores/auth'; +import { ROUTES } from '../../../../../../../navigation/navigation'; +import { ChannelPostCard } from '../../../../../organisms/channel-post-card'; +import type { ChannelFeedListProps, ViewedImage } from '../types'; +import { ChannelFeedEmpty } from './ChannelFeedEmpty'; +import { NoSubscribersNote } from './NoSubscribersNote'; + +// Loads on the first image tap: most visits never open it. +const PostLightbox = dynamic(() => + import('../../../../../organisms/post-lightbox').then( + (mod) => mod.PostLightbox, + ), +); + +/** + * The channel's posts, newest first, locked premium posts in their place among the free ones. The + * server renders the first page as every visitor sees it; the gates wait for the viewer, and a + * subscriber's or the creator's locked posts open in place. Older pages load on request; one that + * fails shows an inline retry at the end while the posts stay. The creator's newest premium post + * says when no one subscribes yet (C5 ۱.۴), in the browser only. + * + * A tap on an open post's image opens the viewer over the channel at that image, with a back + * arrow (C4 ۴.۳); the rest of the card leads to the post page. A post open on this page stays open + * until the next load, even if the subscription ends meanwhile (C5 §۵). + */ +export function ChannelFeedList({ + creatorId, + username, + avatarUrl, + firstPage, + now, + layout, +}: ChannelFeedListProps) { + const { t } = useTranslation(['channel', 'errors']); + const account = useCurrentAccount(); + const entitled = useChannelEntitled(creatorId); + const gate = useChannelGate(creatorId); + const standing = useChannelStanding(creatorId); + const { posts, isEmpty, hasMore, loadMore, isLoadingMore, loadMoreError } = + useChannelFeedPart({ + creatorId, + firstPage, + entitled, + }); + // The last image tapped stays after the viewer closes, so it closes in place: it fades out and + // focus goes back to the image. + const [viewed, setViewed] = useState(null); + const [isViewing, setIsViewing] = useState(false); + const viewedPost = viewed && posts.find((post) => post.id === viewed.postId); + const isDesktop = layout === 'desktop'; + const isOwner = account?.id === creatorId; + + if (isEmpty) return ; + + return ( + <> + + {isOwner && posts[0]?.accessLevel === 'premium' && ( + + )} + {posts.map((post) => ( + { + setViewed({ postId: post.id, index }); + setIsViewing(true); + } + } + paymentPending={standing?.paymentPending ?? false} + className={isDesktop ? 'p-6' : undefined} + /> + ))} + {loadMoreError ? ( + + ) : ( + hasMore && ( + + ) + )} + + {viewed && + viewedPost && + !viewedPost.locked && + viewedPost.media.length > 0 && ( + + setViewed({ postId: viewedPost.id, index }) + } + onClose={() => setIsViewing(false)} + /> + )} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/components/NoSubscribersNote.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/components/NoSubscribersNote.tsx new file mode 100644 index 0000000..6e167fa --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/components/NoSubscribersNote.tsx @@ -0,0 +1,21 @@ +import { Banner } from '@lumina/island/molecules/banner'; +import { useTranslation } from 'react-i18next'; + +import { useOwnSubscriberCount } from '../../../../../../../../features/overview'; + +/** + * Over the creator's newest post when it is premium and nobody subscribes yet (C5 ۱.۴): not an + * error, the post waits locked for everyone. Nothing while the count is unknown or failed to load. + */ +export function NoSubscribersNote() { + const { t } = useTranslation('channel'); + const subscribers = useOwnSubscriberCount({ enabled: true }); + + if (subscribers !== 0) return null; + + return ( + + {t('feed.no-subscribers')} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/server.ts b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/server.ts new file mode 100644 index 0000000..5ac9189 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/server.ts @@ -0,0 +1,4 @@ +import 'server-only'; + +export { ChannelFeed } from './ChannelFeed'; +export type { ChannelFeedLayout, ChannelFeedProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/types.ts b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/types.ts new file mode 100644 index 0000000..c55ea90 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-feed/types.ts @@ -0,0 +1,30 @@ +import type { PublicCreatorPayload } from '../../../../../../../features/channel'; +import type { PostPagePayload } from '../../../../../../../features/post'; + +export type ChannelFeedLayout = 'mobile' | 'desktop'; + +export type ChannelFeedProps = { + channel: PublicCreatorPayload; + /** What the posts' relative times count from: the server render's time. */ + now: string; + layout: ChannelFeedLayout; +}; + +export type ChannelFeedListProps = { + creatorId: string; + username: string; + avatarUrl: string | null; + firstPage: PostPagePayload; + now: string; + layout: ChannelFeedLayout; +}; + +/** The image last opened in the viewer: which post, and its place among the post's images. */ +export type ViewedImage = { + postId: string; + index: number; +}; + +export type ChannelFeedEmptyProps = { + creatorId: string; +}; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/ChannelHeader.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/ChannelHeader.tsx new file mode 100644 index 0000000..85fe493 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/ChannelHeader.tsx @@ -0,0 +1,124 @@ +import { Avatar } from '@lumina/island/atoms/avatar'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Tag } from '@lumina/island/atoms/tag'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Card } from '@lumina/island/molecules/card'; +import { Element } from '@lumina/island/primitives/element'; + +import { ChannelLinks } from './components/ChannelLinks'; +import type { ChannelHeaderProps } from './types'; + +/** + * The channel header (U6), the same for every visitor; only the action area differs, and it loads + * in the browser. Fixed order: the avatar, @username with the verified mark and the channel's + * address, the bio in full, the market chips, the links, the track record and the actions. + * Optional blocks leave no gap. Every channel the API returns is approved, so every public one is + * verified; the creator's own pending, rejected or suspended tab has no mark (C6 ۱.۲, ۱.۳). + * Desktop moves the actions up under the identity row. + */ +export function ChannelHeader({ + channel, + channelUrl, + layout, + share, + stats, + actions, + labels, + muted = false, + verified = true, +}: ChannelHeaderProps) { + const isDesktop = layout === 'desktop'; + + const identity = ( + + + + + + + @{channel.username} + + + {verified && ( + + )} + + + + {channelUrl} + + + + {share} + + ); + + const body = ( + <> + {channel.bio && ( + + {channel.bio} + + )} + {channel.markets.length > 0 && ( + + {channel.markets.map((market) => ( + + {labels.marketNames[market]} + + ))} + + )} + {channel.socialLinks.length > 0 && ( + + )} + {stats} + + ); + + if (isDesktop) { + return ( + + + {identity} + {actions} + {body} + + + ); + } + + return ( + + {identity} + {body} + {actions} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/ChannelHeaderSkeleton.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/ChannelHeaderSkeleton.tsx new file mode 100644 index 0000000..dd64ed5 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/ChannelHeaderSkeleton.tsx @@ -0,0 +1,24 @@ +import { Card } from '@lumina/island/molecules/card'; +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; + +import type { ChannelHeaderSkeletonProps } from './types'; + +/** + * The header while it loads, in the header's own frame: the band under the top bar on mobile, the + * 640 column's panel on desktop. + */ +export function ChannelHeaderSkeleton({ + layout, + label, + delayed, +}: ChannelHeaderSkeletonProps) { + const skeleton = ( + + ); + return layout === 'desktop' ? {skeleton} : skeleton; +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/components/ChannelLinks.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/components/ChannelLinks.tsx new file mode 100644 index 0000000..d328c6b --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/components/ChannelLinks.tsx @@ -0,0 +1,56 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Element } from '@lumina/island/primitives/element'; + +import { + displaySocialUrl, + fromSocialUrl, +} from '../../../../../../../../shared/utils'; +import type { ChannelLinksProps } from '../types'; + +/** + * The creator's links in their saved order, each a link icon and the platform's name (a website + * shows its address), opening in a new tab. Never platform logos. + */ +export function ChannelLinks({ links, labels }: ChannelLinksProps) { + return ( + + {links.map(({ label, url }) => { + const { platform } = fromSocialUrl(label, url); + return ( + + + + + {platform === 'website' ? ( + + {displaySocialUrl(url)} + + ) : ( + labels.platforms[platform] + )} + + + {labels.opensNewTab} + + + + ); + })} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/index.ts b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/index.ts new file mode 100644 index 0000000..22f076f --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/index.ts @@ -0,0 +1,8 @@ +export { ChannelHeader } from './ChannelHeader'; +export { ChannelHeaderSkeleton } from './ChannelHeaderSkeleton'; +export { channelHeaderLabels } from './labels'; +export type { + ChannelHeaderLabels, + ChannelHeaderProps, + ChannelHeaderSkeletonProps, +} from './types'; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/labels.ts b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/labels.ts new file mode 100644 index 0000000..4fd45f0 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/labels.ts @@ -0,0 +1,29 @@ +import type { TFunction } from 'i18next'; + +import { MARKETS } from '../../../../../../../shared/constants'; +import type { Market } from '../../../../../../../shared/constants'; +import type { ChannelHeaderLabels } from './types'; + +/** The header's texts, from the server's translations. */ +export function channelHeaderLabels( + t: TFunction<'channel'>, + tCommon: TFunction<'common'>, +): ChannelHeaderLabels { + return { + verified: t('header.verified'), + markets: t('header.markets'), + marketNames: Object.fromEntries( + MARKETS.map((market) => [market, tCommon(`markets.${market}`)]), + ) as Record, + links: t('header.links'), + platforms: { + telegram: t('header.platforms.telegram'), + instagram: t('header.platforms.instagram'), + x: t('header.platforms.x'), + youtube: t('header.platforms.youtube'), + aparat: t('header.platforms.aparat'), + linkedin: t('header.platforms.linkedin'), + }, + opensNewTab: t('header.opens-new-tab'), + }; +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/types.ts b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/types.ts new file mode 100644 index 0000000..0be3f7f --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-header/types.ts @@ -0,0 +1,55 @@ +import type { ReactNode } from 'react'; + +import type { PublicCreatorPayload } from '../../../../../../../features/channel'; +import type { Market } from '../../../../../../../shared/constants'; +import type { SocialPlatform } from '../../../../../../../shared/validations'; + +/** Every text of the header, from the translations (the app builds them on the server). */ +export type ChannelHeaderLabels = { + /** The verified mark's accessible name: «تأییدشده». */ + verified: string; + /** The market list's accessible name: «بازارهای تخصصی». */ + markets: string; + /** Each market's name: «طلا و سکه». */ + marketNames: Record; + /** The link list's accessible name: «لینک‌های تحلیلگر». */ + links: string; + /** Each platform's name; a website shows its address instead. */ + platforms: Record, string>; + /** After each link, for screen readers: «در زبانه‌ی جدید باز می‌شود». */ + opensNewTab: string; +}; + +export type ChannelHeaderProps = { + channel: PublicCreatorPayload; + /** The channel's address without the scheme: «lumina.ir/@sara_gold». */ + channelUrl: string; + /** mobile: flush under the top bar. desktop: a panel in the 640 column. */ + layout: 'mobile' | 'desktop'; + /** The share button, at the identity row's end. */ + share: ReactNode; + /** CreatorStats in its boundary; renders nothing below the threshold. */ + stats: ReactNode; + /** Subscribe and follow, which load in the browser. */ + actions: ReactNode; + /** The creator's own suspended channel: a greyed avatar. */ + muted?: boolean; + /** + * The verified mark after @username. Every public channel is approved, so `true` by default; + * the creator's own pending, rejected or suspended tab passes `false` (C6 ۱.۲, ۱.۳). + */ + verified?: boolean; + labels: ChannelHeaderLabels; +}; + +export type ChannelLinksProps = Pick & { + links: PublicCreatorPayload['socialLinks']; +}; + +export type ChannelHeaderSkeletonProps = { + layout: ChannelHeaderProps['layout']; + /** Hidden status text, such as «در حال بارگذاری کانال…». */ + label: string; + /** Fades in after 300ms, so a quick answer never flashes grey. */ + delayed?: boolean; +}; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/ChannelNotFound.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/ChannelNotFound.tsx new file mode 100644 index 0000000..0663c20 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/ChannelNotFound.tsx @@ -0,0 +1,60 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { ErrorState } from '@lumina/island/molecules/error-state'; +import { useTranslation } from 'react-i18next'; + +import { ROUTES } from '../../../../../../navigation/navigation'; +import { ChannelHeaderSkeleton } from '../channel-header'; +import { OwnPendingChannel } from './components/OwnPendingChannel'; +import { useOwnAddress } from './hooks/use-own-address'; +import type { ChannelNotFoundProps } from './types'; + +/** + * An address with no public channel behind it (S3 04): neutral, with the way home. The creator + * whose channel isn't public yet sees their own page instead, under review. Which of the two + * depends on the viewer, so until then it is the header's skeleton, which is also where the own + * page starts; the server render is the same for every visitor. + */ +export function ChannelNotFound({ layout, siteHost }: ChannelNotFoundProps) { + const { t } = useTranslation('channel'); + const own = useOwnAddress(); + + if (own.kind === 'unknown') { + return ( + + ); + } + + if (own.kind === 'own') { + return ( + + ); + } + + const state = ( + + + + ); + + // The mobile page is flush, for the own page's header; the message keeps the page's inset. + return layout === 'mobile' ? ( + + {state} + + ) : ( + state + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/ChannelNotFoundTopBar.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/ChannelNotFoundTopBar.tsx new file mode 100644 index 0000000..848d00d --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/ChannelNotFoundTopBar.tsx @@ -0,0 +1,21 @@ +'use client'; + +import { MobileTopBar } from '../../../../../../navigation/components/mobile-top-bar'; +import { useOwnAddress } from './hooks/use-own-address'; +import type { ChannelNotFoundTopBarProps } from './types'; + +/** + * The mobile bar over an address with no public channel: the pushed bar (back · «کانال») for + * everyone, except the creator whose channel isn't public yet, who is on their own tab and sees + * the tab bar (C6 ۱.۲). Decided in the browser: until the viewer is known the bar keeps its height + * and shows a skeleton where its start goes, the same for every visitor in the server render. + */ +export function ChannelNotFoundTopBar({ title }: ChannelNotFoundTopBarProps) { + const own = useOwnAddress(); + return ( + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/components/OwnPendingChannel.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/components/OwnPendingChannel.tsx new file mode 100644 index 0000000..bde08ca --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/components/OwnPendingChannel.tsx @@ -0,0 +1,114 @@ +'use client'; + +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Banner } from '@lumina/island/molecules/banner'; +import { Card } from '@lumina/island/molecules/card'; +import { EmptyState } from '@lumina/island/molecules/empty-state'; +import { useTranslation } from 'react-i18next'; + +import { useOwnChannel } from '../../../../../../../../features/channel'; +import { usePostDraftStore } from '../../../../../../../../stores/post-draft'; +import { ROUTES } from '../../../../../../../navigation/navigation'; +import { + ChannelHeader, + channelHeaderLabels, + ChannelHeaderSkeleton, +} from '../../channel-header'; +import { ChannelShare } from '../../channel-share'; +import type { OwnPendingChannelProps } from '../types'; + +/** + * A creator's own channel while their identity is under review (C6 ۱.۲) or was rejected: the + * banner that says so (rejected: the admin's reason, tapping into their account, C4 ۲.۵), their + * header with no verified mark, share frozen, and no posts: the draft kept for later, or the own + * empty state (C4 ۲.۴, ۷.۵). Nobody else sees this: to them the address doesn't exist yet. + */ +export function OwnPendingChannel({ + layout, + channelUrl, +}: OwnPendingChannelProps) { + const { t } = useTranslation('channel'); + const { t: tCommon } = useTranslation('common'); + const own = useOwnChannel(); + const draft = usePostDraftStore((state) => state.draft); + + if (own.status === 'pending') { + return ; + } + const { channel, standing, rejectionReason } = own; + const banner = + standing === 'rejected' ? ( + + {rejectionReason + ? t('own.rejected-reason', { reason: rejectionReason }) + : t('own.rejected')} + + ) : ( + + {t('own.pending')} + + ); + // A post written before the review: kept, to publish once approved (C6 ۱.۲). + const hasDraft = draft?.creatorId === channel.creatorId; + const body = hasDraft ? ( + + + + {t('own.draft-title')} + + + {t('own.draft-description')} + + + + ) : ( + + ); + const header = ( + + } + stats={null} + actions={null} + labels={channelHeaderLabels(t, tCommon)} + /> + ); + + // Mobile: the banner in its strip under the top bar, the header flush (C6 ۱.۲, ۱.۳). Desktop: + // the 640 column's panels (C4 ۷.۵). + if (layout === 'desktop') { + return ( + + {banner} + {header} + {body} + + ); + } + return ( + + + {banner} + + {header} + + {body} + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/hooks/use-own-address.ts b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/hooks/use-own-address.ts new file mode 100644 index 0000000..0d67f0f --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/hooks/use-own-address.ts @@ -0,0 +1,45 @@ +import { usePathname } from 'next/navigation'; + +import { + useCurrentAccount, + useViewerStatus, +} from '../../../../../../../../stores/auth'; +import { + CHANNEL_PREFIX, + CHANNEL_ROUTE_PREFIX, +} from '../../../../../../../navigation/constants'; +import type { OwnAddress } from '../types'; + +/** The username an address names, whichever form the router reports it in. */ +function usernameIn(pathname: string): string | null { + for (const prefix of [CHANNEL_PREFIX, CHANNEL_ROUTE_PREFIX]) { + if (pathname.startsWith(prefix)) { + const segment = pathname.slice(prefix.length).split('/')[0]; + // A malformed escape names no channel anyone owns. + try { + return decodeURIComponent(segment).toLowerCase(); + } catch { + return null; + } + } + } + return null; +} + +/** + * Whose address this is, for an address with no public channel: the signed-in creator's own + * (C6 ۱.۲), someone else's, or `unknown` until the browser knows the viewer, which is always the + * case in the server render. The not-found page gets no params, so the address comes from the + * router. + */ +export function useOwnAddress(): OwnAddress { + const status = useViewerStatus(); + const account = useCurrentAccount(); + const username = usernameIn(usePathname()); + + if (status === 'unknown') return { kind: 'unknown' }; + return account?.role === 'creator' && + username === account.username.toLowerCase() + ? { kind: 'own', account } + : { kind: 'other' }; +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/index.ts b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/index.ts new file mode 100644 index 0000000..fdfd20e --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/index.ts @@ -0,0 +1,3 @@ +export { ChannelNotFound } from './ChannelNotFound'; +export { ChannelNotFoundTopBar } from './ChannelNotFoundTopBar'; +export type { ChannelNotFoundProps, ChannelNotFoundTopBarProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/types.ts b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/types.ts new file mode 100644 index 0000000..cfe520e --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-not-found/types.ts @@ -0,0 +1,26 @@ +import type { AccountPayload } from '../../../../../../../features/auth'; + +type ChannelLayoutProps = { + /** mobile: flush header and bottom sheets. desktop: panels in the 640 column. */ + layout: 'mobile' | 'desktop'; +}; + +export type ChannelNotFoundProps = ChannelLayoutProps & { + /** The site's address as people read it, «lumina.ir»; the own page's channel address follows it. */ + siteHost: string; +}; + +export type OwnPendingChannelProps = ChannelLayoutProps & { + channelUrl: string; +}; + +export type ChannelNotFoundTopBarProps = { + /** The pushed bar's title: «کانال». */ + title: string; +}; + +/** Whose an address with no public channel is; `unknown` until the browser knows the viewer. */ +export type OwnAddress = + | { kind: 'unknown' } + | { kind: 'own'; account: AccountPayload } + | { kind: 'other' }; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-share/ChannelShare.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-share/ChannelShare.tsx new file mode 100644 index 0000000..d5b0e0e --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-share/ChannelShare.tsx @@ -0,0 +1,70 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { useTranslation } from 'react-i18next'; + +import { + useChannelShareSheet, + useShareLink, +} from '../../../../../../../features/channel'; +import { useCurrentAccount } from '../../../../../../../stores/auth'; +import { ROUTES } from '../../../../../../navigation/navigation'; +import { OwnerShareSheet } from './components/OwnerShareSheet'; +import type { ChannelShareProps } from './types'; + +/** + * The header's share icon. The creator gets their caption sheet (C6); everyone else hands the bare + * link to the device's share sheet, or copies it on desktop. + */ +export function ChannelShare({ + creatorId, + username, + channelUrl, + layout, + frozenReason, +}: ChannelShareProps) { + const { t } = useTranslation('channel'); + const account = useCurrentAccount(); + const share = useShareLink(); + const path = ROUTES.channel(username); + const native = layout === 'mobile'; + const sheet = useChannelShareSheet({ path, native }); + const isOwner = account?.id === creatorId; + + if (frozenReason) { + return ( + + ) : ( + + )} + + + ); + + return ( + + {body} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-share/index.ts b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-share/index.ts new file mode 100644 index 0000000..bd4a4f4 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-share/index.ts @@ -0,0 +1,2 @@ +export { ChannelShare } from './ChannelShare'; +export type { ChannelShareProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-share/types.ts b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-share/types.ts new file mode 100644 index 0000000..346f247 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-share/types.ts @@ -0,0 +1,19 @@ +import type { ChannelShareSheetModel } from '../../../../../../../features/channel'; + +export type ChannelShareProps = { + /** The creator's account id: they get the caption sheet, everyone else the link. */ + creatorId: string; + username: string; + /** «lumina.ir/@sara_gold», shown read-only in the creator's sheet. */ + channelUrl: string; + /** mobile: share sheets and a bottom sheet. desktop: copying and a popover. */ + layout: 'mobile' | 'desktop'; + /** The creator can't share yet (identity under review): the icon is frozen with this reason. */ + frozenReason?: string; +}; + +export type OwnerShareSheetProps = { + model: ChannelShareSheetModel; + channelUrl: string; + layout: 'mobile' | 'desktop'; +}; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-stats/ChannelStats.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-stats/ChannelStats.tsx new file mode 100644 index 0000000..b317e2f --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-stats/ChannelStats.tsx @@ -0,0 +1,22 @@ +import { CreatorStats } from '@lumina/island/organisms/creator-stats'; + +import { PREDICTION_STATS_MIN_CLOSED } from '../../../../../../../features/prediction'; +import { getPredictionStats } from '../../../../../../../features/prediction/caches/server'; +import type { ChannelStatsProps } from './types'; + +/** + * The creator's track record in the header, the same for every visitor. All or nothing: below the + * threshold it renders nothing, never zeros, and the header closes the gap. + */ +export async function ChannelStats({ creatorId, labels }: ChannelStatsProps) { + const stats = await getPredictionStats(creatorId); + return ( + = PREDICTION_STATS_MIN_CLOSED ? stats : null + } + trendOrder="oldest-first" + labels={labels} + /> + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-stats/server.ts b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-stats/server.ts new file mode 100644 index 0000000..9c71da4 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-stats/server.ts @@ -0,0 +1,4 @@ +import 'server-only'; + +export { ChannelStats } from './ChannelStats'; +export type { ChannelStatsProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-stats/types.ts b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-stats/types.ts new file mode 100644 index 0000000..c6444c7 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-stats/types.ts @@ -0,0 +1,7 @@ +import type { CreatorStatsLabels } from '@lumina/island/organisms/creator-stats'; + +export type ChannelStatsProps = { + /** The creator's account id. */ + creatorId: string; + labels: CreatorStatsLabels; +}; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-unavailable/ChannelUnavailable.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-unavailable/ChannelUnavailable.tsx new file mode 100644 index 0000000..53ccc58 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-unavailable/ChannelUnavailable.tsx @@ -0,0 +1,86 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { EmptyState } from '@lumina/island/molecules/empty-state'; +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; +import { useTranslation } from 'react-i18next'; + +import { + useCurrentAccount, + useViewerStatus, +} from '../../../../../../../stores/auth'; +import { ROUTES } from '../../../../../../navigation/navigation'; +import { OwnSuspendedChannel } from './components/OwnSuspendedChannel'; +import type { ChannelUnavailableProps } from './types'; + +/** + * A suspended creator's channel, the same for every visitor: no header, posts or actions, only + * this message. Suspension outranks everything else, including the paywall. On the channel page + * the creator themself sees their suspended tab instead, so there it waits for the viewer in the + * message's skeleton; a post link shows the message at once. + */ +export function ChannelUnavailable({ + context, + channel, + channelUrl, + layout = 'mobile', +}: ChannelUnavailableProps) { + const { t } = useTranslation('channel'); + const status = useViewerStatus(); + const account = useCurrentAccount(); + const ownerAware = channel !== undefined && channelUrl !== undefined; + + // Only the browser knows the viewer: the creator's own tab replaces the message for them. + if (ownerAware && account?.id === channel.creatorId) { + return ( + + ); + } + + const message = + ownerAware && status === 'unknown' ? ( + + + + ) : ( + + {context === 'post' && ( + + )} + + ); + + // The mobile channel page is flush, for the own tab's header; the message keeps the page's inset. + return context === 'channel' && layout === 'mobile' ? ( + + {message} + + ) : ( + message + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-unavailable/components/OwnSuspendedChannel.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-unavailable/components/OwnSuspendedChannel.tsx new file mode 100644 index 0000000..cb42153 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-unavailable/components/OwnSuspendedChannel.tsx @@ -0,0 +1,62 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Banner } from '@lumina/island/molecules/banner'; +import { useTranslation } from 'react-i18next'; + +import { ChannelHeader, channelHeaderLabels } from '../../channel-header'; +import { ChannelShare } from '../../channel-share'; +import type { OwnSuspendedChannelProps } from '../types'; + +/** + * A suspended creator's own tab (C6 ۱.۳): the banner, a greyed avatar and their name with no + * verified mark, share frozen, and nothing else. Suspension is final from here, so it offers no + * next step. Only a safeguard: a suspended account can't sign in. Mobile puts the banner in its + * strip under the top bar and the header flush; desktop stacks them in the 640 column. + */ +export function OwnSuspendedChannel({ + channel, + channelUrl, + layout, +}: OwnSuspendedChannelProps) { + const { t } = useTranslation('channel'); + const { t: tCommon } = useTranslation('common'); + const isDesktop = layout === 'desktop'; + const banner = ( + + {t('own.suspended')} + + ); + + return ( + + {isDesktop ? ( + banner + ) : ( + + {banner} + + )} + + } + stats={null} + actions={null} + labels={channelHeaderLabels(t, tCommon)} + /> + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-unavailable/index.ts b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-unavailable/index.ts new file mode 100644 index 0000000..002d6b0 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-unavailable/index.ts @@ -0,0 +1,2 @@ +export { ChannelUnavailable } from './ChannelUnavailable'; +export type { ChannelUnavailableProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-unavailable/types.ts b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-unavailable/types.ts new file mode 100644 index 0000000..3e08ba9 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/organisms/channel-unavailable/types.ts @@ -0,0 +1,17 @@ +import type { PublicCreatorPayload } from '../../../../../../../features/channel'; + +export type ChannelUnavailableProps = { + /** channel: the whole page (U6 ۱.۳). post: a post link into it (C4b ۵.۲). */ + context: 'channel' | 'post'; + /** The channel page passes it, so its own creator sees their suspended tab (C6 ۱.۳). */ + channel?: PublicCreatorPayload; + /** «lumina.ir/@sara_gold». */ + channelUrl?: string; + layout?: 'mobile' | 'desktop'; +}; + +export type OwnSuspendedChannelProps = { + channel: PublicCreatorPayload; + channelUrl: string; + layout: 'mobile' | 'desktop'; +}; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/PostChannelBar.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/PostChannelBar.tsx new file mode 100644 index 0000000..54e3fb7 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/PostChannelBar.tsx @@ -0,0 +1,64 @@ +import { Avatar } from '@lumina/island/atoms/avatar'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Card } from '@lumina/island/molecules/card'; +import { Element } from '@lumina/island/primitives/element'; +import NextLink from 'next/link'; + +import { ROUTES } from '../../../../../../../../navigation/navigation'; +import type { PostChannelBarProps } from './types'; + +/** + * The post page's mini header (C4b, U8): the creator, linking to the channel, over the same + * subscribe and follow controls as the channel header, so a shared link can convert on the spot. + */ +export function PostChannelBar({ + channel, + layout, + actions, + verifiedLabel, +}: PostChannelBarProps) { + const content = ( + + + + + + @{channel.username} + + + + + {actions} + + ); + + return layout === 'desktop' ? ( + + {content} + + ) : ( + + {content} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/index.ts b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/index.ts new file mode 100644 index 0000000..26d6240 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/index.ts @@ -0,0 +1,2 @@ +export { PostChannelBar } from './PostChannelBar'; +export type { PostChannelBarProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/types.ts b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/types.ts new file mode 100644 index 0000000..d6a04ce --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-channel-bar/types.ts @@ -0,0 +1,13 @@ +import type { ReactNode } from 'react'; + +import type { PublicCreatorPayload } from '../../../../../../../../../features/channel'; + +export type PostChannelBarProps = { + channel: PublicCreatorPayload; + /** mobile: flush under the top bar. desktop: a panel in the 640 column. */ + layout: 'mobile' | 'desktop'; + /** Subscribe and follow, the same part as the channel header's. */ + actions: ReactNode; + /** The verified mark's accessible name: «تأییدشده». */ + verifiedLabel: string; +}; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-missing/PostMissing.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-missing/PostMissing.tsx new file mode 100644 index 0000000..7eca684 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-missing/PostMissing.tsx @@ -0,0 +1,34 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { ErrorState } from '@lumina/island/molecules/error-state'; +import { Element } from '@lumina/island/primitives/element'; +import { useTranslation } from 'react-i18next'; + +import { ROUTES } from '../../../../../../../../navigation/navigation'; +import type { PostMissingProps } from './types'; + +/** + * A link to a post that was deleted or never existed: the API can't tell them apart, so they read + * the same. Calm, with one way out, to the channel. + */ +export function PostMissing({ username }: PostMissingProps) { + const { t } = useTranslation('channel'); + + return ( + + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-missing/index.ts b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-missing/index.ts new file mode 100644 index 0000000..9d58dcf --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-missing/index.ts @@ -0,0 +1,2 @@ +export { PostMissing } from './PostMissing'; +export type { PostMissingProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-missing/types.ts b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-missing/types.ts new file mode 100644 index 0000000..de36b0e --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-missing/types.ts @@ -0,0 +1,4 @@ +export type PostMissingProps = { + /** The channel the link pointed into: the one way out. */ + username: string; +}; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/PostView.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/PostView.tsx new file mode 100644 index 0000000..c78465a --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/PostView.tsx @@ -0,0 +1,139 @@ +'use client'; + +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import dynamic from 'next/dynamic'; +import { useRouter, useSearchParams } from 'next/navigation'; +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { + useChannelEntitled, + useChannelGate, + useChannelStanding, +} from '../../../../../../../../../features/channel'; +import { usePostPart } from '../../../../../../../../../features/post'; +import { useCurrentAccount } from '../../../../../../../../../stores/auth'; +import { PREVIEW_PARAM } from '../../../../../../../../navigation/constants'; +import { ROUTES } from '../../../../../../../../navigation/navigation'; +import { + ChannelPostCard, + toPostPreview, +} from '../../../../../../organisms/channel-post-card'; +import { AccessEndedBanner } from './components/AccessEndedBanner'; +import { PreviewBanner } from './components/PreviewBanner'; +import type { PostViewProps } from './types'; + +// Loads on the first image tap: most visits never open it. +const PostLightbox = dynamic(() => + import('../../../../../../organisms/post-lightbox').then( + (mod) => mod.PostLightbox, + ), +); + +/** + * The post in full on its own page (C4b). It starts as every visitor sees it and opens in place + * for a subscriber or the creator. A tap on an image opens the viewer there, with a back arrow; + * a locked post has no images to open. The creator can preview their premium post as a visitor or + * a subscriber sees it (`?preview`), and after deleting it goes to the channel. + * + * A subscriber's open premium post ends with how they have it, «دسترسی از طریق اشتراک سالانه» + * (Post--unlocked). If the subscription ends while they read, the line goes, the post stays open + * until the next load, and a banner says so (C5 ۵.۲). + */ +export function PostView({ + post: serverPost, + username, + avatarUrl, + now, + layout, +}: PostViewProps) { + const { t } = useTranslation('content'); + const { t: tCommon } = useTranslation('common'); + const account = useCurrentAccount(); + const entitled = useChannelEntitled(serverPost.creatorId); + const gate = useChannelGate(serverPost.creatorId); + const standing = useChannelStanding(serverPost.creatorId); + const { post, accessPeriod, accessEnded } = usePostPart({ + post: serverPost, + entitled, + subscription: standing?.subscription ?? null, + }); + // The last image tapped stays after the viewer closes, so it closes in place: it fades out and + // focus goes back to the image. + const [viewedAt, setViewedAt] = useState(null); + const [isViewing, setIsViewing] = useState(false); + const router = useRouter(); + const requested = toPostPreview(useSearchParams().get(PREVIEW_PARAM)); + const path = ROUTES.post(username, serverPost.id); + const isOwner = account?.id === post.creatorId; + // Only the creator previews, and only their own premium post they can read in full. + const preview = + isOwner && !post.locked && post.accessLevel === 'premium' + ? requested + : undefined; + // Only an investor on someone else's channel has a standing, so never the creator's own post. + const accessNote = accessPeriod + ? t('post.access-via', { + period: tCommon(`billing-periods.${accessPeriod}`), + }) + : undefined; + + const card = ( + { + setViewedAt(index); + setIsViewing(true); + }} + onDeleted={() => router.replace(ROUTES.channel(username))} + preview={preview} + paymentPending={standing?.paymentPending ?? false} + accessNote={accessNote} + className={layout === 'desktop' ? 'p-6' : undefined} + /> + ); + + return ( + <> + {preview ? ( + + + router.replace(`${path}?${PREVIEW_PARAM}=${next}`, { + scroll: false, + }) + } + onExit={() => router.replace(path, { scroll: false })} + /> + {card} + + ) : ( + card + )} + {viewedAt !== null && + !post.locked && + post.media.length > 0 && + !preview && ( + setIsViewing(false)} + /> + )} + {accessEnded && } + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/components/AccessEndedBanner.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/components/AccessEndedBanner.tsx new file mode 100644 index 0000000..3ec7eb5 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/components/AccessEndedBanner.tsx @@ -0,0 +1,25 @@ +import { Banner } from '@lumina/island/molecules/banner'; +import { cn } from '@lumina/island/tools/cn'; +import { useTranslation } from 'react-i18next'; + +import { ACCESS_ENDED_PLACEMENT } from '../constants'; +import type { AccessEndedBannerProps } from '../types'; + +/** + * The subscription ended while the subscriber was reading (C5 ۵.۲): the post stays open until the + * next load, and this says so. It floats over the page, above the content and under any dialog, + * and is announced once (the banner's status role). No close: it goes with the page. + */ +export function AccessEndedBanner({ layout }: AccessEndedBannerProps) { + const { t } = useTranslation('content'); + + return ( + + {t('post.access-ended')} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/components/PreviewBanner.tsx b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/components/PreviewBanner.tsx new file mode 100644 index 0000000..db6bad8 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/components/PreviewBanner.tsx @@ -0,0 +1,53 @@ +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Banner } from '@lumina/island/molecules/banner'; +import { SegmentedChoice } from '@lumina/island/molecules/segmented-choice'; +import { useTranslation } from 'react-i18next'; + +import type { PreviewBannerProps } from '../types'; + +/** + * The creator's preview (C5 §6): which view this is, a switch between the visitor's and the + * subscriber's, and the way out. Not a second session: only how this page renders. + */ +export function PreviewBanner({ + preview, + onSwitch, + onExit, +}: PreviewBannerProps) { + const { t } = useTranslation('content'); + + return ( + + + + + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/constants.ts b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/constants.ts new file mode 100644 index 0000000..f2ebd8f --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/constants.ts @@ -0,0 +1,8 @@ +/** + * Where the ended subscription's banner floats (C5 ۵.۲), as the toasts do. Mobile: 16px from the + * sides, 80px up, over the bottom nav. Desktop: centred, 420px wide, 32px up. + */ +export const ACCESS_ENDED_PLACEMENT = { + mobile: 'inset-x-4 bottom-20 w-auto', + desktop: 'inset-x-0 bottom-8 mx-auto w-105', +} as const; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/index.ts b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/index.ts new file mode 100644 index 0000000..e260f24 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/index.ts @@ -0,0 +1,2 @@ +export { PostView } from './PostView'; +export type { PostViewProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/types.ts b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/types.ts new file mode 100644 index 0000000..228db05 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/channels/[username]/posts/[id]/organisms/post-view/types.ts @@ -0,0 +1,21 @@ +import type { PostPayload } from '../../../../../../../../../features/post'; +import type { PostPreview } from '../../../../../../organisms/channel-post-card'; + +export type PostViewProps = { + post: PostPayload; + username: string; + avatarUrl: string | null; + /** What the time counts from: the server render's time. */ + now: string; + layout: 'mobile' | 'desktop'; +}; + +export type PreviewBannerProps = { + preview: PostPreview; + onSwitch: (preview: PostPreview) => void; + onExit: () => void; +}; + +export type AccessEndedBannerProps = { + layout: 'mobile' | 'desktop'; +}; diff --git a/platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/FollowingList.tsx b/platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/FollowingList.tsx new file mode 100644 index 0000000..7091737 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/FollowingList.tsx @@ -0,0 +1,127 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { useOnline } from '@lumina/island/hooks/use-online'; +import { ErrorState } from '@lumina/island/molecules/error-state'; +import { useRef } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { useFollowingPart } from '../../../../../../../features/channel'; +import { UnfollowConfirm } from '../../../../organisms/unfollow-confirm'; +import { FollowingEmpty } from './components/FollowingEmpty'; +import { FollowingRow } from './components/FollowingRow'; +import type { FollowingListProps } from './types'; + +/** + * داشبورد › دنبال‌شده‌ها (U8 §۴, ۶.۱): the creators the investor follows, newest follow first, one + * card per row, in the browser only. A row opens its channel; a suspended creator's row is dimmed + * and opens nothing, its unfollow still live (U8 ۴.۴). Unfollow asks first, in a bottom sheet on + * mobile and a modal on desktop (U8 ۴.۲, ۶.۲), and the question waits for the answer. While a + * subscription is active the unfollow is frozen and says why (U8 ۴.۷), and offline every unfollow + * is (S4-02). No follows: the U8 ۴.۳ empty state. + * + * Once a row leaves, focus goes to the row now in its place, or the one before it, or the empty + * state's way on. An older page that fails shows an inline retry in place of «more». + */ +export function FollowingList({ layout }: FollowingListProps) { + const { t } = useTranslation(['dashboard', 'errors']); + const { + rows, + hasMore, + loadMore, + isLoadingMore, + loadMoreError, + unfollowTarget, + isConfirmingUnfollow, + isUnfollowing, + askUnfollow, + confirmUnfollow, + cancelUnfollow, + } = useFollowingPart(); + const offline = !useOnline(); + const listRef = useRef(null); + const emptyActionRef = useRef(null); + // Where the row asked about stood, so focus lands nearby once it leaves. + const askedIndex = useRef(0); + const gap = layout === 'desktop' ? 'gap-4' : 'gap-3'; + + // The browser returns focus to the unfollow button, gone with its row: focus its neighbour. + const focusAfterUnfollow = () => { + const target = unfollowTarget; + if (!target || rows.some((row) => row.creatorId === target.creatorId)) + return; + const items = listRef.current?.children ?? []; + const item = items[Math.min(askedIndex.current, items.length - 1)]; + // The stretched link, or the unfollow of a suspended creator's row, which has none. + const next = + item?.querySelector('a[href], button') ?? + emptyActionRef.current; + next?.focus(); + }; + + return ( + <> + {rows.length === 0 ? ( + + ) : ( + + + {rows.map((row, index) => ( + { + askedIndex.current = index; + askUnfollow(row); + }} + /> + ))} + + {loadMoreError ? ( + + ) : ( + hasMore && ( + + ) + )} + + )} + {/* Outside the list, so it closes in place when the last row leaves. */} + {unfollowTarget && ( + + )} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/components/FollowingEmpty.tsx b/platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/components/FollowingEmpty.tsx new file mode 100644 index 0000000..d0c9bbe --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/components/FollowingEmpty.tsx @@ -0,0 +1,30 @@ +import { Button } from '@lumina/island/atoms/button'; +import { Card } from '@lumina/island/molecules/card'; +import { EmptyState } from '@lumina/island/molecules/empty-state'; +import { useTranslation } from 'react-i18next'; + +import { ROUTES } from '../../../../../../../navigation/navigation'; +import type { FollowingEmptyProps } from '../types'; + +/** + * No follows yet (U8 ۴.۳): one way on, to خانه. Mobile centres it in the tab's body at page size; + * desktop puts it in a card in the column, at section size, as the sibling tabs do (S2-Desktop 01). + */ +export function FollowingEmpty({ layout, actionRef }: FollowingEmptyProps) { + const { t } = useTranslation('dashboard'); + const isDesktop = layout === 'desktop'; + const state = ( + + + + ); + + return isDesktop ? {state} : state; +} diff --git a/platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/components/FollowingRow.tsx b/platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/components/FollowingRow.tsx new file mode 100644 index 0000000..c34bd09 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/components/FollowingRow.tsx @@ -0,0 +1,134 @@ +import { Avatar } from '@lumina/island/atoms/avatar'; +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Card } from '@lumina/island/molecules/card'; +import { Element } from '@lumina/island/primitives/element'; +import NextLink from 'next/link'; +import { useTranslation } from 'react-i18next'; + +import { ROUTES } from '../../../../../../../navigation/navigation'; +import type { FollowingRowProps } from '../types'; + +/** + * One followed creator (U8 ۴.۱, ۶.۱): the 40px avatar, the @username with its verified tick, and + * «دنبال نکردن». The name is a link stretched over the card, so a tap anywhere but the button opens + * the channel, and the card draws the link's focus ring. A suspended creator's card is dimmed and + * opens nothing: a lock replaces the tick and a line says why, while the unfollow stays at full + * opacity and live (U8 ۴.۴). An active subscription freezes the unfollow, suspended or not, because + * the API refuses it (U8 ۴.۷); so does being offline, with its own reason (S4-02). The frozen + * reason sits at the button's end, so it stays on a phone's screen. + */ +export function FollowingRow({ + row, + layout, + offline, + onUnfollow, +}: FollowingRowProps) { + const { t } = useTranslation(['dashboard', 'channel', 'common']); + const { creator, subscribed } = row; + const isSuspended = creator.suspended; + const unfollowLabel = t('following.unfollow', { username: creator.username }); + + // Left to right, so a long handle is cut at its end: «@reza_a…». + const username = ( + + @{creator.username} + + ); + + return ( + + {/* The card is the row, so the dimming reaches each part but the button. */} + + + + {isSuspended ? ( + + + {username} + + + + {t('following.suspended')} + + + ) : ( + + {username} + {creator.verified && ( + + )} + + )} + + {/* Above the stretched link, and at full opacity on a dimmed card. */} + + {subscribed || offline ? ( + + ) : ( + + )} + + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/index.ts b/platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/index.ts new file mode 100644 index 0000000..c1a30e7 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/index.ts @@ -0,0 +1,2 @@ +export { FollowingList } from './FollowingList'; +export type { FollowingListLayout, FollowingListProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/types.ts b/platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/types.ts new file mode 100644 index 0000000..8cf8fdc --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/following/organisms/following-list/types.ts @@ -0,0 +1,25 @@ +import type { Ref } from 'react'; + +import type { FollowingPayload } from '../../../../../../../features/follow'; + +/** mobile: rows padded `md`, 12px apart, and a bottom sheet. desktop: `lg`, 16px, and a modal. */ +export type FollowingListLayout = 'mobile' | 'desktop'; + +export type FollowingListProps = { + layout: FollowingListLayout; +}; + +export type FollowingRowProps = { + row: FollowingPayload; + layout: FollowingListLayout; + /** The device is offline: the unfollow is frozen and says it needs the internet (S4-02). */ + offline: boolean; + /** Asks before unfollowing; a frozen row never calls it. */ + onUnfollow: () => void; +}; + +export type FollowingEmptyProps = { + layout: FollowingListLayout; + /** «رفتن به خانه», focused when the last row's unfollow leaves the list empty. */ + actionRef?: Ref; +}; diff --git a/platforms/market/src/app/screens/(main)/dashboard/organisms/dashboard-tabs/DashboardTabs.tsx b/platforms/market/src/app/screens/(main)/dashboard/organisms/dashboard-tabs/DashboardTabs.tsx new file mode 100644 index 0000000..379a97c --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/organisms/dashboard-tabs/DashboardTabs.tsx @@ -0,0 +1,32 @@ +'use client'; + +import { TabLinks } from '@lumina/island/molecules/tab-links'; +import { usePathname } from 'next/navigation'; +import { useTranslation } from 'react-i18next'; + +import { INVESTOR_TABS } from './constants'; +import type { DashboardTabsProps } from './types'; + +/** + * The investor داشبورد's section row: «اشتراک‌ها» · «تراکنش‌ها» · «دنبال‌شده‌ها», full width, the + * current section underlined (U8 ۴.۱, ۶.۱; U8 ۵.۲). The dashboard layout renders it once, so it + * stays put while a section loads; the current one comes from the URL, which the server render + * already knows. + */ +export function DashboardTabs({ layout }: DashboardTabsProps) { + const { t } = useTranslation('dashboard'); + const pathname = usePathname(); + + return ( + ({ + href, + label: t(label), + isActive: pathname === href || pathname.startsWith(`${href}/`), + }))} + label={t('tabs.label')} + fill + band={layout === 'mobile'} + /> + ); +} diff --git a/platforms/market/src/app/screens/(main)/dashboard/organisms/dashboard-tabs/constants.ts b/platforms/market/src/app/screens/(main)/dashboard/organisms/dashboard-tabs/constants.ts new file mode 100644 index 0000000..23c9767 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/organisms/dashboard-tabs/constants.ts @@ -0,0 +1,8 @@ +import { ROUTES } from '../../../../../navigation/navigation'; + +/** The investor's داشبورد sections in reading order, each its own route (U2; U8 ۴.۱, ۶.۱). */ +export const INVESTOR_TABS = [ + { href: ROUTES.dashboard.subscriptions, label: 'tabs.subscriptions' }, + { href: ROUTES.dashboard.transactions, label: 'tabs.transactions' }, + { href: ROUTES.dashboard.following, label: 'tabs.following' }, +] as const; diff --git a/platforms/market/src/app/screens/(main)/dashboard/organisms/dashboard-tabs/index.ts b/platforms/market/src/app/screens/(main)/dashboard/organisms/dashboard-tabs/index.ts new file mode 100644 index 0000000..2e5f7ba --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/organisms/dashboard-tabs/index.ts @@ -0,0 +1,2 @@ +export { DashboardTabs } from './DashboardTabs'; +export type { DashboardTabsProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/dashboard/organisms/dashboard-tabs/types.ts b/platforms/market/src/app/screens/(main)/dashboard/organisms/dashboard-tabs/types.ts new file mode 100644 index 0000000..f4677a0 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/organisms/dashboard-tabs/types.ts @@ -0,0 +1,4 @@ +export type DashboardTabsProps = { + /** mobile: the surface band under the top bar. desktop: in the 640 column, under the heading. */ + layout: 'mobile' | 'desktop'; +}; diff --git a/platforms/market/src/app/screens/(main)/organisms/channel-post-card/ChannelPostCard.tsx b/platforms/market/src/app/screens/(main)/organisms/channel-post-card/ChannelPostCard.tsx new file mode 100644 index 0000000..96b86d7 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/channel-post-card/ChannelPostCard.tsx @@ -0,0 +1,233 @@ +'use client'; + +import { PostCard } from '@lumina/island/organisms/post-card'; +import dynamic from 'next/dynamic'; +import { useRouter } from 'next/navigation'; +import { useMemo } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { useShareLink } from '../../../../../features/channel'; +import { useOwnerPostPart } from '../../../../../features/post'; +import { MARKETS } from '../../../../../shared/constants'; +import type { Market } from '../../../../../shared/constants'; +import { + postCardLabels, + predictionCardLabels, +} from '../../../../../shared/labels'; +import { PREVIEW_PARAM } from '../../../../navigation/constants'; +import { loginRoute, ROUTES } from '../../../../navigation/navigation'; +import { DeletePostConfirm } from '../delete-post-confirm'; +import type { ChannelPostCardProps } from './types'; +import { teaserOf, toMediaItems, toPredictionData } from './utils'; + +// Only the creator ever closes a prediction: the sheet and its form load on the first tap. +const ClosePredictionSheet = dynamic(() => + import('../close-prediction-sheet').then((mod) => mod.ClosePredictionSheet), +); + +const isMarket = (market: string): market is Market => + (MARKETS as readonly string[]).includes(market); + +/** + * A channel's post as PostCard draws it, in the channel and home feeds and on the post page. A + * locked post shows the gate for who is looking: «ورود/ثبت‌نام» back to this page for a guest, + * «اشتراک در کانال» into checkout for an investor, and that CTA frozen for another creator, who + * can't subscribe. Everyone may share it: the device's share sheet on + * mobile, a menu with «کپی لینک» on desktop (C4b ۳.۴, ۶.۱). The creator's own post gets the + * owner's footer: preview (premium), share, edit (frozen after 15 minutes), delete, and closing an + * open prediction; past the 15 minutes a channel card also shows its access level, frozen with it + * (C5 ۱.۶). In the creator's preview it renders as others see it, with nothing that acts. + */ +export function ChannelPostCard({ + post, + username, + avatarUrl, + verified = true, + variant, + linked, + viewer, + isOwner, + now, + returnPath, + layout, + onImageClick, + onDeleted, + preview, + paymentPending = false, + accessNote, + className, +}: ChannelPostCardProps) { + const { t } = useTranslation('content'); + const { t: tCommon } = useTranslation('common'); + const router = useRouter(); + const share = useShareLink(); + const labels = useMemo(() => postCardLabels(t), [t]); + const predictionLabels = useMemo(() => predictionCardLabels(t), [t]); + const owner = useOwnerPostPart({ post, enabled: isOwner, onDeleted }); + + const path = ROUTES.post(username, post.id); + const isPremium = post.accessLevel === 'premium'; + const onShare = () => + void share({ kind: 'post', path, username, native: layout === 'mobile' }); + // Desktop has no share sheet: share opens the one-item menu, which copies the link. + const onCopyLink = + layout === 'desktop' + ? () => void share({ kind: 'post', path, username, native: false }) + : undefined; + const canClosePrediction = + isOwner && + !post.locked && + post.prediction != null && + post.prediction.status === 'open'; + + const footer = preview + ? {} + : isOwner + ? { + owner: { + onShare, + onCopyLink, + onPreview: isPremium + ? () => router.push(`${path}?${PREVIEW_PARAM}=visitor`) + : undefined, + onEdit: () => router.push(ROUTES.editPost(post.id)), + editFrozen: owner.isEditFrozen, + // C5 ۱.۶: on the channel the access level locks with the content. + accessFrozen: + variant === 'compact' && + owner.isEditFrozen && + !post.locked && + post.prediction == null, + onDelete: owner.askDelete, + onClosePrediction: canClosePrediction + ? owner.openClosePrediction + : undefined, + }, + } + : { onShare, onCopyLink }; + const common = { + author: { username, avatar: avatarUrl, verified }, + channelHref: ROUTES.channel(username), + href: linked ? path : undefined, + publishedAt: post.publishedAt ?? post.createdAt, + now, + premium: isPremium, + edited: post.editedAt != null, + // C4b: the creator's own post says so on its page. + ownerTag: + isOwner && variant === 'expanded' && !preview + ? t('post.yours') + : undefined, + variant, + predictionLabels, + labels, + className, + ...footer, + }; + const marketName = (market: string) => + isMarket(market) ? tCommon(`markets.${market}`) : market; + + // A visitor's view of the creator's own premium post: the member's lock, its CTA inert. + if (preview === 'visitor' && !post.locked) { + return ( + + ); + } + + // The creator's own premium post arrives locked from the server render until it is read again, + // and its footer's delete already works then. + const deleteConfirm = isOwner && !preview && ( + + ); + + if (post.locked) { + return ( + <> + + {deleteConfirm} + + ); + } + + return ( + <> + + {deleteConfirm} + {canClosePrediction && owner.isClosingPrediction && post.prediction && ( + + )} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/organisms/channel-post-card/constants.ts b/platforms/market/src/app/screens/(main)/organisms/channel-post-card/constants.ts new file mode 100644 index 0000000..9782c64 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/channel-post-card/constants.ts @@ -0,0 +1,5 @@ +/** The box an image reserves when the API doesn't know its size (4:3). */ +export const FALLBACK_IMAGE_SIZE = { width: 1200, height: 900 } as const; + +/** The API's teaser length; the creator's preview cuts the text at the same place. */ +export const CAPTION_PREVIEW_LENGTH = 140; diff --git a/platforms/market/src/app/screens/(main)/organisms/channel-post-card/index.ts b/platforms/market/src/app/screens/(main)/organisms/channel-post-card/index.ts new file mode 100644 index 0000000..9f8181a --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/channel-post-card/index.ts @@ -0,0 +1,3 @@ +export { ChannelPostCard } from './ChannelPostCard'; +export { toPostPreview } from './preview'; +export type { ChannelPostCardProps, PostPreview } from './types'; diff --git a/platforms/market/src/app/screens/(main)/organisms/channel-post-card/preview.ts b/platforms/market/src/app/screens/(main)/organisms/channel-post-card/preview.ts new file mode 100644 index 0000000..6a4e850 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/channel-post-card/preview.ts @@ -0,0 +1,6 @@ +import type { PostPreview } from './types'; + +/** The preview a link asks for; anything else is no preview. */ +export function toPostPreview(value: string | null): PostPreview | undefined { + return value === 'visitor' || value === 'subscriber' ? value : undefined; +} diff --git a/platforms/market/src/app/screens/(main)/organisms/channel-post-card/types.ts b/platforms/market/src/app/screens/(main)/organisms/channel-post-card/types.ts new file mode 100644 index 0000000..9f8df45 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/channel-post-card/types.ts @@ -0,0 +1,44 @@ +import type { ReactNode } from 'react'; + +import type { ChannelGate } from '../../../../../features/channel'; +import type { PostPayload } from '../../../../../features/post'; + +/** The creator previewing their own premium post as a visitor or as a subscriber sees it. */ +export type PostPreview = 'visitor' | 'subscriber'; + +export type ChannelPostCardProps = { + post: PostPayload; + /** The channel the post belongs to: its header shows them, and its links lead there. */ + username: string; + avatarUrl: string | null; + /** The verified mark on the avatar: on the channel and the post page, not on the home feed (U7). */ + verified?: boolean; + /** compact: the channel and home feeds. expanded: the post page. */ + variant: 'compact' | 'expanded'; + /** In the feed the card links to the post page, all but its images. */ + linked: boolean; + /** Picks a locked post's gate: `pending` until the viewer is known to be its reader. */ + viewer: ChannelGate; + /** The creator's own post: the owner's footer. */ + isOwner: boolean; + /** What the relative time counts from: the server render's time. */ + now: string; + /** Where a guest returns after logging in from the gate. */ + returnPath: string; + /** mobile: the device's share sheet and bottom sheets. desktop: copy, modals. */ + layout: 'mobile' | 'desktop'; + /** An open post's image tap, on the post page and in the feed: opens the viewer at that image. */ + onImageClick?: (index: number) => void; + /** The post page: after the creator deletes it. */ + onDeleted?: () => void; + /** The creator's preview: the card as others see it, every control inert. */ + preview?: PostPreview; + /** The viewer's payment waits for the bank: a locked post's CTA is frozen and says so. */ + paymentPending?: boolean; + /** + * The post page, an open post: how the subscriber has it, «دسترسی از طریق اشتراک سالانه» + * (Post--unlocked). Not in the creator's preview. + */ + accessNote?: ReactNode; + className?: string; +}; diff --git a/platforms/market/src/app/screens/(main)/organisms/channel-post-card/utils.ts b/platforms/market/src/app/screens/(main)/organisms/channel-post-card/utils.ts new file mode 100644 index 0000000..48c91de --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/channel-post-card/utils.ts @@ -0,0 +1,40 @@ +import type { MediaItem } from '@lumina/island/molecules/media-carousel'; +import type { PredictionData } from '@lumina/island/organisms/prediction-card'; +import type { ReactNode } from 'react'; + +import type { + PostImagePayload, + PredictionPayload, + UnlockedPostPayload, +} from '../../../../../features/post'; +import { CAPTION_PREVIEW_LENGTH, FALLBACK_IMAGE_SIZE } from './constants'; + +/** A post's images in their order, each reserving its own box before it loads. */ +export function toMediaItems(media: PostImagePayload[]): MediaItem[] { + return [...media] + .sort((a, b) => a.order - b.order) + .map((image) => ({ + src: image.url, + width: image.width ?? FALLBACK_IMAGE_SIZE.width, + height: image.height ?? FALLBACK_IMAGE_SIZE.height, + // The API has no alt text; the image buttons are named by their place instead. + alt: '', + })); +} + +/** The prediction as PredictionCard draws it, with the market's name instead of its key. */ +export function toPredictionData( + prediction: PredictionPayload, + marketName: (market: string) => ReactNode, +): PredictionData { + return { ...prediction, market: marketName(prediction.market) }; +} + +/** What the API's teaser would hold: the text cut where the API cuts it. */ +export function teaserOf(post: UnlockedPostPayload): string | undefined { + const caption = post.caption?.trim(); + if (!caption) return undefined; + return caption.length > CAPTION_PREVIEW_LENGTH + ? `${caption.slice(0, CAPTION_PREVIEW_LENGTH).trim()}…` + : caption; +} diff --git a/platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/ClosePredictionSheet.tsx b/platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/ClosePredictionSheet.tsx new file mode 100644 index 0000000..f5d711e --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/ClosePredictionSheet.tsx @@ -0,0 +1,149 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Banner } from '@lumina/island/molecules/banner'; +import { Modal } from '@lumina/island/molecules/modal'; +import { Sheet } from '@lumina/island/molecules/sheet'; +import { TextInput } from '@lumina/island/molecules/text-input'; +import { Element } from '@lumina/island/primitives/element'; +import { cn } from '@lumina/island/tools/cn'; +import { signedPercent } from '@lumina/tools/format'; +import { useId } from 'react'; +import type { FormEvent } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { useClosePredictionPart } from '../../../../../features/prediction'; +import { translateMessage } from '../../../../../shared/utils'; +import { PredictionSummary } from './components/PredictionSummary'; +import { OUTCOME_STYLE } from './constants'; +import type { ClosePredictionSheetProps } from './types'; + +/** + * «بستن پیش‌بینی» (R1 03): the close price, the outcome and return it will record, live, and a + * plain warning that it is final. A bottom sheet on mobile, a modal on desktop; «انصراف» cancels, + * so there is no ✕. Enter submits. + */ +export function ClosePredictionSheet({ + post, + open, + onClose, + layout, +}: ClosePredictionSheetProps) { + const { t } = useTranslation('content'); + const formId = useId(); + const { form, preview, submit, isSubmitting, formError } = + useClosePredictionPart({ post, onDone: onClose }); + const size = layout === 'mobile' ? 'lg' : undefined; + const fieldError = form.formState.errors.closedPrice?.message; + + const body = ( + { + event.preventDefault(); + submit(); + }} + > + + + {t('prediction.close.description')} + + + {formError && } + + {preview && ( + + + + {t('prediction.close.result', { + outcome: t(`prediction.status.${preview.outcome}`), + })}{' '} + {signedPercent(preview.roi)} + + + )} + + + + {t('prediction.close.warning')} + + + + + ); + const buttons = ( + <> + + + + ); + + return layout === 'mobile' ? ( + + {body} + + ) : ( + + {body} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/components/PredictionSummary.tsx b/platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/components/PredictionSummary.tsx new file mode 100644 index 0000000..b140a59 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/components/PredictionSummary.tsx @@ -0,0 +1,59 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Element } from '@lumina/island/primitives/element'; +import { iso, price } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { PredictionSummaryProps } from '../types'; +import { SummaryRow } from './SummaryRow'; + +/** What is being closed: the asset and direction, the entry, the final target and the stop. */ +export function PredictionSummary({ prediction }: PredictionSummaryProps) { + const { t } = useTranslation('content'); + const finalTarget = prediction.targetPrices.at(-1); + + return ( + + + + + {prediction.symbol} + + + {t(`prediction.direction.${prediction.direction}`)} + + + + {iso(price(prediction.entryPrice))} + + {finalTarget != null && ( + 1 + ? t('prediction.levels.final-target') + : t('prediction.levels.target') + } + > + {iso(price(finalTarget))} + + )} + {prediction.stopLoss != null && ( + + {iso(price(prediction.stopLoss))} + + )} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/components/SummaryRow.tsx b/platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/components/SummaryRow.tsx new file mode 100644 index 0000000..6334d92 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/components/SummaryRow.tsx @@ -0,0 +1,22 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; + +import type { SummaryRowProps } from '../types'; + +/** One line of the summary: its name, then its value at the end, LTR. */ +export function SummaryRow({ label, children }: SummaryRowProps) { + return ( + + + {label} + + + {children} + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/constants.ts b/platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/constants.ts new file mode 100644 index 0000000..024cfa1 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/constants.ts @@ -0,0 +1,15 @@ +/** The live result line by outcome: its icon and its tone. */ +export const OUTCOME_STYLE = { + win: { + icon: 'trend-up', + className: 'bg-success-subtle text-success-text', + }, + loss: { + icon: 'trend-down', + className: 'bg-danger-subtle text-danger-text', + }, + breakeven: { + icon: 'minus', + className: 'bg-surface-sunken text-text-secondary', + }, +} as const; diff --git a/platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/index.ts b/platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/index.ts new file mode 100644 index 0000000..763444d --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/index.ts @@ -0,0 +1,2 @@ +export { ClosePredictionSheet } from './ClosePredictionSheet'; +export type { ClosePredictionSheetProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/types.ts b/platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/types.ts new file mode 100644 index 0000000..a404cdd --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/close-prediction-sheet/types.ts @@ -0,0 +1,24 @@ +import type { ReactNode } from 'react'; + +import type { + PredictionPayload, + UnlockedPostPayload, +} from '../../../../../features/post'; + +export type ClosePredictionSheetProps = { + /** The creator's own open prediction post. */ + post: UnlockedPostPayload & { prediction: PredictionPayload }; + open: boolean; + onClose: () => void; + /** mobile: a bottom sheet. desktop: a modal. */ + layout: 'mobile' | 'desktop'; +}; + +export type PredictionSummaryProps = { + prediction: PredictionPayload; +}; + +export type SummaryRowProps = { + label: string; + children: ReactNode; +}; diff --git a/platforms/market/src/app/screens/(main)/organisms/delete-post-confirm/DeletePostConfirm.tsx b/platforms/market/src/app/screens/(main)/organisms/delete-post-confirm/DeletePostConfirm.tsx new file mode 100644 index 0000000..21cf22d --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/delete-post-confirm/DeletePostConfirm.tsx @@ -0,0 +1,66 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { Modal } from '@lumina/island/molecules/modal'; +import { Sheet } from '@lumina/island/molecules/sheet'; +import { useTranslation } from 'react-i18next'; + +import type { DeletePostConfirmProps } from './types'; + +/** + * «آیا از حذف این پست اطمینان دارید؟» (C4 ۵.۵): the destructive «بله، حذف کن» first, «انصراف» + * under it, no ✕. A bottom sheet on mobile, a modal on desktop. Once sent, only the answer + * closes it. + */ +export function DeletePostConfirm({ + open, + isDeleting, + onConfirm, + onCancel, + layout, +}: DeletePostConfirmProps) { + const { t } = useTranslation('content'); + const size = layout === 'mobile' ? 'lg' : undefined; + const title = t('post.delete.title'); + const buttons = ( + <> + + + + ); + + return layout === 'mobile' ? ( + + ) : ( + + ); +} diff --git a/platforms/market/src/app/screens/(main)/organisms/delete-post-confirm/index.ts b/platforms/market/src/app/screens/(main)/organisms/delete-post-confirm/index.ts new file mode 100644 index 0000000..bc9a994 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/delete-post-confirm/index.ts @@ -0,0 +1,2 @@ +export { DeletePostConfirm } from './DeletePostConfirm'; +export type { DeletePostConfirmProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/organisms/delete-post-confirm/types.ts b/platforms/market/src/app/screens/(main)/organisms/delete-post-confirm/types.ts new file mode 100644 index 0000000..9a24dcf --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/delete-post-confirm/types.ts @@ -0,0 +1,7 @@ +export type DeletePostConfirmProps = { + open: boolean; + isDeleting: boolean; + onConfirm: () => void; + onCancel: () => void; + layout: 'mobile' | 'desktop'; +}; diff --git a/platforms/market/src/app/screens/(main)/organisms/home-feed/HomeFeed.tsx b/platforms/market/src/app/screens/(main)/organisms/home-feed/HomeFeed.tsx new file mode 100644 index 0000000..b31cd2d --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/home-feed/HomeFeed.tsx @@ -0,0 +1,137 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { ErrorState } from '@lumina/island/molecules/error-state'; +import dynamic from 'next/dynamic'; +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { useHomeFeedPart } from '../../../../../features/feed'; +import { ROUTES } from '../../../../navigation/navigation'; +import { ChannelPostCard } from '../channel-post-card'; +import { HomeFeedEmpty } from './components/HomeFeedEmpty'; +import type { HomeFeedProps, ViewedImage } from './types'; + +// Loads on the first image tap: most visits never open it. +const PostLightbox = dynamic(() => + import('../post-lightbox').then((mod) => mod.PostLightbox), +); + +/** + * The investor's خانه: the posts of every creator they follow, newest first, locked premium posts + * in their place among the open ones, never filtered or grouped (U7 §۲). Each card is its + * creator's: @username and photo only, no verified mark or «دنبال می‌کنید» (U7). In the browser + * only, for an investor; older pages load on request, as on a channel, and one that fails shows an + * inline retry at the end while the posts stay. + * + * The card leads to the post page and its author to the channel; a locked post's gate starts the + * subscription at checkout without leaving the feed (U7 ۲.۶). A tap on an open post's image opens + * the viewer over the feed at that image (C4 ۴.۳). Share is the device's sheet on mobile and the + * «کپی لینک» menu on desktop (C4b ۳.۴). + */ +export function HomeFeed({ layout, exampleChannelUrl }: HomeFeedProps) { + const { t } = useTranslation(['home', 'errors']); + const { + posts, + isEmpty, + hasMore, + loadMore, + isLoadingMore, + loadMoreError, + followsAnyone, + now, + } = useHomeFeedPart(); + // The last image tapped stays after the viewer closes, so it closes in place: it fades out and + // focus goes back to the image. + const [viewed, setViewed] = useState(null); + const [isViewing, setIsViewing] = useState(false); + const viewedPost = viewed && posts.find((post) => post.id === viewed.postId); + const isDesktop = layout === 'desktop'; + + if (isEmpty) { + return ( + + ); + } + + return ( + <> + + {posts.map((post) => ( + { + setViewed({ postId: post.id, index }); + setIsViewing(true); + } + } + className={isDesktop ? 'p-6' : undefined} + /> + ))} + {loadMoreError ? ( + + ) : ( + hasMore && ( + + ) + )} + + {viewed && + viewedPost && + !viewedPost.locked && + viewedPost.media.length > 0 && ( + + setViewed({ postId: viewedPost.id, index }) + } + onClose={() => setIsViewing(false)} + /> + )} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/organisms/home-feed/HomeFeedSkeleton.tsx b/platforms/market/src/app/screens/(main)/organisms/home-feed/HomeFeedSkeleton.tsx new file mode 100644 index 0000000..3a51769 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/home-feed/HomeFeedSkeleton.tsx @@ -0,0 +1,34 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; +import { Element } from '@lumina/island/primitives/element'; + +import type { HomeFeedSkeletonProps } from './types'; + +/** + * خانه before its posts arrive (S1-03): three post cards, the first with media. The same in the + * route's loading, until the browser knows the viewer, and while the first page is read, so + * nothing moves; on desktop inside the 640 column (S1-Desktop ۰۱). The first card's region + * announces the label; the rest are hidden, so it is said once. + */ +export function HomeFeedSkeleton({ + label, + layout, + delayed, +}: HomeFeedSkeletonProps) { + return ( + + + + + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/organisms/home-feed/HomeGuard.tsx b/platforms/market/src/app/screens/(main)/organisms/home-feed/HomeGuard.tsx new file mode 100644 index 0000000..0fc8635 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/home-feed/HomeGuard.tsx @@ -0,0 +1,38 @@ +'use client'; + +import { useRouter } from 'next/navigation'; +import { useEffect } from 'react'; + +import { useCurrentAccount, useNeedsProfile } from '../../../../../stores/auth'; +import { AuthGuard } from '../../../../guards/auth-guard'; +import { ROUTES } from '../../../../navigation/navigation'; +import type { HomeGuardProps } from './types'; + +/** + * خانه is the investor's tab. A creator has none: their home tab is their own کانال, so they are + * sent there in place, with no history entry to come back to (or to registration step 5 first, as + * login sends them). A guest goes to login, which returns here; any other role gets the no-access + * state. The feed's skeleton stays until the browser knows the viewer, and while a creator leaves. + */ +export function HomeGuard({ fallback, children }: HomeGuardProps) { + const account = useCurrentAccount(); + const needsProfile = useNeedsProfile(); + const router = useRouter(); + const creatorHome = + account?.role === 'creator' + ? needsProfile + ? ROUTES.onboarding.creatorProfile + : ROUTES.channel(account.username) + : null; + + useEffect(() => { + if (creatorHome) router.replace(creatorHome); + }, [creatorHome, router]); + + if (creatorHome) return fallback; + return ( + + {children} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/organisms/home-feed/components/HomeFeedEmpty.tsx b/platforms/market/src/app/screens/(main)/organisms/home-feed/components/HomeFeedEmpty.tsx new file mode 100644 index 0000000..a66d146 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/home-feed/components/HomeFeedEmpty.tsx @@ -0,0 +1,43 @@ +'use client'; + +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Card } from '@lumina/island/molecules/card'; +import { EmptyState } from '@lumina/island/molecules/empty-state'; +import { useTranslation } from 'react-i18next'; + +import type { HomeFeedEmptyProps } from '../types'; + +/** + * خانه with no posts. Following nobody yet is the first use (S2-01): how to follow a channel, with + * no action, since there is no discovery. Following creators who have nothing to show yet says so, + * with the same way to follow more. Centred in the page on mobile; a card in the column on desktop + * (S2-Desktop ۰۱). + */ +export function HomeFeedEmpty({ + followsAnyone, + exampleChannelUrl, + layout, +}: HomeFeedEmptyProps) { + const { t } = useTranslation('home'); + const copy = followsAnyone ? 'no-posts' : 'empty'; + const isDesktop = layout === 'desktop'; + const state = ( + + ); + + if (isDesktop) return {state}; + return ( + + {state} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/organisms/home-feed/constants.ts b/platforms/market/src/app/screens/(main)/organisms/home-feed/constants.ts new file mode 100644 index 0000000..f658b8d --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/home-feed/constants.ts @@ -0,0 +1,2 @@ +/** The sample channel the empty feed names, as S2-01 draws it: «lumina.ir/@ali_gold». */ +export const EXAMPLE_CHANNEL_USERNAME = 'ali_gold'; diff --git a/platforms/market/src/app/screens/(main)/organisms/home-feed/index.ts b/platforms/market/src/app/screens/(main)/organisms/home-feed/index.ts new file mode 100644 index 0000000..b1fca04 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/home-feed/index.ts @@ -0,0 +1,10 @@ +export { EXAMPLE_CHANNEL_USERNAME } from './constants'; +export { HomeFeed } from './HomeFeed'; +export { HomeFeedSkeleton } from './HomeFeedSkeleton'; +export { HomeGuard } from './HomeGuard'; +export type { + HomeFeedLayout, + HomeFeedProps, + HomeFeedSkeletonProps, + HomeGuardProps, +} from './types'; diff --git a/platforms/market/src/app/screens/(main)/organisms/home-feed/types.ts b/platforms/market/src/app/screens/(main)/organisms/home-feed/types.ts new file mode 100644 index 0000000..2eb1b75 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/home-feed/types.ts @@ -0,0 +1,37 @@ +import type { ReactNode } from 'react'; + +/** mobile: the device's share sheet and bottom sheets. desktop: the 640 column, copy, modals. */ +export type HomeFeedLayout = 'mobile' | 'desktop'; + +export type HomeFeedProps = { + layout: HomeFeedLayout; + /** A channel's address as people read it, the empty feed's example: «lumina.ir/@ali_gold». */ + exampleChannelUrl: string; +}; + +export type HomeFeedSkeletonProps = { + /** Hidden status text: «در حال بارگذاری پست‌ها…». */ + label: string; + layout: HomeFeedLayout; + /** loading.tsx only: fades in after 300ms. */ + delayed?: boolean; +}; + +export type HomeGuardProps = { + /** The feed's same-size skeleton, until the viewer is known and while a creator leaves. */ + fallback: ReactNode; + children: ReactNode; +}; + +export type HomeFeedEmptyProps = { + /** Follows creators who have nothing to show yet, rather than nobody (S2-01). */ + followsAnyone: boolean; + exampleChannelUrl: string; + layout: HomeFeedLayout; +}; + +/** The image last opened in the viewer: which post, and its place among the post's images. */ +export type ViewedImage = { + postId: string; + index: number; +}; diff --git a/platforms/market/src/app/screens/(main)/organisms/post-lightbox/PostLightbox.tsx b/platforms/market/src/app/screens/(main)/organisms/post-lightbox/PostLightbox.tsx new file mode 100644 index 0000000..e51d0aa --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/post-lightbox/PostLightbox.tsx @@ -0,0 +1,49 @@ +'use client'; + +import { Lightbox } from '@lumina/island/organisms/lightbox'; +import { useMemo } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { lightboxLabels } from '../../../../../shared/labels'; +import type { PostLightboxProps } from './types'; + +/** + * An open post's image viewer, over the channel (C4 ۴.۳) or the home feed, or on the post page + * (C4b ۳.۱): its images in their order, each named by its place and the channel, with the back + * arrow and zoom. Callers load it in its own chunk on the first image tap, and never for a locked + * post or in the creator's preview; from then on it stays mounted and `open` shows and hides it. + */ +export function PostLightbox({ + media, + username, + open, + index, + onIndexChange, + onClose, +}: PostLightboxProps) { + const { t } = useTranslation('content'); + const labels = useMemo(() => lightboxLabels(t), [t]); + const images = [...media] + .sort((a, b) => a.order - b.order) + .map((image, place, all) => ({ + src: image.url, + alt: t('lightbox.image', { + n: String(place + 1), + total: String(all.length), + username, + }), + })); + + return ( + + ); +} diff --git a/platforms/market/src/app/screens/(main)/organisms/post-lightbox/index.ts b/platforms/market/src/app/screens/(main)/organisms/post-lightbox/index.ts new file mode 100644 index 0000000..711ddff --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/post-lightbox/index.ts @@ -0,0 +1,2 @@ +export { PostLightbox } from './PostLightbox'; +export type { PostLightboxProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/organisms/post-lightbox/types.ts b/platforms/market/src/app/screens/(main)/organisms/post-lightbox/types.ts new file mode 100644 index 0000000..7a877c3 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/post-lightbox/types.ts @@ -0,0 +1,18 @@ +import type { PostImagePayload } from '../../../../../features/post'; + +export type PostLightboxProps = { + /** The open post's images, in any order: the viewer shows them by `order`. */ + media: PostImagePayload[]; + /** The post's channel, in each image's name. */ + username: string; + /** + * Shown. Callers keep it mounted once opened and close it through this, so the viewer fades out + * and focus goes back to the tapped image. + */ + open: boolean; + /** The image on screen. */ + index: number; + onIndexChange: (index: number) => void; + /** Back, Escape or a swipe down. */ + onClose: () => void; +}; diff --git a/platforms/market/src/app/screens/(main)/organisms/unfollow-confirm/UnfollowConfirm.tsx b/platforms/market/src/app/screens/(main)/organisms/unfollow-confirm/UnfollowConfirm.tsx new file mode 100644 index 0000000..3e84589 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/unfollow-confirm/UnfollowConfirm.tsx @@ -0,0 +1,77 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Modal } from '@lumina/island/molecules/modal'; +import { Sheet } from '@lumina/island/molecules/sheet'; +import { useTranslation } from 'react-i18next'; + +import type { UnfollowConfirmProps } from './types'; + +/** + * Asks before unfollowing, on the channel and in the following list (U8 ۴.۲, ۶.۲), naming the + * channel and what changes: its posts leave the home feed. «بله، دنبال نکن» first, «انصراف» under + * it; Escape and the scrim cancel too, except while the unfollow is on its way. + */ +export function UnfollowConfirm({ + open, + username, + layout, + onConfirm, + onCancel, + pending = false, + onExited, +}: UnfollowConfirmProps) { + const { t } = useTranslation('channel'); + const size = layout === 'mobile' ? 'lg' : undefined; + const title = t('follow.confirm.title', { username }); + const description = ( + {t('follow.confirm.description')} + ); + const buttons = ( + <> + + + + ); + + return layout === 'mobile' ? ( + + {description} + + ) : ( + + {description} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/organisms/unfollow-confirm/index.ts b/platforms/market/src/app/screens/(main)/organisms/unfollow-confirm/index.ts new file mode 100644 index 0000000..e543bbf --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/unfollow-confirm/index.ts @@ -0,0 +1,2 @@ +export { UnfollowConfirm } from './UnfollowConfirm'; +export type { UnfollowConfirmProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/organisms/unfollow-confirm/types.ts b/platforms/market/src/app/screens/(main)/organisms/unfollow-confirm/types.ts new file mode 100644 index 0000000..97fec4d --- /dev/null +++ b/platforms/market/src/app/screens/(main)/organisms/unfollow-confirm/types.ts @@ -0,0 +1,15 @@ +export type UnfollowConfirmProps = { + open: boolean; + /** The channel being unfollowed, named in the title. */ + username: string; + /** mobile: a bottom sheet. desktop: a modal. */ + layout: 'mobile' | 'desktop'; + onConfirm: () => void; + onCancel: () => void; + /** + * The unfollow is on its way: «بله، دنبال نکن» spins, and «انصراف», Escape and the scrim wait. + */ + pending?: boolean; + /** The question has closed and focus is back on the page. */ + onExited?: () => void; +}; diff --git a/platforms/market/src/app/screens/organisms/support-entry/SupportEntry.tsx b/platforms/market/src/app/screens/organisms/support-entry/SupportEntry.tsx index 0dfdaed..abc1396 100644 --- a/platforms/market/src/app/screens/organisms/support-entry/SupportEntry.tsx +++ b/platforms/market/src/app/screens/organisms/support-entry/SupportEntry.tsx @@ -8,7 +8,7 @@ import { useState } from 'react'; import { useTranslation } from 'react-i18next'; import { getEnv } from '../../../../env'; -import { ROUTES } from '../../../navigation'; +import { ROUTES } from '../../../navigation/navigation'; import { SUPPORT_CHAT_URLS } from './constants'; import type { SupportEntryProps } from './types'; diff --git a/platforms/market/src/app/seo/constants.ts b/platforms/market/src/app/seo/constants.ts new file mode 100644 index 0000000..abf7efb --- /dev/null +++ b/platforms/market/src/app/seo/constants.ts @@ -0,0 +1,3 @@ +/** Search results cut titles and descriptions around these lengths. */ +export const TITLE_MAX_LENGTH = 60; +export const DESCRIPTION_MAX_LENGTH = 160; diff --git a/platforms/market/src/app/seo/metadata.ts b/platforms/market/src/app/seo/metadata.ts new file mode 100644 index 0000000..0a4c238 --- /dev/null +++ b/platforms/market/src/app/seo/metadata.ts @@ -0,0 +1,76 @@ +import 'server-only'; + +import type { Metadata } from 'next'; + +import { ROUTES } from '../navigation/navigation'; +import { DESCRIPTION_MAX_LENGTH, TITLE_MAX_LENGTH } from './constants'; +import type { ChannelMetadataArgs, PostMetadataArgs } from './types'; + +/** Cut at a word, with «…», when it runs past `max`. */ +function clip(text: string, max: number): string { + if (text.length <= max) return text; + const cut = text.slice(0, max - 1); + const space = cut.lastIndexOf(' '); + return `${(space > max / 2 ? cut.slice(0, space) : cut).trimEnd()}…`; +} + +/** A channel's title, description, canonical `/@username` and profile card. */ +export function channelMetadata({ + channel, + title, + description, +}: ChannelMetadataArgs): Metadata { + const url = ROUTES.channel(channel.username); + const summary = clip( + channel.bio?.replace(/\s+/g, ' ') ?? description, + DESCRIPTION_MAX_LENGTH, + ); + return { + title, + description: summary, + alternates: { canonical: url }, + openGraph: { + type: 'profile', + title, + description: summary, + url, + username: channel.username, + images: channel.avatarUrl ? [channel.avatarUrl] : undefined, + }, + }; +} + +/** + * A post's metadata from what every visitor may read: a premium post's teaser, never its full + * text, and never its images, which are paywalled. The first line of text names it. + */ +export function postMetadata({ + channel, + post, + fallbackTitle, +}: PostMetadataArgs): Metadata { + const text = (post.locked ? post.captionPreview : post.caption)?.trim(); + const firstLine = text + ?.split('\n') + .find((line) => line.trim()) + ?.trim(); + const title = firstLine ? clip(firstLine, TITLE_MAX_LENGTH) : fallbackTitle; + const description = text + ? clip(text.replace(/\s+/g, ' '), DESCRIPTION_MAX_LENGTH) + : undefined; + const url = ROUTES.post(channel.username, post.id); + return { + title, + description, + alternates: { canonical: url }, + openGraph: { + type: 'article', + title, + description, + url, + publishedTime: post.publishedAt ?? undefined, + authors: [ROUTES.channel(channel.username)], + images: channel.avatarUrl ? [channel.avatarUrl] : undefined, + }, + }; +} diff --git a/platforms/market/src/app/seo/server.ts b/platforms/market/src/app/seo/server.ts new file mode 100644 index 0000000..f985338 --- /dev/null +++ b/platforms/market/src/app/seo/server.ts @@ -0,0 +1,4 @@ +import 'server-only'; + +export { channelMetadata, postMetadata } from './metadata'; +export type { ChannelMetadataArgs, PostMetadataArgs } from './types'; diff --git a/platforms/market/src/app/seo/types.ts b/platforms/market/src/app/seo/types.ts new file mode 100644 index 0000000..78bc309 --- /dev/null +++ b/platforms/market/src/app/seo/types.ts @@ -0,0 +1,17 @@ +import type { PublicCreatorPayload } from '../../features/channel'; +import type { PostPayload } from '../../features/post'; + +export type ChannelMetadataArgs = { + channel: PublicCreatorPayload; + /** «@sara_gold»; the root layout adds « · لومینا». */ + title: string; + description: string; +}; + +export type PostMetadataArgs = { + channel: PublicCreatorPayload; + /** As every visitor sees it: a premium post is its teaser. */ + post: PostPayload; + /** When the post has no text to name it: «پست @sara_gold». */ + fallbackTitle: string; +}; diff --git a/platforms/market/src/features/channel/caches/channel.ts b/platforms/market/src/features/channel/caches/channel.ts new file mode 100644 index 0000000..3e019a5 --- /dev/null +++ b/platforms/market/src/features/channel/caches/channel.ts @@ -0,0 +1,15 @@ +import 'server-only'; + +import { cache } from 'react'; + +import { channelRepository } from '../repositories/channel'; +import type { PublicCreatorPayload } from '../repositories/channel'; + +/** + * The channel at `/@username`, once per render per username: the page and its metadata share one + * request. Pass the username as the API stores it (no «@», lower case). 404 reaches the caller. + */ +export const getChannel = cache( + (username: string): Promise => + channelRepository.getCreatorByUsername({ username }), +); diff --git a/platforms/market/src/features/channel/caches/server.ts b/platforms/market/src/features/channel/caches/server.ts index 0099998..06797a6 100644 --- a/platforms/market/src/features/channel/caches/server.ts +++ b/platforms/market/src/features/channel/caches/server.ts @@ -1,4 +1,5 @@ import 'server-only'; +export { getChannel } from './channel'; export { getPublicCreator } from './public-creator'; export { getPublicTiers } from './public-tiers'; diff --git a/platforms/market/src/features/channel/entities/public-creator/types.ts b/platforms/market/src/features/channel/entities/public-creator/types.ts index efe82a3..476a2d2 100644 --- a/platforms/market/src/features/channel/entities/public-creator/types.ts +++ b/platforms/market/src/features/channel/entities/public-creator/types.ts @@ -15,4 +15,6 @@ export type PublicCreatorEntity = { socialLinks?: { label: string; url: string; _id?: string }[]; tradingStyle?: TradingStyle | null; markets?: Market[]; + /** Suspended by an admin: the channel shows as unavailable to everyone. */ + suspended?: boolean; }; diff --git a/platforms/market/src/features/channel/index.ts b/platforms/market/src/features/channel/index.ts index eaa9985..ec53acb 100644 --- a/platforms/market/src/features/channel/index.ts +++ b/platforms/market/src/features/channel/index.ts @@ -1,4 +1,33 @@ export type { PublicTierEntity } from './entities/public-tier'; +export { + useChannelActionsPart, + useChannelEntitled, + useChannelGate, + useChannelStanding, + useChannelViewer, +} from './models/channel'; +export type { + ChannelActionsPartModel, + ChannelGate, + ChannelStanding, + ChannelViewer, + UseChannelActionsPartOptions, +} from './models/channel'; +export { syncFollowCaches } from './models/follow-caches'; +export { useFollowingPart } from './models/following'; +export type { FollowingPartModel } from './models/following'; +export { useOwnChannel } from './models/own-channel'; +export type { OwnChannelModel } from './models/own-channel'; +export { + SHARE_CAPTION_MAX_LENGTH, + useChannelShareSheet, + useShareLink, +} from './models/share'; +export type { + ChannelShareSheetModel, + ShareLinkArgs, + UseChannelShareSheetOptions, +} from './models/share'; export { channelKeys, channelRepository } from './repositories/channel'; export type { ChannelArgs, diff --git a/platforms/market/src/features/channel/models/.gitkeep b/platforms/market/src/features/channel/models/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/channel/models/channel/index.ts b/platforms/market/src/features/channel/models/channel/index.ts new file mode 100644 index 0000000..9fae983 --- /dev/null +++ b/platforms/market/src/features/channel/models/channel/index.ts @@ -0,0 +1,14 @@ +export { useChannelActionsPart } from './use-channel-actions-part'; +export { + useChannelEntitled, + useChannelGate, + useChannelStanding, + useChannelViewer, +} from './use-channel-viewer'; +export type { + ChannelActionsPartModel, + ChannelGate, + ChannelStanding, + ChannelViewer, + UseChannelActionsPartOptions, +} from './types'; diff --git a/platforms/market/src/features/channel/models/channel/read-standing.ts b/platforms/market/src/features/channel/models/channel/read-standing.ts new file mode 100644 index 0000000..e56bedc --- /dev/null +++ b/platforms/market/src/features/channel/models/channel/read-standing.ts @@ -0,0 +1,36 @@ +import { isHttpError } from '@lumina/libs/http'; + +import { checkoutRepository } from '../../../checkout'; +import { followRepository } from '../../../follow'; +import type { ChannelStanding } from './types'; + +/** + * The investor's standing with a creator. There is no single endpoint: the follow status says + * following and subscribed, the checkout screen says a payment in flight or one that was in review + * and then failed (U10 ۵.۴; a gateway cancel is not), the waitlist, and the active subscription's + * end. `null` when checkout answers 403, which only a + * suspended creator's channel does. + */ +export async function readStanding( + creatorId: string, + signal?: AbortSignal, +): Promise { + try { + const [follow, checkout] = await Promise.all([ + followRepository.getStatus({ creatorId }, { signal }), + checkoutRepository.getScreen(creatorId, { signal }), + ]); + return { + following: follow.following, + subscribed: follow.subscribed, + paymentPending: checkout.cta.state === 'pending_review', + paymentFailed: + checkout.cta.state === 'subscribe' && checkout.lastPayment !== null, + waitlisted: checkout.waitlisted, + subscription: checkout.activeSubscription, + }; + } catch (error) { + if (isHttpError(error) && error.status === 403) return null; + throw error; + } +} diff --git a/platforms/market/src/features/channel/models/channel/types.ts b/platforms/market/src/features/channel/models/channel/types.ts new file mode 100644 index 0000000..8c61afa --- /dev/null +++ b/platforms/market/src/features/channel/models/channel/types.ts @@ -0,0 +1,73 @@ +import type { BillingPeriod } from '../../../../shared/constants'; + +/** The signed-in investor's follow and subscription with this creator. */ +export type ChannelStanding = { + following: boolean; + /** An active subscription: premium posts open and unfollow is frozen. */ + subscribed: boolean; + /** A payment waits for the bank's confirmation: subscribe is frozen. */ + paymentPending: boolean; + /** + * The latest payment to this creator failed in the last 72 hours and nothing replaced it: subscribe + * is live again, with the reverted payment's note (U10 ۵.۴ pending-reverted). + */ + paymentFailed: boolean; + /** On the full channel's capacity waitlist. */ + waitlisted: boolean; + /** + * The active subscription's end of access and the period last bought, for the post page's access + * line («دسترسی از طریق اشتراک سالانه») and the expiry while reading (C5 ۵.۲). `null` when not + * subscribed. + */ + subscription: { + id: string; + endsAt: string; + billingPeriod: BillingPeriod; + } | null; +}; + +/** + * Who is looking at the channel, as its action area shows it. `pending`: not known yet (the server + * render and the first browser render). `creator`: another creator, who can't follow or subscribe. + * `unavailable`: the API refuses this channel's checkout, which only a suspended creator gets. + */ +export type ChannelViewer = + | { kind: 'pending' } + | { kind: 'guest' } + | { kind: 'own' } + | { kind: 'creator' } + | { kind: 'unavailable' } + | { kind: 'investor'; standing: ChannelStanding }; + +/** + * The gate a locked post on this channel shows. `pending`: the viewer isn't known yet, an + * investor's standing is still on its way, or the creator's or a subscriber's locked posts are + * being read again in full. `member`: an investor without a subscription, sent to checkout. + * `creator`: another creator, who can't subscribe, so the CTA is frozen. + */ +export type ChannelGate = 'pending' | 'guest' | 'member' | 'creator'; + +export type UseChannelActionsPartOptions = { + /** The creator's account id. */ + creatorId: string; + /** For the toasts: «@username را دنبال می‌کنید.» */ + username: string; +}; + +export type ChannelActionsPartModel = { + viewer: ChannelViewer; + /** Follows at once (optimistic); a failure turns it back and says so. */ + follow: () => void; + /** Opens the unfollow confirmation. */ + askUnfollow: () => void; + isConfirmingUnfollow: boolean; + /** Unfollows at once (optimistic) and closes the confirmation. */ + confirmUnfollow: () => void; + cancelUnfollow: () => void; + /** A guest tapped follow: the login prompt. */ + isGuestPromptOpen: boolean; + openGuestPrompt: () => void; + closeGuestPrompt: () => void; + leaveWaitlist: () => void; + isLeavingWaitlist: boolean; +}; diff --git a/platforms/market/src/features/channel/models/channel/use-channel-actions-part.ts b/platforms/market/src/features/channel/models/channel/use-channel-actions-part.ts new file mode 100644 index 0000000..edde504 --- /dev/null +++ b/platforms/market/src/features/channel/models/channel/use-channel-actions-part.ts @@ -0,0 +1,117 @@ +import { showToast } from '@lumina/island/molecules/toast'; +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { showActionError } from '../../../../shared/utils'; +import { checkoutKeys, leaveWaitlist } from '../../../checkout'; +import { followCreator, unfollowCreator } from '../../../follow'; +import { channelKeys } from '../../repositories/channel'; +import { syncFollowCaches } from '../follow-caches'; +import type { + ChannelActionsPartModel, + ChannelStanding, + UseChannelActionsPartOptions, +} from './types'; +import { useChannelViewer } from './use-channel-viewer'; + +/** + * The channel's action area: subscribe, follow and unfollow, and the waitlist note. Follow and + * unfollow change the button at once and turn it back with an error toast if the request fails; + * unfollow asks first. Both refresh the home feed and the following list. A change made while + * the last one is on its way waits for it, then goes, so the last one tapped is what stays. + */ +export function useChannelActionsPart({ + creatorId, + username, +}: UseChannelActionsPartOptions): ChannelActionsPartModel { + const { t } = useTranslation('channel'); + const queryClient = useQueryClient(); + const viewer = useChannelViewer(creatorId); + const [isConfirmingUnfollow, setIsConfirmingUnfollow] = useState(false); + const [isGuestPromptOpen, setIsGuestPromptOpen] = useState(false); + const standingKey = channelKeys.standing(creatorId); + const changeFollowKey = [...standingKey, 'change-follow']; + // A later change waits behind this one: that one settles the button and says so. + const isSuperseded = () => + queryClient.isMutating({ mutationKey: changeFollowKey }) > 1; + + const patchStanding = (patch: Partial) => + queryClient.setQueryData( + standingKey, + (standing) => standing && { ...standing, ...patch }, + ); + + const changeFollow = useMutation({ + mutationKey: changeFollowKey, + // One at a time, in the order tapped; both requests are safe to send twice. + scope: { id: changeFollowKey.join(':') }, + mutationFn: (following: boolean) => + following ? followCreator({ creatorId }) : unfollowCreator({ creatorId }), + onMutate: async (following) => { + await queryClient.cancelQueries({ queryKey: standingKey }); + patchStanding({ following }); + }, + onSuccess: (_change, following) => { + if (isSuperseded()) return; + syncFollowCaches(queryClient, { creatorId, following }); + showToast( + following + ? { + tone: 'success', + message: t('follow.followed', { username }), + description: t('follow.followed-description'), + } + : { tone: 'success', message: t('follow.unfollowed', { username }) }, + ); + }, + onError: (error, following) => { + if (isSuperseded()) return; + patchStanding({ following: !following }); + // The control is the retry; a 409 (subscribed meanwhile) reloads the standing instead. + showActionError(error, { + t, + failedMessage: following + ? t('follow.follow-failed', { username }) + : t('follow.unfollow-failed', { username }), + reload: () => + void queryClient.invalidateQueries({ queryKey: standingKey }), + }); + }, + }); + + const leave = useMutation({ + mutationFn: () => leaveWaitlist({ creatorId }), + onSuccess: () => { + patchStanding({ waitlisted: false }); + void queryClient.invalidateQueries({ + queryKey: checkoutKeys.screen(creatorId), + }); + showToast({ tone: 'info', icon: 'check', message: t('waitlist.left') }); + }, + onError: (error) => + // Leaving twice is harmless, so the toast may offer to try again. + showActionError(error, { + t, + failedMessage: t('waitlist.leave-failed'), + retry: () => leave.mutate(), + }), + }); + + return { + viewer, + follow: () => changeFollow.mutate(true), + askUnfollow: () => setIsConfirmingUnfollow(true), + isConfirmingUnfollow, + confirmUnfollow: () => { + setIsConfirmingUnfollow(false); + changeFollow.mutate(false); + }, + cancelUnfollow: () => setIsConfirmingUnfollow(false), + isGuestPromptOpen, + openGuestPrompt: () => setIsGuestPromptOpen(true), + closeGuestPrompt: () => setIsGuestPromptOpen(false), + leaveWaitlist: () => leave.mutate(), + isLeavingWaitlist: leave.isPending, + }; +} diff --git a/platforms/market/src/features/channel/models/channel/use-channel-viewer.ts b/platforms/market/src/features/channel/models/channel/use-channel-viewer.ts new file mode 100644 index 0000000..dae21c4 --- /dev/null +++ b/platforms/market/src/features/channel/models/channel/use-channel-viewer.ts @@ -0,0 +1,82 @@ +import { useQuery } from '@tanstack/react-query'; + +import { useCurrentAccount, useViewerStatus } from '../../../../stores/auth'; +import { channelKeys } from '../../repositories/channel'; +import { readStanding } from './read-standing'; +import type { ChannelGate, ChannelStanding, ChannelViewer } from './types'; + +/** The standing query; only an investor on someone else's channel has one. */ +function useStandingQuery(creatorId: string, throwOnError: boolean) { + const status = useViewerStatus(); + const account = useCurrentAccount(); + const isInvestor = + status === 'member' && + account?.role === 'investor' && + account.id !== creatorId; + + return useQuery({ + queryKey: channelKeys.standing(creatorId), + queryFn: ({ signal }) => readStanding(creatorId, signal), + enabled: isInvestor, + ...(throwOnError ? {} : { throwOnError: false }), + }); +} + +/** + * Who is looking at the channel. Browser only in effect: the viewer is `pending` on the server + * and in the first browser render, and an investor's standing loads in the browser with their + * session. A failed first read throws to the action area's boundary. + */ +export function useChannelViewer(creatorId: string): ChannelViewer { + const status = useViewerStatus(); + const account = useCurrentAccount(); + const standing = useStandingQuery(creatorId, true); + + if (status === 'unknown') return { kind: 'pending' }; + if (status === 'guest' || !account) return { kind: 'guest' }; + if (account.id === creatorId) return { kind: 'own' }; + if (account.role !== 'investor') return { kind: 'creator' }; + if (standing.isPending) return { kind: 'pending' }; + return standing.data + ? { kind: 'investor', standing: standing.data } + : { kind: 'unavailable' }; +} + +/** + * The signed-in investor's standing with this creator, or `null` while unknown or for anyone + * else. It never throws: a failed read shows in the action area only. + */ +export function useChannelStanding(creatorId: string): ChannelStanding | null { + return useStandingQuery(creatorId, false).data ?? null; +} + +/** + * Whether the viewer reads this channel's premium posts in full: the creator themself, or an + * active subscriber. It never throws: a failed standing read shows in the action area, and the + * posts stay as every visitor sees them. + */ +export function useChannelEntitled(creatorId: string): boolean { + const account = useCurrentAccount(); + const standing = useChannelStanding(creatorId); + if (account?.id === creatorId) return true; + return standing?.subscribed ?? false; +} + +/** + * Which gate this channel's locked posts show the viewer. Nobody sees a CTA before it is known to + * be theirs: a subscriber waits for their standing, never seeing «اشتراک در کانال» on the way. + */ +export function useChannelGate(creatorId: string): ChannelGate { + const status = useViewerStatus(); + const account = useCurrentAccount(); + const standing = useStandingQuery(creatorId, false); + + if (status === 'unknown') return 'pending'; + if (status === 'guest' || !account) return 'guest'; + // The creator's own locked posts are read again in full. + if (account.id === creatorId) return 'pending'; + if (account.role !== 'investor') return 'creator'; + if (standing.isPending) return 'pending'; + // A failed standing read leaves the posts as every visitor sees them. + return standing.data?.subscribed ? 'pending' : 'member'; +} diff --git a/platforms/market/src/features/channel/models/follow-caches/index.ts b/platforms/market/src/features/channel/models/follow-caches/index.ts new file mode 100644 index 0000000..29ed47f --- /dev/null +++ b/platforms/market/src/features/channel/models/follow-caches/index.ts @@ -0,0 +1 @@ +export { syncFollowCaches } from './sync-follow-caches'; diff --git a/platforms/market/src/features/channel/models/follow-caches/sync-follow-caches.ts b/platforms/market/src/features/channel/models/follow-caches/sync-follow-caches.ts new file mode 100644 index 0000000..ad90599 --- /dev/null +++ b/platforms/market/src/features/channel/models/follow-caches/sync-follow-caches.ts @@ -0,0 +1,23 @@ +import type { QueryClient } from '@tanstack/react-query'; + +import { feedKeys } from '../../../feed'; +import { followKeys } from '../../../follow'; +import { channelKeys } from '../../repositories/channel'; +import type { ChannelStanding } from '../channel'; + +/** + * A follow or unfollow of the creator succeeded, on their channel or in the following list: their + * channel's standing shows it, and the home feed and the following list read again. No follower + * count is cached in the browser: the channel's counts come from its server render. + */ +export function syncFollowCaches( + queryClient: QueryClient, + { creatorId, following }: { creatorId: string; following: boolean }, +): void { + queryClient.setQueryData( + channelKeys.standing(creatorId), + (standing) => standing && { ...standing, following }, + ); + void queryClient.invalidateQueries({ queryKey: feedKeys.all }); + void queryClient.invalidateQueries({ queryKey: followKeys.following() }); +} diff --git a/platforms/market/src/features/channel/models/following/index.ts b/platforms/market/src/features/channel/models/following/index.ts new file mode 100644 index 0000000..ea90163 --- /dev/null +++ b/platforms/market/src/features/channel/models/following/index.ts @@ -0,0 +1,2 @@ +export { useFollowingPart } from './use-following-part'; +export type { FollowingPartModel } from './types'; diff --git a/platforms/market/src/features/channel/models/following/types.ts b/platforms/market/src/features/channel/models/following/types.ts new file mode 100644 index 0000000..24420aa --- /dev/null +++ b/platforms/market/src/features/channel/models/following/types.ts @@ -0,0 +1,30 @@ +import type { LoadMoreErrorKind } from '../../../../shared/utils'; +import type { FollowingPayload } from '../../../follow'; + +export type FollowingPartModel = { + /** The creators the investor follows, newest follow first, each once. */ + rows: FollowingPayload[]; + /** The API holds more follows than the pages read so far; rare, a page holds 50. */ + hasMore: boolean; + /** Reads the next page; nothing while any read of the list is on its way. Also its retry. */ + loadMore: () => void; + isLoadingMore: boolean; + /** + * The next page failed: an inline row with a retry takes the «more» button's place, and the + * rows read so far stay. `null` otherwise. + */ + loadMoreError: LoadMoreErrorKind | null; + /** + * The row whose unfollow is being asked about. It stays after the question closes, so the sheet + * or modal closes on the same name. + */ + unfollowTarget: FollowingPayload | null; + isConfirmingUnfollow: boolean; + /** The unfollow is on its way: the question waits, its confirm spinning. */ + isUnfollowing: boolean; + /** Opens the unfollow question for a row whose unfollow is live. */ + askUnfollow: (row: FollowingPayload) => void; + /** Sends the unfollow; the row leaves once the API agrees. */ + confirmUnfollow: () => void; + cancelUnfollow: () => void; +}; diff --git a/platforms/market/src/features/channel/models/following/use-following-part.ts b/platforms/market/src/features/channel/models/following/use-following-part.ts new file mode 100644 index 0000000..9a1df58 --- /dev/null +++ b/platforms/market/src/features/channel/models/following/use-following-part.ts @@ -0,0 +1,144 @@ +import { showToast } from '@lumina/island/molecules/toast'; +import { classifyError } from '@lumina/libs/error-handler'; +import { isHttpError } from '@lumina/libs/http'; +import { + useMutation, + useQueryClient, + useSuspenseInfiniteQuery, +} from '@tanstack/react-query'; +import type { InfiniteData } from '@tanstack/react-query'; +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { + firstOfEach, + loadMoreErrorKind, + showActionError, +} from '../../../../shared/utils'; +import { + FOLLOWING_PAGE_LIMIT, + followKeys, + followRepository, + unfollowCreator, +} from '../../../follow'; +import type { FollowingPagePayload, FollowingPayload } from '../../../follow'; +import { syncFollowCaches } from '../follow-caches'; +import type { FollowingPartModel } from './types'; + +/** The read pages without the creator just unfollowed. */ +function withoutCreator( + data: InfiniteData, + creatorId: string, +): InfiniteData { + return { + ...data, + pages: data.pages.map((page) => ({ + ...page, + items: page.items.filter((row) => row.creatorId !== creatorId), + })), + }; +} + +/** + * The investor's following list (U8 §۴, ۶.۱), read in the browser with their session, newest + * follow first. Unfollow asks first (U8 ۴.۲, ۶.۲) and waits for the API: the row leaves with a + * toast once it agrees, and the creator's channel and the home feed catch up (`syncFollowCaches`). + * A failure keeps the row as it was with an error toast and no retry, because the row's control is + * the retry (U8 ۴.۶); a 404 reads the list again, so the row shows what is true now. A 409 means + * the investor subscribed meanwhile: the list is read again, so the row's unfollow freezes, and + * the toast gives the frozen reason rather than the server's message. + */ +export function useFollowingPart(): FollowingPartModel { + const { t } = useTranslation('channel'); + const queryClient = useQueryClient(); + const [unfollowTarget, setUnfollowTarget] = useState( + null, + ); + const [isConfirmingUnfollow, setIsConfirmingUnfollow] = useState(false); + + const following = useSuspenseInfiniteQuery({ + queryKey: followKeys.following(), + queryFn: ({ pageParam, signal }) => + followRepository.listFollowing( + { page: pageParam, limit: FOLLOWING_PAGE_LIMIT }, + { signal }, + ), + initialPageParam: 1, + getNextPageParam: ({ page, limit, total }) => + page * limit < total ? page + 1 : undefined, + }); + + const unfollow = useMutation({ + mutationFn: ({ creatorId }: FollowingPayload) => + unfollowCreator({ creatorId }), + onSuccess: (_change, { creatorId, creator }) => { + setIsConfirmingUnfollow(false); + queryClient.setQueryData>( + followKeys.following(), + (data) => data && withoutCreator(data, creatorId), + ); + syncFollowCaches(queryClient, { creatorId, following: false }); + showToast({ + tone: 'success', + message: t('follow.unfollowed', { username: creator.username }), + }); + }, + onError: (error, { creator }) => { + setIsConfirmingUnfollow(false); + if (isHttpError(error) && error.status === 409) { + void queryClient.invalidateQueries({ + queryKey: followKeys.following(), + }); + showToast({ + tone: 'error', + message: t('follow.unfollow-failed', { username: creator.username }), + description: t('actions.unfollow-frozen'), + }); + return; + } + if (classifyError(error).retry === 'reload') { + void queryClient.invalidateQueries({ + queryKey: followKeys.following(), + }); + } + showActionError(error, { + t, + failedMessage: t('follow.unfollow-failed', { + username: creator.username, + }), + }); + }, + }); + + return { + rows: firstOfEach( + following.data.pages.flatMap((page) => page.items), + (row) => row.creatorId, + ), + hasMore: following.hasNextPage, + loadMore: () => { + // fetchNextPage cancels a read of every page on its way (cancelRefetch), and would add the + // next page to the pages read before it, skipping or repeating rows: wait for it instead. + if (!following.isFetching) void following.fetchNextPage(); + }, + isLoadingMore: following.isFetchingNextPage, + loadMoreError: following.isFetchNextPageError + ? loadMoreErrorKind(following.error) + : null, + unfollowTarget, + isConfirmingUnfollow, + isUnfollowing: unfollow.isPending, + askUnfollow: (row) => { + setUnfollowTarget(row); + setIsConfirmingUnfollow(true); + }, + confirmUnfollow: () => { + if (unfollowTarget && !unfollow.isPending) + unfollow.mutate(unfollowTarget); + }, + cancelUnfollow: () => { + // Once sent, the answer closes the question. + if (!unfollow.isPending) setIsConfirmingUnfollow(false); + }, + }; +} diff --git a/platforms/market/src/features/channel/models/own-channel/index.ts b/platforms/market/src/features/channel/models/own-channel/index.ts new file mode 100644 index 0000000..9f977cf --- /dev/null +++ b/platforms/market/src/features/channel/models/own-channel/index.ts @@ -0,0 +1,2 @@ +export { useOwnChannel } from './use-own-channel'; +export type { OwnChannelModel } from './types'; diff --git a/platforms/market/src/features/channel/models/own-channel/types.ts b/platforms/market/src/features/channel/models/own-channel/types.ts new file mode 100644 index 0000000..81a642b --- /dev/null +++ b/platforms/market/src/features/channel/models/own-channel/types.ts @@ -0,0 +1,13 @@ +import type { CreatorStanding } from '../../../profile'; +import type { PublicCreatorPayload } from '../../repositories/channel'; + +export type OwnChannelModel = + | { status: 'pending' } + | { + status: 'ready'; + /** Their profile as the channel header draws it. */ + channel: PublicCreatorPayload; + standing: CreatorStanding; + /** Why the identity check was rejected, when the admin gave a reason (C4 ۲.۵). */ + rejectionReason: string | null; + }; diff --git a/platforms/market/src/features/channel/models/own-channel/use-own-channel.ts b/platforms/market/src/features/channel/models/own-channel/use-own-channel.ts new file mode 100644 index 0000000..3158e47 --- /dev/null +++ b/platforms/market/src/features/channel/models/own-channel/use-own-channel.ts @@ -0,0 +1,44 @@ +import { useQuery } from '@tanstack/react-query'; + +import { + creatorStandingOf, + profileKeys, + profileRepository, +} from '../../../profile'; +import type { CreatorProfilePayload } from '../../../profile'; +import type { PublicCreatorPayload } from '../../repositories/channel'; +import type { OwnChannelModel } from './types'; + +function toChannel(profile: CreatorProfilePayload): PublicCreatorPayload { + return { + profileId: profile.profileId, + creatorId: profile.creatorId, + username: profile.username, + displayName: profile.displayName, + bio: profile.bio, + avatarUrl: profile.avatarUrl, + socialLinks: profile.socialLinks, + tradingStyle: profile.tradingStyle, + markets: profile.markets, + suspended: profile.kycStatus === 'suspended', + }; +} + +/** + * A creator's own channel before it is public (C6 ۱.۲): the API serves the public channel only + * once their identity is approved, so their own page reads their profile with their session. + */ +export function useOwnChannel(): OwnChannelModel { + const query = useQuery({ + queryKey: profileKeys.mine(), + queryFn: ({ signal }) => profileRepository.getMine({ signal }), + }); + if (!query.data) return { status: 'pending' }; + const profile = query.data; + return { + status: 'ready', + channel: toChannel(profile), + standing: creatorStandingOf(profile), + rejectionReason: profile.rejectionReason, + }; +} diff --git a/platforms/market/src/features/channel/models/share/constants.ts b/platforms/market/src/features/channel/models/share/constants.ts new file mode 100644 index 0000000..fbea97a --- /dev/null +++ b/platforms/market/src/features/channel/models/share/constants.ts @@ -0,0 +1,5 @@ +/** The creator's last confirmed share caption, on this device; logout clears `session.` keys. */ +export const SHARE_CAPTION_KEY = 'session.channel-share-caption'; + +/** C6 ۲.۱: a caption is a line, not a post. */ +export const SHARE_CAPTION_MAX_LENGTH = 150; diff --git a/platforms/market/src/features/channel/models/share/index.ts b/platforms/market/src/features/channel/models/share/index.ts new file mode 100644 index 0000000..4008295 --- /dev/null +++ b/platforms/market/src/features/channel/models/share/index.ts @@ -0,0 +1,8 @@ +export { SHARE_CAPTION_MAX_LENGTH } from './constants'; +export { useChannelShareSheet } from './use-channel-share-sheet'; +export { useShareLink } from './use-share-link'; +export type { + ChannelShareSheetModel, + ShareLinkArgs, + UseChannelShareSheetOptions, +} from './types'; diff --git a/platforms/market/src/features/channel/models/share/types.ts b/platforms/market/src/features/channel/models/share/types.ts new file mode 100644 index 0000000..9eb4c0f --- /dev/null +++ b/platforms/market/src/features/channel/models/share/types.ts @@ -0,0 +1,32 @@ +export type ShareLinkArgs = { + /** What is shared: it picks the shared text and the copied toast. */ + kind: 'channel' | 'post'; + /** A path on this site: `/@sara_gold`, `/@sara_gold/posts/…`. */ + path: string; + /** The channel's username, for the shared text. */ + username: string; + /** Mobile: the device's share sheet when it has one. Desktop: copy the link. */ + native: boolean; +}; + +export type UseChannelShareSheetOptions = { + /** The channel's path on this site: `/@sara_gold`. */ + path: string; + /** Mobile: «اشتراک‌گذاری» hands caption and link to the device's share sheet. */ + native: boolean; +}; + +export type ChannelShareSheetModel = { + isOpen: boolean; + open: () => void; + close: () => void; + caption: string; + setCaption: (caption: string) => void; + /** Mobile: the share sheet; desktop: «کپی همه». Either way the caption is remembered. */ + shareAll: () => void; + /** The bare link only; the caption isn't remembered. */ + copyLink: () => void; + /** The browser refused the clipboard: the sheet stays open with its caption. */ + failed: 'all' | 'link' | null; + retry: () => void; +}; diff --git a/platforms/market/src/features/channel/models/share/use-channel-share-sheet.ts b/platforms/market/src/features/channel/models/share/use-channel-share-sheet.ts new file mode 100644 index 0000000..2b45439 --- /dev/null +++ b/platforms/market/src/features/channel/models/share/use-channel-share-sheet.ts @@ -0,0 +1,91 @@ +import { showToast } from '@lumina/island/molecules/toast'; +import { storage } from '@lumina/libs/local-storage'; +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { SHARE_CAPTION_KEY } from './constants'; +import type { + ChannelShareSheetModel, + UseChannelShareSheetOptions, +} from './types'; + +/** + * The creator's channel share (C6): a short caption above the link, the last one they confirmed + * kept on this device («من را در لومینا دنبال کن 👇» until then). Mobile hands caption and link to + * the share sheet, and copies them when that sheet can't open; desktop copies them. «کپی لینک» + * copies the bare link and forgets nothing. A clipboard refusal keeps the sheet open, so the + * caption isn't lost. + */ +export function useChannelShareSheet({ + path, + native, +}: UseChannelShareSheetOptions): ChannelShareSheetModel { + const { t } = useTranslation('channel'); + const [isOpen, setIsOpen] = useState(false); + const [caption, setCaption] = useState(''); + const [failed, setFailed] = useState<'all' | 'link' | null>(null); + const url = () => new URL(path, window.location.origin).toString(); + const withCaption = () => { + const text = caption.trim(); + return text ? `${text}\n${url()}` : url(); + }; + const close = () => { + setIsOpen(false); + setFailed(null); + }; + + const copy = async (kind: 'all' | 'link') => { + try { + await navigator.clipboard.writeText( + kind === 'all' ? withCaption() : url(), + ); + if (kind === 'all') storage.setItem(SHARE_CAPTION_KEY, caption); + close(); + showToast({ + tone: 'success', + message: t( + kind === 'all' ? 'share.owner.all-copied' : 'share.channel-copied', + ), + }); + } catch { + setFailed(kind); + } + }; + + const shareAll = async () => { + if (!native || typeof navigator.share !== 'function') { + await copy('all'); + return; + } + try { + await navigator.share({ text: caption.trim() || undefined, url: url() }); + } catch (error) { + // Closing the device's sheet is a change of mind, not a failure: this sheet stays as it was, + // and the caption isn't kept, since it was never shared. + if (error instanceof DOMException && error.name === 'AbortError') return; + // The sheet couldn't open: copying still works. + await copy('all'); + return; + } + storage.setItem(SHARE_CAPTION_KEY, caption); + close(); + }; + + return { + isOpen, + open: () => { + setCaption( + storage.getItem(SHARE_CAPTION_KEY) ?? t('share.owner.default-caption'), + ); + setFailed(null); + setIsOpen(true); + }, + close, + caption, + setCaption, + shareAll: () => void shareAll(), + copyLink: () => void copy('link'), + failed, + retry: () => void copy(failed ?? 'all'), + }; +} diff --git a/platforms/market/src/features/channel/models/share/use-share-link.ts b/platforms/market/src/features/channel/models/share/use-share-link.ts new file mode 100644 index 0000000..63b4665 --- /dev/null +++ b/platforms/market/src/features/channel/models/share/use-share-link.ts @@ -0,0 +1,55 @@ +import { showToast } from '@lumina/island/molecules/toast'; +import { useCallback } from 'react'; +import { useTranslation } from 'react-i18next'; + +import type { ShareLinkArgs } from './types'; + +/** + * Shares a channel or a post by its link. On mobile it hands the link to the device's share sheet, + * which picks the destinations; without one, and on desktop, it copies the link and says so. + * Closing the share sheet is not a failure. + */ +export function useShareLink(): (args: ShareLinkArgs) => Promise { + const { t } = useTranslation('channel'); + + return useCallback( + async ({ kind, path, username, native }: ShareLinkArgs) => { + const url = new URL(path, window.location.origin).toString(); + if (native && typeof navigator.share === 'function') { + try { + await navigator.share({ + text: t( + kind === 'channel' ? 'share.channel-text' : 'share.post-text', + { + username, + }, + ), + url, + }); + return; + } catch (error) { + if (error instanceof DOMException && error.name === 'AbortError') { + return; + } + // The sheet couldn't open: copying still works. + } + } + try { + await navigator.clipboard.writeText(url); + showToast({ + tone: 'success', + message: t( + kind === 'channel' ? 'share.channel-copied' : 'share.post-copied', + ), + }); + } catch { + showToast({ + tone: 'error', + message: t('share.copy-failed'), + description: t('share.copy-failed-description'), + }); + } + }, + [t], + ); +} diff --git a/platforms/market/src/features/channel/repositories/channel/constants.ts b/platforms/market/src/features/channel/repositories/channel/constants.ts index 677a1a5..2a2c584 100644 --- a/platforms/market/src/features/channel/repositories/channel/constants.ts +++ b/platforms/market/src/features/channel/repositories/channel/constants.ts @@ -16,4 +16,7 @@ export const channelKeys = { [...channelKeys.creator(creatorId), 'tiers'] as const, byUsername: (username: string) => [...channelKeys.all, 'username', username] as const, + /** The signed-in investor's follow and subscription with this creator. */ + standing: (creatorId: string) => + [...channelKeys.creator(creatorId), 'standing'] as const, }; diff --git a/platforms/market/src/features/channel/repositories/channel/mappers.ts b/platforms/market/src/features/channel/repositories/channel/mappers.ts index e12bbb6..f56aeac 100644 --- a/platforms/market/src/features/channel/repositories/channel/mappers.ts +++ b/platforms/market/src/features/channel/repositories/channel/mappers.ts @@ -23,6 +23,7 @@ export function toPublicCreatorPayload( })), tradingStyle: dto.tradingStyle ?? null, markets: dto.markets ?? [], + suspended: dto.suspended ?? false, }; } diff --git a/platforms/market/src/features/channel/repositories/channel/types.ts b/platforms/market/src/features/channel/repositories/channel/types.ts index 22e47bb..1e97791 100644 --- a/platforms/market/src/features/channel/repositories/channel/types.ts +++ b/platforms/market/src/features/channel/repositories/channel/types.ts @@ -28,6 +28,8 @@ export type PublicCreatorPayload = { socialLinks: SocialLinkPayload[]; tradingStyle: TradingStyle | null; markets: Market[]; + /** Suspended: no header, posts or actions for anyone, only «این کانال در دسترس نیست». */ + suspended: boolean; }; export type PublicCreatorResponseDto = PublicCreatorEntity; diff --git a/platforms/market/src/features/checkout/actions/.gitkeep b/platforms/market/src/features/checkout/actions/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/checkout/actions/leave-waitlist/actions.ts b/platforms/market/src/features/checkout/actions/leave-waitlist/actions.ts new file mode 100644 index 0000000..470487a --- /dev/null +++ b/platforms/market/src/features/checkout/actions/leave-waitlist/actions.ts @@ -0,0 +1,17 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { CHECKOUT_EVENTS } from '../../constants'; +import { checkoutRepository } from '../../repositories/checkout'; + +/** + * Takes the investor off a full channel's waitlist: no notice when a seat opens. Succeeds when + * they were not on it too. Emits `checkout.waitlist-left`. + */ +export async function leaveWaitlist( + { creatorId }: { creatorId: string }, + { emit = true }: { emit?: boolean } = {}, +): Promise<'ok'> { + await checkoutRepository.leaveWaitlist(creatorId); + if (emit) eventEmitter.emit(CHECKOUT_EVENTS.waitlistLeft, { creatorId }); + return 'ok'; +} diff --git a/platforms/market/src/features/checkout/actions/leave-waitlist/index.ts b/platforms/market/src/features/checkout/actions/leave-waitlist/index.ts new file mode 100644 index 0000000..09ec772 --- /dev/null +++ b/platforms/market/src/features/checkout/actions/leave-waitlist/index.ts @@ -0,0 +1 @@ +export { leaveWaitlist } from './actions'; diff --git a/platforms/market/src/features/checkout/constants.ts b/platforms/market/src/features/checkout/constants.ts new file mode 100644 index 0000000..690b0fe --- /dev/null +++ b/platforms/market/src/features/checkout/constants.ts @@ -0,0 +1,4 @@ +/** Events checkout actions emit when they succeed. */ +export const CHECKOUT_EVENTS = { + waitlistLeft: 'checkout.waitlist-left', +} as const; diff --git a/platforms/market/src/features/checkout/index.ts b/platforms/market/src/features/checkout/index.ts index f3dd620..dcb9f0a 100644 --- a/platforms/market/src/features/checkout/index.ts +++ b/platforms/market/src/features/checkout/index.ts @@ -1,3 +1,7 @@ +import './types'; + +export { leaveWaitlist } from './actions/leave-waitlist'; +export { CHECKOUT_EVENTS } from './constants'; export type { CheckoutResultEntity } from './entities/checkout-result'; export { checkoutKeys, diff --git a/platforms/market/src/features/checkout/repositories/checkout/mappers.ts b/platforms/market/src/features/checkout/repositories/checkout/mappers.ts index e4ad011..65d703a 100644 --- a/platforms/market/src/features/checkout/repositories/checkout/mappers.ts +++ b/platforms/market/src/features/checkout/repositories/checkout/mappers.ts @@ -60,6 +60,20 @@ export function toCheckoutPayload(dto: CheckoutResponseDto): CheckoutPayload { pendingPaymentId: dto.cta.paymentId, }, waitlisted: dto.waitlist.joined, + lastPayment: dto.lastPayment + ? { + status: dto.lastPayment.status, + at: dto.lastPayment.at, + paymentId: dto.lastPayment.paymentId, + } + : null, + activeSubscription: dto.activeSubscription + ? { + id: dto.activeSubscription.subscriptionId, + endsAt: dto.activeSubscription.endsAt, + billingPeriod: dto.activeSubscription.billingPeriod, + } + : null, }; } diff --git a/platforms/market/src/features/checkout/repositories/checkout/types.ts b/platforms/market/src/features/checkout/repositories/checkout/types.ts index 7568491..dee76d5 100644 --- a/platforms/market/src/features/checkout/repositories/checkout/types.ts +++ b/platforms/market/src/features/checkout/repositories/checkout/types.ts @@ -51,6 +51,25 @@ export type CheckoutResponseDto = { explanationFa: string | null; paymentId: string | null; }; + /** + * `subscribe` only: the investor's latest payment to this creator that reached the bank, when it + * was in review and then failed or expired in the last 72 hours; `null` otherwise, a gateway + * cancel included. An API older than this field leaves it out. + */ + lastPayment?: { + status: 'failed' | 'expired'; + at: string; + paymentId: string; + } | null; + /** + * `active` only: the running subscription; `endsAt` is its `currentPeriodEnd` and + * `billingPeriod` its tier's. `null` otherwise. An API older than this field leaves it out. + */ + activeSubscription?: { + subscriptionId: string; + endsAt: string; + billingPeriod: BillingPeriod; + } | null; }; /** A tier on the checkout screen. */ @@ -92,6 +111,25 @@ export type CheckoutPayload = { }; /** On this creator's capacity waitlist; paying stays possible. */ waitlisted: boolean; + /** + * While `cta.state` is `subscribe`: the latest payment to this creator that reached the bank was + * in review («پرداخت در حال بررسی») and then failed or expired in the last 72 hours, and nothing + * replaced it (U10 ۵.۴). `null` otherwise: cancelling at the gateway is not a failure (U10 §۶). + */ + lastPayment: { + status: 'failed' | 'expired'; + at: string; + paymentId: string; + } | null; + /** + * While `cta.state` is `active`: the subscription's id, the end of its access (`endsAt`, renewals + * included) and the period last bought. `null` otherwise. + */ + activeSubscription: { + id: string; + endsAt: string; + billingPeriod: BillingPeriod; + } | null; }; // POST /subscriptions/referral/validate and POST /subscriptions/waitlist diff --git a/platforms/market/src/features/checkout/types.ts b/platforms/market/src/features/checkout/types.ts new file mode 100644 index 0000000..261aa89 --- /dev/null +++ b/platforms/market/src/features/checkout/types.ts @@ -0,0 +1,7 @@ +declare module '@lumina/libs/event-emitter' { + interface EventMap { + 'checkout.waitlist-left': { creatorId: string }; + } +} + +export {}; diff --git a/platforms/market/src/features/feed/entities/.gitkeep b/platforms/market/src/features/feed/entities/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/feed/entities/feed-item/index.ts b/platforms/market/src/features/feed/entities/feed-item/index.ts new file mode 100644 index 0000000..990a460 --- /dev/null +++ b/platforms/market/src/features/feed/entities/feed-item/index.ts @@ -0,0 +1 @@ +export type { FeedCreatorEntity, FeedItemEntity } from './types'; diff --git a/platforms/market/src/features/feed/entities/feed-item/types.ts b/platforms/market/src/features/feed/entities/feed-item/types.ts new file mode 100644 index 0000000..881dc35 --- /dev/null +++ b/platforms/market/src/features/feed/entities/feed-item/types.ts @@ -0,0 +1,20 @@ +import type { PostEntity } from '../../../post'; + +/** + * The author of a feed item: content-service's creator card. `id` is the creator's user id (the + * post's `creatorId`). The feed leaves out suspended and unapproved creators, so `suspended` is + * always `false` here; it is kept so every creator card has one shape. + */ +export type FeedCreatorEntity = { + id: string; + /** Without the «@». */ + username: string; + /** A root-relative upload path (`/uploads/avatars/…`); `null` without a photo. */ + avatar: string | null; + /** trader-service `verificationStatus` is `approved`. */ + verified: boolean; + suspended: boolean; +}; + +/** content-service `listFeed`: one post as the investor may see it (`toPostView`), with its author. */ +export type FeedItemEntity = PostEntity & { creator: FeedCreatorEntity }; diff --git a/platforms/market/src/features/feed/index.ts b/platforms/market/src/features/feed/index.ts index c382479..d0fa76e 100644 --- a/platforms/market/src/features/feed/index.ts +++ b/platforms/market/src/features/feed/index.ts @@ -1,7 +1,14 @@ +export { useHomeFeedPart } from './models/home-feed'; +export type { HomeFeedPartModel } from './models/home-feed'; export { FEED_ENDPOINT, FEED_PAGE_LIMIT, feedKeys, feedRepository, } from './repositories/feed'; -export type { FeedPayload, ListFeedArgs } from './repositories/feed'; +export type { + FeedCreatorPayload, + FeedItemPayload, + FeedPayload, + ListFeedArgs, +} from './repositories/feed'; diff --git a/platforms/market/src/features/feed/models/.gitkeep b/platforms/market/src/features/feed/models/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/feed/models/home-feed/index.ts b/platforms/market/src/features/feed/models/home-feed/index.ts new file mode 100644 index 0000000..467bfbc --- /dev/null +++ b/platforms/market/src/features/feed/models/home-feed/index.ts @@ -0,0 +1,2 @@ +export { useHomeFeedPart } from './use-home-feed-part'; +export type { HomeFeedPartModel } from './types'; diff --git a/platforms/market/src/features/feed/models/home-feed/types.ts b/platforms/market/src/features/feed/models/home-feed/types.ts new file mode 100644 index 0000000..c5f68a9 --- /dev/null +++ b/platforms/market/src/features/feed/models/home-feed/types.ts @@ -0,0 +1,16 @@ +import type { PostListModel } from '../../../post'; +import type { FeedItemPayload } from '../../repositories/feed'; + +export type HomeFeedPartModel = PostListModel & { + /** + * The investor follows at least one creator, suspended ones included. With no posts, `false` is + * S2-01 (following nobody yet) and `true` means the creators they follow have nothing to show: + * no posts yet, or suspended. + */ + followsAnyone: boolean; + /** + * What the posts' relative times count from: when the pages were last read. The feed is read in + * the browser only, so the server render's time would date every later page. + */ + now: string; +}; diff --git a/platforms/market/src/features/feed/models/home-feed/use-home-feed-part.ts b/platforms/market/src/features/feed/models/home-feed/use-home-feed-part.ts new file mode 100644 index 0000000..2774a97 --- /dev/null +++ b/platforms/market/src/features/feed/models/home-feed/use-home-feed-part.ts @@ -0,0 +1,40 @@ +import { useSuspenseInfiniteQuery } from '@tanstack/react-query'; + +import { usePostList } from '../../../post'; +import { + FEED_PAGE_LIMIT, + feedKeys, + feedRepository, +} from '../../repositories/feed'; +import type { HomeFeedPartModel } from './types'; + +/** + * The investor's خانه: the published posts of every creator they follow, newest first, each with + * its author, page after page. Investors only, so it is read in the browser alone, with the + * session: premium posts the investor subscribes to arrive open, and nothing is read again for + * them. The feed is not refreshed in the background (U10 ۲.۳, U11 ۲.۴): never on window focus, and + * on reconnect only as every query is, once (S4-04). A follow or unfollow elsewhere marks it stale + * (`syncFollowCaches`), so the next visit reads it again. A post read in full stays open while the + * list is mounted (C5 §۵), as `usePostList` keeps it. + */ +export function useHomeFeedPart(): HomeFeedPartModel { + const feed = useSuspenseInfiniteQuery({ + queryKey: feedKeys.home(), + queryFn: ({ pageParam, signal }) => + feedRepository.listHome( + { page: pageParam, limit: FEED_PAGE_LIMIT }, + { signal }, + ), + initialPageParam: 1, + getNextPageParam: ({ page, limit, total }) => + page * limit < total ? page + 1 : undefined, + refetchOnWindowFocus: false, + }); + const list = usePostList({ query: feed }); + + return { + ...list, + followsAnyone: (feed.data.pages[0]?.followingCount ?? 0) > 0, + now: new Date(feed.dataUpdatedAt).toISOString(), + }; +} diff --git a/platforms/market/src/features/feed/repositories/feed/constants.ts b/platforms/market/src/features/feed/repositories/feed/constants.ts index 0ef7b23..0cda4ac 100644 --- a/platforms/market/src/features/feed/repositories/feed/constants.ts +++ b/platforms/market/src/features/feed/repositories/feed/constants.ts @@ -1,12 +1,10 @@ -import type { ListFeedArgs } from './types'; - export const FEED_ENDPOINT = '/posts/feed'; -/** The page size the feed asks for, so a server-rendered first page and the next pages agree. */ +/** The page size the home feed asks for, so every page it loads agrees. */ export const FEED_PAGE_LIMIT = 20; export const feedKeys = { all: ['feed'] as const, - lists: () => [...feedKeys.all, 'list'] as const, - list: (args: ListFeedArgs = {}) => [...feedKeys.lists(), args] as const, + /** The investor's home feed, page after page, as it loads them: no page in the key. */ + home: () => [...feedKeys.all, 'home'] as const, }; diff --git a/platforms/market/src/features/feed/repositories/feed/feed.ts b/platforms/market/src/features/feed/repositories/feed/feed.ts index 97eeadc..26d4d11 100644 --- a/platforms/market/src/features/feed/repositories/feed/feed.ts +++ b/platforms/market/src/features/feed/repositories/feed/feed.ts @@ -5,11 +5,12 @@ import type { FeedPayload, ListFeedArgs, ListFeedResponseDto } from './types'; /** * The investor's home feed: published posts of every creator they follow, newest first, premium - * ones locked unless subscribed. Investors only: 401 for a guest, 403 for a creator. Following - * nobody gives an empty page. + * ones locked unless subscribed. Each item carries its author. Suspended and unapproved creators' + * posts are left out before paging, so `total` counts only what can be shown. Investors only: 401 + * for a guest, 403 for a creator. Following nobody gives an empty page with `followingCount: 0`. */ export const feedRepository = { - async list( + async listHome( { page, limit }: ListFeedArgs = {}, { signal }: { signal?: AbortSignal } = {}, ): Promise { diff --git a/platforms/market/src/features/feed/repositories/feed/index.ts b/platforms/market/src/features/feed/repositories/feed/index.ts index 7d4b98f..535fa21 100644 --- a/platforms/market/src/features/feed/repositories/feed/index.ts +++ b/platforms/market/src/features/feed/repositories/feed/index.ts @@ -1,3 +1,8 @@ export { FEED_ENDPOINT, FEED_PAGE_LIMIT, feedKeys } from './constants'; export { feedRepository } from './feed'; -export type { FeedPayload, ListFeedArgs } from './types'; +export type { + FeedCreatorPayload, + FeedItemPayload, + FeedPayload, + ListFeedArgs, +} from './types'; diff --git a/platforms/market/src/features/feed/repositories/feed/mappers.ts b/platforms/market/src/features/feed/repositories/feed/mappers.ts index 56b814a..e13be9b 100644 --- a/platforms/market/src/features/feed/repositories/feed/mappers.ts +++ b/platforms/market/src/features/feed/repositories/feed/mappers.ts @@ -1,11 +1,36 @@ +import { toApiUrl } from '../../../../shared/utils'; import { toPostPayload } from '../../../post'; -import type { FeedPayload, ListFeedResponseDto } from './types'; +import type { + FeedCreatorEntity, + FeedItemEntity, +} from '../../entities/feed-item'; +import type { + FeedCreatorPayload, + FeedItemPayload, + FeedPayload, + ListFeedResponseDto, +} from './types'; + +function toFeedCreatorPayload(dto: FeedCreatorEntity): FeedCreatorPayload { + return { + id: dto.id, + username: dto.username, + avatarUrl: toApiUrl(dto.avatar), + verified: dto.verified, + suspended: dto.suspended, + }; +} + +function toFeedItemPayload(dto: FeedItemEntity): FeedItemPayload { + return { ...toPostPayload(dto), creator: toFeedCreatorPayload(dto.creator) }; +} export function toFeedPayload(dto: ListFeedResponseDto): FeedPayload { return { - items: dto.items.map(toPostPayload), + items: dto.items.map(toFeedItemPayload), total: dto.total, page: dto.page, limit: dto.limit, + followingCount: dto.followingCount, }; } diff --git a/platforms/market/src/features/feed/repositories/feed/types.ts b/platforms/market/src/features/feed/repositories/feed/types.ts index 2f11609..99449ca 100644 --- a/platforms/market/src/features/feed/repositories/feed/types.ts +++ b/platforms/market/src/features/feed/repositories/feed/types.ts @@ -1,16 +1,46 @@ -import type { PostEntity, PostPagePayload } from '../../../post'; +import type { PostPayload } from '../../../post'; +import type { FeedItemEntity } from '../../entities/feed-item'; export type ListFeedArgs = { - /** From 1; the API defaults to 1. */ + /** From 1; the API defaults to 1 and raises anything lower to 1. */ page?: number; - /** The API defaults to 20. */ + /** 1 to 50; the API defaults to 20. */ limit?: number; }; export type ListFeedResponseDto = { - items: PostEntity[]; + items: FeedItemEntity[]; total: number; page: number; limit: number; + followingCount: number; +}; + +/** The author of a feed item, as its card draws it. `id` is the creator's user id. */ +export type FeedCreatorPayload = { + id: string; + /** Without the «@». */ + username: string; + /** Absolute, through the API proxy; `null` without a photo. */ + avatarUrl: string | null; + verified: boolean; + /** Always `false` on the feed: a suspended creator's posts are left out. */ + suspended: boolean; +}; + +/** One home feed item: the post as the investor may see it, with its author. */ +export type FeedItemPayload = PostPayload & { creator: FeedCreatorPayload }; + +/** A page of the home feed, newest first, paged like a channel's posts. */ +export type FeedPayload = { + items: FeedItemPayload[]; + /** Posts that can be shown: suspended and unapproved creators' posts are not counted. */ + total: number; + page: number; + limit: number; + /** + * How many creators the investor follows, suspended ones included, though their posts are left + * out. `0` with no items: following nobody. More than `0` with no items: the creators they follow + * have nothing to show, because they have not posted yet or are suspended. + */ + followingCount: number; }; -/** A page of the home feed: the same posts and paging as a channel list. */ -export type FeedPayload = PostPagePayload; diff --git a/platforms/market/src/features/follow/actions/.gitkeep b/platforms/market/src/features/follow/actions/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/follow/actions/follow-creator/actions.ts b/platforms/market/src/features/follow/actions/follow-creator/actions.ts new file mode 100644 index 0000000..c4dbac4 --- /dev/null +++ b/platforms/market/src/features/follow/actions/follow-creator/actions.ts @@ -0,0 +1,23 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { FOLLOW_EVENTS } from '../../constants'; +import { followRepository } from '../../repositories/follow'; +import type { + FollowArgs, + FollowChangePayload, +} from '../../repositories/follow'; + +/** + * Follows a creator: free, no code, no limit, and no notice to the creator. Their posts join the + * investor's home feed; premium ones stay locked. Idempotent. Emits `follow.follow`. + */ +export async function followCreator( + args: FollowArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const change = await followRepository.follow(args); + if (emit) { + eventEmitter.emit(FOLLOW_EVENTS.follow, { creatorId: args.creatorId }); + } + return change; +} diff --git a/platforms/market/src/features/follow/actions/follow-creator/index.ts b/platforms/market/src/features/follow/actions/follow-creator/index.ts new file mode 100644 index 0000000..41561be --- /dev/null +++ b/platforms/market/src/features/follow/actions/follow-creator/index.ts @@ -0,0 +1 @@ +export { followCreator } from './actions'; diff --git a/platforms/market/src/features/follow/actions/unfollow-creator/actions.ts b/platforms/market/src/features/follow/actions/unfollow-creator/actions.ts new file mode 100644 index 0000000..0fc6f5f --- /dev/null +++ b/platforms/market/src/features/follow/actions/unfollow-creator/actions.ts @@ -0,0 +1,23 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { FOLLOW_EVENTS } from '../../constants'; +import { followRepository } from '../../repositories/follow'; +import type { + FollowArgs, + FollowChangePayload, +} from '../../repositories/follow'; + +/** + * Stops following a creator: their posts leave the home feed. The API refuses (409) while the + * investor has an active subscription to them. Emits `follow.unfollow`. + */ +export async function unfollowCreator( + args: FollowArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const change = await followRepository.unfollow(args); + if (emit) { + eventEmitter.emit(FOLLOW_EVENTS.unfollow, { creatorId: args.creatorId }); + } + return change; +} diff --git a/platforms/market/src/features/follow/actions/unfollow-creator/index.ts b/platforms/market/src/features/follow/actions/unfollow-creator/index.ts new file mode 100644 index 0000000..cd43d5c --- /dev/null +++ b/platforms/market/src/features/follow/actions/unfollow-creator/index.ts @@ -0,0 +1 @@ +export { unfollowCreator } from './actions'; diff --git a/platforms/market/src/features/follow/constants.ts b/platforms/market/src/features/follow/constants.ts new file mode 100644 index 0000000..f55f598 --- /dev/null +++ b/platforms/market/src/features/follow/constants.ts @@ -0,0 +1,5 @@ +/** Events follow actions emit when they succeed. */ +export const FOLLOW_EVENTS = { + follow: 'follow.follow', + unfollow: 'follow.unfollow', +} as const; diff --git a/platforms/market/src/features/follow/entities/following/index.ts b/platforms/market/src/features/follow/entities/following/index.ts new file mode 100644 index 0000000..fc22318 --- /dev/null +++ b/platforms/market/src/features/follow/entities/following/index.ts @@ -0,0 +1 @@ +export type { FollowedCreatorEntity, FollowingEntity } from './types'; diff --git a/platforms/market/src/features/follow/entities/following/types.ts b/platforms/market/src/features/follow/entities/following/types.ts new file mode 100644 index 0000000..1262b1e --- /dev/null +++ b/platforms/market/src/features/follow/entities/following/types.ts @@ -0,0 +1,28 @@ +/** + * The creator on a following row: content-service's creator card. `id` is the creator's user id + * (the row's `creatorId`). + */ +export type FollowedCreatorEntity = { + id: string; + /** Without the «@». */ + username: string; + /** A root-relative upload path (`/uploads/avatars/…`); `null` without a photo. */ + avatar: string | null; + /** trader-service `verificationStatus` is `approved`. */ + verified: boolean; + /** The channel is blacked out; the follow is kept for reinstatement. */ + suspended: boolean; +}; + +/** + * content-service `listFollowing`: one creator the signed-in investor follows. Follows of creators + * without an approved profile are left out; a suspended creator stays, with `creator.suspended`. + */ +export type FollowingEntity = { + creatorId: string; + /** ISO 8601. Following again after an unfollow starts a new time. */ + followedAt: string; + /** An active subscription to this creator: unfollow is frozen (409). */ + subscribed: boolean; + creator: FollowedCreatorEntity; +}; diff --git a/platforms/market/src/features/follow/index.ts b/platforms/market/src/features/follow/index.ts index bfddd9a..b4cb755 100644 --- a/platforms/market/src/features/follow/index.ts +++ b/platforms/market/src/features/follow/index.ts @@ -1,6 +1,19 @@ -export { followKeys, followRepository } from './repositories/follow'; +import './types'; + +export { followCreator } from './actions/follow-creator'; +export { unfollowCreator } from './actions/unfollow-creator'; +export { FOLLOW_EVENTS } from './constants'; +export { + FOLLOWING_PAGE_LIMIT, + followKeys, + followRepository, +} from './repositories/follow'; export type { FollowArgs, FollowChangePayload, + FollowedCreatorPayload, + FollowingPagePayload, + FollowingPayload, FollowStatusPayload, + ListFollowingArgs, } from './repositories/follow'; diff --git a/platforms/market/src/features/follow/repositories/follow/constants.ts b/platforms/market/src/features/follow/repositories/follow/constants.ts index 6be1613..9cfa538 100644 --- a/platforms/market/src/features/follow/repositories/follow/constants.ts +++ b/platforms/market/src/features/follow/repositories/follow/constants.ts @@ -2,12 +2,19 @@ const creatorPath = (creatorId: string) => `/creators/${encodeURIComponent(creatorId)}`; export const FOLLOW_ENDPOINTS = { + /** The signed-in investor's follows. */ + following: '/creators/following', follow: (creatorId: string) => `${creatorPath(creatorId)}/follow`, status: (creatorId: string) => `${creatorPath(creatorId)}/follow-status`, } as const; +/** The page size the following list asks for: the API's default, more than an investor follows. */ +export const FOLLOWING_PAGE_LIMIT = 50; + export const followKeys = { all: ['follow'] as const, statuses: () => [...followKeys.all, 'status'] as const, status: (creatorId: string) => [...followKeys.statuses(), creatorId] as const, + /** The investor's following list, page after page, as it loads them: no page in the key. */ + following: () => [...followKeys.all, 'following'] as const, }; diff --git a/platforms/market/src/features/follow/repositories/follow/follow.ts b/platforms/market/src/features/follow/repositories/follow/follow.ts index 032d2de..b3fd17d 100644 --- a/platforms/market/src/features/follow/repositories/follow/follow.ts +++ b/platforms/market/src/features/follow/repositories/follow/follow.ts @@ -1,21 +1,44 @@ import { followHttp } from '../../http'; import { FOLLOW_ENDPOINTS } from './constants'; -import { toFollowChangePayload, toFollowStatusPayload } from './mappers'; +import { + toFollowChangePayload, + toFollowingPagePayload, + toFollowStatusPayload, +} from './mappers'; import type { FollowArgs, FollowChangePayload, + FollowingPagePayload, FollowResponseDto, FollowStatusPayload, FollowStatusResponseDto, + ListFollowingArgs, + ListFollowingResponseDto, UnfollowResponseDto, } from './types'; /** - * Investor follows (`/creators/:creatorId/follow`): 401 without a session, 403 for a creator. - * Following is idempotent, and subscribing follows automatically. Unfollow answers 409 while the - * investor has an active subscription to the creator (`FollowStatusPayload.frozen`). + * Investor follows (`/creators/:creatorId/follow`, `/creators/following`): 401 without a session, + * 403 for a creator. Following is idempotent, and subscribing follows automatically. Unfollow + * answers 409 while the investor has an active subscription to the creator + * (`FollowStatusPayload.frozen`, `FollowingPayload.subscribed`). */ export const followRepository = { + /** + * The creators the investor follows, newest follow first. Creators without an approved profile + * are left out; suspended ones stay, marked. One page holds every follow in practice. + */ + async listFollowing( + { page, limit }: ListFollowingArgs = {}, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await followHttp.get( + FOLLOW_ENDPOINTS.following, + { params: { page, limit }, signal }, + ); + return toFollowingPagePayload(response); + }, + async getStatus( args: FollowArgs, { signal }: { signal?: AbortSignal } = {}, diff --git a/platforms/market/src/features/follow/repositories/follow/index.ts b/platforms/market/src/features/follow/repositories/follow/index.ts index 1848c8d..ca49d9e 100644 --- a/platforms/market/src/features/follow/repositories/follow/index.ts +++ b/platforms/market/src/features/follow/repositories/follow/index.ts @@ -1,7 +1,11 @@ -export { followKeys } from './constants'; +export { FOLLOWING_PAGE_LIMIT, followKeys } from './constants'; export { followRepository } from './follow'; export type { FollowArgs, FollowChangePayload, + FollowedCreatorPayload, + FollowingPagePayload, + FollowingPayload, FollowStatusPayload, + ListFollowingArgs, } from './types'; diff --git a/platforms/market/src/features/follow/repositories/follow/mappers.ts b/platforms/market/src/features/follow/repositories/follow/mappers.ts index 2cf0735..4ac05a4 100644 --- a/platforms/market/src/features/follow/repositories/follow/mappers.ts +++ b/platforms/market/src/features/follow/repositories/follow/mappers.ts @@ -1,8 +1,17 @@ +import { toApiUrl } from '../../../../shared/utils'; +import type { + FollowedCreatorEntity, + FollowingEntity, +} from '../../entities/following'; import type { FollowChangePayload, + FollowedCreatorPayload, + FollowingPagePayload, + FollowingPayload, FollowResponseDto, FollowStatusPayload, FollowStatusResponseDto, + ListFollowingResponseDto, UnfollowResponseDto, } from './types'; @@ -22,3 +31,35 @@ export function toFollowChangePayload( ): FollowChangePayload { return { following: dto.following }; } + +function toFollowedCreatorPayload( + dto: FollowedCreatorEntity, +): FollowedCreatorPayload { + return { + id: dto.id, + username: dto.username, + avatarUrl: toApiUrl(dto.avatar), + verified: dto.verified, + suspended: dto.suspended, + }; +} + +function toFollowingPayload(dto: FollowingEntity): FollowingPayload { + return { + creatorId: dto.creatorId, + followedAt: dto.followedAt, + subscribed: dto.subscribed, + creator: toFollowedCreatorPayload(dto.creator), + }; +} + +export function toFollowingPagePayload( + dto: ListFollowingResponseDto, +): FollowingPagePayload { + return { + items: dto.items.map(toFollowingPayload), + total: dto.total, + page: dto.page, + limit: dto.limit, + }; +} diff --git a/platforms/market/src/features/follow/repositories/follow/types.ts b/platforms/market/src/features/follow/repositories/follow/types.ts index 2123ef5..8ad026a 100644 --- a/platforms/market/src/features/follow/repositories/follow/types.ts +++ b/platforms/market/src/features/follow/repositories/follow/types.ts @@ -1,4 +1,5 @@ import type { FollowStatusEntity } from '../../entities/follow-status'; +import type { FollowingEntity } from '../../entities/following'; /** The creator's account id (`creatorId` of the channel payloads). */ export type FollowArgs = { creatorId: string }; @@ -24,3 +25,46 @@ export type UnfollowResponseDto = { /** The follow state after a follow or unfollow. */ export type FollowChangePayload = { following: boolean }; + +export type ListFollowingArgs = { + /** From 1; the API defaults to 1 and raises anything lower to 1. */ + page?: number; + /** 1 to 100; the API defaults to 50. */ + limit?: number; +}; +export type ListFollowingResponseDto = { + items: FollowingEntity[]; + total: number; + page: number; + limit: number; +}; + +/** The creator on a following row. `id` is the creator's user id. */ +export type FollowedCreatorPayload = { + id: string; + /** Without the «@». */ + username: string; + /** Absolute, through the API proxy; `null` without a photo. */ + avatarUrl: string | null; + verified: boolean; + /** The channel is blacked out: the row is dimmed and opens nothing. */ + suspended: boolean; +}; + +/** One creator the signed-in investor follows. */ +export type FollowingPayload = { + creatorId: string; + /** ISO 8601. */ + followedAt: string; + /** An active subscription to this creator: unfollow is frozen, even while suspended. */ + subscribed: boolean; + creator: FollowedCreatorPayload; +}; + +/** A page of the investor's follows, newest follow first. */ +export type FollowingPagePayload = { + items: FollowingPayload[]; + total: number; + page: number; + limit: number; +}; diff --git a/platforms/market/src/features/follow/types.ts b/platforms/market/src/features/follow/types.ts new file mode 100644 index 0000000..702295d --- /dev/null +++ b/platforms/market/src/features/follow/types.ts @@ -0,0 +1,8 @@ +declare module '@lumina/libs/event-emitter' { + interface EventMap { + 'follow.follow': { creatorId: string }; + 'follow.unfollow': { creatorId: string }; + } +} + +export {}; diff --git a/platforms/market/src/features/overview/index.ts b/platforms/market/src/features/overview/index.ts index 63f290e..cf891b3 100644 --- a/platforms/market/src/features/overview/index.ts +++ b/platforms/market/src/features/overview/index.ts @@ -1,3 +1,5 @@ +export { useOwnSubscriberCount } from './models/own-subscriber-count'; +export type { UseOwnSubscriberCountOptions } from './models/own-subscriber-count'; export { creatorDashboardRepository, overviewKeys, diff --git a/platforms/market/src/features/overview/models/.gitkeep b/platforms/market/src/features/overview/models/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/overview/models/own-subscriber-count/index.ts b/platforms/market/src/features/overview/models/own-subscriber-count/index.ts new file mode 100644 index 0000000..772a364 --- /dev/null +++ b/platforms/market/src/features/overview/models/own-subscriber-count/index.ts @@ -0,0 +1,2 @@ +export { useOwnSubscriberCount } from './use-own-subscriber-count'; +export type { UseOwnSubscriberCountOptions } from './types'; diff --git a/platforms/market/src/features/overview/models/own-subscriber-count/types.ts b/platforms/market/src/features/overview/models/own-subscriber-count/types.ts new file mode 100644 index 0000000..23969c8 --- /dev/null +++ b/platforms/market/src/features/overview/models/own-subscriber-count/types.ts @@ -0,0 +1,4 @@ +export type UseOwnSubscriberCountOptions = { + /** Read it only where the count is shown, such as the creator's own channel. */ + enabled: boolean; +}; diff --git a/platforms/market/src/features/overview/models/own-subscriber-count/use-own-subscriber-count.ts b/platforms/market/src/features/overview/models/own-subscriber-count/use-own-subscriber-count.ts new file mode 100644 index 0000000..81773b1 --- /dev/null +++ b/platforms/market/src/features/overview/models/own-subscriber-count/use-own-subscriber-count.ts @@ -0,0 +1,29 @@ +import { useQuery } from '@tanstack/react-query'; + +import { useCurrentAccount, useViewerStatus } from '../../../../stores/auth'; +import { + creatorDashboardRepository, + overviewKeys, +} from '../../repositories/creator-dashboard'; +import type { UseOwnSubscriberCountOptions } from './types'; + +/** + * How many subscriptions the signed-in creator has running now, from their داشبورد figures: with + * none, a premium post stays locked for everyone (C5 ۱.۴). Browser only, and read only for a + * signed-in creator, since an investor gets 403. `null` while unknown: before the read, for anyone + * else, and after a failed read, which never throws. + */ +export function useOwnSubscriberCount({ + enabled, +}: UseOwnSubscriberCountOptions): number | null { + const status = useViewerStatus(); + const account = useCurrentAccount(); + const isCreator = status === 'member' && account?.role === 'creator'; + const query = useQuery({ + queryKey: overviewKeys.dashboard(), + queryFn: ({ signal }) => creatorDashboardRepository.get({ signal }), + enabled: enabled && isCreator, + throwOnError: false, + }); + return isCreator ? (query.data?.activeSubscribers ?? null) : null; +} diff --git a/platforms/market/src/features/post/actions/.gitkeep b/platforms/market/src/features/post/actions/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/post/actions/delete-post/actions.ts b/platforms/market/src/features/post/actions/delete-post/actions.ts new file mode 100644 index 0000000..e136f00 --- /dev/null +++ b/platforms/market/src/features/post/actions/delete-post/actions.ts @@ -0,0 +1,17 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { POST_EVENTS } from '../../constants'; +import { postRepository } from '../../repositories/post'; + +/** + * Deletes a creator's post for good, at any time: it leaves the channel, the feeds and its link. + * Investors are told nothing. Emits `post.delete`. + */ +export async function deletePost( + { postId, creatorId }: { postId: string; creatorId: string }, + { emit = true }: { emit?: boolean } = {}, +): Promise<'ok'> { + await postRepository.delete(postId); + if (emit) eventEmitter.emit(POST_EVENTS.delete, { postId, creatorId }); + return 'ok'; +} diff --git a/platforms/market/src/features/post/actions/delete-post/index.ts b/platforms/market/src/features/post/actions/delete-post/index.ts new file mode 100644 index 0000000..621c7f0 --- /dev/null +++ b/platforms/market/src/features/post/actions/delete-post/index.ts @@ -0,0 +1 @@ +export { deletePost } from './actions'; diff --git a/platforms/market/src/features/post/actions/edit-post/actions.ts b/platforms/market/src/features/post/actions/edit-post/actions.ts new file mode 100644 index 0000000..1fac4f5 --- /dev/null +++ b/platforms/market/src/features/post/actions/edit-post/actions.ts @@ -0,0 +1,24 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { POST_EVENTS } from '../../constants'; +import { postRepository } from '../../repositories/post'; +import type { PostPayload, UpdatePostArgs } from '../../repositories/post'; + +/** + * Saves a creator's changes to their post: text, images and access level, within 15 minutes of + * publishing (the API answers 403 after that). The post shows «ویرایش‌شده». Emits `post.edit`. + */ +export async function editPost( + postId: string, + args: UpdatePostArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const post = await postRepository.update(postId, args); + if (emit) { + eventEmitter.emit(POST_EVENTS.edit, { + postId, + creatorId: post.creatorId, + }); + } + return post; +} diff --git a/platforms/market/src/features/post/actions/edit-post/index.ts b/platforms/market/src/features/post/actions/edit-post/index.ts new file mode 100644 index 0000000..199d7f0 --- /dev/null +++ b/platforms/market/src/features/post/actions/edit-post/index.ts @@ -0,0 +1 @@ +export { editPost } from './actions'; diff --git a/platforms/market/src/features/post/actions/publish-post/actions.ts b/platforms/market/src/features/post/actions/publish-post/actions.ts new file mode 100644 index 0000000..3592850 --- /dev/null +++ b/platforms/market/src/features/post/actions/publish-post/actions.ts @@ -0,0 +1,24 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { POST_EVENTS } from '../../constants'; +import { postRepository } from '../../repositories/post'; +import type { CreatePostArgs, PostPayload } from '../../repositories/post'; + +/** + * Publishes a creator's post. It goes live at once: in the channel and in followers' home feeds, + * locked for non-subscribers when premium. Emits `post.publish`. + */ +export async function publishPost( + args: CreatePostArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const post = await postRepository.create({ ...args, status: 'published' }); + if (emit) { + eventEmitter.emit(POST_EVENTS.publish, { + postId: post.id, + creatorId: post.creatorId, + accessLevel: post.accessLevel, + }); + } + return post; +} diff --git a/platforms/market/src/features/post/actions/publish-post/index.ts b/platforms/market/src/features/post/actions/publish-post/index.ts new file mode 100644 index 0000000..fbba6de --- /dev/null +++ b/platforms/market/src/features/post/actions/publish-post/index.ts @@ -0,0 +1 @@ +export { publishPost } from './actions'; diff --git a/platforms/market/src/features/post/constants.ts b/platforms/market/src/features/post/constants.ts new file mode 100644 index 0000000..c8f6e49 --- /dev/null +++ b/platforms/market/src/features/post/constants.ts @@ -0,0 +1,18 @@ +/** Events post actions emit when they succeed. */ +export const POST_EVENTS = { + publish: 'post.publish', + edit: 'post.edit', + delete: 'post.delete', +} as const; + +/** + * The composer's limits (C4), the same the API enforces: text up to 2000 characters, up to four + * JPG, PNG or WebP images of 5 MB each, and 15 minutes to edit a published post. + */ +export const POST_LIMITS = { + captionMaxLength: 2000, + maxImages: 4, + imageMaxBytes: 5 * 1024 * 1024, + imageMimeTypes: ['image/jpeg', 'image/png', 'image/webp'], + editWindowMs: 15 * 60 * 1000, +} as const; diff --git a/platforms/market/src/features/post/entities/post/index.ts b/platforms/market/src/features/post/entities/post/index.ts index 63f2713..cf46ada 100644 --- a/platforms/market/src/features/post/entities/post/index.ts +++ b/platforms/market/src/features/post/entities/post/index.ts @@ -4,7 +4,6 @@ export type { PostAccessLevel, PostEntity, PostMediaEntity, - PostMediaPreviewEntity, PostStatus, PostType, PredictionDirection, diff --git a/platforms/market/src/features/post/entities/post/types.ts b/platforms/market/src/features/post/entities/post/types.ts index 9b174d2..88a6af2 100644 --- a/platforms/market/src/features/post/entities/post/types.ts +++ b/platforms/market/src/features/post/entities/post/types.ts @@ -46,18 +46,13 @@ export type PredictionEntity = { closedAt?: string; }; -/** A locked premium image: its box and blurHash only, never its file id or URL. */ -export type PostMediaPreviewEntity = { - order: number; - blurHash?: string; - width?: number; - height?: number; -}; - -/** A locked premium prediction: only these three fields are sent. */ +/** + * A locked premium prediction: whether it is open, and the outcome once closed (results are never + * paywalled). Never the symbol, the direction or the levels. + */ export type LockedPredictionEntity = Pick< PredictionEntity, - 'symbol' | 'direction' | 'status' + 'status' | 'outcome' >; type PostEntityBase = { @@ -69,6 +64,8 @@ type PostEntityBase = { createdAt: string; /** Absent on a draft. */ publishedAt?: string; + /** When a published post's text, images or access level last changed. */ + editedAt?: string; }; /** Free, or premium for the creator and active subscribers. */ @@ -80,11 +77,13 @@ export type UnlockedPostEntity = PostEntityBase & { prediction?: PredictionEntity; }; -/** Premium for anyone else: a teaser with the caption cut to 140 characters and no media. */ +/** + * Premium for anyone else: a teaser with the caption cut to 140 characters and the image count. + * No media and no media preview (no blurHash or size). + */ export type LockedPostEntity = PostEntityBase & { locked: true; captionPreview?: string; - mediaPreview: PostMediaPreviewEntity[]; mediaCount: number; prediction?: LockedPredictionEntity; }; diff --git a/platforms/market/src/features/post/index.ts b/platforms/market/src/features/post/index.ts index 313cf9e..375d6c7 100644 --- a/platforms/market/src/features/post/index.ts +++ b/platforms/market/src/features/post/index.ts @@ -1,3 +1,5 @@ +import './types'; + export type { FileKind, FileStatus, FileVisibility } from './entities/file'; export type { PostAccessLevel, @@ -16,8 +18,49 @@ export type { UploadFileArgs, UploadFileOptions, } from './repositories/file'; +export { deletePost } from './actions/delete-post'; +export { editPost } from './actions/edit-post'; +export { publishPost } from './actions/publish-post'; +export { POST_EVENTS, POST_LIMITS } from './constants'; +export { useChannelFeedPart } from './models/channel-feed'; +export type { + ChannelFeedPartModel, + UseChannelFeedPartOptions, +} from './models/channel-feed'; +export { usePostComposerPage } from './models/composer'; +export type { + ComposerImage, + ComposerImageError, + ComposerImagesModel, + ComposerPhase, + PostComposerPageModel, + UsePostComposerPageOptions, +} from './models/composer'; +export { useEditablePost } from './models/editable-post'; +export type { EditablePostModel } from './models/editable-post'; +export { useOwnerPostPart } from './models/owner-post'; +export type { + OwnerPostPartModel, + UseOwnerPostPartOptions, +} from './models/owner-post'; +export { usePostPart } from './models/post'; +export { + isChannelOnScreen, + removeCachedPost, + replaceCachedPost, + resetCachedChannel, +} from './models/post-cache'; +export type { PostPartModel, UsePostPartOptions } from './models/post'; +export { usePostList } from './models/post-list'; +export type { + ListedPost, + PostListModel, + PostListQuery, + UsePostListOptions, +} from './models/post-list'; export { POST_ENDPOINTS, + POST_ID_PATTERN, POST_PAGE_LIMIT, postKeys, postRepository, @@ -30,7 +73,6 @@ export type { LockedPostPayload, LockedPredictionPayload, PostImagePayload, - PostImagePreviewPayload, PostMediaArgs, PostPagePayload, PostPayload, diff --git a/platforms/market/src/features/post/models/.gitkeep b/platforms/market/src/features/post/models/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/post/models/channel-feed/index.ts b/platforms/market/src/features/post/models/channel-feed/index.ts new file mode 100644 index 0000000..e2c182d --- /dev/null +++ b/platforms/market/src/features/post/models/channel-feed/index.ts @@ -0,0 +1,2 @@ +export { useChannelFeedPart } from './use-channel-feed-part'; +export type { ChannelFeedPartModel, UseChannelFeedPartOptions } from './types'; diff --git a/platforms/market/src/features/post/models/channel-feed/types.ts b/platforms/market/src/features/post/models/channel-feed/types.ts new file mode 100644 index 0000000..8ce06cf --- /dev/null +++ b/platforms/market/src/features/post/models/channel-feed/types.ts @@ -0,0 +1,13 @@ +import type { PostPagePayload, PostPayload } from '../../repositories/post'; +import type { PostListModel } from '../post-list'; + +export type UseChannelFeedPartOptions = { + /** The creator's account id. */ + creatorId: string; + /** The first page as the server read it: every visitor's view, premium posts locked. */ + firstPage: PostPagePayload; + /** The creator or an active subscriber: the pages are read again with their session. */ + entitled: boolean; +}; + +export type ChannelFeedPartModel = PostListModel; diff --git a/platforms/market/src/features/post/models/channel-feed/use-channel-feed-part.ts b/platforms/market/src/features/post/models/channel-feed/use-channel-feed-part.ts new file mode 100644 index 0000000..865b573 --- /dev/null +++ b/platforms/market/src/features/post/models/channel-feed/use-channel-feed-part.ts @@ -0,0 +1,37 @@ +import { useInfiniteQuery } from '@tanstack/react-query'; + +import { + POST_PAGE_LIMIT, + postKeys, + postRepository, +} from '../../repositories/post'; +import { usePostList } from '../post-list'; +import type { ChannelFeedPartModel, UseChannelFeedPartOptions } from './types'; + +/** + * A channel's posts, page after page. The first page comes from the server render, which carries + * no session, so premium posts arrive locked; for the creator or a subscriber the loaded pages are + * read again in the browser and those posts open in place. Drafts reach only the creator and + * stay out of the channel. A post read in full stays open while the list is mounted (C5 §۵), as + * `usePostList` keeps it. + */ +export function useChannelFeedPart({ + creatorId, + firstPage, + entitled, +}: UseChannelFeedPartOptions): ChannelFeedPartModel { + const feed = useInfiniteQuery({ + queryKey: postKeys.channelFeed(creatorId), + queryFn: ({ pageParam, signal }) => + postRepository.listByCreator( + { creatorId, page: pageParam, limit: POST_PAGE_LIMIT }, + { signal }, + ), + initialPageParam: 1, + getNextPageParam: ({ page, limit, total }) => + page * limit < total ? page + 1 : undefined, + initialData: { pages: [firstPage], pageParams: [1] }, + }); + + return usePostList({ query: feed, entitled }); +} diff --git a/platforms/market/src/features/post/models/composer/index.ts b/platforms/market/src/features/post/models/composer/index.ts new file mode 100644 index 0000000..f3acaa2 --- /dev/null +++ b/platforms/market/src/features/post/models/composer/index.ts @@ -0,0 +1,9 @@ +export { usePostComposerPage } from './use-post-composer-page'; +export type { + ComposerImage, + ComposerImageError, + ComposerImagesModel, + ComposerPhase, + PostComposerPageModel, + UsePostComposerPageOptions, +} from './types'; diff --git a/platforms/market/src/features/post/models/composer/initial-images.ts b/platforms/market/src/features/post/models/composer/initial-images.ts new file mode 100644 index 0000000..11038d4 --- /dev/null +++ b/platforms/market/src/features/post/models/composer/initial-images.ts @@ -0,0 +1,28 @@ +import type { PostDraft } from '../../../../stores/post-draft'; +import type { UnlockedPostPayload } from '../../repositories/post'; +import type { ComposerImage } from './types'; + +/** The images the composer opens with: the post's own when editing, else a restored draft's. */ +export function initialImages( + post: UnlockedPostPayload | undefined, + draft: PostDraft | null, +): ComposerImage[] { + const stored = post + ? [...post.media] + .sort((a, b) => a.order - b.order) + .map((image) => ({ + fileId: image.fileId, + url: image.url, + name: image.fileId, + })) + : (draft?.images ?? []); + return stored.map((image) => ({ + key: image.fileId, + status: 'ready', + previewUrl: image.url, + name: image.name, + progress: 100, + fileId: image.fileId, + url: image.url, + })); +} diff --git a/platforms/market/src/features/post/models/composer/types.ts b/platforms/market/src/features/post/models/composer/types.ts new file mode 100644 index 0000000..c64e997 --- /dev/null +++ b/platforms/market/src/features/post/models/composer/types.ts @@ -0,0 +1,83 @@ +import type { UseFormReturn } from 'react-hook-form'; + +import type { PostComposerFormValues } from '../../../../shared/validations'; +import type { PostPayload, UnlockedPostPayload } from '../../repositories/post'; + +/** One image in the composer, from the moment it is picked to its stored file. */ +export type ComposerImage = { + /** Local and stable while the image is in the composer. */ + key: string; + status: 'uploading' | 'ready' | 'failed'; + /** + * What the thumbnail shows: the picked file's local preview, kept after it uploads so the + * thumbnail doesn't load again; the stored file's address for a post's or a draft's own images. + */ + previewUrl: string; + name: string; + /** 0–100 while uploading. */ + progress: number; + /** The stored file, once uploaded. */ + fileId: string | null; + /** The stored file's address, once uploaded: what a draft keeps, since a local preview dies. */ + url: string | null; +}; + +/** Why a picked file was refused; it replaces the format hint under the images. */ +export type ComposerImageError = 'type' | 'size' | 'count'; + +export type ComposerImagesModel = { + images: ComposerImage[]; + error: ComposerImageError | null; + /** Below four images. */ + canAdd: boolean; + add: (files: Iterable) => void; + remove: (key: string) => void; + /** Sends a failed image again. */ + retry: (key: string) => void; + /** Stops every upload in flight, as the composer closes. */ + abortAll: () => void; +}; + +export type UsePostComposerPageOptions = { + creatorId: string; + /** Edit mode: the creator's own published post, in full. */ + post?: UnlockedPostPayload; + /** Saved or published: where to go next. */ + onDone: (post: PostPayload) => void; + /** Left without saving. */ + onLeave: () => void; +}; + +/** + * idle → saving → failed and back to idle with the form alert, or saved: it stays saving, every + * control held, until `onDone`'s navigation takes the composer away, so nothing sends twice. + */ +export type ComposerPhase = 'idle' | 'saving'; + +export type PostComposerPageModel = { + mode: 'create' | 'edit'; + form: UseFormReturn; + images: ComposerImagesModel; + phase: ComposerPhase; + /** Why the CTA can't send yet: an upload in flight or a failed one (its number, from 1). */ + blocker: { kind: 'uploading' } | { kind: 'failed'; number: number } | null; + /** + * No text and no image yet: the CTA waits frozen, and `submit` answers with the field's + * «پست نمی‌تواند خالی باشد» (C4 ۱.۳, ۳.۱). + */ + isEmpty: boolean; + submit: () => void; + /** The form alert after a failed save. */ + submitError: string | undefined; + /** A draft from an earlier visit was put back. */ + restored: boolean; + /** Back or «انصراف»: asks first when there is something to lose. */ + requestLeave: () => void; + isConfirmingLeave: boolean; + confirmLeave: () => void; + cancelLeave: () => void; + /** Edit mode: whole minutes left in the 15-minute window; `null` while unknown. */ + minutesLeft: number | null; + /** Edit mode: the window has passed, so saving is no longer possible. */ + isEditExpired: boolean; +}; diff --git a/platforms/market/src/features/post/models/composer/use-composer-images.ts b/platforms/market/src/features/post/models/composer/use-composer-images.ts new file mode 100644 index 0000000..a141006 --- /dev/null +++ b/platforms/market/src/features/post/models/composer/use-composer-images.ts @@ -0,0 +1,181 @@ +import { classifyError } from '@lumina/libs/error-handler'; +import { useCallback, useEffect, useReducer, useRef, useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { showActionError } from '../../../../shared/utils'; +import { POST_LIMITS } from '../../constants'; +import { fileRepository } from '../../repositories/file'; +import type { + ComposerImage, + ComposerImageError, + ComposerImagesModel, +} from './types'; + +type ImageAction = + | { type: 'add'; image: ComposerImage } + | { type: 'progress'; key: string; progress: number } + | { type: 'ready'; key: string; fileId: string; url: string } + | { type: 'failed'; key: string } + | { type: 'retry'; key: string } + | { type: 'remove'; key: string }; + +function imagesReducer( + images: ComposerImage[], + action: ImageAction, +): ComposerImage[] { + if (action.type === 'add') return [...images, action.image]; + const { key } = action; + const update = (patch: Partial) => + images.map((image) => (image.key === key ? { ...image, ...patch } : image)); + switch (action.type) { + case 'progress': + return update({ progress: action.progress }); + case 'ready': + return update({ + status: 'ready', + progress: 100, + fileId: action.fileId, + url: action.url, + }); + case 'failed': + return update({ status: 'failed' }); + case 'retry': + return update({ status: 'uploading', progress: 0 }); + case 'remove': + return images.filter((image) => image.key !== action.key); + } +} + +const isLocalPreview = (url: string) => url.startsWith('blob:'); + +/** + * The composer's images. Each uploads as soon as it is picked, with its progress; removing one + * cancels its upload, and a failed one can be sent again. A file of the wrong type or over 5 MB, + * or past the fourth, is refused before it uploads. + */ +export function useComposerImages( + initial: () => ComposerImage[], +): ComposerImagesModel { + const { t } = useTranslation('content'); + const [images, dispatch] = useReducer(imagesReducer, undefined, initial); + const [error, setError] = useState(null); + // Read in handlers and on unmount only: what is on screen, and each upload's file and abort. + const latest = useRef(images); + const uploads = useRef( + new Map(), + ); + useEffect(() => { + latest.current = images; + }); + + function upload(key: string, file: File) { + const controller = new AbortController(); + uploads.current.set(key, { file, controller }); + fileRepository + .upload( + { file }, + { + signal: controller.signal, + onProgress: ({ percent }) => + dispatch({ type: 'progress', key, progress: percent }), + }, + ) + .then((stored) => + dispatch({ type: 'ready', key, fileId: stored.id, url: stored.url }), + ) + .catch((uploadError: unknown) => { + // Removing the image aborted it: nothing to say. + if (classifyError(uploadError).action === 'silent') return; + dispatch({ type: 'failed', key }); + // Sending the same file again is safe: it is the retry. + showActionError(uploadError, { + t, + failedMessage: t('composer.images.upload-failed'), + retry: () => retry(key), + }); + }); + } + + function retry(key: string) { + const pending = uploads.current.get(key); + if (!pending) return; + dispatch({ type: 'retry', key }); + upload(key, pending.file); + } + + const add = (files: Iterable) => { + let count = images.length; + let refused: ComposerImageError | null = null; + for (const file of files) { + if (count >= POST_LIMITS.maxImages) { + refused = 'count'; + break; + } + if ( + !(POST_LIMITS.imageMimeTypes as readonly string[]).includes(file.type) + ) { + refused = 'type'; + continue; + } + if (file.size > POST_LIMITS.imageMaxBytes) { + refused = 'size'; + continue; + } + const key = crypto.randomUUID(); + dispatch({ + type: 'add', + image: { + key, + status: 'uploading', + previewUrl: URL.createObjectURL(file), + name: file.name, + progress: 0, + fileId: null, + url: null, + }, + }); + upload(key, file); + count += 1; + } + setError(refused); + }; + + const remove = (key: string) => { + uploads.current.get(key)?.controller.abort(); + uploads.current.delete(key); + const image = images.find((item) => item.key === key); + if (image && isLocalPreview(image.previewUrl)) { + URL.revokeObjectURL(image.previewUrl); + } + dispatch({ type: 'remove', key }); + setError(null); + }; + + const abortAll = useCallback(() => { + for (const { controller } of uploads.current.values()) controller.abort(); + uploads.current.clear(); + }, []); + + // Leaving the composer stops what is still uploading and frees the local previews. + useEffect( + () => () => { + abortAll(); + for (const image of latest.current) { + if (isLocalPreview(image.previewUrl)) { + URL.revokeObjectURL(image.previewUrl); + } + } + }, + [abortAll], + ); + + return { + images, + error, + canAdd: images.length < POST_LIMITS.maxImages, + add, + remove, + retry, + abortAll, + }; +} diff --git a/platforms/market/src/features/post/models/composer/use-post-composer-page.ts b/platforms/market/src/features/post/models/composer/use-post-composer-page.ts new file mode 100644 index 0000000..9f52788 --- /dev/null +++ b/platforms/market/src/features/post/models/composer/use-post-composer-page.ts @@ -0,0 +1,251 @@ +import { valibotResolver } from '@hookform/resolvers/valibot'; +import { useCountdown } from '@lumina/island/hooks/use-countdown'; +import { showToast } from '@lumina/island/molecules/toast'; +import { isHttpError } from '@lumina/libs/http'; +import { useQueryClient } from '@tanstack/react-query'; +import { useEffect, useEffectEvent, useState } from 'react'; +import { useForm, useWatch } from 'react-hook-form'; +import { useTranslation } from 'react-i18next'; + +import { applyServerErrors, showActionError } from '../../../../shared/utils'; +import { postComposerSchema } from '../../../../shared/validations'; +import type { PostComposerFormValues } from '../../../../shared/validations'; +import { usePostDraftStore } from '../../../../stores/post-draft'; +import { editPost } from '../../actions/edit-post'; +import { publishPost } from '../../actions/publish-post'; +import { POST_LIMITS } from '../../constants'; +import type { PostPayload, UpdatePostArgs } from '../../repositories/post'; +import { replaceCachedPost, resetCachedChannel } from '../post-cache'; +import { initialImages } from './initial-images'; +import type { + ComposerImage, + ComposerPhase, + PostComposerPageModel, + UsePostComposerPageOptions, +} from './types'; +import { useComposerImages } from './use-composer-images'; + +const SECONDS_PER_MINUTE = 60; + +const storedIds = (images: { fileId: string | null }[]) => + images.map((image) => image.fileId).join(); + +/** + * The post composer (C4, C5): text up to 2000 characters, up to four images uploaded as they are + * picked, and free or premium. A new post keeps its draft on the device until it is published or + * thrown away. Editing a published post works for 15 minutes after it went live; the countdown + * shows it, and saving after that is refused. + */ +export function usePostComposerPage({ + creatorId, + post, + onDone, + onLeave, +}: UsePostComposerPageOptions): PostComposerPageModel { + const { t } = useTranslation('content'); + const queryClient = useQueryClient(); + const mode = post ? 'edit' : 'create'; + const [draft] = useState(() => { + if (post) return null; + const saved = usePostDraftStore.getState().draft; + return saved?.creatorId === creatorId ? saved : null; + }); + const form = useForm({ + resolver: valibotResolver(postComposerSchema), + mode: 'onTouched', + defaultValues: { + caption: post?.caption ?? draft?.caption ?? '', + accessLevel: post?.accessLevel ?? draft?.accessLevel ?? 'free', + }, + }); + // Read once, as the composer opens. + const images = useComposerImages(() => initialImages(post, draft)); + // Renders again only when the text starts or stops being blank, not on every keystroke. + const hasText = useWatch({ + control: form.control, + name: 'caption', + compute: (caption) => caption.trim() !== '', + }); + const isEmpty = !hasText && images.images.length === 0; + const [phase, setPhase] = useState('idle'); + const [isConfirmingLeave, setIsConfirmingLeave] = useState(false); + + const editEndsAt = post?.publishedAt + ? new Date(post.publishedAt).getTime() + POST_LIMITS.editWindowMs + : undefined; + const secondsLeft = useCountdown(editEndsAt, { + intervalMs: SECONDS_PER_MINUTE * 1000, + }); + const isEditExpired = mode === 'edit' && secondsLeft === 0; + + // A new post's draft follows every change; an empty composer keeps none. + const keepDraft = useEffectEvent(() => { + if (post) return; + const { caption, accessLevel } = form.getValues(); + const ready = images.images.filter( + (image): image is ComposerImage & { fileId: string; url: string } => + image.status === 'ready' && image.fileId !== null && image.url !== null, + ); + const store = usePostDraftStore.getState(); + if (!caption.trim() && ready.length === 0) { + store.clearDraft(); + return; + } + store.saveDraft({ + creatorId, + caption, + accessLevel, + images: ready.map(({ fileId, url, name }) => ({ fileId, url, name })), + }); + }); + useEffect( + () => + form.subscribe({ + formState: { values: true }, + callback: () => keepDraft(), + }), + [form], + ); + useEffect(() => keepDraft(), [images.images]); + + // «پست نمی‌تواند خالی باشد» goes once there is text or an image (C4 ۳.۱). + useEffect(() => { + if (!isEmpty && form.getFieldState('caption').error?.type === 'empty') { + form.clearErrors('caption'); + } + }, [isEmpty, form]); + + const uploading = images.images.some((image) => image.status === 'uploading'); + const failedIndex = images.images.findIndex( + (image) => image.status === 'failed', + ); + const blocker = uploading + ? ({ kind: 'uploading' } as const) + : failedIndex >= 0 + ? ({ kind: 'failed', number: failedIndex + 1 } as const) + : null; + + const changesOf = ( + caption: string, + accessLevel: PostComposerFormValues['accessLevel'], + media: { fileId: string; order: number }[], + ): UpdatePostArgs => { + if (!post) return {}; + const changes: UpdatePostArgs = {}; + if (caption !== (post.caption ?? '')) changes.caption = caption; + if (accessLevel !== post.accessLevel) changes.accessLevel = accessLevel; + const before = [...post.media].sort((a, b) => a.order - b.order); + if (storedIds(media) !== storedIds(before)) changes.media = media; + return changes; + }; + + const submit = form.handleSubmit(async ({ caption, accessLevel }) => { + if (blocker || phase === 'saving' || isEditExpired) return; + const text = caption.trim(); + const media = images.images + .filter((image) => image.status === 'ready' && image.fileId !== null) + .map((image, order) => ({ fileId: image.fileId as string, order })); + if (!text && media.length === 0) { + form.setError( + 'caption', + { type: 'empty', message: 'content:validation.post-empty' }, + { shouldFocus: true }, + ); + return; + } + + setPhase('saving'); + let saved: PostPayload; + try { + if (post) { + const changes = changesOf(text, accessLevel, media); + saved = + Object.keys(changes).length > 0 + ? await editPost(post.id, changes) + : post; + } else { + saved = await publishPost({ + type: media.length > 0 ? 'image' : 'text', + caption: text || undefined, + accessLevel, + media: media.length > 0 ? media : undefined, + }); + } + } catch (error) { + const failedMessage = t( + post ? 'composer.save-failed' : 'composer.publish-failed', + ); + // The window closed while editing: the post stays as it was published. + if (post && isHttpError(error) && error.status === 403) { + form.setError('root.server', { + type: 'server', + message: t('composer.edit-expired'), + }); + showActionError(error, { t, failedMessage }); + } else { + // Publishing twice would post twice, so «انتشار» is the retry, not the toast. + applyServerErrors(form, error, { t, failedMessage }); + } + // Only a failed request frees the CTA. Saved, it stays held until `onDone`'s navigation + // takes the composer away: a second tap would publish again, or save again and go back twice. + setPhase('idle'); + return; + } + if (post) { + replaceCachedPost(queryClient, saved); + showToast({ tone: 'success', message: t('composer.saved') }); + } else { + usePostDraftStore.getState().clearDraft(); + resetCachedChannel(queryClient, creatorId); + showToast({ tone: 'success', message: t('composer.published') }); + } + onDone(saved); + }); + + const hasSomethingToLose = () => { + const { caption, accessLevel } = form.getValues(); + if (post) { + const media = images.images.map((image, order) => ({ + fileId: image.fileId ?? image.key, + order, + })); + return ( + Object.keys(changesOf(caption.trim(), accessLevel, media)).length > 0 + ); + } + return caption.trim() !== '' || images.images.length > 0; + }; + + const leave = () => { + images.abortAll(); + if (!post) usePostDraftStore.getState().clearDraft(); + onLeave(); + }; + + return { + mode, + form, + images, + phase, + blocker, + isEmpty, + submit: () => void submit(), + submitError: form.formState.errors.root?.server?.message, + restored: draft !== null, + requestLeave: () => { + // Saving, or saved and already on its way out. + if (phase === 'saving') return; + if (hasSomethingToLose()) setIsConfirmingLeave(true); + else leave(); + }, + isConfirmingLeave, + confirmLeave: () => { + setIsConfirmingLeave(false); + leave(); + }, + cancelLeave: () => setIsConfirmingLeave(false), + minutesLeft: + secondsLeft === null ? null : Math.ceil(secondsLeft / SECONDS_PER_MINUTE), + isEditExpired, + }; +} diff --git a/platforms/market/src/features/post/models/editable-post/index.ts b/platforms/market/src/features/post/models/editable-post/index.ts new file mode 100644 index 0000000..2e37a2b --- /dev/null +++ b/platforms/market/src/features/post/models/editable-post/index.ts @@ -0,0 +1,2 @@ +export { useEditablePost } from './use-editable-post'; +export type { EditablePostModel } from './types'; diff --git a/platforms/market/src/features/post/models/editable-post/types.ts b/platforms/market/src/features/post/models/editable-post/types.ts new file mode 100644 index 0000000..d4c5880 --- /dev/null +++ b/platforms/market/src/features/post/models/editable-post/types.ts @@ -0,0 +1,7 @@ +import type { UnlockedPostPayload } from '../../repositories/post'; + +export type EditablePostModel = + | { status: 'pending' } + /** Not the creator's own, or a prediction: predictions stay as published. */ + | { status: 'not-editable' } + | { status: 'ready'; post: UnlockedPostPayload }; diff --git a/platforms/market/src/features/post/models/editable-post/use-editable-post.ts b/platforms/market/src/features/post/models/editable-post/use-editable-post.ts new file mode 100644 index 0000000..1514905 --- /dev/null +++ b/platforms/market/src/features/post/models/editable-post/use-editable-post.ts @@ -0,0 +1,33 @@ +import { useQuery } from '@tanstack/react-query'; + +import { postKeys, postRepository } from '../../repositories/post'; +import type { EditablePostModel } from './types'; + +/** + * The post the creator opened for editing, read in the browser with their session, so it arrives + * in full. Only their own text or image post can be edited; a prediction never can. A missing post + * throws to the page's boundary as not found. A cached copy read without the session (the post + * page starts from the server's) is locked however fresh, so it is read again before it counts. + */ +export function useEditablePost( + postId: string, + creatorId: string, +): EditablePostModel { + const query = useQuery({ + queryKey: postKeys.detail(postId), + queryFn: ({ signal }) => postRepository.get(postId, { signal }), + refetchOnMount: ({ state }) => (state.data?.locked ? 'always' : true), + }); + const post = query.data; + // A failed first read throws to the boundary, so no data means it is still loading. + if (!post || (post.locked && query.isFetching)) return { status: 'pending' }; + if ( + post.locked || + post.creatorId !== creatorId || + post.type === 'prediction' || + post.status !== 'published' + ) { + return { status: 'not-editable' }; + } + return { status: 'ready', post }; +} diff --git a/platforms/market/src/features/post/models/owner-post/index.ts b/platforms/market/src/features/post/models/owner-post/index.ts new file mode 100644 index 0000000..b61710b --- /dev/null +++ b/platforms/market/src/features/post/models/owner-post/index.ts @@ -0,0 +1,2 @@ +export { useOwnerPostPart } from './use-owner-post-part'; +export type { OwnerPostPartModel, UseOwnerPostPartOptions } from './types'; diff --git a/platforms/market/src/features/post/models/owner-post/types.ts b/platforms/market/src/features/post/models/owner-post/types.ts new file mode 100644 index 0000000..7bfe5c5 --- /dev/null +++ b/platforms/market/src/features/post/models/owner-post/types.ts @@ -0,0 +1,23 @@ +import type { PostPayload } from '../../repositories/post'; + +export type UseOwnerPostPartOptions = { + post: PostPayload; + /** The viewer is the post's creator; nothing runs for anyone else. */ + enabled: boolean; + /** After a delete: the post page leaves for the channel, read fresh, so nothing refreshes. */ + onDeleted?: () => void; +}; + +export type OwnerPostPartModel = { + /** Past the 15 minutes after publishing: edit stays visible, frozen. */ + isEditFrozen: boolean; + isConfirmingDelete: boolean; + askDelete: () => void; + cancelDelete: () => void; + confirmDelete: () => void; + isDeleting: boolean; + /** The close-prediction sheet. */ + isClosingPrediction: boolean; + openClosePrediction: () => void; + closeClosePrediction: () => void; +}; diff --git a/platforms/market/src/features/post/models/owner-post/use-owner-post-part.ts b/platforms/market/src/features/post/models/owner-post/use-owner-post-part.ts new file mode 100644 index 0000000..2614519 --- /dev/null +++ b/platforms/market/src/features/post/models/owner-post/use-owner-post-part.ts @@ -0,0 +1,71 @@ +import { useCountdown } from '@lumina/island/hooks/use-countdown'; +import { showToast } from '@lumina/island/molecules/toast'; +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { useRouter } from 'next/navigation'; +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { showActionError } from '../../../../shared/utils'; +import { deletePost } from '../../actions/delete-post'; +import { POST_LIMITS } from '../../constants'; +import { removeCachedPost } from '../post-cache'; +import type { OwnerPostPartModel, UseOwnerPostPartOptions } from './types'; + +const MINUTE_MS = 60_000; + +/** + * The creator's own post: edit for 15 minutes after publishing, then frozen; delete at any time + * after asking, which takes it out of every list at once; and closing an open prediction. + */ +export function useOwnerPostPart({ + post, + enabled, + onDeleted, +}: UseOwnerPostPartOptions): OwnerPostPartModel { + const { t } = useTranslation('content'); + const queryClient = useQueryClient(); + const router = useRouter(); + const [isConfirmingDelete, setIsConfirmingDelete] = useState(false); + const [isClosingPrediction, setIsClosingPrediction] = useState(false); + const editEndsAt = + enabled && post.publishedAt + ? new Date(post.publishedAt).getTime() + POST_LIMITS.editWindowMs + : undefined; + const secondsLeft = useCountdown(editEndsAt, { intervalMs: MINUTE_MS }); + + const remove = useMutation({ + mutationFn: () => + deletePost({ postId: post.id, creatorId: post.creatorId }), + onSuccess: () => { + setIsConfirmingDelete(false); + removeCachedPost(queryClient, post); + showToast({ tone: 'success', message: t('post.delete.deleted') }); + // The channel's first page and track record are rendered on the server: the page it goes + // to is read fresh, and one it stays on renders again. Refreshed before leaving, the post + // page would flash its «deleted» state first. + if (onDeleted) onDeleted(); + else router.refresh(); + }, + onError: (error) => + // Deleting twice is harmless, so the toast may offer to try again. + showActionError(error, { + t, + failedMessage: t('post.delete.failed'), + retry: () => remove.mutate(), + }), + }); + + return { + isEditFrozen: secondsLeft === 0, + isConfirmingDelete, + askDelete: () => setIsConfirmingDelete(true), + cancelDelete: () => setIsConfirmingDelete(false), + confirmDelete: () => { + if (!remove.isPending) remove.mutate(); + }, + isDeleting: remove.isPending, + isClosingPrediction, + openClosePrediction: () => setIsClosingPrediction(true), + closeClosePrediction: () => setIsClosingPrediction(false), + }; +} diff --git a/platforms/market/src/features/post/models/post-cache/index.ts b/platforms/market/src/features/post/models/post-cache/index.ts new file mode 100644 index 0000000..551ba56 --- /dev/null +++ b/platforms/market/src/features/post/models/post-cache/index.ts @@ -0,0 +1,6 @@ +export { + isChannelOnScreen, + removeCachedPost, + replaceCachedPost, + resetCachedChannel, +} from './post-cache'; diff --git a/platforms/market/src/features/post/models/post-cache/post-cache.ts b/platforms/market/src/features/post/models/post-cache/post-cache.ts new file mode 100644 index 0000000..d7fd3db --- /dev/null +++ b/platforms/market/src/features/post/models/post-cache/post-cache.ts @@ -0,0 +1,77 @@ +import type { InfiniteData, QueryClient } from '@tanstack/react-query'; + +import { postKeys } from '../../repositories/post'; +import type { PostPagePayload, PostPayload } from '../../repositories/post'; + +type ChannelFeed = InfiniteData; + +function mapFeed( + queryClient: QueryClient, + creatorId: string, + map: (items: PostPayload[]) => PostPayload[], +): void { + queryClient.setQueryData( + postKeys.channelFeed(creatorId), + (feed) => + feed && { + ...feed, + pages: feed.pages.map((page) => ({ ...page, items: map(page.items) })), + }, + ); +} + +/** A post changed (edited, closed): every cached copy shows the new one in its place. */ +export function replaceCachedPost( + queryClient: QueryClient, + post: PostPayload, +): void { + queryClient.setQueryData(postKeys.detail(post.id), post); + mapFeed(queryClient, post.creatorId, (items) => + items.map((item) => (item.id === post.id ? post : item)), + ); +} + +/** + * A post is gone: out of the channel's loaded pages at once, and its own entry dropped. The pages + * are read by offset, so they are read again too, as after a new post: kept, the next page would + * start one post late and skip one. + */ +export function removeCachedPost( + queryClient: QueryClient, + { id, creatorId }: { id: string; creatorId: string }, +): void { + queryClient.removeQueries({ queryKey: postKeys.detail(id), exact: true }); + mapFeed(queryClient, creatorId, (items) => + items.filter((item) => item.id !== id), + ); + resetCachedChannel(queryClient, creatorId); +} + +/** The channel's feed is on screen, such as under the desktop composer dialog. */ +export function isChannelOnScreen( + queryClient: QueryClient, + creatorId: string, +): boolean { + const observers = queryClient + .getQueryCache() + .find({ queryKey: postKeys.channelFeed(creatorId), exact: true }) + ?.getObserversCount(); + return (observers ?? 0) > 0; +} + +/** + * A new post: the channel shows it at the top. A channel on screen (under the desktop composer + * dialog) reads its pages again now; otherwise its cached pages are dropped, so the channel reads + * its first page from the server when it opens. + */ +export function resetCachedChannel( + queryClient: QueryClient, + creatorId: string, +): void { + const queryKey = postKeys.channelFeed(creatorId); + if (isChannelOnScreen(queryClient, creatorId)) { + void queryClient.invalidateQueries({ queryKey, exact: true }); + } else { + queryClient.removeQueries({ queryKey }); + } +} diff --git a/platforms/market/src/features/post/models/post-list/index.ts b/platforms/market/src/features/post/models/post-list/index.ts new file mode 100644 index 0000000..a2bb3ce --- /dev/null +++ b/platforms/market/src/features/post/models/post-list/index.ts @@ -0,0 +1,7 @@ +export { usePostList } from './use-post-list'; +export type { + ListedPost, + PostListModel, + PostListQuery, + UsePostListOptions, +} from './types'; diff --git a/platforms/market/src/features/post/models/post-list/types.ts b/platforms/market/src/features/post/models/post-list/types.ts new file mode 100644 index 0000000..5edf4ed --- /dev/null +++ b/platforms/market/src/features/post/models/post-list/types.ts @@ -0,0 +1,50 @@ +import type { LoadMoreErrorKind } from '../../../../shared/utils'; +import type { PostPayload } from '../../repositories/post'; + +/** What a list reads of each post; a list's items may carry more, such as the home feed's creator. */ +export type ListedPost = Pick; + +/** The last copy of each post read in full, by id. */ +export type OpenPostCopies = ReadonlyMap; + +/** The paged read behind a list: an infinite query over pages of posts, with its data loaded. */ +export type PostListQuery = { + data: { pages: readonly { items: readonly T[] }[] }; + hasNextPage: boolean; + /** Any read of the pages is on its way, the next page or all of them again. */ + isFetching: boolean; + isFetchingNextPage: boolean; + /** The last read was of the next page, and it failed; `error` says why. */ + isFetchNextPageError: boolean; + error: unknown; + fetchNextPage: () => Promise; + refetch: () => Promise; +}; + +export type UsePostListOptions = { + query: PostListQuery; + /** + * The pages may have been read without the viewer's session (a channel's first page comes from + * the server render) and the viewer may read its premium posts: locked posts are read again. + */ + entitled?: boolean; +}; + +export type PostListModel = { + /** + * Published posts, newest first, each once; one read in full on this page stays open until the + * next load. + */ + posts: T[]; + /** No post to show, and no page left to read: the list's empty state. */ + isEmpty: boolean; + hasMore: boolean; + /** Reads the next page; nothing while any read of the list is on its way. Also its retry. */ + loadMore: () => void; + isLoadingMore: boolean; + /** + * The next page failed: an inline row with a retry takes the «more» button's place, and the + * posts read so far stay. `null` otherwise. + */ + loadMoreError: LoadMoreErrorKind | null; +}; diff --git a/platforms/market/src/features/post/models/post-list/use-post-list.ts b/platforms/market/src/features/post/models/post-list/use-post-list.ts new file mode 100644 index 0000000..a844332 --- /dev/null +++ b/platforms/market/src/features/post/models/post-list/use-post-list.ts @@ -0,0 +1,87 @@ +import { useEffect, useState } from 'react'; + +import { firstOfEach, loadMoreErrorKind } from '../../../../shared/utils'; +import { useCurrentAccount } from '../../../../stores/auth'; +import type { + ListedPost, + OpenPostCopies, + PostListModel, + UsePostListOptions, +} from './types'; + +/** The kept copies with each post now read in full put in; the same map when nothing changed. */ +function keepOpen( + kept: OpenPostCopies, + posts: readonly T[], +): OpenPostCopies { + const read = posts.filter( + (post) => !post.locked && kept.get(post.id) !== post, + ); + if (read.length === 0) return kept; + return new Map([...kept, ...read.map((post) => [post.id, post] as const)]); +} + +/** + * A list of posts read page after page, as the channel and home feeds show it: published posts + * only, each once. + * + * A post open on this page stays open while the list is mounted: a later read that comes back + * locked (a refetch after the subscription ended, on focus or on reconnect) keeps the copy on + * screen, and the lock shows on the next load (C5 §۵). Nothing says the access ended (U11). The + * copies belong to the viewer who read them: another viewer (a sign-out, a session that ended) + * starts from what the pages show them. When the pages were read without the viewer's session and + * the viewer is `entitled`, the locked posts are read again and open in place. + */ +export function usePostList({ + query, + entitled = false, +}: UsePostListOptions): PostListModel { + // Each post once: kept twice, its two copies would take turns as the kept one on every render. + const read = firstOfEach( + query.data.pages + .flatMap((page) => page.items) + .filter((post) => post.status === 'published'), + (post) => post.id, + ); + // The last copy of each post read in full, on this page only and for this viewer only. + const viewerId = useCurrentAccount()?.id ?? null; + const [keptFor, setKeptFor] = useState(viewerId); + const [open, setOpen] = useState(() => + keepOpen(new Map(), read), + ); + const kept = keepOpen(keptFor === viewerId ? open : new Map(), read); + if (keptFor !== viewerId) setKeptFor(viewerId); + if (kept !== open) setOpen(kept); + const posts = read.map((post) => + post.locked ? (kept.get(post.id) ?? post) : post, + ); + const hasLocked = read.some((post) => post.locked); + const { refetch, fetchNextPage, isFetching, isFetchNextPageError } = query; + // The creator's own pages hold their drafts too, which never show. + const isBlank = read.length === 0 && query.hasNextPage; + + useEffect(() => { + if (entitled && hasLocked) void refetch(); + }, [entitled, hasLocked, refetch]); + + // Nothing to show yet with more behind it: read on, rather than look empty. A failed page stops + // it, with the «more» row's retry. + useEffect(() => { + if (isBlank && !isFetching && !isFetchNextPageError) void fetchNextPage(); + }, [isBlank, isFetching, isFetchNextPageError, fetchNextPage]); + + return { + posts, + isEmpty: read.length === 0 && !query.hasNextPage, + hasMore: query.hasNextPage, + loadMore: () => { + // fetchNextPage cancels a read of every page on its way (cancelRefetch), and would add the + // next page to the pages read before it, skipping or repeating posts: wait for it instead. + if (!query.isFetching) void query.fetchNextPage(); + }, + isLoadingMore: query.isFetchingNextPage, + loadMoreError: query.isFetchNextPageError + ? loadMoreErrorKind(query.error) + : null, + }; +} diff --git a/platforms/market/src/features/post/models/post/index.ts b/platforms/market/src/features/post/models/post/index.ts new file mode 100644 index 0000000..826228d --- /dev/null +++ b/platforms/market/src/features/post/models/post/index.ts @@ -0,0 +1,6 @@ +export { usePostPart } from './use-post-part'; +export type { + PostPartModel, + PostReaderSubscription, + UsePostPartOptions, +} from './types'; diff --git a/platforms/market/src/features/post/models/post/types.ts b/platforms/market/src/features/post/models/post/types.ts new file mode 100644 index 0000000..333d9ef --- /dev/null +++ b/platforms/market/src/features/post/models/post/types.ts @@ -0,0 +1,33 @@ +import type { BillingPeriod } from '../../../../shared/constants'; +import type { PostPayload } from '../../repositories/post'; + +/** The subscription a reader has the channel's premium posts through. */ +export type PostReaderSubscription = { + /** The end of access, ISO: renewals already added. */ + endsAt: string; + /** The period last bought, for «دسترسی از طریق اشتراک سالانه». */ + billingPeriod: BillingPeriod; +}; + +export type UsePostPartOptions = { + /** The post as the server read it: every visitor's view, locked when premium. */ + post: PostPayload; + /** The creator or an active subscriber: the post is read again with their session. */ + entitled: boolean; + /** The subscriber's active subscription; `null` (the default) for anyone else or while unknown. */ + subscription?: PostReaderSubscription | null; +}; + +export type PostPartModel = { + post: PostPayload; + /** + * The period a subscriber reads this open premium post through (Post--unlocked), while the + * subscription runs; `null` otherwise. + */ + accessPeriod: BillingPeriod | null; + /** + * The subscription ended while this open premium post was on screen (C5 ۵.۲): the post stays open + * until the next load. + */ + accessEnded: boolean; +}; diff --git a/platforms/market/src/features/post/models/post/use-post-part.ts b/platforms/market/src/features/post/models/post/use-post-part.ts new file mode 100644 index 0000000..a3237d2 --- /dev/null +++ b/platforms/market/src/features/post/models/post/use-post-part.ts @@ -0,0 +1,62 @@ +import { useCountdown } from '@lumina/island/hooks/use-countdown'; +import { useQuery } from '@tanstack/react-query'; +import { useEffect, useState } from 'react'; + +import { useCurrentAccount } from '../../../../stores/auth'; +import { postKeys, postRepository } from '../../repositories/post'; +import type { PostPartModel, UsePostPartOptions } from './types'; + +// The end of access only has to land on time: a tick a day at most until then, then none. +const DAY_MS = 86_400_000; + +/** + * The post page's post. It starts from the server's read, which carries no session; for the + * creator or a subscriber a locked post is read again in the browser and opens in place. + * + * Once open, it stays open on this page: a later read that comes back locked (a refetch after the + * subscription ended, on focus or on reconnect) keeps the copy on screen until the next load + * (C5 ۵.۲). The subscription is kept the same way, so its end still shows after the standing is + * read again without it. Both belong to the viewer who read them: another viewer (a sign-out, a + * session that ended) starts from what the post shows them. + */ +export function usePostPart({ + post: serverPost, + entitled, + subscription = null, +}: UsePostPartOptions): PostPartModel { + const query = useQuery({ + queryKey: postKeys.detail(serverPost.id), + queryFn: ({ signal }) => postRepository.get(serverPost.id, { signal }), + initialData: serverPost, + }); + const { refetch, data } = query; + const isLocked = data.locked; + // The last copy read in full and the last subscription seen, both on this page only. + const viewerId = useCurrentAccount()?.id ?? null; + const [keptFor, setKeptFor] = useState(viewerId); + const [open, setOpen] = useState(isLocked ? null : data); + const [access, setAccess] = useState(subscription); + if (keptFor !== viewerId) { + setKeptFor(viewerId); + setOpen(isLocked ? null : data); + setAccess(subscription); + } else { + if (!isLocked && data !== open) setOpen(data); + if (subscription && subscription !== access) setAccess(subscription); + } + const ended = useCountdown(access?.endsAt, { intervalMs: DAY_MS }) === 0; + + useEffect(() => { + if (entitled && isLocked) void refetch(); + }, [entitled, isLocked, refetch]); + + const post = isLocked && open ? open : data; + const isOpenPremium = !post.locked && post.accessLevel === 'premium'; + + return { + post, + accessPeriod: + isOpenPremium && access && !ended ? access.billingPeriod : null, + accessEnded: isOpenPremium && access != null && ended, + }; +} diff --git a/platforms/market/src/features/post/repositories/post/constants.ts b/platforms/market/src/features/post/repositories/post/constants.ts index 5678bd9..2f9e1cf 100644 --- a/platforms/market/src/features/post/repositories/post/constants.ts +++ b/platforms/market/src/features/post/repositories/post/constants.ts @@ -13,10 +13,16 @@ export const POST_ENDPOINTS = { /** The page size lists ask for, so a server-rendered first page and the next pages agree. */ export const POST_PAGE_LIMIT = 20; +/** A post id is a Mongo ObjectId; anything else is a 404 without asking (the API would 500). */ +export const POST_ID_PATTERN = /^[a-f\d]{24}$/i; + export const postKeys = { all: ['post'] as const, details: () => [...postKeys.all, 'detail'] as const, detail: (id: string) => [...postKeys.details(), id] as const, lists: () => [...postKeys.all, 'list'] as const, list: (args: ListCreatorPostsArgs) => [...postKeys.lists(), args] as const, + /** A channel's posts page after page, as its feed loads them. */ + channelFeed: (creatorId: string) => + [...postKeys.lists(), 'channel', creatorId] as const, }; diff --git a/platforms/market/src/features/post/repositories/post/index.ts b/platforms/market/src/features/post/repositories/post/index.ts index 8a65f52..0a0f8bb 100644 --- a/platforms/market/src/features/post/repositories/post/index.ts +++ b/platforms/market/src/features/post/repositories/post/index.ts @@ -1,4 +1,9 @@ -export { POST_ENDPOINTS, POST_PAGE_LIMIT, postKeys } from './constants'; +export { + POST_ENDPOINTS, + POST_ID_PATTERN, + POST_PAGE_LIMIT, + postKeys, +} from './constants'; export { toPostPayload } from './mappers'; export { postRepository } from './post'; export type { @@ -8,7 +13,6 @@ export type { LockedPostPayload, LockedPredictionPayload, PostImagePayload, - PostImagePreviewPayload, PostMediaArgs, PostPagePayload, PostPayload, diff --git a/platforms/market/src/features/post/repositories/post/mappers.ts b/platforms/market/src/features/post/repositories/post/mappers.ts index f0210a2..388b769 100644 --- a/platforms/market/src/features/post/repositories/post/mappers.ts +++ b/platforms/market/src/features/post/repositories/post/mappers.ts @@ -58,23 +58,18 @@ export function toPostPayload(dto: PostResponseDto): PostPayload { status: dto.status, createdAt: dto.createdAt, publishedAt: dto.publishedAt ?? null, + editedAt: dto.editedAt ?? null, }; if (dto.locked) { return { ...base, locked: true, captionPreview: dto.captionPreview ?? null, - mediaPreview: dto.mediaPreview.map(({ order, width, height }) => ({ - order, - width: width ?? null, - height: height ?? null, - })), mediaCount: dto.mediaCount, prediction: dto.prediction ? { - symbol: dto.prediction.symbol, - direction: dto.prediction.direction, status: dto.prediction.status, + outcome: dto.prediction.outcome ?? null, } : null, }; diff --git a/platforms/market/src/features/post/repositories/post/post.ts b/platforms/market/src/features/post/repositories/post/post.ts index 7538b74..f51398d 100644 --- a/platforms/market/src/features/post/repositories/post/post.ts +++ b/platforms/market/src/features/post/repositories/post/post.ts @@ -24,7 +24,8 @@ import type { /** * Posts. Reads work without a session: a premium post the viewer is not subscribed to comes back - * locked (`locked: true`, a teaser), and a draft is a 404 for anyone but its creator. Writes are + * locked (`locked: true`: a teaser that never carries the call or anything of the media), and a + * draft is a 404 for anyone but its creator. Writes are * the creator's own posts only; another creator's post is a 404. Request field names match the * `*Args` names, so field errors need no renaming. */ diff --git a/platforms/market/src/features/post/repositories/post/types.ts b/platforms/market/src/features/post/repositories/post/types.ts index 80638c8..4e5dc29 100644 --- a/platforms/market/src/features/post/repositories/post/types.ts +++ b/platforms/market/src/features/post/repositories/post/types.ts @@ -30,11 +30,13 @@ export type PredictionPayload = { closedAt: string | null; }; -/** A locked premium prediction's frame: the API sends nothing else, not even the outcome. */ +/** + * A locked premium prediction: whether it is open, with the outcome once closed. Never the call + * itself: no symbol, direction or levels. + */ export type LockedPredictionPayload = { - symbol: string; - direction: PredictionDirection; status: PredictionStatus; + outcome: PredictionOutcome | null; }; /** One image of an image post. `url` is absolute and paywalled: it streams with the viewer's cookies. */ @@ -46,13 +48,6 @@ export type PostImagePayload = { height: number | null; }; -/** A locked image's box, to size its placeholder. The API's blurHash is dropped: it is never drawn. */ -export type PostImagePreviewPayload = { - order: number; - width: number | null; - height: number | null; -}; - type PostPayloadBase = { id: string; creatorId: string; @@ -63,6 +58,8 @@ type PostPayloadBase = { createdAt: string; /** `null` on a draft. */ publishedAt: string | null; + /** Set once a published post was edited: «ویرایش‌شده». */ + editedAt: string | null; }; /** A post the viewer may read in full: free, or premium for its creator and active subscribers. */ @@ -75,18 +72,21 @@ export type UnlockedPostPayload = PostPayloadBase & { prediction: PredictionPayload | null; }; -/** A premium post for anyone else: the teaser, with the caption cut to 140 characters. */ +/** + * A premium post for anyone else: the teaser, with the caption cut to 140 characters and the image + * count. Nothing of the media and nothing of the call. + */ export type LockedPostPayload = PostPayloadBase & { locked: true; captionPreview: string | null; - mediaPreview: PostImagePreviewPayload[]; mediaCount: number; prediction: LockedPredictionPayload | null; }; /** - * A post as the viewer may see it, told apart by `locked`. The API does not include the author: - * pair `creatorId` with the creator's profile for the username and avatar. + * A post as the viewer may see it, told apart by `locked`. Post reads do not include the author: + * pair `creatorId` with the creator's profile for the username and avatar. Home feed items carry + * it (`FeedItemPayload`). */ export type PostPayload = UnlockedPostPayload | LockedPostPayload; @@ -145,7 +145,9 @@ export type CreatePostArgs = { /** * A partial edit; only the keys given change. `status: 'published'` publishes a draft (one way); - * `prediction` is editable only while the post is a draft. + * `prediction` is editable only while the post is a draft. There is no `type`: the API sets it + * from `media`, so a text post given images becomes an image post, and one left with none a text + * post. */ export type UpdatePostArgs = Partial>; diff --git a/platforms/market/src/features/post/types.ts b/platforms/market/src/features/post/types.ts new file mode 100644 index 0000000..33d8a57 --- /dev/null +++ b/platforms/market/src/features/post/types.ts @@ -0,0 +1,13 @@ +import type { PostAccessLevel } from './entities/post'; + +declare module '@lumina/libs/event-emitter' { + interface EventMap { + 'post.publish': { + postId: string; + creatorId: string; + accessLevel: PostAccessLevel; + }; + 'post.edit': { postId: string; creatorId: string }; + 'post.delete': { postId: string; creatorId: string }; + } +} diff --git a/platforms/market/src/features/prediction/actions/.gitkeep b/platforms/market/src/features/prediction/actions/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/prediction/actions/close-prediction/actions.ts b/platforms/market/src/features/prediction/actions/close-prediction/actions.ts new file mode 100644 index 0000000..91fcda2 --- /dev/null +++ b/platforms/market/src/features/prediction/actions/close-prediction/actions.ts @@ -0,0 +1,26 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import type { PostPayload } from '../../../post'; +import { PREDICTION_EVENTS } from '../../constants'; +import { predictionRepository } from '../../repositories/prediction'; +import type { ClosePredictionArgs } from '../../repositories/prediction'; + +/** + * Closes the creator's own open prediction at a price. The API records the outcome and the ROI in + * the track record for good: there is no undo. Emits `prediction.close`. + */ +export async function closePrediction( + { postId, closedPrice }: ClosePredictionArgs & { postId: string }, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const post = await predictionRepository.close(postId, { closedPrice }); + const outcome = !post.locked ? post.prediction?.outcome : null; + if (emit && outcome) { + eventEmitter.emit(PREDICTION_EVENTS.close, { + postId, + creatorId: post.creatorId, + outcome, + }); + } + return post; +} diff --git a/platforms/market/src/features/prediction/actions/close-prediction/index.ts b/platforms/market/src/features/prediction/actions/close-prediction/index.ts new file mode 100644 index 0000000..ad40a5a --- /dev/null +++ b/platforms/market/src/features/prediction/actions/close-prediction/index.ts @@ -0,0 +1 @@ +export { closePrediction } from './actions'; diff --git a/platforms/market/src/features/prediction/constants.ts b/platforms/market/src/features/prediction/constants.ts new file mode 100644 index 0000000..036f3aa --- /dev/null +++ b/platforms/market/src/features/prediction/constants.ts @@ -0,0 +1,4 @@ +/** Events prediction actions emit when they succeed. */ +export const PREDICTION_EVENTS = { + close: 'prediction.close', +} as const; diff --git a/platforms/market/src/features/prediction/index.ts b/platforms/market/src/features/prediction/index.ts index 9bc60af..24f04b8 100644 --- a/platforms/market/src/features/prediction/index.ts +++ b/platforms/market/src/features/prediction/index.ts @@ -1,5 +1,19 @@ +import './types'; + +export { closePrediction } from './actions/close-prediction'; +export { PREDICTION_EVENTS } from './constants'; +export { + outcomeAt, + roiAt, + useClosePredictionPart, +} from './models/close-prediction'; +export type { + ClosePredictionPartModel, + UseClosePredictionPartOptions, +} from './models/close-prediction'; export { PREDICTION_ENDPOINTS, + PREDICTION_STATS_MIN_CLOSED, predictionKeys, predictionRepository, } from './repositories/prediction'; diff --git a/platforms/market/src/features/prediction/models/.gitkeep b/platforms/market/src/features/prediction/models/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/prediction/models/close-prediction/index.ts b/platforms/market/src/features/prediction/models/close-prediction/index.ts new file mode 100644 index 0000000..376438f --- /dev/null +++ b/platforms/market/src/features/prediction/models/close-prediction/index.ts @@ -0,0 +1,6 @@ +export { outcomeAt, roiAt } from './outcome'; +export { useClosePredictionPart } from './use-close-prediction-part'; +export type { + ClosePredictionPartModel, + UseClosePredictionPartOptions, +} from './types'; diff --git a/platforms/market/src/features/prediction/models/close-prediction/outcome.ts b/platforms/market/src/features/prediction/models/close-prediction/outcome.ts new file mode 100644 index 0000000..367695f --- /dev/null +++ b/platforms/market/src/features/prediction/models/close-prediction/outcome.ts @@ -0,0 +1,29 @@ +import type { PredictionOutcome, PredictionPayload } from '../../../post'; + +/** The outcome the API will record for a close price: the same rule, so the preview never lies. */ +export function outcomeAt( + { + direction, + entryPrice, + }: Pick, + closedPrice: number, +): PredictionOutcome { + if (closedPrice === entryPrice) return 'breakeven'; + const rose = closedPrice > entryPrice; + return (direction === 'long' ? rose : !rose) ? 'win' : 'loss'; +} + +/** The return in the prediction's own direction, as a percentage. */ +export function roiAt( + { + direction, + entryPrice, + }: Pick, + closedPrice: number, +): number { + const change = + direction === 'long' + ? (closedPrice - entryPrice) / entryPrice + : (entryPrice - closedPrice) / entryPrice; + return change * 100; +} diff --git a/platforms/market/src/features/prediction/models/close-prediction/types.ts b/platforms/market/src/features/prediction/models/close-prediction/types.ts new file mode 100644 index 0000000..8077db1 --- /dev/null +++ b/platforms/market/src/features/prediction/models/close-prediction/types.ts @@ -0,0 +1,31 @@ +import type { UseFormReturn } from 'react-hook-form'; + +import type { + ClosePredictionFormOutput, + ClosePredictionFormValues, +} from '../../../../shared/validations'; +import type { + PredictionOutcome, + PredictionPayload, + UnlockedPostPayload, +} from '../../../post'; + +export type UseClosePredictionPartOptions = { + /** The creator's own published prediction post, still open. */ + post: UnlockedPostPayload & { prediction: PredictionPayload }; + /** The sheet closes: the prediction closed, or the creator cancelled. */ + onDone: () => void; +}; + +export type ClosePredictionPartModel = { + form: UseFormReturn< + ClosePredictionFormValues, + unknown, + ClosePredictionFormOutput + >; + /** What the typed price would record, live; `null` until it is a price. */ + preview: { outcome: PredictionOutcome; roi: number } | null; + submit: () => void; + isSubmitting: boolean; + formError: string | undefined; +}; diff --git a/platforms/market/src/features/prediction/models/close-prediction/use-close-prediction-part.ts b/platforms/market/src/features/prediction/models/close-prediction/use-close-prediction-part.ts new file mode 100644 index 0000000..1d7a2b1 --- /dev/null +++ b/platforms/market/src/features/prediction/models/close-prediction/use-close-prediction-part.ts @@ -0,0 +1,96 @@ +import { valibotResolver } from '@hookform/resolvers/valibot'; +import { showToast } from '@lumina/island/molecules/toast'; +import { signedPercent } from '@lumina/tools/format'; +import { useQueryClient } from '@tanstack/react-query'; +import { useRouter } from 'next/navigation'; +import { useForm, useWatch } from 'react-hook-form'; +import { useTranslation } from 'react-i18next'; + +import { applyServerErrors, toPriceNumber } from '../../../../shared/utils'; +import { closePredictionSchema } from '../../../../shared/validations'; +import type { + ClosePredictionFormOutput, + ClosePredictionFormValues, +} from '../../../../shared/validations'; +import { replaceCachedPost } from '../../../post'; +import { closePrediction } from '../../actions/close-prediction'; +import { predictionKeys } from '../../repositories/prediction'; +import { outcomeAt, roiAt } from './outcome'; +import type { + ClosePredictionPartModel, + UseClosePredictionPartOptions, +} from './types'; + +/** + * Closing a prediction (R1 03): the creator types the close price and sees, live, the outcome and + * return it will record. Saving is final. The post updates in place wherever it shows, and the + * channel's track record, rendered on the server, renders again. + */ +export function useClosePredictionPart({ + post, + onDone, +}: UseClosePredictionPartOptions): ClosePredictionPartModel { + const { t } = useTranslation('content'); + const queryClient = useQueryClient(); + const router = useRouter(); + const form = useForm< + ClosePredictionFormValues, + unknown, + ClosePredictionFormOutput + >({ + resolver: valibotResolver(closePredictionSchema), + mode: 'onTouched', + defaultValues: { closedPrice: '' }, + }); + const typed = useWatch({ control: form.control, name: 'closedPrice' }); + const price = toPriceNumber(typed); + const preview = + Number.isFinite(price) && price > 0 + ? { + outcome: outcomeAt(post.prediction, price), + roi: roiAt(post.prediction, price), + } + : null; + + const symbol = post.prediction.symbol; + const submit = form.handleSubmit(async ({ closedPrice }) => { + try { + const closed = await closePrediction({ postId: post.id, closedPrice }); + replaceCachedPost(queryClient, closed); + void queryClient.invalidateQueries({ + queryKey: predictionKeys.stats(post.creatorId), + }); + // The track record in the channel header is rendered on the server. + router.refresh(); + // What the API recorded, as the card and the track record show it; the API sends no ROI + // per post, so it follows from the recorded price. + const recorded = closed.locked ? null : closed.prediction; + const recordedPrice = recorded?.closedPrice ?? closedPrice; + const outcome = + recorded?.outcome ?? outcomeAt(post.prediction, recordedPrice); + showToast({ + tone: 'success', + message: t('prediction.close.closed', { symbol }), + description: t('prediction.close.closed-description', { + outcome: t(`prediction.status.${outcome}`), + roi: signedPercent(roiAt(post.prediction, recordedPrice)), + }), + }); + onDone(); + } catch (error) { + // Not safe to send twice: the form keeps the price and submitting is the retry. + applyServerErrors(form, error, { + t, + failedMessage: t('prediction.close.failed', { symbol }), + }); + } + }); + + return { + form, + preview, + submit: () => void submit(), + isSubmitting: form.formState.isSubmitting, + formError: form.formState.errors.root?.server?.message, + }; +} diff --git a/platforms/market/src/features/prediction/repositories/prediction/constants.ts b/platforms/market/src/features/prediction/repositories/prediction/constants.ts index dff67f0..e16b5a7 100644 --- a/platforms/market/src/features/prediction/repositories/prediction/constants.ts +++ b/platforms/market/src/features/prediction/repositories/prediction/constants.ts @@ -9,3 +9,9 @@ export const predictionKeys = { stats: (creatorId: string) => [...predictionKeys.all, 'stats', creatorId] as const, }; + +/** + * The track record shows from this many closed predictions; below it the block is left out, never + * shown as zeros. The API has no threshold of its own (product: the minimum is still open). + */ +export const PREDICTION_STATS_MIN_CLOSED = 1; diff --git a/platforms/market/src/features/prediction/repositories/prediction/index.ts b/platforms/market/src/features/prediction/repositories/prediction/index.ts index a3fdb8c..af6dc00 100644 --- a/platforms/market/src/features/prediction/repositories/prediction/index.ts +++ b/platforms/market/src/features/prediction/repositories/prediction/index.ts @@ -1,3 +1,7 @@ -export { PREDICTION_ENDPOINTS, predictionKeys } from './constants'; +export { + PREDICTION_ENDPOINTS, + PREDICTION_STATS_MIN_CLOSED, + predictionKeys, +} from './constants'; export { predictionRepository } from './prediction'; export type { ClosePredictionArgs, PredictionStatsPayload } from './types'; diff --git a/platforms/market/src/features/prediction/types.ts b/platforms/market/src/features/prediction/types.ts new file mode 100644 index 0000000..0d0afba --- /dev/null +++ b/platforms/market/src/features/prediction/types.ts @@ -0,0 +1,11 @@ +import type { PredictionOutcome } from '../post'; + +declare module '@lumina/libs/event-emitter' { + interface EventMap { + 'prediction.close': { + postId: string; + creatorId: string; + outcome: PredictionOutcome; + }; + } +} diff --git a/platforms/market/src/features/profile/entities/creator-profile/types.ts b/platforms/market/src/features/profile/entities/creator-profile/types.ts index 6f0568e..aca500a 100644 --- a/platforms/market/src/features/profile/entities/creator-profile/types.ts +++ b/platforms/market/src/features/profile/entities/creator-profile/types.ts @@ -40,6 +40,11 @@ export type CreatorProfileEntity = { kycStatus: KycStatus; kycSubmittedAt: string; verificationStatus: VerificationStatus; + /** + * Why an admin rejected the identity check, trimmed; `null` unless `verificationStatus` is + * `rejected`. An API older than this field leaves it out. + */ + rejectionReason?: string | null; bio?: string | null; avatar?: string | null; socialLinks?: SocialLinkEntity[]; diff --git a/platforms/market/src/features/profile/index.ts b/platforms/market/src/features/profile/index.ts index 3078e71..d3183c9 100644 --- a/platforms/market/src/features/profile/index.ts +++ b/platforms/market/src/features/profile/index.ts @@ -4,6 +4,11 @@ export { completeCreatorProfile } from './actions/complete-creator-profile'; export { PROFILE_EVENTS, TRADING_STYLES } from './constants'; export type { KycStatus, TradingStyle } from './entities/creator-profile'; export { useCreatorProfileDonePage } from './models/creator-profile-done'; +export { + creatorStandingOf, + useCreatorStanding, +} from './models/creator-standing'; +export type { CreatorStanding } from './models/creator-standing'; export type { CreatorProfileDonePageModel, UseCreatorProfileDonePageOptions, diff --git a/platforms/market/src/features/profile/models/creator-standing/creator-standing-of.ts b/platforms/market/src/features/profile/models/creator-standing/creator-standing-of.ts new file mode 100644 index 0000000..7310899 --- /dev/null +++ b/platforms/market/src/features/profile/models/creator-standing/creator-standing-of.ts @@ -0,0 +1,12 @@ +import type { CreatorProfilePayload } from '../../repositories/profile'; +import type { CreatorStanding } from './types'; + +/** The creator's standing as their own profile states it; the one rule behind publishing. */ +export function creatorStandingOf( + profile: Pick, +): Exclude { + if (profile.kycStatus === 'suspended') return 'suspended'; + if (profile.verificationStatus === 'approved') return 'verified'; + if (profile.verificationStatus === 'rejected') return 'rejected'; + return 'pending'; +} diff --git a/platforms/market/src/features/profile/models/creator-standing/index.ts b/platforms/market/src/features/profile/models/creator-standing/index.ts new file mode 100644 index 0000000..425089e --- /dev/null +++ b/platforms/market/src/features/profile/models/creator-standing/index.ts @@ -0,0 +1,3 @@ +export { creatorStandingOf } from './creator-standing-of'; +export { useCreatorStanding } from './use-creator-standing'; +export type { CreatorStanding } from './types'; diff --git a/platforms/market/src/features/profile/models/creator-standing/types.ts b/platforms/market/src/features/profile/models/creator-standing/types.ts new file mode 100644 index 0000000..8d33da9 --- /dev/null +++ b/platforms/market/src/features/profile/models/creator-standing/types.ts @@ -0,0 +1,10 @@ +/** + * Whether the creator may publish (C4 §2): `verified` may; `pending` waits for identity review, + * `rejected` must resubmit, `suspended` may not at all. `unknown` while it loads. + */ +export type CreatorStanding = + | 'unknown' + | 'verified' + | 'pending' + | 'rejected' + | 'suspended'; diff --git a/platforms/market/src/features/profile/models/creator-standing/use-creator-standing.ts b/platforms/market/src/features/profile/models/creator-standing/use-creator-standing.ts new file mode 100644 index 0000000..e7d5e41 --- /dev/null +++ b/platforms/market/src/features/profile/models/creator-standing/use-creator-standing.ts @@ -0,0 +1,20 @@ +import { useQuery } from '@tanstack/react-query'; + +import { profileKeys, profileRepository } from '../../repositories/profile'; +import { creatorStandingOf } from './creator-standing-of'; +import type { CreatorStanding } from './types'; + +/** + * The signed-in creator's standing, from their own profile: it decides whether «انتشار» opens the + * publish menu or explains why it can't. Read only for a creator (`enabled`); a failed read keeps + * `unknown`, so nothing is blocked by a network error. + */ +export function useCreatorStanding(enabled: boolean): CreatorStanding { + const query = useQuery({ + queryKey: profileKeys.mine(), + queryFn: ({ signal }) => profileRepository.getMine({ signal }), + enabled, + throwOnError: false, + }); + return query.data ? creatorStandingOf(query.data) : 'unknown'; +} diff --git a/platforms/market/src/features/profile/repositories/profile/mappers.ts b/platforms/market/src/features/profile/repositories/profile/mappers.ts index a422492..6bf6454 100644 --- a/platforms/market/src/features/profile/repositories/profile/mappers.ts +++ b/platforms/market/src/features/profile/repositories/profile/mappers.ts @@ -33,6 +33,10 @@ export function toCreatorProfilePayload( url, })), verificationStatus: dto.verificationStatus, + rejectionReason: + dto.verificationStatus === 'rejected' + ? dto.rejectionReason?.trim() || null + : null, kycStatus: dto.kycStatus, kycSubmittedAt: dto.kycSubmittedAt, profileComplete: dto.profileComplete, diff --git a/platforms/market/src/features/profile/repositories/profile/types.ts b/platforms/market/src/features/profile/repositories/profile/types.ts index 668332e..62abad5 100644 --- a/platforms/market/src/features/profile/repositories/profile/types.ts +++ b/platforms/market/src/features/profile/repositories/profile/types.ts @@ -25,6 +25,8 @@ export type CreatorProfilePayload = { socialLinks: SocialLinkPayload[]; /** Only `approved` creators are public and can be subscribed to. */ verificationStatus: VerificationStatus; + /** The admin's reason while `verificationStatus` is `rejected` (C4 ۲.۵); `null` otherwise. */ + rejectionReason: string | null; kycStatus: KycStatus; kycSubmittedAt: string; /** Display name and at least one market are set: the creator may publish. */ diff --git a/platforms/market/src/index.ts b/platforms/market/src/index.ts index b5656af..3a7943d 100644 --- a/platforms/market/src/index.ts +++ b/platforms/market/src/index.ts @@ -25,11 +25,15 @@ export type { OnboardingGuardProps } from './app/guards/onboarding-guard'; export { PageError } from './app/screens/organisms/page-error'; export type { PageErrorProps } from './app/screens/organisms/page-error'; export { + BottomNav, CHANNEL_PREFIX, + DesktopHeader, loginRoute, + MobileTopBar, ROUTES, safeReturnPath, } from './app/navigation'; +export type { MobileTopBarProps } from './app/navigation'; export { getEnv, setEnv } from './env'; export type { MarketEnv } from './env'; export { @@ -66,7 +70,12 @@ export type { UserStatus, VerifyOtpArgs, } from './features/auth'; -export { renameFieldErrors, toApiUrl, toE164Mobile } from './shared/utils'; +export { + renameFieldErrors, + toApiUrl, + toChannelUsername, + toE164Mobile, +} from './shared/utils'; export { BILLING_PERIODS, CHECKOUT_KINDS, @@ -105,18 +114,46 @@ export type { UpdateProfileArgs, UploadAvatarArgs, } from './features/profile'; -export { channelKeys, channelRepository } from './features/channel'; +export { + channelKeys, + channelRepository, + syncFollowCaches, + useChannelActionsPart, + useChannelEntitled, + useChannelGate, + useChannelViewer, + useFollowingPart, + useShareLink, +} from './features/channel'; export type { + ChannelActionsPartModel, ChannelArgs, + ChannelGate, + ChannelStanding, + ChannelViewer, + FollowingPartModel, + ShareLinkArgs, + UseChannelActionsPartOptions, PublicCreatorPayload, PublicTierPayload, TierPromotionPayload, } from './features/channel'; -export { followKeys, followRepository } from './features/follow'; +export { + FOLLOW_EVENTS, + FOLLOWING_PAGE_LIMIT, + followCreator, + followKeys, + followRepository, + unfollowCreator, +} from './features/follow'; export type { FollowArgs, FollowChangePayload, + FollowedCreatorPayload, + FollowingPagePayload, + FollowingPayload, FollowStatusPayload, + ListFollowingArgs, } from './features/follow'; export { notificationKeys, @@ -135,11 +172,16 @@ export { fileKeys, fileRepository, POST_ENDPOINTS, + POST_ID_PATTERN, POST_PAGE_LIMIT, postKeys, postRepository, + useChannelFeedPart, + usePostList, + usePostPart, } from './features/post'; export type { + ChannelFeedPartModel, CreatePostArgs, DeletedPostPayload, FileKind, @@ -148,12 +190,14 @@ export type { FileStatus, FileVisibility, ListCreatorPostsArgs, + ListedPost, ListMyFilesArgs, LockedPostPayload, LockedPredictionPayload, PostAccessLevel, PostImagePayload, - PostImagePreviewPayload, + PostListModel, + PostListQuery, PostMediaArgs, PostPagePayload, PostPayload, @@ -164,14 +208,19 @@ export type { PredictionOutcome, PredictionPayload, PredictionStatus, + PostPartModel, PurgedPostPayload, UnlockedPostPayload, UpdatePostArgs, UploadFileArgs, UploadFileOptions, + UseChannelFeedPartOptions, + UsePostListOptions, + UsePostPartOptions, } from './features/post'; export { PREDICTION_ENDPOINTS, + PREDICTION_STATS_MIN_CLOSED, predictionKeys, predictionRepository, } from './features/prediction'; @@ -184,8 +233,15 @@ export { FEED_PAGE_LIMIT, feedKeys, feedRepository, + useHomeFeedPart, +} from './features/feed'; +export type { + FeedCreatorPayload, + FeedItemPayload, + FeedPayload, + HomeFeedPartModel, + ListFeedArgs, } from './features/feed'; -export type { FeedPayload, ListFeedArgs } from './features/feed'; export { pricingKeys, pricingRepository } from './features/pricing'; export type { GetPricingFormArgs, @@ -200,7 +256,12 @@ export type { PricingValidationPayload, SavePricingArgs, } from './features/pricing'; -export { checkoutKeys, checkoutRepository } from './features/checkout'; +export { + CHECKOUT_EVENTS, + checkoutKeys, + checkoutRepository, + leaveWaitlist, +} from './features/checkout'; export type { CheckoutCtaState, CheckoutPayload, diff --git a/platforms/market/src/server.ts b/platforms/market/src/server.ts index 21a7ef8..9e8334e 100644 --- a/platforms/market/src/server.ts +++ b/platforms/market/src/server.ts @@ -3,10 +3,14 @@ import 'server-only'; // Public server-only API, exposed as the `/server` subpath. index.ts never imports this file. // Server reads carry no session: only what is the same for every visitor is read here. export { readOnServer } from './app/error-boundaries/server'; +export { channelMetadata, postMetadata } from './app/seo/server'; +export type { ChannelMetadataArgs, PostMetadataArgs } from './app/seo/server'; export type { ServerRead } from './app/error-boundaries/server'; export { + getChannel, getPublicCreator, getPublicTiers, } from './features/channel/caches/server'; export { getCreatorPosts, getPost } from './features/post/caches/server'; export { getPredictionStats } from './features/prediction/caches/server'; +export { getRequestTime } from './shared/utils/request-time'; diff --git a/platforms/market/src/shared/labels/content-labels.tsx b/platforms/market/src/shared/labels/content-labels.tsx new file mode 100644 index 0000000..276925c --- /dev/null +++ b/platforms/market/src/shared/labels/content-labels.tsx @@ -0,0 +1,186 @@ +import type { CreatorStatsLabels } from '@lumina/island/organisms/creator-stats'; +import type { LightboxLabels } from '@lumina/island/organisms/lightbox'; +import type { PostCardLabels } from '@lumina/island/organisms/post-card'; +import type { PredictionCardLabels } from '@lumina/island/organisms/prediction-card'; +import { number } from '@lumina/tools/format'; + +import type { ContentT } from './types'; + +// Island organisms take every text as props (0005). These build them from the `content` +// namespace once, so the channel, the post page and the feed word a post the same way. + +/** PostCard's texts: the header, the image buttons, the locked gate and the owner's footer. */ +export function postCardLabels(t: ContentT): PostCardLabels { + return { + premium: t('post.premium'), + edited: t('post.edited'), + verified: t('post.verified'), + images: t('post.images'), + openImage: (alt) => + alt ? t('post.open-image-alt', { alt }) : t('post.open-image'), + openSlide: (n, total, alt) => + alt + ? t('post.open-slide-alt', { n, total, alt }) + : t('post.open-slide', { n, total }), + imageCount: (n) => t('post.image-count', { n }), + share: t('post.share'), + copyLink: t('post.copy-link'), + owner: { + preview: t('post.owner.preview'), + edit: t('post.owner.edit'), + editFrozen: t('post.owner.edit-frozen'), + delete: t('post.owner.delete'), + access: t('post.owner.access'), + free: t('post.owner.free'), + }, + locked: { + guest: t('post.locked.guest'), + member: t('post.locked.member'), + login: t('post.locked.login'), + subscribe: t('post.locked.subscribe'), + media: t('post.locked.media'), + }, + }; +} + +/** PredictionCard's texts, embedded in a post or on its own. */ +export function predictionCardLabels(t: ContentT): PredictionCardLabels { + const target = (n?: string) => + n ? t('prediction.levels.target-n', { n }) : t('prediction.levels.target'); + + return { + status: { + open: t('prediction.status.open'), + win: t('prediction.status.win'), + loss: t('prediction.status.loss'), + breakeven: t('prediction.status.breakeven'), + }, + premium: t('prediction.premium'), + direction: { + long: t('prediction.direction.long'), + short: t('prediction.direction.short'), + }, + horizon: (horizon) => t('prediction.horizon', { horizon }), + timeLeft: { + daysLeft: (days) => t('prediction.days-left', { days: number(days) }), + underDays: (days) => t('prediction.under-days', { days: number(days) }), + }, + roi: t('prediction.roi'), + closedPrice: (price) => ( + <> + {t('prediction.closed-price')} {price} + + ), + heldFor: (duration) => t('prediction.held-for', { duration }), + toTarget: t('prediction.to-target'), + toFinalTarget: t('prediction.to-final-target'), + toStop: t('prediction.to-stop'), + riskReward: t('prediction.risk-reward'), + levels: { + stop: t('prediction.levels.stop'), + entry: t('prediction.levels.entry'), + base: t('prediction.levels.base'), + target, + finalTarget: t('prediction.levels.final-target'), + close: t('prediction.levels.close'), + horizon: t('prediction.levels.horizon'), + }, + ladder: { + level: t('prediction.ladder.level'), + price: t('prediction.ladder.price'), + change: t('prediction.ladder.change'), + state: t('prediction.ladder.state'), + reached: t('prediction.ladder.reached'), + missed: t('prediction.ladder.missed'), + triggered: t('prediction.ladder.triggered'), + notTriggered: t('prediction.ladder.not-triggered'), + }, + rangeLabel: ({ stop, entry, targets, close }) => { + const several = targets.length > 1; + const values = [ + stop && t('prediction.range.stop', { price: stop }), + t('prediction.range.entry', { price: entry }), + ...targets.map((price, index) => + several + ? t('prediction.range.target-n', { n: number(index + 1), price }) + : t('prediction.range.target', { price }), + ), + close && t('prediction.range.close', { price: close }), + ]; + return t('prediction.range.label', { + values: values.filter(Boolean).join('، '), + }); + }, + horizonElapsed: (duration) => t('prediction.horizon-elapsed', { duration }), + horizonEnd: (date) => t('prediction.horizon-end', { date }), + horizonProgress: t('prediction.horizon-progress'), + seal: (date) => ( + <> + {t('prediction.seal')} {date} + + ), + immutable: t('prediction.immutable'), + closePrediction: t('prediction.close-prediction'), + locked: { + title: t('prediction.locked.title'), + description: t('prediction.locked.description'), + hidden: t('prediction.locked.hidden'), + content: t('prediction.locked.content'), + }, + }; +} + +/** CreatorStats' texts and screen-reader sentences; counts arrive already formatted. */ +export function creatorStatsLabels(t: ContentT): CreatorStatsLabels { + return { + title: t('stats.title'), + viewRecord: t('stats.view-record'), + winRate: t('stats.win-rate'), + closedCount: (n) => t('stats.closed-count', { n }), + outcomes: { + win: t('stats.outcomes.win'), + loss: t('stats.outcomes.loss'), + breakeven: t('stats.outcomes.breakeven'), + }, + splitLegend: (count, outcome) => ( + <> + {count} {outcome} + + ), + splitSentence: ({ win, breakeven, loss }) => + t('stats.split-sentence', { win, breakeven, loss }), + avgRoi: t('stats.avg-roi'), + total: t('stats.total'), + active: t('stats.active'), + trendTitle: t('stats.trend-title'), + trendWindow: (n) => t('stats.trend-window', { n }), + tally: (wins, total) => t('stats.tally', { wins, total }), + curveLabel: (n, outcomes) => + t('stats.curve-label', { n, outcomes: outcomes.join('، ') }), + newestPoint: (outcome) => t('stats.newest-point', { outcome }), + older: t('stats.older'), + newest: t('stats.newest'), + keyLabel: t('stats.key'), + insights: { + above: t('stats.insights.above'), + below: t('stats.insights.below'), + level: t('stats.insights.level'), + allTime: (rate) => t('stats.insights.all-time', { rate }), + }, + streak: (n, outcome) => t('stats.streak', { n, outcome }), + }; +} + +/** The post-image viewer's buttons. The counter keeps the component's «۱ / ۳». */ +export function lightboxLabels(t: ContentT): LightboxLabels { + return { + dialog: t('lightbox.dialog'), + close: t('lightbox.close'), + back: t('lightbox.back'), + previous: t('lightbox.previous'), + next: t('lightbox.next'), + zoomIn: t('lightbox.zoom-in'), + zoomOut: t('lightbox.zoom-out'), + download: t('lightbox.download'), + }; +} diff --git a/platforms/market/src/shared/labels/index.ts b/platforms/market/src/shared/labels/index.ts new file mode 100644 index 0000000..a16e440 --- /dev/null +++ b/platforms/market/src/shared/labels/index.ts @@ -0,0 +1,7 @@ +export { + creatorStatsLabels, + lightboxLabels, + postCardLabels, + predictionCardLabels, +} from './content-labels'; +export type { ContentT } from './types'; diff --git a/platforms/market/src/shared/labels/types.ts b/platforms/market/src/shared/labels/types.ts new file mode 100644 index 0000000..bf44bd9 --- /dev/null +++ b/platforms/market/src/shared/labels/types.ts @@ -0,0 +1,7 @@ +import type { TFunction } from 'i18next'; + +/** + * `t` fixed to the `content` namespace: `useTranslation('content').t` in a client component, + * `i18n.getFixedT(null, 'content')` on the server. + */ +export type ContentT = TFunction<'content'>; diff --git a/platforms/market/src/shared/locales/fa/channel.json b/platforms/market/src/shared/locales/fa/channel.json new file mode 100644 index 0000000..b3d6399 --- /dev/null +++ b/platforms/market/src/shared/locales/fa/channel.json @@ -0,0 +1,142 @@ +{ + "meta": { + "title": "@{{username}}", + "description": "کانال @{{username}} در لومینا: پست‌ها و پیش‌بینی‌های ثبت‌شده، با کارنامه‌ای که پیش از اشتراک می‌بینید.", + "post-title": "پست @{{username}}", + "post-missing-title": "پست پیدا نشد", + "unavailable-title": "کانال در دسترس نیست" + }, + "top-bar": { + "channel": "کانال", + "post": "پست" + }, + "loading": "در حال بارگذاری کانال…", + "header": { + "verified": "تأییدشده", + "share": "اشتراک‌گذاری کانال", + "markets": "بازارهای تخصصی", + "links": "لینک‌های تحلیلگر", + "opens-new-tab": "در زبانه‌ی جدید باز می‌شود", + "platforms": { + "telegram": "تلگرام", + "instagram": "اینستاگرام", + "x": "ایکس", + "youtube": "یوتیوب", + "aparat": "آپارات", + "linkedin": "لینکدین" + } + }, + "actions": { + "loading": "در حال بارگذاری وضعیت شما در این کانال…", + "subscribe": "اشتراک", + "subscribed": "مشترک هستید", + "follow": "دنبال کردن", + "unfollow": "دنبال نکردن", + "unfollow-frozen": "تا زمانی که اشتراک این کانال فعال است، امکان لغو دنبال‌کردن وجود ندارد.", + "pending": "پرداخت در حال بررسی", + "pending-description": "پرداخت شما در حال بررسی است. پس از تأیید، اشتراک شما فعال می‌شود. اگر پرداخت انجام شده و اشتراک فعال نشد، با پشتیبانی در ارتباط باشید.", + "payment-failed": "پرداخت شما تأیید نشد و اشتراکی ثبت نشده است.", + "payment-failed-description": "اگر مبلغی از حساب شما کسر شده، بانک آن را حداکثر تا 72 ساعت به حساب شما بازمی‌گرداند." + }, + "follow": { + "followed": "⁦@{{username}}⁩ را دنبال می‌کنید.", + "followed-description": "پست‌های این تحلیلگر از این پس در خانه شما نمایش داده می‌شود.", + "unfollowed": "دنبال کردن ⁦@{{username}}⁩ لغو شد.", + "follow-failed": "دنبال کردن ⁦@{{username}}⁩ انجام نشد.", + "unfollow-failed": "لغو دنبال کردن ⁦@{{username}}⁩ انجام نشد.", + "confirm": { + "title": "دنبال نکردن ⁦@{{username}}⁩", + "description": "با این کار، پست‌های این تحلیلگر دیگر در خانه شما نمایش داده نمی‌شود. آیا مطمئن هستید؟", + "confirm": "بله، دنبال نکن", + "cancel": "انصراف" + } + }, + "guest": { + "title": "برای دنبال کردن وارد شوید", + "description": "پس از ورود به همین کانال بازمی‌گردید.", + "login": "ورود/ثبت‌نام", + "close": "بستن" + }, + "waitlist": { + "note": "در صورت باز شدن ظرفیت به شما اطلاع داده می‌شود.", + "leave": "لغو اطلاع‌رسانی", + "left": "اطلاع‌رسانی لغو شد.", + "leave-failed": "اطلاع‌رسانی لغو نشد." + }, + "share": { + "channel-text": "کانال ⁦@{{username}}⁩ در لومینا", + "post-text": "پستی از ⁦@{{username}}⁩ در لومینا", + "channel-copied": "لینک کانال کپی شد.", + "post-copied": "لینک پست کپی شد.", + "copy-failed": "لینک کپی نشد.", + "copy-failed-description": "مرورگر اجازه‌ی دسترسی به حافظه‌ی موقت را نداد. دوباره تلاش کنید.", + "owner": { + "title": "اشتراک‌گذاری کانال", + "caption": "پیام اشتراک‌گذاری کانال", + "placeholder": "پیامی برای همراه شدن با لینک بنویسید", + "default-caption": "من را در لومینا دنبال کن 👇", + "limit": "به حداکثر تعداد کاراکتر رسیدید.", + "share": "اشتراک‌گذاری", + "copy-all": "کپی همه", + "copy-link": "کپی لینک", + "all-copied": "متن و لینک کپی شد.", + "copy-failed": "کپی ناموفق بود. دوباره تلاش کنید.", + "retry": "تلاش مجدد", + "close": "بستن", + "pending": "برای اشتراک‌گذاری کانال، ابتدا باید احراز هویت شما تأیید شود.", + "suspended": "حساب شما تعلیق شده است. امکان اشتراک‌گذاری کانال وجود ندارد." + } + }, + "stats": { + "loading": "در حال بارگذاری عملکرد پیش‌بینی‌ها…", + "error-title": "عملکرد پیش‌بینی‌ها بارگذاری نشد", + "error-description": "بقیه کانال در دسترس است. این بخش را دوباره بارگذاری کنید." + }, + "feed": { + "label": "پست‌های کانال", + "loading": "در حال بارگذاری پست‌ها…", + "more": "نمایش پست‌های قدیمی‌تر", + "more-failed": "پست‌های قدیمی‌تر بارگذاری نشد.", + "no-subscribers": "این پست تا پیوستن نخستین مشترک، برای همه قفل می‌ماند.", + "empty": { + "title": "این کانال هنوز پستی منتشر نکرده است", + "description": "با دنبال کردن، از پست‌ها و پیش‌بینی‌های تازه باخبر می‌شوید." + }, + "own-empty": { + "title": "هنوز پستی منتشر نکرده‌اید", + "description": "اولین پست یا پیش‌بینی خود را منتشر کنید تا دنبال‌کنندگان آن را ببینند.", + "post": "پست جدید", + "prediction": "پیش‌بینی جدید" + } + }, + "post": { + "loading": "در حال بارگذاری پست…" + }, + "post-missing": { + "title": "این پست حذف شده است.", + "description": "پست مورد نظر حذف شده یا وجود ندارد.", + "channel": "مشاهده کانال" + }, + "not-found": { + "title": "کانال پیدا نشد", + "description": "کانالی با این نام کاربری وجود ندارد. نشانی را بررسی کنید.", + "home": "بازگشت به خانه" + }, + "unavailable": { + "channel-title": "این کانال در دسترس نیست", + "channel-description": "ممکن است حساب حذف یا تعلیق شده باشد.", + "post-title": "این کانال در حال حاضر در دسترس نیست.", + "post-description": "محتوای این پست نمایش داده نمی‌شود.", + "home": "رفتن به خانه" + }, + "own": { + "loading": "در حال بارگذاری کانال شما…", + "pending": "حساب شما در انتظار تأیید است. پس از تأیید تیم پشتیبانی می‌توانید محتوا منتشر کنید.", + "rejected": "احراز هویت شما تأیید نشد. برای انتشار پست، ابتدا اطلاعات هویتی خود را اصلاح و ارسال مجدد کنید.", + "rejected-reason": "احراز هویت شما تأیید نشد. دلیل: {{reason}}", + "empty-title": "هنوز پستی منتشر نکرده‌اید.", + "draft-title": "پیش‌نویس ذخیره شد", + "draft-description": "پس از تأیید احراز هویت می‌توانید منتشر کنید.", + "suspended": "حساب شما تعلیق شده است." + } +} diff --git a/platforms/market/src/shared/locales/fa/common.json b/platforms/market/src/shared/locales/fa/common.json index 3048afe..45370c8 100644 --- a/platforms/market/src/shared/locales/fa/common.json +++ b/platforms/market/src/shared/locales/fa/common.json @@ -26,11 +26,48 @@ "automotive": "خودرو", "USDT": "تتر (دلار و ارز)" }, + "billing-periods": { + "monthly": "ماهانه", + "quarterly": "سه‌ماهه", + "semi_annual": "شش‌ماهه", + "yearly": "سالانه" + }, "status": { "verification": { "pending": "در انتظار احراز هویت", "approved": "تأییدشده", "rejected": "رد شده" } + }, + "nav": { + "label": "ناوبری اصلی", + "brand": "لومینا", + "brand-home": "صفحه اصلی لومینا", + "home": "خانه", + "dashboard": "داشبورد", + "channel": "کانال", + "back": "بازگشت", + "login": "ورود/ثبت‌نام", + "account": "حساب کاربری" + }, + "publish": { + "menu": "انتشار", + "post": "پست جدید", + "prediction": "پیش‌بینی جدید", + "close": "بستن", + "pending": { + "title": "در انتظار تأیید", + "reason": "برای انتشار پست، ابتدا باید احراز هویت شما تأیید شود.", + "action": "مشاهده وضعیت احراز هویت" + }, + "rejected": { + "title": "احراز هویت تأیید نشد", + "reason": "احراز هویت شما تأیید نشد. برای انتشار پست، ابتدا اطلاعات هویتی خود را اصلاح و ارسال مجدد کنید.", + "action": "اصلاح و ارسال مجدد" + }, + "suspended": { + "title": "حساب تعلیق شده", + "reason": "حساب شما تعلیق شده است. امکان انتشار پست وجود ندارد." + } } } diff --git a/platforms/market/src/shared/locales/fa/content.json b/platforms/market/src/shared/locales/fa/content.json new file mode 100644 index 0000000..6e497e0 --- /dev/null +++ b/platforms/market/src/shared/locales/fa/content.json @@ -0,0 +1,227 @@ +{ + "post": { + "premium": "پریمیوم", + "edited": "ویرایش‌شده", + "verified": "تأییدشده", + "images": "تصاویر پست", + "open-image": "نمایش تصویر", + "open-image-alt": "نمایش تصویر، {{alt}}", + "open-slide": "نمایش تصویر {{n}} از {{total}}", + "open-slide-alt": "نمایش تصویر {{n}} از {{total}}، {{alt}}", + "image-count": "{{n}} تصویر", + "share": "اشتراک‌گذاری پست", + "copy-link": "کپی لینک", + "owner": { + "preview": "مشاهده به عنوان کاربر", + "edit": "ویرایش پست", + "edit-frozen": "مهلت ویرایش این پست به پایان رسیده است.", + "delete": "حذف پست", + "access": "سطح دسترسی پست", + "free": "رایگان" + }, + "locked": { + "guest": "برای مشاهده محتوای پریمیوم، وارد شوید یا ثبت‌نام کنید.", + "member": "برای مشاهده این محتوا، نیاز به اشتراک در کانال آن دارید.", + "login": "ورود/ثبت‌نام", + "subscribe": "اشتراک در کانال", + "creator-reason": "اشتراک کانال فقط برای حساب سرمایه‌گذار است.", + "media": "تصاویر قفل‌شده", + "pending": "پرداخت در حال بررسی", + "pending-reason": "پرداخت شما در حال بررسی است. پس از تأیید، اشتراک شما فعال می‌شود. اگر پرداخت انجام شده و اشتراک فعال نشد، با پشتیبانی در ارتباط باشید." + }, + "delete": { + "title": "آیا از حذف این پست اطمینان دارید؟ این عملیات غیرقابل بازگشت است.", + "confirm": "بله، حذف کن", + "cancel": "انصراف", + "deleted": "پست حذف شد.", + "failed": "خطا در حذف پست." + }, + "yours": "پست شما", + "access-via": "دسترسی از طریق اشتراک {{period}}", + "access-ended": "اشتراک شما پایان یافت. این پست تا بارگذاری بعدی باز می‌ماند." + }, + "prediction": { + "status": { + "open": "فعال", + "win": "موفق", + "loss": "ناموفق", + "breakeven": "سربه‌سر" + }, + "premium": "پریمیوم", + "direction": { + "long": "خرید", + "short": "فروش" + }, + "horizon": "افق {{horizon}}", + "days-left": "{{days}} روز مانده", + "under-days": "کمتر از {{days}} روز مانده", + "roi": "بازدهی", + "closed-price": "بسته‌شدن", + "held-for": "پس از {{duration}}", + "to-target": "تا هدف", + "to-final-target": "تا هدف نهایی", + "to-stop": "تا حد ضرر", + "risk-reward": "ریسک به ریوارد", + "levels": { + "stop": "حد ضرر", + "entry": "ورود", + "base": "مبنا", + "target": "هدف", + "target-n": "هدف {{n}}", + "final-target": "هدف نهایی", + "close": "بسته‌شدن", + "horizon": "افق" + }, + "ladder": { + "level": "سطح", + "price": "قیمت", + "change": "تغییر از ورود", + "state": "وضعیت", + "reached": "رسید", + "missed": "نرسید", + "triggered": "فعال شد", + "not-triggered": "فعال نشد" + }, + "range": { + "label": "محدوده پیش‌بینی: {{values}}", + "stop": "حد ضرر {{price}}", + "entry": "ورود {{price}}", + "target": "هدف {{price}}", + "target-n": "هدف {{n}} {{price}}", + "close": "بسته‌شدن {{price}}" + }, + "horizon-elapsed": "گذشته از افق: {{duration}}", + "horizon-end": "پایان افق: {{date}}", + "horizon-progress": "زمان سپری‌شده از افق", + "seal": "ثبت‌شده در", + "immutable": "غیرقابل ویرایش", + "close-prediction": "بستن پیش‌بینی", + "locked": { + "title": "پیش‌بینی پریمیوم", + "description": "دارایی، جهت، ورود، اهداف و حد ضرر پنهان است.", + "hidden": "پنهان", + "content": "محتوای پریمیوم" + }, + "close": { + "title": "بستن پیش‌بینی", + "description": "قیمت بسته‌شدن را وارد کنید. نتیجه و بازدهی با همین قیمت در کارنامه شما ثبت می‌شود.", + "summary": "پیش‌بینی", + "price": "قیمت بسته‌شدن", + "result": "نتیجه: {{outcome}}، بازدهی", + "warning": "پس از ثبت، نتیجه نهایی است و قابل ویرایش یا حذف نیست.", + "submit": "ثبت و بستن", + "cancel": "انصراف", + "closed": "پیش‌بینی ⁦{{symbol}}⁩ بسته شد.", + "closed-description": "نتیجه: {{outcome}}، بازدهی {{roi}}", + "failed": "پیش‌بینی ⁦{{symbol}}⁩ بسته نشد." + } + }, + "stats": { + "title": "عملکرد پیش‌بینی‌ها", + "view-record": "مشاهده کارنامه کامل", + "win-rate": "نرخ موفقیت", + "closed-count": "از {{n}} پیش‌بینی بسته‌شده", + "outcomes": { + "win": "موفق", + "loss": "ناموفق", + "breakeven": "سربه‌سر" + }, + "split-sentence": "{{win}} موفق، {{breakeven}} سربه‌سر، {{loss}} ناموفق", + "avg-roi": "بازدهی میانگین", + "total": "کل پیش‌بینی‌ها", + "active": "پیش‌بینی‌های فعال", + "trend-title": "روند دقت", + "trend-window": "{{n}} پیش‌بینی اخیر", + "tally": "{{wins}} از {{total}} موفق", + "curve-label": "منحنی نتیجه {{n}} پیش‌بینی اخیر، از قدیمی‌ترین به جدیدترین: {{outcomes}}. هر موفق یک پله بالا، هر ناموفق یک پله پایین.", + "newest-point": "{{outcome}} (جدیدترین)", + "older": "قدیمی‌تر", + "newest": "جدیدترین", + "key": "راهنما", + "insights": { + "above": "بالاتر از میانگین کل", + "below": "پایین‌تر از میانگین کل", + "level": "هم‌سطح میانگین کل", + "all-time": "({{rate}})" + }, + "streak": "{{n}} {{outcome}} پیاپی" + }, + "lightbox": { + "dialog": "تصاویر پست", + "close": "بستن", + "back": "بازگشت", + "previous": "تصویر قبلی", + "next": "تصویر بعدی", + "zoom-in": "بزرگ‌نمایی", + "zoom-out": "کوچک‌نمایی", + "download": "دانلود", + "image": "تصویر {{n}} از {{total}}، از پست ⁦@{{username}}⁩" + }, + "validation": { + "price-required": "قیمت بسته‌شدن را وارد کنید.", + "price-invalid": "قیمت را فقط با عدد و بزرگ‌تر از صفر وارد کنید؛ مثلاً ۶۵۲۸۰.", + "post-empty": "پست نمی‌تواند خالی باشد. متن یا تصویر اضافه کنید.", + "caption-long": "متن پست حداکثر ۲۰۰۰ کاراکتر است." + }, + "composer": { + "new-title": "پست جدید", + "edit-title": "ویرایش پست", + "loading": "در حال آماده‌سازی نوشتن پست…", + "visibility": "سطح دسترسی پست", + "free": "رایگان", + "premium": "پریمیوم", + "premium-hint": "فقط مشترکان کانال شما این پست را می‌بینند.", + "caption": "متن پست", + "placeholder": "تحلیل یا دیدگاه خود را بنویسید...", + "limit": "به حداکثر تعداد کاراکتر رسیدید.", + "images": { + "label": "تصاویر پست", + "add": "افزودن تصویر", + "add-tile": "افزودن", + "hint": "فرمت‌های مجاز: JPG، PNG، WebP — حداکثر حجم هر تصویر: ۵ مگابایت", + "type": "فقط فایل‌های JPG، PNG و WebP مجاز هستند.", + "size": "حجم هر تصویر نباید بیشتر از ۵ مگابایت باشد.", + "count": "امکان افزودن بیش از ۴ تصویر وجود ندارد.", + "failed": "آپلود تصویر {{n}} ناموفق بود. تصویر را حذف یا جایگزین کنید.", + "thumb": "تصویر {{n}}", + "uploading": "در حال آپلود تصویر {{n}}: {{percent}}", + "remove": "حذف تصویر {{n}}", + "retry": "آپلود دوباره تصویر {{n}}", + "upload-failed": "آپلود تصویر ناموفق بود." + }, + "publish": "انتشار", + "publishing": "در حال انتشار...", + "save": "ذخیره تغییرات", + "cancel": "انصراف", + "uploading-reason": "صبر کنید تا آپلود تصاویر تمام شود.", + "published": "پست شما با موفقیت منتشر شد.", + "saved": "تغییرات پست ذخیره شد.", + "publish-failed": "انتشار پست ناموفق بود.", + "save-failed": "خطا در ذخیره تغییرات. دوباره تلاش کنید.", + "edit-expired": "مهلت ویرایش این پست به پایان رسیده است.", + "minutes-left": "{{n}} دقیقه مانده", + "restored": "پیش‌نویس شما بازیابی شد.", + "leave": { + "title": "پست شما ذخیره نشده است. آیا می‌خواهید خارج شوید؟", + "edit-title": "تغییرات شما ذخیره نشده است. آیا می‌خواهید خارج شوید؟", + "confirm": "خروج", + "cancel": "ادامه ویرایش" + }, + "retry": "تلاش مجدد", + "not-editable": { + "title": "این پست قابل ویرایش نیست", + "description": "پیش‌بینی‌ها پس از انتشار ثابت می‌مانند و پست‌ها فقط تا ۱۵ دقیقه پس از انتشار ویرایش می‌شوند.", + "back": "بازگشت به کانال" + } + }, + "preview": { + "title": "پیش‌نمایش پست", + "as": "نمایش پست به عنوان", + "visitor": "بازدید کننده", + "subscriber": "کاربر مشترک", + "visitor-banner": "شما در حال مشاهده این پست به شکلی هستید که کاربران غیر عضو می‌بینند.", + "subscriber-banner": "شما در حال مشاهده این پست به شکلی هستید که کاربران عضو می‌بینند.", + "exit": "خروج از پیش‌نمایش", + "inert": "این دکمه در پیش‌نمایش کاری انجام نمی‌دهد." + } +} diff --git a/platforms/market/src/shared/locales/fa/dashboard.json b/platforms/market/src/shared/locales/fa/dashboard.json new file mode 100644 index 0000000..b7d663d --- /dev/null +++ b/platforms/market/src/shared/locales/fa/dashboard.json @@ -0,0 +1,23 @@ +{ + "tabs": { + "label": "بخش‌های داشبورد", + "subscriptions": "اشتراک‌ها", + "transactions": "تراکنش‌ها", + "following": "دنبال‌شده‌ها" + }, + "following": { + "meta-title": "دنبال‌شده‌ها", + "label": "تحلیلگرانی که دنبال می‌کنید", + "loading": "در حال بارگذاری دنبال‌شده‌ها…", + "error": "خطا در بارگذاری لیست. دوباره تلاش کنید.", + "unfollow": "دنبال نکردن ⁦@{{username}}⁩", + "unavailable": "در دسترس نیست", + "suspended": "کانال این تحلیلگر موقتاً در دسترس نیست.", + "more": "نمایش تحلیلگران بیشتر", + "more-failed": "ادامه‌ی فهرست دنبال‌شده‌ها بارگذاری نشد.", + "empty": { + "title": "هنوز تحلیلگری را دنبال نکرده‌اید.", + "home": "رفتن به خانه" + } + } +} diff --git a/platforms/market/src/shared/locales/fa/home.json b/platforms/market/src/shared/locales/fa/home.json new file mode 100644 index 0000000..8d27944 --- /dev/null +++ b/platforms/market/src/shared/locales/fa/home.json @@ -0,0 +1,20 @@ +{ + "meta": { + "title": "خانه" + }, + "heading": "خانه", + "feed": { + "label": "پست‌های کانال‌هایی که دنبال می‌کنید", + "loading": "در حال بارگذاری پست‌ها…", + "more": "نمایش پست‌های قدیمی‌تر", + "more-failed": "پست‌های قدیمی‌تر بارگذاری نشد." + }, + "empty": { + "title": "هنوز کانالی را دنبال نمی‌کنید", + "description": "با باز کردن لینک کانال یک تحلیلگر، مثل ⁦{{channelUrl}}⁩، می‌توانید او را دنبال کنید و پست‌هایش را اینجا ببینید." + }, + "no-posts": { + "title": "فعلاً پستی از کانال‌هایی که دنبال می‌کنید برای نمایش نیست", + "description": "با باز کردن لینک کانال تحلیلگری دیگر، مثل ⁦{{channelUrl}}⁩، می‌توانید او را هم دنبال کنید و پست‌هایش را اینجا ببینید." + } +} diff --git a/platforms/market/src/shared/locales/resources.ts b/platforms/market/src/shared/locales/resources.ts index 464ca48..c3fb4ee 100644 --- a/platforms/market/src/shared/locales/resources.ts +++ b/platforms/market/src/shared/locales/resources.ts @@ -1,6 +1,10 @@ import faAuth from './fa/auth.json'; +import faChannel from './fa/channel.json'; import faCommon from './fa/common.json'; +import faContent from './fa/content.json'; +import faDashboard from './fa/dashboard.json'; import faErrors from './fa/errors.json'; +import faHome from './fa/home.json'; /** The product is Persian only; every route loads every namespace, because any route can fail. */ export const DEFAULT_LOCALE = 'fa'; @@ -12,6 +16,10 @@ export const resources = { common: faCommon, auth: faAuth, errors: faErrors, + content: faContent, + channel: faChannel, + home: faHome, + dashboard: faDashboard, }, } as const; diff --git a/platforms/market/src/shared/utils/apply-server-errors.ts b/platforms/market/src/shared/utils/apply-server-errors.ts index c7e9362..508c08e 100644 --- a/platforms/market/src/shared/utils/apply-server-errors.ts +++ b/platforms/market/src/shared/utils/apply-server-errors.ts @@ -12,8 +12,8 @@ import type { ShowActionErrorOptions } from './show-action-error'; * to the form alert (`root.server`), then the action-error toast. A field counts as rendered when * it has a value, so every form sets `defaultValues` for every field. The form keeps every value. */ -export function applyServerErrors( - form: UseFormReturn, +export function applyServerErrors( + form: UseFormReturn, error: unknown, options: ShowActionErrorOptions, ): void { diff --git a/platforms/market/src/shared/utils/channel-username.ts b/platforms/market/src/shared/utils/channel-username.ts new file mode 100644 index 0000000..a6b6fb2 --- /dev/null +++ b/platforms/market/src/shared/utils/channel-username.ts @@ -0,0 +1,18 @@ +import * as v from 'valibot'; + +import { usernameSchema } from '../validations'; + +/** + * A channel URL's username segment as the API stores it: decoded, without a leading «@», in lower + * case. `null` when it can't be a username, so the page answers 404 without asking the API. + */ +export function toChannelUsername(segment: string): string | null { + let decoded: string; + try { + decoded = decodeURIComponent(segment); + } catch { + return null; + } + const parsed = v.safeParse(usernameSchema, decoded.trim().replace(/^@/, '')); + return parsed.success ? parsed.output : null; +} diff --git a/platforms/market/src/shared/utils/first-of-each.ts b/platforms/market/src/shared/utils/first-of-each.ts new file mode 100644 index 0000000..a67e666 --- /dev/null +++ b/platforms/market/src/shared/utils/first-of-each.ts @@ -0,0 +1,16 @@ +/** + * Each item of a paged list once, where it first shows. Pages are read by offset at different + * times, so an item added or moved between two reads comes back on the next page. + */ +export function firstOfEach( + items: readonly T[], + keyOf: (item: T) => string, +): T[] { + const seen = new Set(); + return items.filter((item) => { + const key = keyOf(item); + if (seen.has(key)) return false; + seen.add(key); + return true; + }); +} diff --git a/platforms/market/src/shared/utils/index.ts b/platforms/market/src/shared/utils/index.ts index 9b93ea0..b279348 100644 --- a/platforms/market/src/shared/utils/index.ts +++ b/platforms/market/src/shared/utils/index.ts @@ -1,7 +1,12 @@ export { applyServerErrors } from './apply-server-errors'; export { toApiUrl } from './api-url'; +export { toChannelUsername } from './channel-username'; +export { firstOfEach } from './first-of-each'; +export { loadMoreErrorKind } from './load-more-error-kind'; +export type { LoadMoreErrorKind } from './load-more-error-kind'; export { toggleMarket } from './markets'; export { formatMobile, toE164Mobile, toLocalMobile } from './mobile'; +export { toPriceNumber } from './price-input'; export { renameFieldErrors } from './rename-field-errors'; export { showActionError } from './show-action-error'; export { diff --git a/platforms/market/src/shared/utils/load-more-error-kind.ts b/platforms/market/src/shared/utils/load-more-error-kind.ts new file mode 100644 index 0000000..291b402 --- /dev/null +++ b/platforms/market/src/shared/utils/load-more-error-kind.ts @@ -0,0 +1,15 @@ +import type { ErrorKind } from '@lumina/island/molecules/error-state'; +import { isHttpError } from '@lumina/libs/http'; + +/** Why an older page failed, as its inline row says: our time limit, the connection, or else. */ +export type LoadMoreErrorKind = Extract< + ErrorKind, + 'timeout' | 'network' | 'error' +>; + +/** How a failed page read is told: our time limit, the connection, or anything else. */ +export function loadMoreErrorKind(error: unknown): LoadMoreErrorKind { + if (isHttpError(error) && error.code === 'TIMEOUT') return 'timeout'; + if (isHttpError(error) && error.code === 'NETWORK_ERROR') return 'network'; + return 'error'; +} diff --git a/platforms/market/src/shared/utils/price-input.ts b/platforms/market/src/shared/utils/price-input.ts new file mode 100644 index 0000000..65315d3 --- /dev/null +++ b/platforms/market/src/shared/utils/price-input.ts @@ -0,0 +1,13 @@ +import { latinDigits } from '@lumina/tools/format'; + +/** + * A typed price as a number: Persian or Latin digits, with or without thousands separators (٬ or + * ,), and ٫ or . for decimals. `NaN` when it isn't one. + */ +export function toPriceNumber(input: string): number { + const normalized = latinDigits(input) + .trim() + .replace(/[٬,\s]/g, '') + .replace('٫', '.'); + return /^\d+(\.\d+)?$/.test(normalized) ? Number(normalized) : Number.NaN; +} diff --git a/platforms/market/src/shared/utils/request-time.ts b/platforms/market/src/shared/utils/request-time.ts new file mode 100644 index 0000000..e5b6bb8 --- /dev/null +++ b/platforms/market/src/shared/utils/request-time.ts @@ -0,0 +1,9 @@ +import 'server-only'; + +import { cache } from 'react'; + +/** + * The time this request renders at, the same for every server component in it, so relative + * times and countdowns render from one clock and hydrate without a mismatch. Pass it down as `now`. + */ +export const getRequestTime = cache((): string => new Date().toISOString()); diff --git a/platforms/market/src/shared/validations/content-validations.ts b/platforms/market/src/shared/validations/content-validations.ts new file mode 100644 index 0000000..5a9ec40 --- /dev/null +++ b/platforms/market/src/shared/validations/content-validations.ts @@ -0,0 +1,30 @@ +import * as v from 'valibot'; + +import { toPriceNumber } from '../utils/price-input'; + +/** The price a creator closes their prediction at: a positive number, typed any way. */ +export const closePredictionSchema = v.object({ + closedPrice: v.pipe( + v.string(), + v.trim(), + v.nonEmpty('content:validation.price-required'), + v.transform(toPriceNumber), + v.number('content:validation.price-invalid'), + v.check( + (price) => Number.isFinite(price) && price > 0, + 'content:validation.price-invalid', + ), + ), +}); + +/** + * The composer's own fields; images live beside the form. Text is optional when there is an image, + * so «empty» is checked on submit with both in view. The field itself stops at 2000. + */ +export const postComposerSchema = v.object({ + caption: v.pipe( + v.string(), + v.maxLength(2000, 'content:validation.caption-long'), + ), + accessLevel: v.picklist(['free', 'premium']), +}); diff --git a/platforms/market/src/shared/validations/index.ts b/platforms/market/src/shared/validations/index.ts index c1750a9..75b7c62 100644 --- a/platforms/market/src/shared/validations/index.ts +++ b/platforms/market/src/shared/validations/index.ts @@ -7,6 +7,10 @@ export { phoneSchema, usernameSchema, } from './auth-validations'; +export { + closePredictionSchema, + postComposerSchema, +} from './content-validations'; export { AVATAR_IMAGE, ID_CARD_IMAGE, @@ -25,6 +29,9 @@ export { export type { AccountTypeFormOutput, AccountTypeFormValues, + ClosePredictionFormOutput, + ClosePredictionFormValues, + PostComposerFormValues, CodeFormValues, CreatorIdentityFormOutput, CreatorIdentityFormValues, diff --git a/platforms/market/src/shared/validations/types.ts b/platforms/market/src/shared/validations/types.ts index 4460841..0044ed8 100644 --- a/platforms/market/src/shared/validations/types.ts +++ b/platforms/market/src/shared/validations/types.ts @@ -8,6 +8,10 @@ import type { phoneSchema, } from './auth-validations'; import type { SOCIAL_PLATFORMS } from './constants'; +import type { + closePredictionSchema, + postComposerSchema, +} from './content-validations'; import type { creatorProfileSchema, investorProfileSchema, @@ -45,3 +49,11 @@ export type InvestorProfileFormOutput = v.InferOutput< >; export type SocialPlatform = (typeof SOCIAL_PLATFORMS)[number]; + +export type ClosePredictionFormValues = v.InferInput< + typeof closePredictionSchema +>; +export type ClosePredictionFormOutput = v.InferOutput< + typeof closePredictionSchema +>; +export type PostComposerFormValues = v.InferInput; diff --git a/platforms/market/src/stores/post-draft/index.ts b/platforms/market/src/stores/post-draft/index.ts new file mode 100644 index 0000000..1438cfb --- /dev/null +++ b/platforms/market/src/stores/post-draft/index.ts @@ -0,0 +1,2 @@ +export { usePostDraftStore } from './post-draft-store'; +export type { PostDraft, PostDraftImage, PostDraftState } from './types'; diff --git a/platforms/market/src/stores/post-draft/post-draft-store.ts b/platforms/market/src/stores/post-draft/post-draft-store.ts new file mode 100644 index 0000000..a0a034a --- /dev/null +++ b/platforms/market/src/stores/post-draft/post-draft-store.ts @@ -0,0 +1,34 @@ +import { storage } from '@lumina/libs/local-storage'; +import { create } from 'zustand'; +import { createJSONStorage, persist } from 'zustand/middleware'; +import { immer } from 'zustand/middleware/immer'; + +import type { PostDraftState } from './types'; + +/** + * The new post being written, kept in local storage under `session.` so logout removes it. Only + * the creator's own content and file ids, never anything about other people. Rehydrated after + * mount by the AppShell, so the server render and the first browser render match. + */ +export const usePostDraftStore = create()( + persist( + immer((set) => ({ + draft: null, + saveDraft: (draft) => + set((state) => { + state.draft = draft; + }), + clearDraft: () => + set((state) => { + state.draft = null; + }), + })), + { + name: 'session.post-draft', + storage: createJSONStorage(() => storage), + version: 1, + partialize: (state) => ({ draft: state.draft }), + skipHydration: true, + }, + ), +); diff --git a/platforms/market/src/stores/post-draft/types.ts b/platforms/market/src/stores/post-draft/types.ts new file mode 100644 index 0000000..c0b547b --- /dev/null +++ b/platforms/market/src/stores/post-draft/types.ts @@ -0,0 +1,24 @@ +import type { PostAccessLevel } from '../../features/post'; + +/** An image already stored on the server, so a restored draft can publish it as is. */ +export type PostDraftImage = { + fileId: string; + /** The owner-only file address, for the thumbnail. */ + url: string; + name: string; +}; + +/** What the composer holds, kept so a closed or reloaded app gives it back (C4 ۳.۹). */ +export type PostDraft = { + /** A draft belongs to the creator who wrote it; another account never sees it. */ + creatorId: string; + caption: string; + accessLevel: PostAccessLevel; + images: PostDraftImage[]; +}; + +export type PostDraftState = { + draft: PostDraft | null; + saveDraft: (draft: PostDraft) => void; + clearDraft: () => void; +};