From 7aaacf4d505f62b13983033af1d0b8f48d390a93 Mon Sep 17 00:00:00 2001 From: Sinclair Chen Date: Wed, 14 Sep 2022 13:19:12 -0700 Subject: [PATCH 01/42] Center tweets --- web/components/editor/tweet-embed.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/components/editor/tweet-embed.tsx b/web/components/editor/tweet-embed.tsx index 91b2fa65..fb7d7810 100644 --- a/web/components/editor/tweet-embed.tsx +++ b/web/components/editor/tweet-embed.tsx @@ -12,7 +12,7 @@ export default function WrappedTwitterTweetEmbed(props: { const tweetId = props.node.attrs.tweetId.slice(1) return ( - + ) From 68b0539fc1ca5399550b3305742c43fb97c8d229 Mon Sep 17 00:00:00 2001 From: Sinclair Chen Date: Wed, 14 Sep 2022 15:06:11 -0700 Subject: [PATCH 02/42] Enable search exclusion and exact searches like `-musk` to remove Elon results or `"eth"` for Ethereum results --- web/components/contract-search.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/web/components/contract-search.tsx b/web/components/contract-search.tsx index 5bd69057..7f64b26b 100644 --- a/web/components/contract-search.tsx +++ b/web/components/contract-search.tsx @@ -164,6 +164,7 @@ export function ContractSearch(props: { numericFilters, page: requestedPage, hitsPerPage: 20, + advancedSyntax: true, }) // if there's a more recent request, forget about this one if (id === requestId.current) { From 3efd968058176905018cdd0af8beab9894a187fc Mon Sep 17 00:00:00 2001 From: Ian Philips Date: Wed, 14 Sep 2022 17:17:32 -0600 Subject: [PATCH 03/42] Allow one-click unsubscribe, slight refactor --- common/notification.ts | 219 ++++++++---- common/user-notification-preferences.ts | 243 +++++++++++++ common/user.ts | 174 +--------- functions/src/create-notification.ts | 24 +- functions/src/create-user.ts | 9 +- functions/src/email-templates/500-mana.html | 321 ------------------ .../src/email-templates/creating-market.html | 2 +- .../email-templates/interesting-markets.html | 2 +- .../market-answer-comment.html | 2 +- .../src/email-templates/market-answer.html | 2 +- .../src/email-templates/market-close.html | 2 +- .../src/email-templates/market-comment.html | 2 +- .../market-resolved-no-bets.html | 2 +- .../src/email-templates/market-resolved.html | 2 +- .../new-market-from-followed-user.html | 2 +- .../email-templates/new-unique-bettor.html | 2 +- .../email-templates/new-unique-bettors.html | 2 +- functions/src/email-templates/one-week.html | 2 +- functions/src/email-templates/thank-you.html | 2 +- functions/src/email-templates/welcome.html | 2 +- functions/src/emails.ts | 61 ++-- .../create-new-notification-preferences.ts | 4 +- functions/src/scripts/create-private-users.ts | 5 +- functions/src/unsubscribe.ts | 252 +++++++++++--- web/components/notification-settings.tsx | 132 ++++--- 25 files changed, 723 insertions(+), 749 deletions(-) create mode 100644 common/user-notification-preferences.ts delete mode 100644 functions/src/email-templates/500-mana.html diff --git a/common/notification.ts b/common/notification.ts index affa33cb..c34f5b9c 100644 --- a/common/notification.ts +++ b/common/notification.ts @@ -1,5 +1,4 @@ -import { notification_subscription_types, PrivateUser } from './user' -import { DOMAIN } from './envs/constants' +import { notification_preference } from './user-notification-preferences' export type Notification = { id: string @@ -29,6 +28,7 @@ export type Notification = { isSeenOnHref?: string } + export type notification_source_types = | 'contract' | 'comment' @@ -54,7 +54,7 @@ export type notification_source_update_types = | 'deleted' | 'closed' -/* Optional - if possible use a keyof notification_subscription_types */ +/* Optional - if possible use a notification_preference */ export type notification_reason_types = | 'tagged_user' | 'on_new_follow' @@ -92,75 +92,152 @@ export type notification_reason_types = | 'your_contract_closed' | 'subsidized_your_market' -// Adding a new key:value here is optional, you can just use a key of notification_subscription_types -// You might want to add a key:value here if there will be multiple notification reasons that map to the same -// subscription type, i.e. 'comment_on_contract_you_follow' and 'comment_on_contract_with_users_answer' both map to -// 'all_comments_on_watched_markets' subscription type -// TODO: perhaps better would be to map notification_subscription_types to arrays of notification_reason_types -export const notificationReasonToSubscriptionType: Partial< - Record -> = { - you_referred_user: 'referral_bonuses', - user_joined_to_bet_on_your_market: 'referral_bonuses', - tip_received: 'tips_on_your_comments', - bet_fill: 'limit_order_fills', - user_joined_from_your_group_invite: 'referral_bonuses', - challenge_accepted: 'limit_order_fills', - betting_streak_incremented: 'betting_streaks', - liked_and_tipped_your_contract: 'tips_on_your_markets', - comment_on_your_contract: 'all_comments_on_my_markets', - answer_on_your_contract: 'all_answers_on_my_markets', - comment_on_contract_you_follow: 'all_comments_on_watched_markets', - answer_on_contract_you_follow: 'all_answers_on_watched_markets', - update_on_contract_you_follow: 'market_updates_on_watched_markets', - resolution_on_contract_you_follow: 'resolutions_on_watched_markets', - comment_on_contract_with_users_shares_in: - 'all_comments_on_contracts_with_shares_in_on_watched_markets', - answer_on_contract_with_users_shares_in: - 'all_answers_on_contracts_with_shares_in_on_watched_markets', - update_on_contract_with_users_shares_in: - 'market_updates_on_watched_markets_with_shares_in', - resolution_on_contract_with_users_shares_in: - 'resolutions_on_watched_markets_with_shares_in', - comment_on_contract_with_users_answer: 'all_comments_on_watched_markets', - update_on_contract_with_users_answer: 'market_updates_on_watched_markets', - resolution_on_contract_with_users_answer: 'resolutions_on_watched_markets', - answer_on_contract_with_users_answer: 'all_answers_on_watched_markets', - comment_on_contract_with_users_comment: 'all_comments_on_watched_markets', - answer_on_contract_with_users_comment: 'all_answers_on_watched_markets', - update_on_contract_with_users_comment: 'market_updates_on_watched_markets', - resolution_on_contract_with_users_comment: 'resolutions_on_watched_markets', - reply_to_users_answer: 'all_replies_to_my_answers_on_watched_markets', - reply_to_users_comment: 'all_replies_to_my_comments_on_watched_markets', -} - -export const getDestinationsForUser = async ( - privateUser: PrivateUser, - reason: notification_reason_types | keyof notification_subscription_types -) => { - const notificationSettings = privateUser.notificationPreferences - let destinations - let subscriptionType: keyof notification_subscription_types | undefined - if (Object.keys(notificationSettings).includes(reason)) { - subscriptionType = reason as keyof notification_subscription_types - destinations = notificationSettings[subscriptionType] - } else { - const key = reason as notification_reason_types - subscriptionType = notificationReasonToSubscriptionType[key] - destinations = subscriptionType - ? notificationSettings[subscriptionType] - : [] - } - // const unsubscribeEndpoint = getFunctionUrl('unsubscribe') - return { - sendToEmail: destinations.includes('email'), - sendToBrowser: destinations.includes('browser'), - // unsubscribeUrl: `${unsubscribeEndpoint}?id=${privateUser.id}&type=${subscriptionType}`, - urlToManageThisNotification: `${DOMAIN}/notifications?tab=settings§ion=${subscriptionType}`, - } -} - export type BettingStreakData = { streak: number bonusAmount: number } + +type notification_descriptions = { + [key in notification_preference]: { + simple: string + detailed: string + } +} +export const NOTIFICATION_DESCRIPTIONS: notification_descriptions = { + all_answers_on_my_markets: { + simple: 'Answers on your markets', + detailed: 'Answers on your own markets', + }, + all_comments_on_my_markets: { + simple: 'Comments on your markets', + detailed: 'Comments on your own markets', + }, + answers_by_followed_users_on_watched_markets: { + simple: 'Only answers by users you follow', + detailed: "Only answers by users you follow on markets you're watching", + }, + answers_by_market_creator_on_watched_markets: { + simple: 'Only answers by market creator', + detailed: "Only answers by market creator on markets you're watching", + }, + betting_streaks: { + simple: 'For predictions made over consecutive days', + detailed: 'Bonuses for predictions made over consecutive days', + }, + comments_by_followed_users_on_watched_markets: { + simple: 'Only comments by users you follow', + detailed: + 'Only comments by users that you follow on markets that you watch', + }, + contract_from_followed_user: { + simple: 'New markets from users you follow', + detailed: 'New markets from users you follow', + }, + limit_order_fills: { + simple: 'Limit order fills', + detailed: 'When your limit order is filled by another user', + }, + loan_income: { + simple: 'Automatic loans from your predictions in unresolved markets', + detailed: + 'Automatic loans from your predictions that are locked in unresolved markets', + }, + market_updates_on_watched_markets: { + simple: 'All creator updates', + detailed: 'All market updates made by the creator', + }, + market_updates_on_watched_markets_with_shares_in: { + simple: "Only creator updates on markets that you're invested in", + detailed: + "Only updates made by the creator on markets that you're invested in", + }, + on_new_follow: { + simple: 'A user followed you', + detailed: 'A user followed you', + }, + onboarding_flow: { + simple: 'Emails to help you get started using Manifold', + detailed: 'Emails to help you learn how to use Manifold', + }, + probability_updates_on_watched_markets: { + simple: 'Large changes in probability on markets that you watch', + detailed: 'Large changes in probability on markets that you watch', + }, + profit_loss_updates: { + simple: 'Weekly profit and loss updates', + detailed: 'Weekly profit and loss updates', + }, + referral_bonuses: { + simple: 'For referring new users', + detailed: 'Bonuses you receive from referring a new user', + }, + resolutions_on_watched_markets: { + simple: 'All market resolutions', + detailed: "All resolutions on markets that you're watching", + }, + resolutions_on_watched_markets_with_shares_in: { + simple: "Only market resolutions that you're invested in", + detailed: + "Only resolutions of markets you're watching and that you're invested in", + }, + subsidized_your_market: { + simple: 'Your market was subsidized', + detailed: 'When someone subsidizes your market', + }, + tagged_user: { + simple: 'A user tagged you', + detailed: 'When another use tags you', + }, + thank_you_for_purchases: { + simple: 'Thank you notes for your purchases', + detailed: 'Thank you notes for your purchases', + }, + tipped_comments_on_watched_markets: { + simple: 'Only highly tipped comments on markets that you watch', + detailed: 'Only highly tipped comments on markets that you watch', + }, + tips_on_your_comments: { + simple: 'Tips on your comments', + detailed: 'Tips on your comments', + }, + tips_on_your_markets: { + simple: 'Tips/Likes on your markets', + detailed: 'Tips/Likes on your markets', + }, + trending_markets: { + simple: 'Weekly interesting markets', + detailed: 'Weekly interesting markets', + }, + unique_bettors_on_your_contract: { + simple: 'For unique predictors on your markets', + detailed: 'Bonuses for unique predictors on your markets', + }, + your_contract_closed: { + simple: 'Your market has closed and you need to resolve it', + detailed: 'Your market has closed and you need to resolve it', + }, + all_comments_on_watched_markets: { + simple: 'All new comments', + detailed: 'All new comments on markets you follow', + }, + all_comments_on_contracts_with_shares_in_on_watched_markets: { + simple: `Only on markets you're invested in`, + detailed: `Comments on markets that you're watching and you're invested in`, + }, + all_replies_to_my_comments_on_watched_markets: { + simple: 'Only replies to your comments', + detailed: "Only replies to your comments on markets you're watching", + }, + all_replies_to_my_answers_on_watched_markets: { + simple: 'Only replies to your answers', + detailed: "Only replies to your answers on markets you're watching", + }, + all_answers_on_watched_markets: { + simple: 'All new answers', + detailed: "All new answers on markets you're watching", + }, + all_answers_on_contracts_with_shares_in_on_watched_markets: { + simple: `Only on markets you're invested in`, + detailed: `Answers on markets that you're watching and that you're invested in`, + }, +} diff --git a/common/user-notification-preferences.ts b/common/user-notification-preferences.ts new file mode 100644 index 00000000..e2402ea9 --- /dev/null +++ b/common/user-notification-preferences.ts @@ -0,0 +1,243 @@ +import { filterDefined } from './util/array' +import { notification_reason_types } from './notification' +import { getFunctionUrl } from './api' +import { DOMAIN } from './envs/constants' +import { PrivateUser } from './user' + +export type notification_destination_types = 'email' | 'browser' +export type notification_preference = keyof notification_preferences +export type notification_preferences = { + // Watched Markets + all_comments_on_watched_markets: notification_destination_types[] + all_answers_on_watched_markets: notification_destination_types[] + + // Comments + tipped_comments_on_watched_markets: notification_destination_types[] + comments_by_followed_users_on_watched_markets: notification_destination_types[] + all_replies_to_my_comments_on_watched_markets: notification_destination_types[] + all_replies_to_my_answers_on_watched_markets: notification_destination_types[] + all_comments_on_contracts_with_shares_in_on_watched_markets: notification_destination_types[] + + // Answers + answers_by_followed_users_on_watched_markets: notification_destination_types[] + answers_by_market_creator_on_watched_markets: notification_destination_types[] + all_answers_on_contracts_with_shares_in_on_watched_markets: notification_destination_types[] + + // On users' markets + your_contract_closed: notification_destination_types[] + all_comments_on_my_markets: notification_destination_types[] + all_answers_on_my_markets: notification_destination_types[] + subsidized_your_market: notification_destination_types[] + + // Market updates + resolutions_on_watched_markets: notification_destination_types[] + resolutions_on_watched_markets_with_shares_in: notification_destination_types[] + market_updates_on_watched_markets: notification_destination_types[] + market_updates_on_watched_markets_with_shares_in: notification_destination_types[] + probability_updates_on_watched_markets: notification_destination_types[] + + // Balance Changes + loan_income: notification_destination_types[] + betting_streaks: notification_destination_types[] + referral_bonuses: notification_destination_types[] + unique_bettors_on_your_contract: notification_destination_types[] + tips_on_your_comments: notification_destination_types[] + tips_on_your_markets: notification_destination_types[] + limit_order_fills: notification_destination_types[] + + // General + tagged_user: notification_destination_types[] + on_new_follow: notification_destination_types[] + contract_from_followed_user: notification_destination_types[] + trending_markets: notification_destination_types[] + profit_loss_updates: notification_destination_types[] + onboarding_flow: notification_destination_types[] + thank_you_for_purchases: notification_destination_types[] +} + +export const getDefaultNotificationPreferences = ( + userId: string, + privateUser?: PrivateUser, + noEmails?: boolean +) => { + const { + unsubscribedFromCommentEmails, + unsubscribedFromAnswerEmails, + unsubscribedFromResolutionEmails, + unsubscribedFromWeeklyTrendingEmails, + unsubscribedFromGenericEmails, + } = privateUser || {} + + const constructPref = (browserIf: boolean, emailIf: boolean) => { + const browser = browserIf ? 'browser' : undefined + const email = noEmails ? undefined : emailIf ? 'email' : undefined + return filterDefined([browser, email]) as notification_destination_types[] + } + return { + // Watched Markets + all_comments_on_watched_markets: constructPref( + true, + !unsubscribedFromCommentEmails + ), + all_answers_on_watched_markets: constructPref( + true, + !unsubscribedFromAnswerEmails + ), + + // Comments + tips_on_your_comments: constructPref(true, !unsubscribedFromCommentEmails), + comments_by_followed_users_on_watched_markets: constructPref(true, false), + all_replies_to_my_comments_on_watched_markets: constructPref( + true, + !unsubscribedFromCommentEmails + ), + all_replies_to_my_answers_on_watched_markets: constructPref( + true, + !unsubscribedFromCommentEmails + ), + all_comments_on_contracts_with_shares_in_on_watched_markets: constructPref( + true, + !unsubscribedFromCommentEmails + ), + + // Answers + answers_by_followed_users_on_watched_markets: constructPref( + true, + !unsubscribedFromAnswerEmails + ), + answers_by_market_creator_on_watched_markets: constructPref( + true, + !unsubscribedFromAnswerEmails + ), + all_answers_on_contracts_with_shares_in_on_watched_markets: constructPref( + true, + !unsubscribedFromAnswerEmails + ), + + // On users' markets + your_contract_closed: constructPref( + true, + !unsubscribedFromResolutionEmails + ), // High priority + all_comments_on_my_markets: constructPref( + true, + !unsubscribedFromCommentEmails + ), + all_answers_on_my_markets: constructPref( + true, + !unsubscribedFromAnswerEmails + ), + subsidized_your_market: constructPref(true, true), + + // Market updates + resolutions_on_watched_markets: constructPref( + true, + !unsubscribedFromResolutionEmails + ), + market_updates_on_watched_markets: constructPref(true, false), + market_updates_on_watched_markets_with_shares_in: constructPref( + true, + false + ), + resolutions_on_watched_markets_with_shares_in: constructPref( + true, + !unsubscribedFromResolutionEmails + ), + + //Balance Changes + loan_income: constructPref(true, false), + betting_streaks: constructPref(true, false), + referral_bonuses: constructPref(true, true), + unique_bettors_on_your_contract: constructPref(true, false), + tipped_comments_on_watched_markets: constructPref( + true, + !unsubscribedFromCommentEmails + ), + tips_on_your_markets: constructPref(true, true), + limit_order_fills: constructPref(true, false), + + // General + tagged_user: constructPref(true, true), + on_new_follow: constructPref(true, true), + contract_from_followed_user: constructPref(true, true), + trending_markets: constructPref( + false, + !unsubscribedFromWeeklyTrendingEmails + ), + profit_loss_updates: constructPref(false, true), + probability_updates_on_watched_markets: constructPref(true, false), + thank_you_for_purchases: constructPref( + false, + !unsubscribedFromGenericEmails + ), + onboarding_flow: constructPref(false, !unsubscribedFromGenericEmails), + } as notification_preferences +} + +// Adding a new key:value here is optional, you can just use a key of notification_subscription_types +// You might want to add a key:value here if there will be multiple notification reasons that map to the same +// subscription type, i.e. 'comment_on_contract_you_follow' and 'comment_on_contract_with_users_answer' both map to +// 'all_comments_on_watched_markets' subscription type +// TODO: perhaps better would be to map notification_subscription_types to arrays of notification_reason_types +const notificationReasonToSubscriptionType: Partial< + Record +> = { + you_referred_user: 'referral_bonuses', + user_joined_to_bet_on_your_market: 'referral_bonuses', + tip_received: 'tips_on_your_comments', + bet_fill: 'limit_order_fills', + user_joined_from_your_group_invite: 'referral_bonuses', + challenge_accepted: 'limit_order_fills', + betting_streak_incremented: 'betting_streaks', + liked_and_tipped_your_contract: 'tips_on_your_markets', + comment_on_your_contract: 'all_comments_on_my_markets', + answer_on_your_contract: 'all_answers_on_my_markets', + comment_on_contract_you_follow: 'all_comments_on_watched_markets', + answer_on_contract_you_follow: 'all_answers_on_watched_markets', + update_on_contract_you_follow: 'market_updates_on_watched_markets', + resolution_on_contract_you_follow: 'resolutions_on_watched_markets', + comment_on_contract_with_users_shares_in: + 'all_comments_on_contracts_with_shares_in_on_watched_markets', + answer_on_contract_with_users_shares_in: + 'all_answers_on_contracts_with_shares_in_on_watched_markets', + update_on_contract_with_users_shares_in: + 'market_updates_on_watched_markets_with_shares_in', + resolution_on_contract_with_users_shares_in: + 'resolutions_on_watched_markets_with_shares_in', + comment_on_contract_with_users_answer: 'all_comments_on_watched_markets', + update_on_contract_with_users_answer: 'market_updates_on_watched_markets', + resolution_on_contract_with_users_answer: 'resolutions_on_watched_markets', + answer_on_contract_with_users_answer: 'all_answers_on_watched_markets', + comment_on_contract_with_users_comment: 'all_comments_on_watched_markets', + answer_on_contract_with_users_comment: 'all_answers_on_watched_markets', + update_on_contract_with_users_comment: 'market_updates_on_watched_markets', + resolution_on_contract_with_users_comment: 'resolutions_on_watched_markets', + reply_to_users_answer: 'all_replies_to_my_answers_on_watched_markets', + reply_to_users_comment: 'all_replies_to_my_comments_on_watched_markets', +} + +export const getNotificationDestinationsForUser = ( + privateUser: PrivateUser, + reason: notification_reason_types | notification_preference +) => { + const notificationSettings = privateUser.notificationPreferences + let destinations + let subscriptionType: notification_preference | undefined + if (Object.keys(notificationSettings).includes(reason)) { + subscriptionType = reason as notification_preference + destinations = notificationSettings[subscriptionType] + } else { + const key = reason as notification_reason_types + subscriptionType = notificationReasonToSubscriptionType[key] + destinations = subscriptionType + ? notificationSettings[subscriptionType] + : [] + } + const unsubscribeEndpoint = getFunctionUrl('unsubscribe') + return { + sendToEmail: destinations.includes('email'), + sendToBrowser: destinations.includes('browser'), + unsubscribeUrl: `${unsubscribeEndpoint}?id=${privateUser.id}&type=${subscriptionType}`, + urlToManageThisNotification: `${DOMAIN}/notifications?tab=settings§ion=${subscriptionType}`, + } +} diff --git a/common/user.ts b/common/user.ts index 7bd89906..16a2b437 100644 --- a/common/user.ts +++ b/common/user.ts @@ -1,4 +1,4 @@ -import { filterDefined } from './util/array' +import { notification_preferences } from './user-notification-preferences' export type User = { id: string @@ -65,7 +65,7 @@ export type PrivateUser = { initialDeviceToken?: string initialIpAddress?: string apiKey?: string - notificationPreferences: notification_subscription_types + notificationPreferences: notification_preferences twitchInfo?: { twitchName: string controlToken: string @@ -73,57 +73,6 @@ export type PrivateUser = { } } -export type notification_destination_types = 'email' | 'browser' -export type notification_subscription_types = { - // Watched Markets - all_comments_on_watched_markets: notification_destination_types[] - all_answers_on_watched_markets: notification_destination_types[] - - // Comments - tipped_comments_on_watched_markets: notification_destination_types[] - comments_by_followed_users_on_watched_markets: notification_destination_types[] - all_replies_to_my_comments_on_watched_markets: notification_destination_types[] - all_replies_to_my_answers_on_watched_markets: notification_destination_types[] - all_comments_on_contracts_with_shares_in_on_watched_markets: notification_destination_types[] - - // Answers - answers_by_followed_users_on_watched_markets: notification_destination_types[] - answers_by_market_creator_on_watched_markets: notification_destination_types[] - all_answers_on_contracts_with_shares_in_on_watched_markets: notification_destination_types[] - - // On users' markets - your_contract_closed: notification_destination_types[] - all_comments_on_my_markets: notification_destination_types[] - all_answers_on_my_markets: notification_destination_types[] - subsidized_your_market: notification_destination_types[] - - // Market updates - resolutions_on_watched_markets: notification_destination_types[] - resolutions_on_watched_markets_with_shares_in: notification_destination_types[] - market_updates_on_watched_markets: notification_destination_types[] - market_updates_on_watched_markets_with_shares_in: notification_destination_types[] - probability_updates_on_watched_markets: notification_destination_types[] - - // Balance Changes - loan_income: notification_destination_types[] - betting_streaks: notification_destination_types[] - referral_bonuses: notification_destination_types[] - unique_bettors_on_your_contract: notification_destination_types[] - tips_on_your_comments: notification_destination_types[] - tips_on_your_markets: notification_destination_types[] - limit_order_fills: notification_destination_types[] - - // General - tagged_user: notification_destination_types[] - on_new_follow: notification_destination_types[] - contract_from_followed_user: notification_destination_types[] - trending_markets: notification_destination_types[] - profit_loss_updates: notification_destination_types[] - onboarding_flow: notification_destination_types[] - thank_you_for_purchases: notification_destination_types[] -} -export type notification_subscribe_types = 'all' | 'less' | 'none' - export type PortfolioMetrics = { investmentValue: number balance: number @@ -134,122 +83,3 @@ export type PortfolioMetrics = { export const MANIFOLD_USERNAME = 'ManifoldMarkets' export const MANIFOLD_AVATAR_URL = 'https://manifold.markets/logo-bg-white.png' - -export const getDefaultNotificationSettings = ( - userId: string, - privateUser?: PrivateUser, - noEmails?: boolean -) => { - const { - unsubscribedFromCommentEmails, - unsubscribedFromAnswerEmails, - unsubscribedFromResolutionEmails, - unsubscribedFromWeeklyTrendingEmails, - unsubscribedFromGenericEmails, - } = privateUser || {} - - const constructPref = (browserIf: boolean, emailIf: boolean) => { - const browser = browserIf ? 'browser' : undefined - const email = noEmails ? undefined : emailIf ? 'email' : undefined - return filterDefined([browser, email]) as notification_destination_types[] - } - return { - // Watched Markets - all_comments_on_watched_markets: constructPref( - true, - !unsubscribedFromCommentEmails - ), - all_answers_on_watched_markets: constructPref( - true, - !unsubscribedFromAnswerEmails - ), - - // Comments - tips_on_your_comments: constructPref(true, !unsubscribedFromCommentEmails), - comments_by_followed_users_on_watched_markets: constructPref(true, false), - all_replies_to_my_comments_on_watched_markets: constructPref( - true, - !unsubscribedFromCommentEmails - ), - all_replies_to_my_answers_on_watched_markets: constructPref( - true, - !unsubscribedFromCommentEmails - ), - all_comments_on_contracts_with_shares_in_on_watched_markets: constructPref( - true, - !unsubscribedFromCommentEmails - ), - - // Answers - answers_by_followed_users_on_watched_markets: constructPref( - true, - !unsubscribedFromAnswerEmails - ), - answers_by_market_creator_on_watched_markets: constructPref( - true, - !unsubscribedFromAnswerEmails - ), - all_answers_on_contracts_with_shares_in_on_watched_markets: constructPref( - true, - !unsubscribedFromAnswerEmails - ), - - // On users' markets - your_contract_closed: constructPref( - true, - !unsubscribedFromResolutionEmails - ), // High priority - all_comments_on_my_markets: constructPref( - true, - !unsubscribedFromCommentEmails - ), - all_answers_on_my_markets: constructPref( - true, - !unsubscribedFromAnswerEmails - ), - subsidized_your_market: constructPref(true, true), - - // Market updates - resolutions_on_watched_markets: constructPref( - true, - !unsubscribedFromResolutionEmails - ), - market_updates_on_watched_markets: constructPref(true, false), - market_updates_on_watched_markets_with_shares_in: constructPref( - true, - false - ), - resolutions_on_watched_markets_with_shares_in: constructPref( - true, - !unsubscribedFromResolutionEmails - ), - - //Balance Changes - loan_income: constructPref(true, false), - betting_streaks: constructPref(true, false), - referral_bonuses: constructPref(true, true), - unique_bettors_on_your_contract: constructPref(true, false), - tipped_comments_on_watched_markets: constructPref( - true, - !unsubscribedFromCommentEmails - ), - tips_on_your_markets: constructPref(true, true), - limit_order_fills: constructPref(true, false), - - // General - tagged_user: constructPref(true, true), - on_new_follow: constructPref(true, true), - contract_from_followed_user: constructPref(true, true), - trending_markets: constructPref( - false, - !unsubscribedFromWeeklyTrendingEmails - ), - profit_loss_updates: constructPref(false, true), - probability_updates_on_watched_markets: constructPref(true, false), - thank_you_for_purchases: constructPref( - false, - !unsubscribedFromGenericEmails - ), - onboarding_flow: constructPref(false, !unsubscribedFromGenericEmails), - } as notification_subscription_types -} diff --git a/functions/src/create-notification.ts b/functions/src/create-notification.ts index 34a8f218..ba9fa5c4 100644 --- a/functions/src/create-notification.ts +++ b/functions/src/create-notification.ts @@ -1,7 +1,6 @@ import * as admin from 'firebase-admin' import { BettingStreakData, - getDestinationsForUser, Notification, notification_reason_types, } from '../../common/notification' @@ -27,6 +26,7 @@ import { sendNewUniqueBettorsEmail, } from './emails' import { filterDefined } from '../../common/util/array' +import { getNotificationDestinationsForUser } from '../../common/user-notification-preferences' const firestore = admin.firestore() type recipients_to_reason_texts = { @@ -66,7 +66,7 @@ export const createNotification = async ( const { reason } = userToReasonTexts[userId] const privateUser = await getPrivateUser(userId) if (!privateUser) continue - const { sendToBrowser, sendToEmail } = await getDestinationsForUser( + const { sendToBrowser, sendToEmail } = getNotificationDestinationsForUser( privateUser, reason ) @@ -236,7 +236,7 @@ export const createCommentOrAnswerOrUpdatedContractNotification = async ( return const privateUser = await getPrivateUser(userId) if (!privateUser) return - const { sendToBrowser, sendToEmail } = await getDestinationsForUser( + const { sendToBrowser, sendToEmail } = getNotificationDestinationsForUser( privateUser, reason ) @@ -468,7 +468,7 @@ export const createTipNotification = async ( ) => { const privateUser = await getPrivateUser(toUser.id) if (!privateUser) return - const { sendToBrowser } = await getDestinationsForUser( + const { sendToBrowser } = getNotificationDestinationsForUser( privateUser, 'tip_received' ) @@ -513,7 +513,7 @@ export const createBetFillNotification = async ( ) => { const privateUser = await getPrivateUser(toUser.id) if (!privateUser) return - const { sendToBrowser } = await getDestinationsForUser( + const { sendToBrowser } = getNotificationDestinationsForUser( privateUser, 'bet_fill' ) @@ -558,7 +558,7 @@ export const createReferralNotification = async ( ) => { const privateUser = await getPrivateUser(toUser.id) if (!privateUser) return - const { sendToBrowser } = await getDestinationsForUser( + const { sendToBrowser } = getNotificationDestinationsForUser( privateUser, 'you_referred_user' ) @@ -612,7 +612,7 @@ export const createLoanIncomeNotification = async ( ) => { const privateUser = await getPrivateUser(toUser.id) if (!privateUser) return - const { sendToBrowser } = await getDestinationsForUser( + const { sendToBrowser } = getNotificationDestinationsForUser( privateUser, 'loan_income' ) @@ -650,7 +650,7 @@ export const createChallengeAcceptedNotification = async ( ) => { const privateUser = await getPrivateUser(challengeCreator.id) if (!privateUser) return - const { sendToBrowser } = await getDestinationsForUser( + const { sendToBrowser } = getNotificationDestinationsForUser( privateUser, 'challenge_accepted' ) @@ -692,7 +692,7 @@ export const createBettingStreakBonusNotification = async ( ) => { const privateUser = await getPrivateUser(user.id) if (!privateUser) return - const { sendToBrowser } = await getDestinationsForUser( + const { sendToBrowser } = getNotificationDestinationsForUser( privateUser, 'betting_streak_incremented' ) @@ -739,7 +739,7 @@ export const createLikeNotification = async ( ) => { const privateUser = await getPrivateUser(toUser.id) if (!privateUser) return - const { sendToBrowser } = await getDestinationsForUser( + const { sendToBrowser } = getNotificationDestinationsForUser( privateUser, 'liked_and_tipped_your_contract' ) @@ -786,7 +786,7 @@ export const createUniqueBettorBonusNotification = async ( ) => { const privateUser = await getPrivateUser(contractCreatorId) if (!privateUser) return - const { sendToBrowser, sendToEmail } = await getDestinationsForUser( + const { sendToBrowser, sendToEmail } = getNotificationDestinationsForUser( privateUser, 'unique_bettors_on_your_contract' ) @@ -876,7 +876,7 @@ export const createNewContractNotification = async ( ) => { const privateUser = await getPrivateUser(userId) if (!privateUser) return - const { sendToBrowser, sendToEmail } = await getDestinationsForUser( + const { sendToBrowser, sendToEmail } = getNotificationDestinationsForUser( privateUser, reason ) diff --git a/functions/src/create-user.ts b/functions/src/create-user.ts index ab5f014a..ab70b4e6 100644 --- a/functions/src/create-user.ts +++ b/functions/src/create-user.ts @@ -1,11 +1,7 @@ import * as admin from 'firebase-admin' import { z } from 'zod' -import { - getDefaultNotificationSettings, - PrivateUser, - User, -} from '../../common/user' +import { PrivateUser, User } from '../../common/user' import { getUser, getUserByUsername, getValues } from './utils' import { randomString } from '../../common/util/random' import { @@ -22,6 +18,7 @@ import { track } from './analytics' import { APIError, newEndpoint, validate } from './api' import { Group } from '../../common/group' import { SUS_STARTING_BALANCE, STARTING_BALANCE } from '../../common/economy' +import { getDefaultNotificationPreferences } from '../../common/user-notification-preferences' const bodySchema = z.object({ deviceToken: z.string().optional(), @@ -83,7 +80,7 @@ export const createuser = newEndpoint(opts, async (req, auth) => { email, initialIpAddress: req.ip, initialDeviceToken: deviceToken, - notificationPreferences: getDefaultNotificationSettings(auth.uid), + notificationPreferences: getDefaultNotificationPreferences(auth.uid), } await firestore.collection('private-users').doc(auth.uid).create(privateUser) diff --git a/functions/src/email-templates/500-mana.html b/functions/src/email-templates/500-mana.html deleted file mode 100644 index c8f6a171..00000000 --- a/functions/src/email-templates/500-mana.html +++ /dev/null @@ -1,321 +0,0 @@ - - - - - Manifold Markets 7th Day Anniversary Gift! - - - - - - - - - - - - - - - -
- -
- - - - - - -
- -
- - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - - -
-
-
-

- Hi {{name}},

-
-
-
-

Thanks for - using Manifold Markets. Running low - on mana (M$)? Click the link below to receive a one time gift of M$500!

-
-
-

-
- - - - -
- - - - -
- - Claim M$500 - -
-
-
-
-

Did - you know, besides making correct predictions, there are - plenty of other ways to earn mana?

- -

 

-

Cheers, -

-

David - from Manifold

-

 

-
-
-
-

- -

 

-

Cheers,

-

David from Manifold

-

 

-
-
-
- -
-
- -
- - - -
- -
- - - - diff --git a/functions/src/email-templates/interesting-markets.html b/functions/src/email-templates/interesting-markets.html index 7c3e653d..0cee6269 100644 --- a/functions/src/email-templates/interesting-markets.html +++ b/functions/src/email-templates/interesting-markets.html @@ -443,7 +443,7 @@ click here to manage your notifications. + " target="_blank">click here to unsubscribe from this type of notification.

diff --git a/functions/src/email-templates/market-answer-comment.html b/functions/src/email-templates/market-answer-comment.html index a19aa7c3..4b98730f 100644 --- a/functions/src/email-templates/market-answer-comment.html +++ b/functions/src/email-templates/market-answer-comment.html @@ -529,7 +529,7 @@ click here to manage your notifications. + " target="_blank">click here to unsubscribe from this type of notification.
- - - -
-
- - - - - -
- -
- - - - - - -
- - - - - - - - - -
-
-

This e-mail has been sent to {{name}}, - click here to manage your notifications. -

-
-
-
-
-
-
-
- -
- - - - - - \ No newline at end of file diff --git a/functions/src/email-templates/creating-market.html b/functions/src/email-templates/creating-market.html index c73f7458..bf163f69 100644 --- a/functions/src/email-templates/creating-market.html +++ b/functions/src/email-templates/creating-market.html @@ -494,7 +494,7 @@ click here to manage your notifications. + " target="_blank">click here to unsubscribe from this type of notification.

diff --git a/functions/src/email-templates/market-answer.html b/functions/src/email-templates/market-answer.html index b2d7f727..e3d42b9d 100644 --- a/functions/src/email-templates/market-answer.html +++ b/functions/src/email-templates/market-answer.html @@ -369,7 +369,7 @@ click here to manage your notifications. + " target="_blank">click here to unsubscribe from this type of notification.
diff --git a/functions/src/email-templates/market-close.html b/functions/src/email-templates/market-close.html index ee7976b0..4abd225e 100644 --- a/functions/src/email-templates/market-close.html +++ b/functions/src/email-templates/market-close.html @@ -487,7 +487,7 @@ click here to manage your notifications. + " target="_blank">click here to unsubscribe from this type of notification. diff --git a/functions/src/email-templates/market-comment.html b/functions/src/email-templates/market-comment.html index 23e20dac..ce0669f1 100644 --- a/functions/src/email-templates/market-comment.html +++ b/functions/src/email-templates/market-comment.html @@ -369,7 +369,7 @@ click here to manage your notifications. + " target="_blank">click here to unsubscribe from this type of notification. diff --git a/functions/src/email-templates/market-resolved-no-bets.html b/functions/src/email-templates/market-resolved-no-bets.html index ff5f541f..5d886adf 100644 --- a/functions/src/email-templates/market-resolved-no-bets.html +++ b/functions/src/email-templates/market-resolved-no-bets.html @@ -470,7 +470,7 @@ click here to manage your notifications. + " target="_blank">click here to unsubscribe from this type of notification. diff --git a/functions/src/email-templates/market-resolved.html b/functions/src/email-templates/market-resolved.html index de29a0f1..767202b6 100644 --- a/functions/src/email-templates/market-resolved.html +++ b/functions/src/email-templates/market-resolved.html @@ -502,7 +502,7 @@ click here to manage your notifications. + " target="_blank">click here to unsubscribe from this type of notification. diff --git a/functions/src/email-templates/new-market-from-followed-user.html b/functions/src/email-templates/new-market-from-followed-user.html index 877d554f..49633fb2 100644 --- a/functions/src/email-templates/new-market-from-followed-user.html +++ b/functions/src/email-templates/new-market-from-followed-user.html @@ -318,7 +318,7 @@ click here to manage your notifications. + " target="_blank">click here to unsubscribe from this type of notification.

diff --git a/functions/src/email-templates/new-unique-bettor.html b/functions/src/email-templates/new-unique-bettor.html index 30da8b99..51026121 100644 --- a/functions/src/email-templates/new-unique-bettor.html +++ b/functions/src/email-templates/new-unique-bettor.html @@ -376,7 +376,7 @@ click here to manage your notifications. + " target="_blank">click here to unsubscribe from this type of notification. diff --git a/functions/src/email-templates/new-unique-bettors.html b/functions/src/email-templates/new-unique-bettors.html index eb4c04e2..09c44d03 100644 --- a/functions/src/email-templates/new-unique-bettors.html +++ b/functions/src/email-templates/new-unique-bettors.html @@ -480,7 +480,7 @@ click here to manage your notifications. + " target="_blank">click here to unsubscribe from this type of notification. diff --git a/functions/src/email-templates/one-week.html b/functions/src/email-templates/one-week.html index b8e233d5..e7d14a7e 100644 --- a/functions/src/email-templates/one-week.html +++ b/functions/src/email-templates/one-week.html @@ -283,7 +283,7 @@ click here to manage your notifications. + " target="_blank">click here to unsubscribe from this type of notification.

diff --git a/functions/src/email-templates/thank-you.html b/functions/src/email-templates/thank-you.html index 7ac72d0a..beef11ee 100644 --- a/functions/src/email-templates/thank-you.html +++ b/functions/src/email-templates/thank-you.html @@ -218,7 +218,7 @@ click here to manage your notifications. + " target="_blank">click here to unsubscribe from this type of notification.

diff --git a/functions/src/email-templates/welcome.html b/functions/src/email-templates/welcome.html index dccec695..d6caaa0c 100644 --- a/functions/src/email-templates/welcome.html +++ b/functions/src/email-templates/welcome.html @@ -290,7 +290,7 @@ click here to manage your notifications. + " target="_blank">click here to unsubscribe from this type of notification.

diff --git a/functions/src/emails.ts b/functions/src/emails.ts index bb9f7195..98309ebe 100644 --- a/functions/src/emails.ts +++ b/functions/src/emails.ts @@ -2,11 +2,7 @@ import { DOMAIN } from '../../common/envs/constants' import { Bet } from '../../common/bet' import { getProbability } from '../../common/calculate' import { Contract } from '../../common/contract' -import { - notification_subscription_types, - PrivateUser, - User, -} from '../../common/user' +import { PrivateUser, User } from '../../common/user' import { formatLargeNumber, formatMoney, @@ -18,11 +14,12 @@ import { formatNumericProbability } from '../../common/pseudo-numeric' import { sendTemplateEmail, sendTextEmail } from './send-email' import { getUser } from './utils' import { buildCardUrl, getOpenGraphProps } from '../../common/contract-details' -import { - notification_reason_types, - getDestinationsForUser, -} from '../../common/notification' +import { notification_reason_types } from '../../common/notification' import { Dictionary } from 'lodash' +import { + getNotificationDestinationsForUser, + notification_preference, +} from '../../common/user-notification-preferences' export const sendMarketResolutionEmail = async ( reason: notification_reason_types, @@ -36,8 +33,10 @@ export const sendMarketResolutionEmail = async ( resolutionProbability?: number, resolutions?: { [outcome: string]: number } ) => { - const { sendToEmail, urlToManageThisNotification: unsubscribeUrl } = - await getDestinationsForUser(privateUser, reason) + const { sendToEmail, unsubscribeUrl } = getNotificationDestinationsForUser( + privateUser, + reason + ) if (!privateUser || !privateUser.email || !sendToEmail) return const user = await getUser(privateUser.id) @@ -154,7 +153,7 @@ export const sendWelcomeEmail = async ( const firstName = name.split(' ')[0] const unsubscribeUrl = `${DOMAIN}/notifications?tab=settings§ion=${ - 'onboarding_flow' as keyof notification_subscription_types + 'onboarding_flow' as notification_preference }` return await sendTemplateEmail( @@ -222,7 +221,7 @@ export const sendOneWeekBonusEmail = async ( const firstName = name.split(' ')[0] const unsubscribeUrl = `${DOMAIN}/notifications?tab=settings§ion=${ - 'onboarding_flow' as keyof notification_subscription_types + 'onboarding_flow' as notification_preference }` return await sendTemplateEmail( privateUser.email, @@ -255,7 +254,7 @@ export const sendCreatorGuideEmail = async ( const firstName = name.split(' ')[0] const unsubscribeUrl = `${DOMAIN}/notifications?tab=settings§ion=${ - 'onboarding_flow' as keyof notification_subscription_types + 'onboarding_flow' as notification_preference }` return await sendTemplateEmail( privateUser.email, @@ -289,7 +288,7 @@ export const sendThankYouEmail = async ( const firstName = name.split(' ')[0] const unsubscribeUrl = `${DOMAIN}/notifications?tab=settings§ion=${ - 'thank_you_for_purchases' as keyof notification_subscription_types + 'thank_you_for_purchases' as notification_preference }` return await sendTemplateEmail( @@ -312,8 +311,10 @@ export const sendMarketCloseEmail = async ( privateUser: PrivateUser, contract: Contract ) => { - const { sendToEmail, urlToManageThisNotification: unsubscribeUrl } = - await getDestinationsForUser(privateUser, reason) + const { sendToEmail, unsubscribeUrl } = getNotificationDestinationsForUser( + privateUser, + reason + ) if (!privateUser.email || !sendToEmail) return @@ -350,8 +351,10 @@ export const sendNewCommentEmail = async ( answerText?: string, answerId?: string ) => { - const { sendToEmail, urlToManageThisNotification: unsubscribeUrl } = - await getDestinationsForUser(privateUser, reason) + const { sendToEmail, unsubscribeUrl } = getNotificationDestinationsForUser( + privateUser, + reason + ) if (!privateUser || !privateUser.email || !sendToEmail) return const { question } = contract @@ -425,8 +428,10 @@ export const sendNewAnswerEmail = async ( // Don't send the creator's own answers. if (privateUser.id === creatorId) return - const { sendToEmail, urlToManageThisNotification: unsubscribeUrl } = - await getDestinationsForUser(privateUser, reason) + const { sendToEmail, unsubscribeUrl } = getNotificationDestinationsForUser( + privateUser, + reason + ) if (!privateUser.email || !sendToEmail) return const { question, creatorUsername, slug } = contract @@ -465,7 +470,7 @@ export const sendInterestingMarketsEmail = async ( return const unsubscribeUrl = `${DOMAIN}/notifications?tab=settings§ion=${ - 'trending_markets' as keyof notification_subscription_types + 'trending_markets' as notification_preference }` const { name } = user @@ -516,8 +521,10 @@ export const sendNewFollowedMarketEmail = async ( privateUser: PrivateUser, contract: Contract ) => { - const { sendToEmail, urlToManageThisNotification: unsubscribeUrl } = - await getDestinationsForUser(privateUser, reason) + const { sendToEmail, unsubscribeUrl } = getNotificationDestinationsForUser( + privateUser, + reason + ) if (!privateUser.email || !sendToEmail) return const user = await getUser(privateUser.id) if (!user) return @@ -553,8 +560,10 @@ export const sendNewUniqueBettorsEmail = async ( userBets: Dictionary<[Bet, ...Bet[]]>, bonusAmount: number ) => { - const { sendToEmail, urlToManageThisNotification: unsubscribeUrl } = - await getDestinationsForUser(privateUser, reason) + const { sendToEmail, unsubscribeUrl } = getNotificationDestinationsForUser( + privateUser, + reason + ) if (!privateUser.email || !sendToEmail) return const user = await getUser(privateUser.id) if (!user) return diff --git a/functions/src/scripts/create-new-notification-preferences.ts b/functions/src/scripts/create-new-notification-preferences.ts index 2796f2f7..4ba2e25e 100644 --- a/functions/src/scripts/create-new-notification-preferences.ts +++ b/functions/src/scripts/create-new-notification-preferences.ts @@ -1,8 +1,8 @@ import * as admin from 'firebase-admin' import { initAdmin } from './script-init' -import { getDefaultNotificationSettings } from 'common/user' import { getAllPrivateUsers, isProd } from 'functions/src/utils' +import { getDefaultNotificationPreferences } from 'common/user-notification-preferences' initAdmin() const firestore = admin.firestore() @@ -17,7 +17,7 @@ async function main() { .collection('private-users') .doc(privateUser.id) .update({ - notificationPreferences: getDefaultNotificationSettings( + notificationPreferences: getDefaultNotificationPreferences( privateUser.id, privateUser, disableEmails diff --git a/functions/src/scripts/create-private-users.ts b/functions/src/scripts/create-private-users.ts index 21e117cf..762e801a 100644 --- a/functions/src/scripts/create-private-users.ts +++ b/functions/src/scripts/create-private-users.ts @@ -3,8 +3,9 @@ import * as admin from 'firebase-admin' import { initAdmin } from './script-init' initAdmin() -import { getDefaultNotificationSettings, PrivateUser, User } from 'common/user' +import { PrivateUser, User } from 'common/user' import { STARTING_BALANCE } from 'common/economy' +import { getDefaultNotificationPreferences } from 'common/user-notification-preferences' const firestore = admin.firestore() @@ -21,7 +22,7 @@ async function main() { id: user.id, email, username, - notificationPreferences: getDefaultNotificationSettings(user.id), + notificationPreferences: getDefaultNotificationPreferences(user.id), } if (user.totalDeposits === undefined) { diff --git a/functions/src/unsubscribe.ts b/functions/src/unsubscribe.ts index da7b507f..418282c7 100644 --- a/functions/src/unsubscribe.ts +++ b/functions/src/unsubscribe.ts @@ -1,79 +1,227 @@ import * as admin from 'firebase-admin' import { EndpointDefinition } from './api' -import { getUser } from './utils' +import { getPrivateUser } from './utils' import { PrivateUser } from '../../common/user' +import { NOTIFICATION_DESCRIPTIONS } from '../../common/notification' +import { notification_preference } from '../../common/user-notification-preferences' export const unsubscribe: EndpointDefinition = { opts: { method: 'GET', minInstances: 1 }, handler: async (req, res) => { const id = req.query.id as string - let type = req.query.type as string + const type = req.query.type as string if (!id || !type) { - res.status(400).send('Empty id or type parameter.') + res.status(400).send('Empty id or subscription type parameter.') + return + } + console.log(`Unsubscribing ${id} from ${type}`) + const notificationSubscriptionType = type as notification_preference + if (notificationSubscriptionType === undefined) { + res.status(400).send('Invalid subscription type parameter.') return } - if (type === 'market-resolved') type = 'market-resolve' - - if ( - ![ - 'market-resolve', - 'market-comment', - 'market-answer', - 'generic', - 'weekly-trending', - ].includes(type) - ) { - res.status(400).send('Invalid type parameter.') - return - } - - const user = await getUser(id) + const user = await getPrivateUser(id) if (!user) { res.send('This user is not currently subscribed or does not exist.') return } - const { name } = user + const previousDestinations = + user.notificationPreferences[notificationSubscriptionType] + + console.log(previousDestinations) + const { email } = user const update: Partial = { - ...(type === 'market-resolve' && { - unsubscribedFromResolutionEmails: true, - }), - ...(type === 'market-comment' && { - unsubscribedFromCommentEmails: true, - }), - ...(type === 'market-answer' && { - unsubscribedFromAnswerEmails: true, - }), - ...(type === 'generic' && { - unsubscribedFromGenericEmails: true, - }), - ...(type === 'weekly-trending' && { - unsubscribedFromWeeklyTrendingEmails: true, - }), + notificationPreferences: { + ...user.notificationPreferences, + [notificationSubscriptionType]: previousDestinations.filter( + (destination) => destination !== 'email' + ), + }, } await firestore.collection('private-users').doc(id).update(update) - if (type === 'market-resolve') - res.send( - `${name}, you have been unsubscribed from market resolution emails on Manifold Markets.` - ) - else if (type === 'market-comment') - res.send( - `${name}, you have been unsubscribed from market comment emails on Manifold Markets.` - ) - else if (type === 'market-answer') - res.send( - `${name}, you have been unsubscribed from market answer emails on Manifold Markets.` - ) - else if (type === 'weekly-trending') - res.send( - `${name}, you have been unsubscribed from weekly trending emails on Manifold Markets.` - ) - else res.send(`${name}, you have been unsubscribed.`) + res.send( + ` + + + + + Manifold Markets 7th Day Anniversary Gift! + + + + + + + + + + + + + + +
+ +
+ + + + + + +
+ +
+ + + + + + + + + + + + + + + +
+ + banner logo + +
+
+

+ Hello!

+
+
+
+

+ + ${email} has been unsubscribed from email notifications related to: + +
+
+ + ${NOTIFICATION_DESCRIPTIONS[notificationSubscriptionType].detailed}. +

+
+
+
+ Click + here + to manage the rest of your notification settings. + +
+ +
+

+
+
+
+
+
+ + +` + ) }, } diff --git a/web/components/notification-settings.tsx b/web/components/notification-settings.tsx index d18896bd..8730ce7f 100644 --- a/web/components/notification-settings.tsx +++ b/web/components/notification-settings.tsx @@ -1,11 +1,7 @@ import React, { memo, ReactNode, useEffect, useState } from 'react' import { Row } from 'web/components/layout/row' import clsx from 'clsx' -import { - notification_subscription_types, - notification_destination_types, - PrivateUser, -} from 'common/user' +import { PrivateUser } from 'common/user' import { updatePrivateUser } from 'web/lib/firebase/users' import { Col } from 'web/components/layout/col' import { @@ -30,6 +26,11 @@ import { usePersistentState, } from 'web/hooks/use-persistent-state' import { safeLocalStorage } from 'web/lib/util/local' +import { NOTIFICATION_DESCRIPTIONS } from 'common/notification' +import { + notification_destination_types, + notification_preference, +} from 'common/user-notification-preferences' export function NotificationSettings(props: { navigateToSection: string | undefined @@ -38,7 +39,7 @@ export function NotificationSettings(props: { const { navigateToSection, privateUser } = props const [showWatchModal, setShowWatchModal] = useState(false) - const emailsEnabled: Array = [ + const emailsEnabled: Array = [ 'all_comments_on_watched_markets', 'all_replies_to_my_comments_on_watched_markets', 'all_comments_on_contracts_with_shares_in_on_watched_markets', @@ -74,7 +75,7 @@ export function NotificationSettings(props: { // 'probability_updates_on_watched_markets', // 'limit_order_fills', ] - const browserDisabled: Array = [ + const browserDisabled: Array = [ 'trending_markets', 'profit_loss_updates', 'onboarding_flow', @@ -83,91 +84,82 @@ export function NotificationSettings(props: { type SectionData = { label: string - subscriptionTypeToDescription: { - [key in keyof Partial]: string - } + subscriptionTypes: Partial[] } const comments: SectionData = { label: 'New Comments', - subscriptionTypeToDescription: { - all_comments_on_watched_markets: 'All new comments', - all_comments_on_contracts_with_shares_in_on_watched_markets: `Only on markets you're invested in`, + subscriptionTypes: [ + 'all_comments_on_watched_markets', + 'all_comments_on_contracts_with_shares_in_on_watched_markets', // TODO: combine these two - all_replies_to_my_comments_on_watched_markets: - 'Only replies to your comments', - all_replies_to_my_answers_on_watched_markets: - 'Only replies to your answers', - // comments_by_followed_users_on_watched_markets: 'By followed users', - }, + 'all_replies_to_my_comments_on_watched_markets', + 'all_replies_to_my_answers_on_watched_markets', + ], } const answers: SectionData = { label: 'New Answers', - subscriptionTypeToDescription: { - all_answers_on_watched_markets: 'All new answers', - all_answers_on_contracts_with_shares_in_on_watched_markets: `Only on markets you're invested in`, - // answers_by_followed_users_on_watched_markets: 'By followed users', - // answers_by_market_creator_on_watched_markets: 'By market creator', - }, + subscriptionTypes: [ + 'all_answers_on_watched_markets', + 'all_answers_on_contracts_with_shares_in_on_watched_markets', + ], } const updates: SectionData = { label: 'Updates & Resolutions', - subscriptionTypeToDescription: { - market_updates_on_watched_markets: 'All creator updates', - market_updates_on_watched_markets_with_shares_in: `Only creator updates on markets you're invested in`, - resolutions_on_watched_markets: 'All market resolutions', - resolutions_on_watched_markets_with_shares_in: `Only market resolutions you're invested in`, - // probability_updates_on_watched_markets: 'Probability updates', - }, + subscriptionTypes: [ + 'market_updates_on_watched_markets', + 'market_updates_on_watched_markets_with_shares_in', + 'resolutions_on_watched_markets', + 'resolutions_on_watched_markets_with_shares_in', + ], } const yourMarkets: SectionData = { label: 'Markets You Created', - subscriptionTypeToDescription: { - your_contract_closed: 'Your market has closed (and needs resolution)', - all_comments_on_my_markets: 'Comments on your markets', - all_answers_on_my_markets: 'Answers on your markets', - subsidized_your_market: 'Your market was subsidized', - tips_on_your_markets: 'Likes on your markets', - }, + subscriptionTypes: [ + 'your_contract_closed', + 'all_comments_on_my_markets', + 'all_answers_on_my_markets', + 'subsidized_your_market', + 'tips_on_your_markets', + ], } const bonuses: SectionData = { label: 'Bonuses', - subscriptionTypeToDescription: { - betting_streaks: 'Prediction streak bonuses', - referral_bonuses: 'Referral bonuses from referring users', - unique_bettors_on_your_contract: 'Unique bettor bonuses on your markets', - }, + subscriptionTypes: [ + 'betting_streaks', + 'referral_bonuses', + 'unique_bettors_on_your_contract', + ], } const otherBalances: SectionData = { label: 'Other', - subscriptionTypeToDescription: { - loan_income: 'Automatic loans from your profitable bets', - limit_order_fills: 'Limit order fills', - tips_on_your_comments: 'Tips on your comments', - }, + subscriptionTypes: [ + 'loan_income', + 'limit_order_fills', + 'tips_on_your_comments', + ], } const userInteractions: SectionData = { label: 'Users', - subscriptionTypeToDescription: { - tagged_user: 'A user tagged you', - on_new_follow: 'Someone followed you', - contract_from_followed_user: 'New markets created by users you follow', - }, + subscriptionTypes: [ + 'tagged_user', + 'on_new_follow', + 'contract_from_followed_user', + ], } const generalOther: SectionData = { label: 'Other', - subscriptionTypeToDescription: { - trending_markets: 'Weekly interesting markets', - thank_you_for_purchases: 'Thank you notes for your purchases', - onboarding_flow: 'Explanatory emails to help you get started', - // profit_loss_updates: 'Weekly profit/loss updates', - }, + subscriptionTypes: [ + 'trending_markets', + 'thank_you_for_purchases', + 'onboarding_flow', + ], } function NotificationSettingLine(props: { description: string - subscriptionTypeKey: keyof notification_subscription_types + subscriptionTypeKey: notification_preference destinations: notification_destination_types[] }) { const { description, subscriptionTypeKey, destinations } = props @@ -237,9 +229,7 @@ export function NotificationSettings(props: { ) } - const getUsersSavedPreference = ( - key: keyof notification_subscription_types - ) => { + const getUsersSavedPreference = (key: notification_preference) => { return privateUser.notificationPreferences[key] ?? [] } @@ -248,17 +238,17 @@ export function NotificationSettings(props: { data: SectionData }) { const { icon, data } = props - const { label, subscriptionTypeToDescription } = data + const { label, subscriptionTypes } = data const expand = navigateToSection && - Object.keys(subscriptionTypeToDescription).includes(navigateToSection) + Object.keys(subscriptionTypes).includes(navigateToSection) // Not sure how to prevent re-render (and collapse of an open section) // due to a private user settings change. Just going to persist expanded state here const [expanded, setExpanded] = usePersistentState(expand ?? false, { key: 'NotificationsSettingsSection-' + - Object.keys(subscriptionTypeToDescription).join('-'), + Object.keys(subscriptionTypes).join('-'), store: storageStore(safeLocalStorage()), }) @@ -287,13 +277,13 @@ export function NotificationSettings(props: { )} - {Object.entries(subscriptionTypeToDescription).map(([key, value]) => ( + {subscriptionTypes.map((subType) => ( ))} From 9aa56dd19300e084361d14cc606ac690aa434f7d Mon Sep 17 00:00:00 2001 From: Ian Philips Date: Wed, 14 Sep 2022 17:25:17 -0600 Subject: [PATCH 04/42] Only show prev opened notif setting section --- web/components/notification-settings.tsx | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/web/components/notification-settings.tsx b/web/components/notification-settings.tsx index 8730ce7f..b806dfb2 100644 --- a/web/components/notification-settings.tsx +++ b/web/components/notification-settings.tsx @@ -241,14 +241,12 @@ export function NotificationSettings(props: { const { label, subscriptionTypes } = data const expand = navigateToSection && - Object.keys(subscriptionTypes).includes(navigateToSection) + subscriptionTypes.includes(navigateToSection as notification_preference) // Not sure how to prevent re-render (and collapse of an open section) // due to a private user settings change. Just going to persist expanded state here const [expanded, setExpanded] = usePersistentState(expand ?? false, { - key: - 'NotificationsSettingsSection-' + - Object.keys(subscriptionTypes).join('-'), + key: 'NotificationsSettingsSection-' + subscriptionTypes.join('-'), store: storageStore(safeLocalStorage()), }) From ccf02bdba8f565e94fbb01fb9ac5cb7c9de93fc2 Mon Sep 17 00:00:00 2001 From: ingawei <46611122+ingawei@users.noreply.github.com> Date: Wed, 14 Sep 2022 22:28:40 -0500 Subject: [PATCH 05/42] Inga/admin rules resolve (#880) * Giving admin permission to resolve all markets that have closed after 7 days. --- common/envs/constants.ts | 5 ++- common/envs/prod.ts | 1 + firestore.rules | 3 +- functions/src/resolve-market.ts | 9 ++++-- .../answers/answer-resolve-panel.tsx | 20 ++++++++++-- web/components/answers/answers-panel.tsx | 28 ++++++++++------- web/components/numeric-resolution-panel.tsx | 20 +++++++++--- web/components/resolution-panel.tsx | 11 +++++-- web/pages/[username]/[contractSlug].tsx | 31 +++++++++++++++---- 9 files changed, 99 insertions(+), 29 deletions(-) diff --git a/common/envs/constants.ts b/common/envs/constants.ts index ba460d58..0502322a 100644 --- a/common/envs/constants.ts +++ b/common/envs/constants.ts @@ -21,7 +21,10 @@ export function isWhitelisted(email?: string) { } // TODO: Before open sourcing, we should turn these into env vars -export function isAdmin(email: string) { +export function isAdmin(email?: string) { + if (!email) { + return false + } return ENV_CONFIG.adminEmails.includes(email) } diff --git a/common/envs/prod.ts b/common/envs/prod.ts index b3b552eb..6bf781b7 100644 --- a/common/envs/prod.ts +++ b/common/envs/prod.ts @@ -74,6 +74,7 @@ export const PROD_CONFIG: EnvConfig = { 'iansphilips@gmail.com', // Ian 'd4vidchee@gmail.com', // D4vid 'federicoruizcassarino@gmail.com', // Fede + 'ingawei@gmail.com', //Inga ], visibility: 'PUBLIC', diff --git a/firestore.rules b/firestore.rules index 6f2ea90a..08214b10 100644 --- a/firestore.rules +++ b/firestore.rules @@ -14,7 +14,8 @@ service cloud.firestore { 'manticmarkets@gmail.com', 'iansphilips@gmail.com', 'd4vidchee@gmail.com', - 'federicoruizcassarino@gmail.com' + 'federicoruizcassarino@gmail.com', + 'ingawei@gmail.com' ] } diff --git a/functions/src/resolve-market.ts b/functions/src/resolve-market.ts index b867b609..44293898 100644 --- a/functions/src/resolve-market.ts +++ b/functions/src/resolve-market.ts @@ -16,7 +16,7 @@ import { groupPayoutsByUser, Payout, } from '../../common/payouts' -import { isManifoldId } from '../../common/envs/constants' +import { isAdmin, isManifoldId } from '../../common/envs/constants' import { removeUndefinedProps } from '../../common/util/object' import { LiquidityProvision } from '../../common/liquidity-provision' import { APIError, newEndpoint, validate } from './api' @@ -76,13 +76,18 @@ export const resolvemarket = newEndpoint(opts, async (req, auth) => { throw new APIError(404, 'No contract exists with the provided ID') const contract = contractSnap.data() as Contract const { creatorId, closeTime } = contract + const firebaseUser = await admin.auth().getUser(auth.uid) const { value, resolutions, probabilityInt, outcome } = getResolutionParams( contract, req.body ) - if (creatorId !== auth.uid && !isManifoldId(auth.uid)) + if ( + creatorId !== auth.uid && + !isManifoldId(auth.uid) && + !isAdmin(firebaseUser.email) + ) throw new APIError(403, 'User is not creator of contract') if (contract.resolution) throw new APIError(400, 'Contract already resolved') diff --git a/web/components/answers/answer-resolve-panel.tsx b/web/components/answers/answer-resolve-panel.tsx index 0a4ac1e1..4594ea35 100644 --- a/web/components/answers/answer-resolve-panel.tsx +++ b/web/components/answers/answer-resolve-panel.tsx @@ -11,6 +11,8 @@ import { ResolveConfirmationButton } from '../confirmation-button' import { removeUndefinedProps } from 'common/util/object' export function AnswerResolvePanel(props: { + isAdmin: boolean + isCreator: boolean contract: FreeResponseContract | MultipleChoiceContract resolveOption: 'CHOOSE' | 'CHOOSE_MULTIPLE' | 'CANCEL' | undefined setResolveOption: ( @@ -18,7 +20,14 @@ export function AnswerResolvePanel(props: { ) => void chosenAnswers: { [answerId: string]: number } }) { - const { contract, resolveOption, setResolveOption, chosenAnswers } = props + const { + contract, + resolveOption, + setResolveOption, + chosenAnswers, + isAdmin, + isCreator, + } = props const answers = Object.keys(chosenAnswers) const [isSubmitting, setIsSubmitting] = useState(false) @@ -76,7 +85,14 @@ export function AnswerResolvePanel(props: { return ( -
Resolve your market
+ +
Resolve your market
+ {isAdmin && !isCreator && ( + + ADMIN + + )} +
)} - {user?.id === creatorId && !resolution && ( - <> - - - - )} + {(user?.id === creatorId || (isAdmin && needsAdminToResolve(contract))) && + !resolution && ( + <> + + + + )} ) } diff --git a/web/components/numeric-resolution-panel.tsx b/web/components/numeric-resolution-panel.tsx index dce36ab9..70fbf01f 100644 --- a/web/components/numeric-resolution-panel.tsx +++ b/web/components/numeric-resolution-panel.tsx @@ -12,11 +12,13 @@ import { BucketInput } from './bucket-input' import { getPseudoProbability } from 'common/pseudo-numeric' export function NumericResolutionPanel(props: { + isAdmin: boolean + isCreator: boolean creator: User contract: NumericContract | PseudoNumericContract className?: string }) { - const { contract, className } = props + const { contract, className, isAdmin, isCreator } = props const { min, max, outcomeType } = contract const [outcomeMode, setOutcomeMode] = useState< @@ -78,10 +80,20 @@ export function NumericResolutionPanel(props: { : 'btn-disabled' return ( - -
Resolve market
+ + {isAdmin && !isCreator && ( + + ADMIN + + )} +
Resolve market
-
Outcome
+
Outcome
diff --git a/web/components/resolution-panel.tsx b/web/components/resolution-panel.tsx index 5a7b993e..6f36331e 100644 --- a/web/components/resolution-panel.tsx +++ b/web/components/resolution-panel.tsx @@ -12,11 +12,13 @@ import { getProbability } from 'common/calculate' import { BinaryContract, resolution } from 'common/contract' export function ResolutionPanel(props: { + isAdmin: boolean + isCreator: boolean creator: User contract: BinaryContract className?: string }) { - const { contract, className } = props + const { contract, className, isAdmin, isCreator } = props // const earnedFees = // contract.mechanism === 'dpm-2' @@ -66,7 +68,12 @@ export function ResolutionPanel(props: { : 'btn-disabled' return ( - + + {isAdmin && !isCreator && ( + + ADMIN + + )}
Resolve market
Outcome
diff --git a/web/pages/[username]/[contractSlug].tsx b/web/pages/[username]/[contractSlug].tsx index de0c7807..2c011c90 100644 --- a/web/pages/[username]/[contractSlug].tsx +++ b/web/pages/[username]/[contractSlug].tsx @@ -45,6 +45,8 @@ import { import { ContractsGrid } from 'web/components/contract/contracts-grid' import { Title } from 'web/components/title' import { usePrefetch } from 'web/hooks/use-prefetch' +import { useAdmin } from 'web/hooks/use-admin' +import dayjs from 'dayjs' export const getStaticProps = fromPropz(getStaticPropz) export async function getStaticPropz(props: { @@ -110,19 +112,28 @@ export default function ContractPage(props: { ) } +// requires an admin to resolve a week after market closes +export function needsAdminToResolve(contract: Contract) { + return !contract.isResolved && dayjs().diff(contract.closeTime, 'day') > 7 +} + export function ContractPageSidebar(props: { user: User | null | undefined contract: Contract }) { const { contract, user } = props const { creatorId, isResolved, outcomeType } = contract - const isCreator = user?.id === creatorId const isBinary = outcomeType === 'BINARY' const isPseudoNumeric = outcomeType === 'PSEUDO_NUMERIC' const isNumeric = outcomeType === 'NUMERIC' const allowTrade = tradingAllowed(contract) - const allowResolve = !isResolved && isCreator && !!user + const isAdmin = useAdmin() + const allowResolve = + !isResolved && + (isCreator || (needsAdminToResolve(contract) && isAdmin)) && + !!user + const hasSidePanel = (isBinary || isNumeric || isPseudoNumeric) && (allowTrade || allowResolve) @@ -139,9 +150,19 @@ export function ContractPageSidebar(props: { ))} {allowResolve && (isNumeric || isPseudoNumeric ? ( - + ) : ( - + ))} ) : null @@ -154,10 +175,8 @@ export function ContractPageContent( } ) { const { backToHome, comments, user } = props - const contract = useContractWithPreload(props.contract) ?? props.contract usePrefetch(user?.id) - useTracking( 'view market', { From 8aaaf5e9e05e138d4ec8dbf436ebf594d9fa0792 Mon Sep 17 00:00:00 2001 From: ingawei <46611122+ingawei@users.noreply.github.com> Date: Thu, 15 Sep 2022 01:46:58 -0500 Subject: [PATCH 06/42] Inga/bettingfix (#879) * making betting action panels much more minimal, particularly for mobile * added tiny follow button --- web/components/button.tsx | 5 +- web/components/contract/contract-details.tsx | 252 ++++++++++-------- .../contract/contract-info-dialog.tsx | 11 +- web/components/contract/contract-overview.tsx | 12 +- .../contract/extra-contract-actions-row.tsx | 57 +--- .../contract/like-market-button.tsx | 20 +- web/components/follow-button.tsx | 67 ++++- web/components/follow-market-button.tsx | 16 +- web/pages/[username]/[contractSlug].tsx | 2 - web/tailwind.config.js | 2 + 10 files changed, 262 insertions(+), 182 deletions(-) diff --git a/web/components/button.tsx b/web/components/button.tsx index cb39cba8..ea9a3e88 100644 --- a/web/components/button.tsx +++ b/web/components/button.tsx @@ -11,6 +11,7 @@ export type ColorType = | 'gray' | 'gradient' | 'gray-white' + | 'highlight-blue' export function Button(props: { className?: string @@ -56,7 +57,9 @@ export function Button(props: { color === 'gradient' && 'border-none bg-gradient-to-r from-indigo-500 to-blue-500 text-white hover:from-indigo-700 hover:to-blue-700', color === 'gray-white' && - 'border-none bg-white text-gray-500 shadow-none hover:bg-gray-200', + 'text-greyscale-6 hover:bg-greyscale-2 border-none shadow-none', + color === 'highlight-blue' && + 'text-highlight-blue border-none shadow-none', className )} disabled={disabled} diff --git a/web/components/contract/contract-details.tsx b/web/components/contract/contract-details.tsx index e28ab41a..fad62c86 100644 --- a/web/components/contract/contract-details.tsx +++ b/web/components/contract/contract-details.tsx @@ -1,9 +1,4 @@ -import { - ClockIcon, - DatabaseIcon, - PencilIcon, - UserGroupIcon, -} from '@heroicons/react/outline' +import { ClockIcon } from '@heroicons/react/outline' import clsx from 'clsx' import { Editor } from '@tiptap/react' import dayjs from 'dayjs' @@ -16,9 +11,8 @@ import { DateTimeTooltip } from '../datetime-tooltip' import { fromNow } from 'web/lib/util/time' import { Avatar } from '../avatar' import { useState } from 'react' -import { ContractInfoDialog } from './contract-info-dialog' import NewContractBadge from '../new-contract-badge' -import { UserFollowButton } from '../follow-button' +import { MiniUserFollowButton } from '../follow-button' import { DAY_MS } from 'common/util/time' import { useUser } from 'web/hooks/use-user' import { exhibitExts } from 'common/util/parse' @@ -34,6 +28,8 @@ import { UserLink } from 'web/components/user-link' import { FeaturedContractBadge } from 'web/components/contract/featured-contract-badge' import { Tooltip } from 'web/components/tooltip' import { useWindowSize } from 'web/hooks/use-window-size' +import { ExtraContractActionsRow } from './extra-contract-actions-row' +import { PlusCircleIcon } from '@heroicons/react/solid' export type ShowTime = 'resolve-date' | 'close-date' @@ -104,90 +100,174 @@ export function AvatarDetails(props: { ) } +export function useIsMobile() { + const { width } = useWindowSize() + return (width ?? 0) < 600 +} + export function ContractDetails(props: { contract: Contract disabled?: boolean }) { const { contract, disabled } = props - const { - closeTime, - creatorName, - creatorUsername, - creatorId, - creatorAvatarUrl, - resolutionTime, - } = contract - const { volumeLabel, resolvedDate } = contractMetrics(contract) + const { creatorName, creatorUsername, creatorId, creatorAvatarUrl } = contract + const { resolvedDate } = contractMetrics(contract) const user = useUser() const isCreator = user?.id === creatorId + const isMobile = useIsMobile() + + return ( + + + + {!disabled && ( +
+ +
+ )} + + + {disabled ? ( + creatorName + ) : ( + + )} + + + + {!isMobile && ( + + )} + + +
+ +
+
+ {/* GROUPS */} + {isMobile && ( +
+ +
+ )} + + ) +} + +export function CloseOrResolveTime(props: { + contract: Contract + resolvedDate: any + isCreator: boolean +}) { + const { contract, resolvedDate, isCreator } = props + const { resolutionTime, closeTime } = contract + console.log(closeTime, resolvedDate) + if (!!closeTime || !!resolvedDate) { + return ( + + {resolvedDate && resolutionTime ? ( + <> + + +
resolved 
+ {resolvedDate} +
+
+ + ) : null} + + {!resolvedDate && closeTime && ( + + {dayjs().isBefore(closeTime) &&
closes 
} + {!dayjs().isBefore(closeTime) &&
closed 
} + +
+ )} +
+ ) + } else return <> +} + +export function MarketGroups(props: { + contract: Contract + isMobile: boolean | undefined + disabled: boolean | undefined +}) { const [open, setOpen] = useState(false) - const { width } = useWindowSize() - const isMobile = (width ?? 0) < 600 + const user = useUser() + const { contract, isMobile, disabled } = props const groupToDisplay = getGroupLinkToDisplay(contract) const groupInfo = groupToDisplay ? ( - - {groupToDisplay.name} +
+ {groupToDisplay.name} +
) : ( - - ) - - return ( - - - - {disabled ? ( - creatorName - ) : ( - +
} - - + > + No Group +
+
+ ) + return ( + <> + {disabled ? ( - groupInfo - ) : !groupToDisplay && !user ? ( -
+ { groupInfo } ) : ( {groupInfo} - {user && groupToDisplay && ( - + + )} )} @@ -201,45 +281,7 @@ export function ContractDetails(props: { - - {(!!closeTime || !!resolvedDate) && ( - - {resolvedDate && resolutionTime ? ( - <> - - - {resolvedDate} - - - ) : null} - - {!resolvedDate && closeTime && user && ( - <> - - - - )} - - )} - {user && ( - <> - - -
{volumeLabel}
-
- {!disabled && ( - - )} - - )} - + ) } @@ -280,12 +322,12 @@ export function ExtraMobileContractDetails(props: { !resolvedDate && closeTime && ( + Closes  - Ends ) )} diff --git a/web/components/contract/contract-info-dialog.tsx b/web/components/contract/contract-info-dialog.tsx index ae586725..07958378 100644 --- a/web/components/contract/contract-info-dialog.tsx +++ b/web/components/contract/contract-info-dialog.tsx @@ -18,6 +18,7 @@ import { deleteField } from 'firebase/firestore' import ShortToggle from '../widgets/short-toggle' import { DuplicateContractButton } from '../copy-contract-button' import { Row } from '../layout/row' +import { Button } from '../button' export const contractDetailsButtonClassName = 'group flex items-center rounded-md px-3 py-2 text-sm font-medium cursor-pointer hover:bg-gray-100 text-gray-400 hover:text-gray-500' @@ -67,19 +68,21 @@ export function ContractInfoDialog(props: { return ( <> - + - + <Title className="!mt-0 !mb-0" text="This Market" /> <table className="table-compact table-zebra table w-full text-gray-500"> <tbody> diff --git a/web/components/contract/contract-overview.tsx b/web/components/contract/contract-overview.tsx index 1bfe84de..bfb4829f 100644 --- a/web/components/contract/contract-overview.tsx +++ b/web/components/contract/contract-overview.tsx @@ -25,11 +25,11 @@ import { NumericContract, PseudoNumericContract, } from 'common/contract' -import { ContractDetails, ExtraMobileContractDetails } from './contract-details' +import { ContractDetails } from './contract-details' import { NumericGraph } from './numeric-graph' const OverviewQuestion = (props: { text: string }) => ( - <Linkify className="text-2xl text-indigo-700 md:text-3xl" text={props.text} /> + <Linkify className="text-lg text-indigo-700 sm:text-2xl" text={props.text} /> ) const BetWidget = (props: { contract: CPMMContract }) => { @@ -73,7 +73,7 @@ const BinaryOverview = (props: { contract: BinaryContract; bets: Bet[] }) => { const { contract, bets } = props return ( <Col className="gap-1 md:gap-2"> - <Col className="gap-3 px-2 sm:gap-4"> + <Col className="gap-1 px-2"> <ContractDetails contract={contract} /> <Row className="justify-between gap-4"> <OverviewQuestion text={contract.question} /> @@ -85,7 +85,6 @@ const BinaryOverview = (props: { contract: BinaryContract; bets: Bet[] }) => { </Row> <Row className="items-center justify-between gap-4 xl:hidden"> <BinaryResolutionOrChance contract={contract} /> - <ExtraMobileContractDetails contract={contract} /> {tradingAllowed(contract) && ( <BetWidget contract={contract as CPMMBinaryContract} /> )} @@ -113,10 +112,6 @@ const ChoiceOverview = (props: { </Col> <Col className={'mb-1 gap-y-2'}> <AnswersGraph contract={contract} bets={[...bets].reverse()} /> - <ExtraMobileContractDetails - contract={contract} - forceShowVolume={true} - /> </Col> </Col> ) @@ -140,7 +135,6 @@ const PseudoNumericOverview = (props: { </Row> <Row className="items-center justify-between gap-4 xl:hidden"> <PseudoNumericResolutionOrExpectation contract={contract} /> - <ExtraMobileContractDetails contract={contract} /> {tradingAllowed(contract) && <BetWidget contract={contract} />} </Row> </Col> diff --git a/web/components/contract/extra-contract-actions-row.tsx b/web/components/contract/extra-contract-actions-row.tsx index 5d5ee4d8..af5db9c3 100644 --- a/web/components/contract/extra-contract-actions-row.tsx +++ b/web/components/contract/extra-contract-actions-row.tsx @@ -11,38 +11,29 @@ import { FollowMarketButton } from 'web/components/follow-market-button' import { LikeMarketButton } from 'web/components/contract/like-market-button' import { ContractInfoDialog } from 'web/components/contract/contract-info-dialog' import { Col } from 'web/components/layout/col' -import { withTracking } from 'web/lib/service/analytics' -import { CreateChallengeModal } from 'web/components/challenges/create-challenge-modal' -import { CHALLENGES_ENABLED } from 'common/challenge' -import ChallengeIcon from 'web/lib/icons/challenge-icon' export function ExtraContractActionsRow(props: { contract: Contract }) { const { contract } = props - const { outcomeType, resolution } = contract const user = useUser() const [isShareOpen, setShareOpen] = useState(false) - const [openCreateChallengeModal, setOpenCreateChallengeModal] = - useState(false) - const showChallenge = - user && outcomeType === 'BINARY' && !resolution && CHALLENGES_ENABLED return ( - <Row className={'mt-0.5 justify-around sm:mt-2 lg:justify-start'}> + <Row> + <FollowMarketButton contract={contract} user={user} /> + {user?.id !== contract.creatorId && ( + <LikeMarketButton contract={contract} user={user} /> + )} <Button - size="lg" + size="sm" color="gray-white" className={'flex'} onClick={() => { setShareOpen(true) }} > - <Col className={'items-center sm:flex-row'}> - <ShareIcon - className={clsx('h-[24px] w-5 sm:mr-2')} - aria-hidden="true" - /> - <span>Share</span> - </Col> + <Row> + <ShareIcon className={clsx('h-5 w-5')} aria-hidden="true" /> + </Row> <ShareModal isOpen={isShareOpen} setOpen={setShareOpen} @@ -50,35 +41,7 @@ export function ExtraContractActionsRow(props: { contract: Contract }) { user={user} /> </Button> - - {showChallenge && ( - <Button - size="lg" - color="gray-white" - className="max-w-xs self-center" - onClick={withTracking( - () => setOpenCreateChallengeModal(true), - 'click challenge button' - )} - > - <Col className="items-center sm:flex-row"> - <ChallengeIcon className="mx-auto h-[24px] w-5 text-gray-500 sm:mr-2" /> - <span>Challenge</span> - </Col> - <CreateChallengeModal - isOpen={openCreateChallengeModal} - setOpen={setOpenCreateChallengeModal} - user={user} - contract={contract} - /> - </Button> - )} - - <FollowMarketButton contract={contract} user={user} /> - {user?.id !== contract.creatorId && ( - <LikeMarketButton contract={contract} user={user} /> - )} - <Col className={'justify-center md:hidden'}> + <Col className={'justify-center'}> <ContractInfoDialog contract={contract} /> </Col> </Row> diff --git a/web/components/contract/like-market-button.tsx b/web/components/contract/like-market-button.tsx index e35e3e7e..01dce32f 100644 --- a/web/components/contract/like-market-button.tsx +++ b/web/components/contract/like-market-button.tsx @@ -38,15 +38,16 @@ export function LikeMarketButton(props: { return ( <Button - size={'lg'} + size={'sm'} className={'max-w-xs self-center'} color={'gray-white'} onClick={onLike} > - <Col className={'items-center sm:flex-row'}> + <Col className={'relative items-center sm:flex-row'}> <HeartIcon className={clsx( - 'h-[24px] w-5 sm:mr-2', + 'h-5 w-5 sm:h-6 sm:w-6', + totalTipped > 0 ? 'mr-2' : '', user && (userLikedContractIds?.includes(contract.id) || (!likes && contract.likedByUserIds?.includes(user.id))) @@ -54,7 +55,18 @@ export function LikeMarketButton(props: { : '' )} /> - Tip {totalTipped > 0 ? `(${formatMoney(totalTipped)})` : ''} + {totalTipped > 0 && ( + <div + className={clsx( + 'bg-greyscale-6 absolute ml-3.5 mt-2 h-4 w-4 rounded-full align-middle text-white sm:mt-3 sm:h-5 sm:w-5 sm:px-1', + totalTipped > 99 + ? 'text-[0.4rem] sm:text-[0.5rem]' + : 'sm:text-2xs text-[0.5rem]' + )} + > + {totalTipped} + </div> + )} </Col> </Button> ) diff --git a/web/components/follow-button.tsx b/web/components/follow-button.tsx index 09495169..6344757d 100644 --- a/web/components/follow-button.tsx +++ b/web/components/follow-button.tsx @@ -1,4 +1,6 @@ +import { CheckCircleIcon, PlusCircleIcon } from '@heroicons/react/solid' import clsx from 'clsx' +import { useEffect, useRef, useState } from 'react' import { useFollows } from 'web/hooks/use-follows' import { useUser } from 'web/hooks/use-user' import { follow, unfollow } from 'web/lib/firebase/users' @@ -54,18 +56,73 @@ export function FollowButton(props: { export function UserFollowButton(props: { userId: string; small?: boolean }) { const { userId, small } = props - const currentUser = useUser() - const following = useFollows(currentUser?.id) + const user = useUser() + const following = useFollows(user?.id) const isFollowing = following?.includes(userId) - if (!currentUser || currentUser.id === userId) return null + if (!user || user.id === userId) return null return ( <FollowButton isFollowing={isFollowing} - onFollow={() => follow(currentUser.id, userId)} - onUnfollow={() => unfollow(currentUser.id, userId)} + onFollow={() => follow(user.id, userId)} + onUnfollow={() => unfollow(user.id, userId)} small={small} /> ) } + +export function MiniUserFollowButton(props: { userId: string }) { + const { userId } = props + const user = useUser() + const following = useFollows(user?.id) + const isFollowing = following?.includes(userId) + const isFirstRender = useRef(true) + const [justFollowed, setJustFollowed] = useState(false) + + useEffect(() => { + if (isFirstRender.current) { + if (isFollowing != undefined) { + isFirstRender.current = false + } + return + } + if (isFollowing) { + setJustFollowed(true) + setTimeout(() => { + setJustFollowed(false) + }, 1000) + } + }, [isFollowing]) + + if (justFollowed) { + return ( + <CheckCircleIcon + className={clsx( + 'text-highlight-blue ml-3 mt-2 h-5 w-5 rounded-full bg-white sm:mr-2' + )} + aria-hidden="true" + /> + ) + } + if ( + !user || + user.id === userId || + isFollowing || + !user || + isFollowing === undefined + ) + return null + return ( + <> + <button onClick={withTracking(() => follow(user.id, userId), 'follow')}> + <PlusCircleIcon + className={clsx( + 'text-highlight-blue hover:text-hover-blue mt-2 ml-3 h-5 w-5 rounded-full bg-white sm:mr-2' + )} + aria-hidden="true" + /> + </button> + </> + ) +} diff --git a/web/components/follow-market-button.tsx b/web/components/follow-market-button.tsx index 1dd261cb..0e65165b 100644 --- a/web/components/follow-market-button.tsx +++ b/web/components/follow-market-button.tsx @@ -25,7 +25,7 @@ export const FollowMarketButton = (props: { return ( <Button - size={'lg'} + size={'sm'} color={'gray-white'} onClick={async () => { if (!user) return firebaseLogin() @@ -56,13 +56,19 @@ export const FollowMarketButton = (props: { > {followers?.includes(user?.id ?? 'nope') ? ( <Col className={'items-center gap-x-2 sm:flex-row'}> - <EyeOffIcon className={clsx('h-6 w-6')} aria-hidden="true" /> - Unwatch + <EyeOffIcon + className={clsx('h-5 w-5 sm:h-6 sm:w-6')} + aria-hidden="true" + /> + {/* Unwatch */} </Col> ) : ( <Col className={'items-center gap-x-2 sm:flex-row'}> - <EyeIcon className={clsx('h-6 w-6')} aria-hidden="true" /> - Watch + <EyeIcon + className={clsx('h-5 w-5 sm:h-6 sm:w-6')} + aria-hidden="true" + /> + {/* Watch */} </Col> )} <WatchMarketModal diff --git a/web/pages/[username]/[contractSlug].tsx b/web/pages/[username]/[contractSlug].tsx index 2c011c90..a0b2ed50 100644 --- a/web/pages/[username]/[contractSlug].tsx +++ b/web/pages/[username]/[contractSlug].tsx @@ -37,7 +37,6 @@ import { User } from 'common/user' import { ContractComment } from 'common/comment' import { getOpenGraphProps } from 'common/contract-details' import { ContractDescription } from 'web/components/contract/contract-description' -import { ExtraContractActionsRow } from 'web/components/contract/extra-contract-actions-row' import { ContractLeaderboard, ContractTopTrades, @@ -257,7 +256,6 @@ export function ContractPageContent( )} <ContractOverview contract={contract} bets={nonChallengeBets} /> - <ExtraContractActionsRow contract={contract} /> <ContractDescription className="mb-6 px-2" contract={contract} /> {outcomeType === 'NUMERIC' && ( diff --git a/web/tailwind.config.js b/web/tailwind.config.js index eb411216..7bea3ec2 100644 --- a/web/tailwind.config.js +++ b/web/tailwind.config.js @@ -26,6 +26,8 @@ module.exports = { 'greyscale-5': '#9191A7', 'greyscale-6': '#66667C', 'greyscale-7': '#111140', + 'highlight-blue': '#5BCEFF', + 'hover-blue': '#90DEFF', }, typography: { quoteless: { From 176acf959fe9fe092dfd84fb446062bf916e5734 Mon Sep 17 00:00:00 2001 From: Pico2x <pico2x@gmail.com> Date: Thu, 15 Sep 2022 13:55:57 +0100 Subject: [PATCH 07/42] Revert "Inga/bettingfix (#879)" This reverts commit 8aaaf5e9e05e138d4ec8dbf436ebf594d9fa0792. --- web/components/button.tsx | 5 +- web/components/contract/contract-details.tsx | 250 ++++++++---------- .../contract/contract-info-dialog.tsx | 11 +- web/components/contract/contract-overview.tsx | 12 +- .../contract/extra-contract-actions-row.tsx | 57 +++- .../contract/like-market-button.tsx | 20 +- web/components/follow-button.tsx | 67 +---- web/components/follow-market-button.tsx | 16 +- web/pages/[username]/[contractSlug].tsx | 2 + web/tailwind.config.js | 2 - 10 files changed, 181 insertions(+), 261 deletions(-) diff --git a/web/components/button.tsx b/web/components/button.tsx index ea9a3e88..cb39cba8 100644 --- a/web/components/button.tsx +++ b/web/components/button.tsx @@ -11,7 +11,6 @@ export type ColorType = | 'gray' | 'gradient' | 'gray-white' - | 'highlight-blue' export function Button(props: { className?: string @@ -57,9 +56,7 @@ export function Button(props: { color === 'gradient' && 'border-none bg-gradient-to-r from-indigo-500 to-blue-500 text-white hover:from-indigo-700 hover:to-blue-700', color === 'gray-white' && - 'text-greyscale-6 hover:bg-greyscale-2 border-none shadow-none', - color === 'highlight-blue' && - 'text-highlight-blue border-none shadow-none', + 'border-none bg-white text-gray-500 shadow-none hover:bg-gray-200', className )} disabled={disabled} diff --git a/web/components/contract/contract-details.tsx b/web/components/contract/contract-details.tsx index fad62c86..e28ab41a 100644 --- a/web/components/contract/contract-details.tsx +++ b/web/components/contract/contract-details.tsx @@ -1,4 +1,9 @@ -import { ClockIcon } from '@heroicons/react/outline' +import { + ClockIcon, + DatabaseIcon, + PencilIcon, + UserGroupIcon, +} from '@heroicons/react/outline' import clsx from 'clsx' import { Editor } from '@tiptap/react' import dayjs from 'dayjs' @@ -11,8 +16,9 @@ import { DateTimeTooltip } from '../datetime-tooltip' import { fromNow } from 'web/lib/util/time' import { Avatar } from '../avatar' import { useState } from 'react' +import { ContractInfoDialog } from './contract-info-dialog' import NewContractBadge from '../new-contract-badge' -import { MiniUserFollowButton } from '../follow-button' +import { UserFollowButton } from '../follow-button' import { DAY_MS } from 'common/util/time' import { useUser } from 'web/hooks/use-user' import { exhibitExts } from 'common/util/parse' @@ -28,8 +34,6 @@ import { UserLink } from 'web/components/user-link' import { FeaturedContractBadge } from 'web/components/contract/featured-contract-badge' import { Tooltip } from 'web/components/tooltip' import { useWindowSize } from 'web/hooks/use-window-size' -import { ExtraContractActionsRow } from './extra-contract-actions-row' -import { PlusCircleIcon } from '@heroicons/react/solid' export type ShowTime = 'resolve-date' | 'close-date' @@ -100,174 +104,90 @@ export function AvatarDetails(props: { ) } -export function useIsMobile() { - const { width } = useWindowSize() - return (width ?? 0) < 600 -} - export function ContractDetails(props: { contract: Contract disabled?: boolean }) { const { contract, disabled } = props - const { creatorName, creatorUsername, creatorId, creatorAvatarUrl } = contract - const { resolvedDate } = contractMetrics(contract) + const { + closeTime, + creatorName, + creatorUsername, + creatorId, + creatorAvatarUrl, + resolutionTime, + } = contract + const { volumeLabel, resolvedDate } = contractMetrics(contract) const user = useUser() const isCreator = user?.id === creatorId - const isMobile = useIsMobile() - - return ( - <Col> - <Row> - <Avatar - username={creatorUsername} - avatarUrl={creatorAvatarUrl} - noLink={disabled} - size={9} - className="mr-1.5" - /> - {!disabled && ( - <div className="absolute mt-3 ml-[11px]"> - <MiniUserFollowButton userId={creatorId} /> - </div> - )} - <Col className="text-greyscale-6 ml-2 flex-1 flex-wrap text-sm"> - <Row className="w-full justify-between "> - {disabled ? ( - creatorName - ) : ( - <UserLink - className="my-auto whitespace-nowrap" - name={creatorName} - username={creatorUsername} - short={isMobile} - /> - )} - </Row> - <Row className="text-2xs text-greyscale-4 gap-2 sm:text-xs"> - <CloseOrResolveTime - contract={contract} - resolvedDate={resolvedDate} - isCreator={isCreator} - /> - {!isMobile && ( - <MarketGroups - contract={contract} - isMobile={isMobile} - disabled={disabled} - /> - )} - </Row> - </Col> - <div className="mt-0"> - <ExtraContractActionsRow contract={contract} /> - </div> - </Row> - {/* GROUPS */} - {isMobile && ( - <div className="mt-2"> - <MarketGroups - contract={contract} - isMobile={isMobile} - disabled={disabled} - /> - </div> - )} - </Col> - ) -} - -export function CloseOrResolveTime(props: { - contract: Contract - resolvedDate: any - isCreator: boolean -}) { - const { contract, resolvedDate, isCreator } = props - const { resolutionTime, closeTime } = contract - console.log(closeTime, resolvedDate) - if (!!closeTime || !!resolvedDate) { - return ( - <Row className="select-none items-center gap-1"> - {resolvedDate && resolutionTime ? ( - <> - <DateTimeTooltip text="Market resolved:" time={resolutionTime}> - <Row> - <div>resolved </div> - {resolvedDate} - </Row> - </DateTimeTooltip> - </> - ) : null} - - {!resolvedDate && closeTime && ( - <Row> - {dayjs().isBefore(closeTime) && <div>closes </div>} - {!dayjs().isBefore(closeTime) && <div>closed </div>} - <EditableCloseDate - closeTime={closeTime} - contract={contract} - isCreator={isCreator ?? false} - /> - </Row> - )} - </Row> - ) - } else return <></> -} - -export function MarketGroups(props: { - contract: Contract - isMobile: boolean | undefined - disabled: boolean | undefined -}) { const [open, setOpen] = useState(false) - const user = useUser() - const { contract, isMobile, disabled } = props + const { width } = useWindowSize() + const isMobile = (width ?? 0) < 600 const groupToDisplay = getGroupLinkToDisplay(contract) const groupInfo = groupToDisplay ? ( <Link prefetch={false} href={groupPath(groupToDisplay.slug)}> <a className={clsx( - 'flex flex-row items-center truncate pr-1', + linkClass, + 'flex flex-row items-center truncate pr-0 sm:pr-2', isMobile ? 'max-w-[140px]' : 'max-w-[250px]' )} > - <div className="bg-greyscale-4 hover:bg-greyscale-3 text-2xs items-center truncate rounded-full px-2 text-white sm:text-xs"> - {groupToDisplay.name} - </div> + <UserGroupIcon className="mx-1 inline h-5 w-5 shrink-0" /> + <span className="items-center truncate">{groupToDisplay.name}</span> </a> </Link> ) : ( - <Row - className={clsx( - 'cursor-default select-none items-center truncate pr-1', - isMobile ? 'max-w-[140px]' : 'max-w-[250px]' - )} + <Button + size={'xs'} + className={'max-w-[200px] pr-2'} + color={'gray-white'} + onClick={() => !groupToDisplay && setOpen(true)} > - <div - className={clsx( - 'bg-greyscale-4 text-2xs items-center truncate rounded-full px-2 text-white sm:text-xs' - )} - > - No Group - </div> - </Row> + <Row> + <UserGroupIcon className="mx-1 inline h-5 w-5 shrink-0" /> + <span className="truncate">No Group</span> + </Row> + </Button> ) + return ( - <> - <Row className="align-middle"> + <Row className="flex-1 flex-wrap items-center gap-2 text-sm text-gray-500 md:gap-x-4 md:gap-y-2"> + <Row className="items-center gap-2"> + <Avatar + username={creatorUsername} + avatarUrl={creatorAvatarUrl} + noLink={disabled} + size={6} + /> {disabled ? ( - { groupInfo } + creatorName + ) : ( + <UserLink + className="whitespace-nowrap" + name={creatorName} + username={creatorUsername} + short={isMobile} + /> + )} + {!disabled && <UserFollowButton userId={creatorId} small />} + </Row> + <Row> + {disabled ? ( + groupInfo + ) : !groupToDisplay && !user ? ( + <div /> ) : ( <Row> {groupInfo} - {user && ( - <button - className="text-greyscale-4 hover:text-greyscale-3" + {user && groupToDisplay && ( + <Button + size={'xs'} + color={'gray-white'} onClick={() => setOpen(!open)} > - <PlusCircleIcon className="mb-0.5 mr-0.5 inline h-4 w-4 shrink-0" /> - </button> + <PencilIcon className="mb-0.5 mr-0.5 inline h-4 w-4 shrink-0" /> + </Button> )} </Row> )} @@ -281,7 +201,45 @@ export function MarketGroups(props: { <ContractGroupsList contract={contract} user={user} /> </Col> </Modal> - </> + + {(!!closeTime || !!resolvedDate) && ( + <Row className="hidden items-center gap-1 md:inline-flex"> + {resolvedDate && resolutionTime ? ( + <> + <ClockIcon className="h-5 w-5" /> + <DateTimeTooltip text="Market resolved:" time={resolutionTime}> + {resolvedDate} + </DateTimeTooltip> + </> + ) : null} + + {!resolvedDate && closeTime && user && ( + <> + <ClockIcon className="h-5 w-5" /> + <EditableCloseDate + closeTime={closeTime} + contract={contract} + isCreator={isCreator ?? false} + /> + </> + )} + </Row> + )} + {user && ( + <> + <Row className="hidden items-center gap-1 md:inline-flex"> + <DatabaseIcon className="h-5 w-5" /> + <div className="whitespace-nowrap">{volumeLabel}</div> + </Row> + {!disabled && ( + <ContractInfoDialog + contract={contract} + className={'hidden md:inline-flex'} + /> + )} + </> + )} + </Row> ) } @@ -322,12 +280,12 @@ export function ExtraMobileContractDetails(props: { !resolvedDate && closeTime && ( <Col className={'items-center text-sm text-gray-500'}> - <Row className={'text-gray-400'}>Closes </Row> <EditableCloseDate closeTime={closeTime} contract={contract} isCreator={creatorId === user?.id} /> + <Row className={'text-gray-400'}>Ends</Row> </Col> ) )} diff --git a/web/components/contract/contract-info-dialog.tsx b/web/components/contract/contract-info-dialog.tsx index 07958378..ae586725 100644 --- a/web/components/contract/contract-info-dialog.tsx +++ b/web/components/contract/contract-info-dialog.tsx @@ -18,7 +18,6 @@ import { deleteField } from 'firebase/firestore' import ShortToggle from '../widgets/short-toggle' import { DuplicateContractButton } from '../copy-contract-button' import { Row } from '../layout/row' -import { Button } from '../button' export const contractDetailsButtonClassName = 'group flex items-center rounded-md px-3 py-2 text-sm font-medium cursor-pointer hover:bg-gray-100 text-gray-400 hover:text-gray-500' @@ -68,21 +67,19 @@ export function ContractInfoDialog(props: { return ( <> - <Button - size="sm" - color="gray-white" + <button className={clsx(contractDetailsButtonClassName, className)} onClick={() => setOpen(true)} > <DotsHorizontalIcon - className={clsx('h-5 w-5 flex-shrink-0')} + className={clsx('h-6 w-6 flex-shrink-0')} aria-hidden="true" /> - </Button> + </button> <Modal open={open} setOpen={setOpen}> <Col className="gap-4 rounded bg-white p-6"> - <Title className="!mt-0 !mb-0" text="This Market" /> + <Title className="!mt-0 !mb-0" text="Market info" /> <table className="table-compact table-zebra table w-full text-gray-500"> <tbody> diff --git a/web/components/contract/contract-overview.tsx b/web/components/contract/contract-overview.tsx index bfb4829f..1bfe84de 100644 --- a/web/components/contract/contract-overview.tsx +++ b/web/components/contract/contract-overview.tsx @@ -25,11 +25,11 @@ import { NumericContract, PseudoNumericContract, } from 'common/contract' -import { ContractDetails } from './contract-details' +import { ContractDetails, ExtraMobileContractDetails } from './contract-details' import { NumericGraph } from './numeric-graph' const OverviewQuestion = (props: { text: string }) => ( - <Linkify className="text-lg text-indigo-700 sm:text-2xl" text={props.text} /> + <Linkify className="text-2xl text-indigo-700 md:text-3xl" text={props.text} /> ) const BetWidget = (props: { contract: CPMMContract }) => { @@ -73,7 +73,7 @@ const BinaryOverview = (props: { contract: BinaryContract; bets: Bet[] }) => { const { contract, bets } = props return ( <Col className="gap-1 md:gap-2"> - <Col className="gap-1 px-2"> + <Col className="gap-3 px-2 sm:gap-4"> <ContractDetails contract={contract} /> <Row className="justify-between gap-4"> <OverviewQuestion text={contract.question} /> @@ -85,6 +85,7 @@ const BinaryOverview = (props: { contract: BinaryContract; bets: Bet[] }) => { </Row> <Row className="items-center justify-between gap-4 xl:hidden"> <BinaryResolutionOrChance contract={contract} /> + <ExtraMobileContractDetails contract={contract} /> {tradingAllowed(contract) && ( <BetWidget contract={contract as CPMMBinaryContract} /> )} @@ -112,6 +113,10 @@ const ChoiceOverview = (props: { </Col> <Col className={'mb-1 gap-y-2'}> <AnswersGraph contract={contract} bets={[...bets].reverse()} /> + <ExtraMobileContractDetails + contract={contract} + forceShowVolume={true} + /> </Col> </Col> ) @@ -135,6 +140,7 @@ const PseudoNumericOverview = (props: { </Row> <Row className="items-center justify-between gap-4 xl:hidden"> <PseudoNumericResolutionOrExpectation contract={contract} /> + <ExtraMobileContractDetails contract={contract} /> {tradingAllowed(contract) && <BetWidget contract={contract} />} </Row> </Col> diff --git a/web/components/contract/extra-contract-actions-row.tsx b/web/components/contract/extra-contract-actions-row.tsx index af5db9c3..5d5ee4d8 100644 --- a/web/components/contract/extra-contract-actions-row.tsx +++ b/web/components/contract/extra-contract-actions-row.tsx @@ -11,29 +11,38 @@ import { FollowMarketButton } from 'web/components/follow-market-button' import { LikeMarketButton } from 'web/components/contract/like-market-button' import { ContractInfoDialog } from 'web/components/contract/contract-info-dialog' import { Col } from 'web/components/layout/col' +import { withTracking } from 'web/lib/service/analytics' +import { CreateChallengeModal } from 'web/components/challenges/create-challenge-modal' +import { CHALLENGES_ENABLED } from 'common/challenge' +import ChallengeIcon from 'web/lib/icons/challenge-icon' export function ExtraContractActionsRow(props: { contract: Contract }) { const { contract } = props + const { outcomeType, resolution } = contract const user = useUser() const [isShareOpen, setShareOpen] = useState(false) + const [openCreateChallengeModal, setOpenCreateChallengeModal] = + useState(false) + const showChallenge = + user && outcomeType === 'BINARY' && !resolution && CHALLENGES_ENABLED return ( - <Row> - <FollowMarketButton contract={contract} user={user} /> - {user?.id !== contract.creatorId && ( - <LikeMarketButton contract={contract} user={user} /> - )} + <Row className={'mt-0.5 justify-around sm:mt-2 lg:justify-start'}> <Button - size="sm" + size="lg" color="gray-white" className={'flex'} onClick={() => { setShareOpen(true) }} > - <Row> - <ShareIcon className={clsx('h-5 w-5')} aria-hidden="true" /> - </Row> + <Col className={'items-center sm:flex-row'}> + <ShareIcon + className={clsx('h-[24px] w-5 sm:mr-2')} + aria-hidden="true" + /> + <span>Share</span> + </Col> <ShareModal isOpen={isShareOpen} setOpen={setShareOpen} @@ -41,7 +50,35 @@ export function ExtraContractActionsRow(props: { contract: Contract }) { user={user} /> </Button> - <Col className={'justify-center'}> + + {showChallenge && ( + <Button + size="lg" + color="gray-white" + className="max-w-xs self-center" + onClick={withTracking( + () => setOpenCreateChallengeModal(true), + 'click challenge button' + )} + > + <Col className="items-center sm:flex-row"> + <ChallengeIcon className="mx-auto h-[24px] w-5 text-gray-500 sm:mr-2" /> + <span>Challenge</span> + </Col> + <CreateChallengeModal + isOpen={openCreateChallengeModal} + setOpen={setOpenCreateChallengeModal} + user={user} + contract={contract} + /> + </Button> + )} + + <FollowMarketButton contract={contract} user={user} /> + {user?.id !== contract.creatorId && ( + <LikeMarketButton contract={contract} user={user} /> + )} + <Col className={'justify-center md:hidden'}> <ContractInfoDialog contract={contract} /> </Col> </Row> diff --git a/web/components/contract/like-market-button.tsx b/web/components/contract/like-market-button.tsx index 01dce32f..e35e3e7e 100644 --- a/web/components/contract/like-market-button.tsx +++ b/web/components/contract/like-market-button.tsx @@ -38,16 +38,15 @@ export function LikeMarketButton(props: { return ( <Button - size={'sm'} + size={'lg'} className={'max-w-xs self-center'} color={'gray-white'} onClick={onLike} > - <Col className={'relative items-center sm:flex-row'}> + <Col className={'items-center sm:flex-row'}> <HeartIcon className={clsx( - 'h-5 w-5 sm:h-6 sm:w-6', - totalTipped > 0 ? 'mr-2' : '', + 'h-[24px] w-5 sm:mr-2', user && (userLikedContractIds?.includes(contract.id) || (!likes && contract.likedByUserIds?.includes(user.id))) @@ -55,18 +54,7 @@ export function LikeMarketButton(props: { : '' )} /> - {totalTipped > 0 && ( - <div - className={clsx( - 'bg-greyscale-6 absolute ml-3.5 mt-2 h-4 w-4 rounded-full align-middle text-white sm:mt-3 sm:h-5 sm:w-5 sm:px-1', - totalTipped > 99 - ? 'text-[0.4rem] sm:text-[0.5rem]' - : 'sm:text-2xs text-[0.5rem]' - )} - > - {totalTipped} - </div> - )} + Tip {totalTipped > 0 ? `(${formatMoney(totalTipped)})` : ''} </Col> </Button> ) diff --git a/web/components/follow-button.tsx b/web/components/follow-button.tsx index 6344757d..09495169 100644 --- a/web/components/follow-button.tsx +++ b/web/components/follow-button.tsx @@ -1,6 +1,4 @@ -import { CheckCircleIcon, PlusCircleIcon } from '@heroicons/react/solid' import clsx from 'clsx' -import { useEffect, useRef, useState } from 'react' import { useFollows } from 'web/hooks/use-follows' import { useUser } from 'web/hooks/use-user' import { follow, unfollow } from 'web/lib/firebase/users' @@ -56,73 +54,18 @@ export function FollowButton(props: { export function UserFollowButton(props: { userId: string; small?: boolean }) { const { userId, small } = props - const user = useUser() - const following = useFollows(user?.id) + const currentUser = useUser() + const following = useFollows(currentUser?.id) const isFollowing = following?.includes(userId) - if (!user || user.id === userId) return null + if (!currentUser || currentUser.id === userId) return null return ( <FollowButton isFollowing={isFollowing} - onFollow={() => follow(user.id, userId)} - onUnfollow={() => unfollow(user.id, userId)} + onFollow={() => follow(currentUser.id, userId)} + onUnfollow={() => unfollow(currentUser.id, userId)} small={small} /> ) } - -export function MiniUserFollowButton(props: { userId: string }) { - const { userId } = props - const user = useUser() - const following = useFollows(user?.id) - const isFollowing = following?.includes(userId) - const isFirstRender = useRef(true) - const [justFollowed, setJustFollowed] = useState(false) - - useEffect(() => { - if (isFirstRender.current) { - if (isFollowing != undefined) { - isFirstRender.current = false - } - return - } - if (isFollowing) { - setJustFollowed(true) - setTimeout(() => { - setJustFollowed(false) - }, 1000) - } - }, [isFollowing]) - - if (justFollowed) { - return ( - <CheckCircleIcon - className={clsx( - 'text-highlight-blue ml-3 mt-2 h-5 w-5 rounded-full bg-white sm:mr-2' - )} - aria-hidden="true" - /> - ) - } - if ( - !user || - user.id === userId || - isFollowing || - !user || - isFollowing === undefined - ) - return null - return ( - <> - <button onClick={withTracking(() => follow(user.id, userId), 'follow')}> - <PlusCircleIcon - className={clsx( - 'text-highlight-blue hover:text-hover-blue mt-2 ml-3 h-5 w-5 rounded-full bg-white sm:mr-2' - )} - aria-hidden="true" - /> - </button> - </> - ) -} diff --git a/web/components/follow-market-button.tsx b/web/components/follow-market-button.tsx index 0e65165b..1dd261cb 100644 --- a/web/components/follow-market-button.tsx +++ b/web/components/follow-market-button.tsx @@ -25,7 +25,7 @@ export const FollowMarketButton = (props: { return ( <Button - size={'sm'} + size={'lg'} color={'gray-white'} onClick={async () => { if (!user) return firebaseLogin() @@ -56,19 +56,13 @@ export const FollowMarketButton = (props: { > {followers?.includes(user?.id ?? 'nope') ? ( <Col className={'items-center gap-x-2 sm:flex-row'}> - <EyeOffIcon - className={clsx('h-5 w-5 sm:h-6 sm:w-6')} - aria-hidden="true" - /> - {/* Unwatch */} + <EyeOffIcon className={clsx('h-6 w-6')} aria-hidden="true" /> + Unwatch </Col> ) : ( <Col className={'items-center gap-x-2 sm:flex-row'}> - <EyeIcon - className={clsx('h-5 w-5 sm:h-6 sm:w-6')} - aria-hidden="true" - /> - {/* Watch */} + <EyeIcon className={clsx('h-6 w-6')} aria-hidden="true" /> + Watch </Col> )} <WatchMarketModal diff --git a/web/pages/[username]/[contractSlug].tsx b/web/pages/[username]/[contractSlug].tsx index a0b2ed50..2c011c90 100644 --- a/web/pages/[username]/[contractSlug].tsx +++ b/web/pages/[username]/[contractSlug].tsx @@ -37,6 +37,7 @@ import { User } from 'common/user' import { ContractComment } from 'common/comment' import { getOpenGraphProps } from 'common/contract-details' import { ContractDescription } from 'web/components/contract/contract-description' +import { ExtraContractActionsRow } from 'web/components/contract/extra-contract-actions-row' import { ContractLeaderboard, ContractTopTrades, @@ -256,6 +257,7 @@ export function ContractPageContent( )} <ContractOverview contract={contract} bets={nonChallengeBets} /> + <ExtraContractActionsRow contract={contract} /> <ContractDescription className="mb-6 px-2" contract={contract} /> {outcomeType === 'NUMERIC' && ( diff --git a/web/tailwind.config.js b/web/tailwind.config.js index 7bea3ec2..eb411216 100644 --- a/web/tailwind.config.js +++ b/web/tailwind.config.js @@ -26,8 +26,6 @@ module.exports = { 'greyscale-5': '#9191A7', 'greyscale-6': '#66667C', 'greyscale-7': '#111140', - 'highlight-blue': '#5BCEFF', - 'hover-blue': '#90DEFF', }, typography: { quoteless: { From e5428ce52540e0b31eb67bd548fa038d00ca5fcd Mon Sep 17 00:00:00 2001 From: Ian Philips <iansphilips@gmail.com> Date: Thu, 15 Sep 2022 07:14:59 -0600 Subject: [PATCH 08/42] Watch market modal copy --- web/components/contract/watch-market-modal.tsx | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/web/components/contract/watch-market-modal.tsx b/web/components/contract/watch-market-modal.tsx index 2fb9bc00..8f79e1ed 100644 --- a/web/components/contract/watch-market-modal.tsx +++ b/web/components/contract/watch-market-modal.tsx @@ -18,21 +18,22 @@ export const WatchMarketModal = (props: { <Col className={'gap-2'}> <span className={'text-indigo-700'}>• What is watching?</span> <span className={'ml-2'}> - You'll receive notifications on markets by betting, commenting, or - clicking the + Watching a market means you'll receive notifications from activity + on it. You automatically start watching a market if you comment on + it, bet on it, or click the <EyeIcon className={clsx('ml-1 inline h-6 w-6 align-top')} aria-hidden="true" /> - ️ button on them. + ️ button. </span> <span className={'text-indigo-700'}> • What types of notifications will I receive? </span> <span className={'ml-2'}> - You'll receive notifications for new comments, answers, and updates - to the question. See the notifications settings pages to customize - which types of notifications you receive on watched markets. + New comments, answers, and updates to the question. See the + notifications settings pages to customize which types of + notifications you receive on watched markets. </span> </Col> </Col> From 4a5c6a42f67fdd1610bf26190837ef9e7c560e15 Mon Sep 17 00:00:00 2001 From: Ian Philips <iansphilips@gmail.com> Date: Thu, 15 Sep 2022 07:45:11 -0600 Subject: [PATCH 09/42] Store bonus txn data in data field --- common/txn.ts | 29 ++++++++++++++-- functions/src/on-create-bet.ts | 4 ++- .../scripts/update-bonus-txn-data-fields.ts | 34 +++++++++++++++++++ 3 files changed, 63 insertions(+), 4 deletions(-) create mode 100644 functions/src/scripts/update-bonus-txn-data-fields.ts diff --git a/common/txn.ts b/common/txn.ts index 00b19570..713d4a38 100644 --- a/common/txn.ts +++ b/common/txn.ts @@ -1,6 +1,12 @@ // A txn (pronounced "texan") respresents a payment between two ids on Manifold // Shortened from "transaction" to distinguish from Firebase transactions (and save chars) -type AnyTxnType = Donation | Tip | Manalink | Referral | Bonus +type AnyTxnType = + | Donation + | Tip + | Manalink + | Referral + | UniqueBettorBonus + | BettingStreakBonus type SourceType = 'USER' | 'CONTRACT' | 'CHARITY' | 'BANK' export type Txn<T extends AnyTxnType = AnyTxnType> = { @@ -60,10 +66,27 @@ type Referral = { category: 'REFERRAL' } -type Bonus = { +type UniqueBettorBonus = { fromType: 'BANK' toType: 'USER' - category: 'UNIQUE_BETTOR_BONUS' | 'BETTING_STREAK_BONUS' + category: 'UNIQUE_BETTOR_BONUS' + // This data was mistakenly stored as a stringified JSON object in description previously + data: { + contractId: string + uniqueNewBettorId?: string + // Previously stored all unique bettor ids in description + uniqueBettorIds?: string[] + } +} + +type BettingStreakBonus = { + fromType: 'BANK' + toType: 'USER' + category: 'BETTING_STREAK_BONUS' + // This data was mistakenly stored as a stringified JSON object in description previously + data: { + currentBettingStreak?: number + } } export type DonationTxn = Txn & Donation diff --git a/functions/src/on-create-bet.ts b/functions/src/on-create-bet.ts index 5fe3fd62..7f4ca067 100644 --- a/functions/src/on-create-bet.ts +++ b/functions/src/on-create-bet.ts @@ -119,6 +119,7 @@ const updateBettingStreak = async ( token: 'M$', category: 'BETTING_STREAK_BONUS', description: JSON.stringify(bonusTxnDetails), + data: bonusTxnDetails, } return await runTxn(trans, bonusTxn) }) @@ -186,7 +187,7 @@ const updateUniqueBettorsAndGiveCreatorBonus = async ( // Create combined txn for all new unique bettors const bonusTxnDetails = { contractId: contract.id, - uniqueBettorIds: newUniqueBettorIds, + uniqueNewBettorId: bettor.id, } const fromUserId = isProd() ? HOUSE_LIQUIDITY_PROVIDER_ID @@ -204,6 +205,7 @@ const updateUniqueBettorsAndGiveCreatorBonus = async ( token: 'M$', category: 'UNIQUE_BETTOR_BONUS', description: JSON.stringify(bonusTxnDetails), + data: bonusTxnDetails, } return await runTxn(trans, bonusTxn) }) diff --git a/functions/src/scripts/update-bonus-txn-data-fields.ts b/functions/src/scripts/update-bonus-txn-data-fields.ts new file mode 100644 index 00000000..82955fa0 --- /dev/null +++ b/functions/src/scripts/update-bonus-txn-data-fields.ts @@ -0,0 +1,34 @@ +import * as admin from 'firebase-admin' + +import { initAdmin } from './script-init' +import { Txn } from 'common/txn' +import { getValues } from 'functions/src/utils' + +initAdmin() + +const firestore = admin.firestore() + +async function main() { + // get all txns + const bonusTxns = await getValues<Txn>( + firestore + .collection('txns') + .where('category', 'in', ['UNIQUE_BETTOR_BONUS', 'BETTING_STREAK_BONUS']) + ) + // JSON parse description field and add to data field + const updatedTxns = bonusTxns.map((txn) => { + txn.data = txn.description && JSON.parse(txn.description) + return txn + }) + console.log('updatedTxns', updatedTxns[0]) + // update txns + await Promise.all( + updatedTxns.map((txn) => { + return firestore.collection('txns').doc(txn.id).update({ + data: txn.data, + }) + }) + ) +} + +if (require.main === module) main().then(() => process.exit()) From 733d2065178aec2e7de32e658c194d2b04e26bbe Mon Sep 17 00:00:00 2001 From: Ian Philips <iansphilips@gmail.com> Date: Thu, 15 Sep 2022 07:50:35 -0600 Subject: [PATCH 10/42] Add txn types --- common/txn.ts | 2 ++ functions/src/on-create-bet.ts | 7 +++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/common/txn.ts b/common/txn.ts index 713d4a38..ac3b76de 100644 --- a/common/txn.ts +++ b/common/txn.ts @@ -93,3 +93,5 @@ export type DonationTxn = Txn & Donation export type TipTxn = Txn & Tip export type ManalinkTxn = Txn & Manalink export type ReferralTxn = Txn & Referral +export type BettingStreakBonusTxn = Txn & BettingStreakBonus +export type UniqueBettorBonusTxn = Txn & UniqueBettorBonus diff --git a/functions/src/on-create-bet.ts b/functions/src/on-create-bet.ts index 7f4ca067..b645e3b7 100644 --- a/functions/src/on-create-bet.ts +++ b/functions/src/on-create-bet.ts @@ -27,6 +27,7 @@ import { User } from '../../common/user' import { UNIQUE_BETTOR_LIQUIDITY_AMOUNT } from '../../common/antes' import { addHouseLiquidity } from './add-liquidity' import { DAY_MS } from '../../common/util/time' +import { BettingStreakBonusTxn, UniqueBettorBonusTxn } from '../../common/txn' const firestore = admin.firestore() const BONUS_START_DATE = new Date('2022-07-13T15:30:00.000Z').getTime() @@ -109,6 +110,7 @@ const updateBettingStreak = async ( const bonusTxnDetails = { currentBettingStreak: newBettingStreak, } + // TODO: set the id of the txn to the eventId to prevent duplicates const result = await firestore.runTransaction(async (trans) => { const bonusTxn: TxnData = { fromId: fromUserId, @@ -120,7 +122,7 @@ const updateBettingStreak = async ( category: 'BETTING_STREAK_BONUS', description: JSON.stringify(bonusTxnDetails), data: bonusTxnDetails, - } + } as Omit<BettingStreakBonusTxn, 'id' | 'createdTime'> return await runTxn(trans, bonusTxn) }) if (!result.txn) { @@ -195,6 +197,7 @@ const updateUniqueBettorsAndGiveCreatorBonus = async ( const fromSnap = await firestore.doc(`users/${fromUserId}`).get() if (!fromSnap.exists) throw new APIError(400, 'From user not found.') const fromUser = fromSnap.data() as User + // TODO: set the id of the txn to the eventId to prevent duplicates const result = await firestore.runTransaction(async (trans) => { const bonusTxn: TxnData = { fromId: fromUser.id, @@ -206,7 +209,7 @@ const updateUniqueBettorsAndGiveCreatorBonus = async ( category: 'UNIQUE_BETTOR_BONUS', description: JSON.stringify(bonusTxnDetails), data: bonusTxnDetails, - } + } as Omit<UniqueBettorBonusTxn, 'id' | 'createdTime'> return await runTxn(trans, bonusTxn) }) From ada9fac343de92313e451e79a823d9319089f55f Mon Sep 17 00:00:00 2001 From: Ian Philips <iansphilips@gmail.com> Date: Thu, 15 Sep 2022 08:07:42 -0600 Subject: [PATCH 11/42] Add logs to on-create-bet --- functions/src/on-create-bet.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/functions/src/on-create-bet.ts b/functions/src/on-create-bet.ts index b645e3b7..ce75f0fe 100644 --- a/functions/src/on-create-bet.ts +++ b/functions/src/on-create-bet.ts @@ -127,6 +127,8 @@ const updateBettingStreak = async ( }) if (!result.txn) { log("betting streak bonus txn couldn't be made") + log('status:', result.status) + log('message:', result.message) return } @@ -214,7 +216,8 @@ const updateUniqueBettorsAndGiveCreatorBonus = async ( }) if (result.status != 'success' || !result.txn) { - log(`No bonus for user: ${contract.creatorId} - reason:`, result.status) + log(`No bonus for user: ${contract.creatorId} - status:`, result.status) + log('message:', result.message) } else { log(`Bonus txn for user: ${contract.creatorId} completed:`, result.txn?.id) await createUniqueBettorBonusNotification( From 772eeb5c93de41b7b2b31aaff121f4918e3ee30a Mon Sep 17 00:00:00 2001 From: Pico2x <pico2x@gmail.com> Date: Thu, 15 Sep 2022 15:45:49 +0100 Subject: [PATCH 12/42] Update [contractSlug].tsx --- web/pages/embed/[username]/[contractSlug].tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/pages/embed/[username]/[contractSlug].tsx b/web/pages/embed/[username]/[contractSlug].tsx index c5fba0c8..fbeef88f 100644 --- a/web/pages/embed/[username]/[contractSlug].tsx +++ b/web/pages/embed/[username]/[contractSlug].tsx @@ -116,7 +116,7 @@ export function ContractEmbed(props: { contract: Contract; bets: Bet[] }) { tradingAllowed(contract) && !betPanelOpen && ( <Button color="gradient" onClick={() => setBetPanelOpen(true)}> - Bet + Predict </Button> )} From 718218c717c1093f7e4706e4bd35badcf171ec65 Mon Sep 17 00:00:00 2001 From: Pico2x <pico2x@gmail.com> Date: Thu, 15 Sep 2022 15:51:14 +0100 Subject: [PATCH 13/42] Update bet-inline.tsx --- web/components/bet-inline.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/components/bet-inline.tsx b/web/components/bet-inline.tsx index af75ff7c..a8f4d718 100644 --- a/web/components/bet-inline.tsx +++ b/web/components/bet-inline.tsx @@ -79,7 +79,7 @@ export function BetInline(props: { return ( <Col className={clsx('items-center', className)}> <Row className="h-12 items-stretch gap-3 rounded bg-indigo-200 py-2 px-3"> - <div className="text-xl">Bet</div> + <div className="text-xl">Predict</div> <YesNoSelector className="space-x-0" btnClassName="rounded-l-none rounded-r-none first:rounded-l-2xl last:rounded-r-2xl" From 4c10c8499b51c4e8a253a7230e8961f2dd03ed96 Mon Sep 17 00:00:00 2001 From: Ian Philips <iansphilips@gmail.com> Date: Thu, 15 Sep 2022 09:12:44 -0600 Subject: [PATCH 14/42] Take back unique bettor bonuses on N/A --- functions/src/resolve-market.ts | 60 ++++++++++++++++++++++++++++++++- 1 file changed, 59 insertions(+), 1 deletion(-) diff --git a/functions/src/resolve-market.ts b/functions/src/resolve-market.ts index 44293898..b99b5c87 100644 --- a/functions/src/resolve-market.ts +++ b/functions/src/resolve-market.ts @@ -9,7 +9,7 @@ import { RESOLUTIONS, } from '../../common/contract' import { Bet } from '../../common/bet' -import { getUser, isProd, payUser } from './utils' +import { getUser, getValues, isProd, log, payUser } from './utils' import { getLoanPayouts, getPayouts, @@ -22,6 +22,12 @@ import { LiquidityProvision } from '../../common/liquidity-provision' import { APIError, newEndpoint, validate } from './api' import { getContractBetMetrics } from '../../common/calculate' import { createCommentOrAnswerOrUpdatedContractNotification } from './create-notification' +import { CancelUniqueBettorBonusTxn, Txn } from '../../common/txn' +import { runTxn, TxnData } from './transact' +import { + DEV_HOUSE_LIQUIDITY_PROVIDER_ID, + HOUSE_LIQUIDITY_PROVIDER_ID, +} from '../../common/antes' const bodySchema = z.object({ contractId: z.string(), @@ -163,6 +169,7 @@ export const resolvemarket = newEndpoint(opts, async (req, auth) => { await processPayouts(liquidityPayouts, true) await processPayouts([...payouts, ...loanPayouts]) + await undoUniqueBettorRewardsIfCancelResolution(contract, outcome) const userPayoutsWithoutLoans = groupPayoutsByUser(payouts) @@ -299,4 +306,55 @@ function validateAnswer( } } +async function undoUniqueBettorRewardsIfCancelResolution( + contract: Contract, + outcome: string +) { + if (outcome === 'CANCEL') { + const creatorsBonusTxns = await getValues<Txn>( + firestore + .collection('txns') + .where('category', '==', 'UNIQUE_BETTOR_BONUS') + .where('toId', '==', contract.creatorId) + ) + + const bonusTxnsOnThisContract = creatorsBonusTxns.filter( + (txn) => txn.data && txn.data.contractId === contract.id + ) + log('total bonusTxnsOnThisContract', bonusTxnsOnThisContract.length) + const totalBonusAmount = sumBy(bonusTxnsOnThisContract, (txn) => txn.amount) + log('totalBonusAmount to be withdrawn', totalBonusAmount) + const result = await firestore.runTransaction(async (trans) => { + const bonusTxn: TxnData = { + fromId: contract.creatorId, + fromType: 'USER', + toId: isProd() + ? HOUSE_LIQUIDITY_PROVIDER_ID + : DEV_HOUSE_LIQUIDITY_PROVIDER_ID, + toType: 'BANK', + amount: totalBonusAmount, + token: 'M$', + category: 'CANCEL_UNIQUE_BETTOR_BONUS', + data: { + contractId: contract.id, + }, + } as Omit<CancelUniqueBettorBonusTxn, 'id' | 'createdTime'> + return await runTxn(trans, bonusTxn) + }) + + if (result.status != 'success' || !result.txn) { + log( + `Couldn't cancel bonus for user: ${contract.creatorId} - status:`, + result.status + ) + log('message:', result.message) + } else { + log( + `Cancel Bonus txn for user: ${contract.creatorId} completed:`, + result.txn?.id + ) + } + } +} + const firestore = admin.firestore() From e9f136a653b6fc6a17a76ebbdad3d9a4e0ea4fb0 Mon Sep 17 00:00:00 2001 From: Ian Philips <iansphilips@gmail.com> Date: Thu, 15 Sep 2022 09:12:56 -0600 Subject: [PATCH 15/42] Single source of truth for predict --- common/envs/prod.ts | 6 ++++++ common/txn.ts | 12 ++++++++++++ common/user.ts | 8 ++++++++ common/util/format.ts | 4 ++++ web/components/bet-button.tsx | 5 +++-- web/components/contract-search.tsx | 6 +++--- web/components/contract/contract-info-dialog.tsx | 3 ++- web/components/contract/contract-leaderboard.tsx | 3 ++- web/components/contract/contract-tabs.tsx | 6 +++--- web/components/feed/feed-bets.tsx | 3 ++- web/components/feed/feed-comments.tsx | 4 ++-- web/components/feed/feed-liquidity.tsx | 4 ++-- web/components/liquidity-panel.tsx | 5 ++++- web/components/nav/nav-bar.tsx | 3 ++- web/components/nav/profile-menu.tsx | 3 ++- web/components/numeric-resolution-panel.tsx | 8 ++++++-- web/components/profile/loans-modal.tsx | 3 ++- web/components/resolution-panel.tsx | 16 +++++++++++----- web/components/user-page.tsx | 5 +++-- web/pages/contract-search-firestore.tsx | 3 ++- web/pages/group/[...slugs]/index.tsx | 3 ++- web/pages/leaderboards.tsx | 5 +++-- web/pages/stats.tsx | 3 ++- 23 files changed, 88 insertions(+), 33 deletions(-) diff --git a/common/envs/prod.ts b/common/envs/prod.ts index 6bf781b7..a9d1ffc3 100644 --- a/common/envs/prod.ts +++ b/common/envs/prod.ts @@ -15,6 +15,9 @@ export type EnvConfig = { // Branding moneyMoniker: string // e.g. 'M$' + bettor?: string // e.g. 'bettor' or 'predictor' + presentBet?: string // e.g. 'bet' or 'predict' + pastBet?: string // e.g. 'bet' or 'prediction' faviconPath?: string // Should be a file in /public navbarLogoPath?: string newQuestionPlaceholders: string[] @@ -79,6 +82,9 @@ export const PROD_CONFIG: EnvConfig = { visibility: 'PUBLIC', moneyMoniker: 'M$', + bettor: 'predictor', + pastBet: 'prediction', + presentBet: 'predict', navbarLogoPath: '', faviconPath: '/favicon.ico', newQuestionPlaceholders: [ diff --git a/common/txn.ts b/common/txn.ts index ac3b76de..9c83761f 100644 --- a/common/txn.ts +++ b/common/txn.ts @@ -7,6 +7,7 @@ type AnyTxnType = | Referral | UniqueBettorBonus | BettingStreakBonus + | CancelUniqueBettorBonus type SourceType = 'USER' | 'CONTRACT' | 'CHARITY' | 'BANK' export type Txn<T extends AnyTxnType = AnyTxnType> = { @@ -29,6 +30,7 @@ export type Txn<T extends AnyTxnType = AnyTxnType> = { | 'REFERRAL' | 'UNIQUE_BETTOR_BONUS' | 'BETTING_STREAK_BONUS' + | 'CANCEL_UNIQUE_BETTOR_BONUS' // Any extra data data?: { [key: string]: any } @@ -89,9 +91,19 @@ type BettingStreakBonus = { } } +type CancelUniqueBettorBonus = { + fromType: 'USER' + toType: 'BANK' + category: 'CANCEL_UNIQUE_BETTOR_BONUS' + data: { + contractId: string + } +} + export type DonationTxn = Txn & Donation export type TipTxn = Txn & Tip export type ManalinkTxn = Txn & Manalink export type ReferralTxn = Txn & Referral export type BettingStreakBonusTxn = Txn & BettingStreakBonus export type UniqueBettorBonusTxn = Txn & UniqueBettorBonus +export type CancelUniqueBettorBonusTxn = Txn & CancelUniqueBettorBonus diff --git a/common/user.ts b/common/user.ts index 16a2b437..b490ab0c 100644 --- a/common/user.ts +++ b/common/user.ts @@ -1,4 +1,5 @@ import { notification_preferences } from './user-notification-preferences' +import { ENV_CONFIG } from 'common/envs/constants' export type User = { id: string @@ -83,3 +84,10 @@ export type PortfolioMetrics = { export const MANIFOLD_USERNAME = 'ManifoldMarkets' export const MANIFOLD_AVATAR_URL = 'https://manifold.markets/logo-bg-white.png' + +export const BETTOR = ENV_CONFIG.bettor ?? 'bettor' // aka predictor +export const BETTORS = ENV_CONFIG.bettor + 's' ?? 'bettors' +export const PRESENT_BET = ENV_CONFIG.presentBet ?? 'bet' // aka predict +export const PRESENT_BETS = ENV_CONFIG.presentBet + 's' ?? 'bets' +export const PAST_BET = ENV_CONFIG.pastBet ?? 'bet' // aka prediction +export const PAST_BETS = ENV_CONFIG.pastBet + 's' ?? 'bets' // aka predictions diff --git a/common/util/format.ts b/common/util/format.ts index 4f123535..9b9ee1df 100644 --- a/common/util/format.ts +++ b/common/util/format.ts @@ -16,6 +16,10 @@ export function formatMoneyWithDecimals(amount: number) { return ENV_CONFIG.moneyMoniker + amount.toFixed(2) } +export function capitalFirst(s: string) { + return s.charAt(0).toUpperCase() + s.slice(1) +} + export function formatWithCommas(amount: number) { return formatter.format(Math.floor(amount)).replace('$', '') } diff --git a/web/components/bet-button.tsx b/web/components/bet-button.tsx index 0bd3702f..c0177fb3 100644 --- a/web/components/bet-button.tsx +++ b/web/components/bet-button.tsx @@ -10,6 +10,7 @@ import { useSaveBinaryShares } from './use-save-binary-shares' import { Col } from './layout/col' import { Button } from 'web/components/button' import { BetSignUpPrompt } from './sign-up-prompt' +import { PRESENT_BET } from 'common/user' /** Button that opens BetPanel in a new modal */ export default function BetButton(props: { @@ -36,12 +37,12 @@ export default function BetButton(props: { <Button size="lg" className={clsx( - 'my-auto inline-flex min-w-[75px] whitespace-nowrap', + 'my-auto inline-flex min-w-[75px] whitespace-nowrap capitalize', btnClassName )} onClick={() => setOpen(true)} > - Predict + {PRESENT_BET} </Button> ) : ( <BetSignUpPrompt /> diff --git a/web/components/contract-search.tsx b/web/components/contract-search.tsx index 7f64b26b..a5e86545 100644 --- a/web/components/contract-search.tsx +++ b/web/components/contract-search.tsx @@ -3,7 +3,7 @@ import algoliasearch from 'algoliasearch/lite' import { SearchOptions } from '@algolia/client-search' import { useRouter } from 'next/router' import { Contract } from 'common/contract' -import { User } from 'common/user' +import { PAST_BETS, User } from 'common/user' import { ContractHighlightOptions, ContractsGrid, @@ -41,7 +41,7 @@ const searchIndexName = ENV === 'DEV' ? 'dev-contracts' : 'contractsIndex' export const SORTS = [ { label: 'Newest', value: 'newest' }, { label: 'Trending', value: 'score' }, - { label: 'Most traded', value: 'most-traded' }, + { label: `Most ${PAST_BETS}`, value: 'most-traded' }, { label: '24h volume', value: '24-hour-vol' }, { label: '24h change', value: 'prob-change-day' }, { label: 'Last updated', value: 'last-updated' }, @@ -450,7 +450,7 @@ function ContractSearchControls(props: { selected={state.pillFilter === 'your-bets'} onSelect={selectPill('your-bets')} > - Your trades + Your {PAST_BETS} </PillButton> )} diff --git a/web/components/contract/contract-info-dialog.tsx b/web/components/contract/contract-info-dialog.tsx index ae586725..9027d38a 100644 --- a/web/components/contract/contract-info-dialog.tsx +++ b/web/components/contract/contract-info-dialog.tsx @@ -18,6 +18,7 @@ import { deleteField } from 'firebase/firestore' import ShortToggle from '../widgets/short-toggle' import { DuplicateContractButton } from '../copy-contract-button' import { Row } from '../layout/row' +import { BETTORS } from 'common/user' export const contractDetailsButtonClassName = 'group flex items-center rounded-md px-3 py-2 text-sm font-medium cursor-pointer hover:bg-gray-100 text-gray-400 hover:text-gray-500' @@ -135,7 +136,7 @@ export function ContractInfoDialog(props: { </tr> */} <tr> - <td>Traders</td> + <td>{BETTORS}</td> <td>{bettorsCount}</td> </tr> diff --git a/web/components/contract/contract-leaderboard.tsx b/web/components/contract/contract-leaderboard.tsx index 54b2c79e..fec6744d 100644 --- a/web/components/contract/contract-leaderboard.tsx +++ b/web/components/contract/contract-leaderboard.tsx @@ -12,6 +12,7 @@ import { FeedComment } from '../feed/feed-comments' import { Spacer } from '../layout/spacer' import { Leaderboard } from '../leaderboard' import { Title } from '../title' +import { BETTORS } from 'common/user' export function ContractLeaderboard(props: { contract: Contract @@ -48,7 +49,7 @@ export function ContractLeaderboard(props: { return users && users.length > 0 ? ( <Leaderboard - title="🏅 Top traders" + title={`🏅 Top ${BETTORS}`} users={users || []} columns={[ { diff --git a/web/components/contract/contract-tabs.tsx b/web/components/contract/contract-tabs.tsx index d63d3963..5b88e005 100644 --- a/web/components/contract/contract-tabs.tsx +++ b/web/components/contract/contract-tabs.tsx @@ -1,7 +1,7 @@ import { Bet } from 'common/bet' import { Contract, CPMMBinaryContract } from 'common/contract' import { ContractComment } from 'common/comment' -import { User } from 'common/user' +import { PAST_BETS, User } from 'common/user' import { ContractCommentsActivity, ContractBetsActivity, @@ -114,13 +114,13 @@ export function ContractTabs(props: { badge: `${comments.length}`, }, { - title: 'Trades', + title: PAST_BETS, content: betActivity, badge: `${visibleBets.length}`, }, ...(!user || !userBets?.length ? [] - : [{ title: 'Your trades', content: yourTrades }]), + : [{ title: `Your ${PAST_BETS}`, content: yourTrades }]), ]} /> {!user ? ( diff --git a/web/components/feed/feed-bets.tsx b/web/components/feed/feed-bets.tsx index def97801..b2852739 100644 --- a/web/components/feed/feed-bets.tsx +++ b/web/components/feed/feed-bets.tsx @@ -14,6 +14,7 @@ import { SiteLink } from 'web/components/site-link' import { getChallenge, getChallengeUrl } from 'web/lib/firebase/challenges' import { Challenge } from 'common/challenge' import { UserLink } from 'web/components/user-link' +import { BETTOR } from 'common/user' export function FeedBet(props: { contract: Contract; bet: Bet }) { const { contract, bet } = props @@ -94,7 +95,7 @@ export function BetStatusText(props: { {!hideUser ? ( <UserLink name={bet.userName} username={bet.userUsername} /> ) : ( - <span>{self?.id === bet.userId ? 'You' : 'A trader'}</span> + <span>{self?.id === bet.userId ? 'You' : `A ${BETTOR}`}</span> )}{' '} {bought} {money} {outOfTotalAmount} diff --git a/web/components/feed/feed-comments.tsx b/web/components/feed/feed-comments.tsx index f896ddb5..9d2ba85e 100644 --- a/web/components/feed/feed-comments.tsx +++ b/web/components/feed/feed-comments.tsx @@ -1,6 +1,6 @@ import { Bet } from 'common/bet' import { ContractComment } from 'common/comment' -import { User } from 'common/user' +import { PRESENT_BET, User } from 'common/user' import { Contract } from 'common/contract' import React, { useEffect, useState } from 'react' import { minBy, maxBy, partition, sumBy, Dictionary } from 'lodash' @@ -255,7 +255,7 @@ function CommentStatus(props: { const { contract, outcome, prob } = props return ( <> - {' betting '} + {` ${PRESENT_BET}ing `} <OutcomeLabel outcome={outcome} contract={contract} truncate="short" /> {prob && ' at ' + Math.round(prob * 100) + '%'} </> diff --git a/web/components/feed/feed-liquidity.tsx b/web/components/feed/feed-liquidity.tsx index 8f8faf9b..181eb4b7 100644 --- a/web/components/feed/feed-liquidity.tsx +++ b/web/components/feed/feed-liquidity.tsx @@ -1,6 +1,6 @@ import clsx from 'clsx' import dayjs from 'dayjs' -import { User } from 'common/user' +import { BETTOR, User } from 'common/user' import { useUser, useUserById } from 'web/hooks/use-user' import { Row } from 'web/components/layout/row' import { Avatar, EmptyAvatar } from 'web/components/avatar' @@ -74,7 +74,7 @@ export function LiquidityStatusText(props: { {bettor ? ( <UserLink name={bettor.name} username={bettor.username} /> ) : ( - <span>{isSelf ? 'You' : 'A trader'}</span> + <span>{isSelf ? 'You' : `A ${BETTOR}`}</span> )}{' '} {bought} a subsidy of {money} <RelativeTimestamp time={createdTime} /> diff --git a/web/components/liquidity-panel.tsx b/web/components/liquidity-panel.tsx index 0474abf7..58f57a8a 100644 --- a/web/components/liquidity-panel.tsx +++ b/web/components/liquidity-panel.tsx @@ -13,6 +13,7 @@ import { NoLabel, YesLabel } from './outcome-label' import { Col } from './layout/col' import { track } from 'web/lib/service/analytics' import { InfoTooltip } from './info-tooltip' +import { BETTORS, PRESENT_BET } from 'common/user' export function LiquidityPanel(props: { contract: CPMMContract }) { const { contract } = props @@ -104,7 +105,9 @@ function AddLiquidityPanel(props: { contract: CPMMContract }) { <> <div className="mb-4 text-gray-500"> Contribute your M$ to make this market more accurate.{' '} - <InfoTooltip text="More liquidity stabilizes the market, encouraging traders to bet. You can withdraw your subsidy at any time." /> + <InfoTooltip + text={`More liquidity stabilizes the market, encouraging ${BETTORS} to ${PRESENT_BET}. You can withdraw your subsidy at any time.`} + /> </div> <Row> diff --git a/web/components/nav/nav-bar.tsx b/web/components/nav/nav-bar.tsx index 242d6ff5..a07fa0ad 100644 --- a/web/components/nav/nav-bar.tsx +++ b/web/components/nav/nav-bar.tsx @@ -17,6 +17,7 @@ import { useRouter } from 'next/router' import NotificationsIcon from 'web/components/notifications-icon' import { useIsIframe } from 'web/hooks/use-is-iframe' import { trackCallback } from 'web/lib/service/analytics' +import { PAST_BETS } from 'common/user' function getNavigation() { return [ @@ -64,7 +65,7 @@ export function BottomNavBar() { item={{ name: formatMoney(user.balance), trackingEventName: 'profile', - href: `/${user.username}?tab=trades`, + href: `/${user.username}?tab=${PAST_BETS}`, icon: () => ( <Avatar className="mx-auto my-1" diff --git a/web/components/nav/profile-menu.tsx b/web/components/nav/profile-menu.tsx index e7cc056f..cf91ac66 100644 --- a/web/components/nav/profile-menu.tsx +++ b/web/components/nav/profile-menu.tsx @@ -4,11 +4,12 @@ import { User } from 'web/lib/firebase/users' import { formatMoney } from 'common/util/format' import { Avatar } from '../avatar' import { trackCallback } from 'web/lib/service/analytics' +import { PAST_BETS } from 'common/user' export function ProfileSummary(props: { user: User }) { const { user } = props return ( - <Link href={`/${user.username}?tab=trades`}> + <Link href={`/${user.username}?tab=${PAST_BETS}`}> <a onClick={trackCallback('sidebar: profile')} className="group mb-3 flex flex-row items-center gap-4 truncate rounded-md py-3 text-gray-500 hover:bg-gray-100 hover:text-gray-700" diff --git a/web/components/numeric-resolution-panel.tsx b/web/components/numeric-resolution-panel.tsx index 70fbf01f..0220f7a7 100644 --- a/web/components/numeric-resolution-panel.tsx +++ b/web/components/numeric-resolution-panel.tsx @@ -10,6 +10,7 @@ import { NumericContract, PseudoNumericContract } from 'common/contract' import { APIError, resolveMarket } from 'web/lib/firebase/api' import { BucketInput } from './bucket-input' import { getPseudoProbability } from 'common/pseudo-numeric' +import { BETTOR, BETTORS, PAST_BETS } from 'common/user' export function NumericResolutionPanel(props: { isAdmin: boolean @@ -111,9 +112,12 @@ export function NumericResolutionPanel(props: { <div> {outcome === 'CANCEL' ? ( - <>All trades will be returned with no fees.</> + <> + All {PAST_BETS} will be returned. Unique {BETTOR} bonuses will be + withdrawn from your account + </> ) : ( - <>Resolving this market will immediately pay out traders.</> + <>Resolving this market will immediately pay out {BETTORS}.</> )} </div> diff --git a/web/components/profile/loans-modal.tsx b/web/components/profile/loans-modal.tsx index 24b23e5b..5dcb8b6b 100644 --- a/web/components/profile/loans-modal.tsx +++ b/web/components/profile/loans-modal.tsx @@ -1,5 +1,6 @@ import { Modal } from 'web/components/layout/modal' import { Col } from 'web/components/layout/col' +import { PAST_BETS } from 'common/user' export function LoansModal(props: { isOpen: boolean @@ -11,7 +12,7 @@ export function LoansModal(props: { <Modal open={isOpen} setOpen={setOpen}> <Col className="items-center gap-4 rounded-md bg-white px-8 py-6"> <span className={'text-8xl'}>🏦</span> - <span className="text-xl">Daily loans on your trades</span> + <span className="text-xl">Daily loans on your {PAST_BETS}</span> <Col className={'gap-2'}> <span className={'text-indigo-700'}>• What are daily loans?</span> <span className={'ml-2'}> diff --git a/web/components/resolution-panel.tsx b/web/components/resolution-panel.tsx index 6f36331e..7ef6e4f3 100644 --- a/web/components/resolution-panel.tsx +++ b/web/components/resolution-panel.tsx @@ -10,6 +10,7 @@ import { APIError, resolveMarket } from 'web/lib/firebase/api' import { ProbabilitySelector } from './probability-selector' import { getProbability } from 'common/calculate' import { BinaryContract, resolution } from 'common/contract' +import { BETTOR, BETTORS, PAST_BETS } from 'common/user' export function ResolutionPanel(props: { isAdmin: boolean @@ -90,23 +91,28 @@ export function ResolutionPanel(props: { <div> {outcome === 'YES' ? ( <> - Winnings will be paid out to traders who bought YES. + Winnings will be paid out to {BETTORS} who bought YES. {/* <br /> <br /> You will earn {earnedFees}. */} </> ) : outcome === 'NO' ? ( <> - Winnings will be paid out to traders who bought NO. + Winnings will be paid out to {BETTORS} who bought NO. {/* <br /> <br /> You will earn {earnedFees}. */} </> ) : outcome === 'CANCEL' ? ( - <>All trades will be returned with no fees.</> + <> + All {PAST_BETS} will be returned. Unique {BETTOR} bonuses will be + withdrawn from your account + </> ) : outcome === 'MKT' ? ( <Col className="gap-6"> - <div>Traders will be paid out at the probability you specify:</div> + <div> + {PAST_BETS} will be paid out at the probability you specify: + </div> <ProbabilitySelector probabilityInt={Math.round(prob)} setProbabilityInt={setProb} @@ -114,7 +120,7 @@ export function ResolutionPanel(props: { {/* You will earn {earnedFees}. */} </Col> ) : ( - <>Resolving this market will immediately pay out traders.</> + <>Resolving this market will immediately pay out {BETTORS}.</> )} </div> diff --git a/web/components/user-page.tsx b/web/components/user-page.tsx index 5485267c..9dfd3491 100644 --- a/web/components/user-page.tsx +++ b/web/components/user-page.tsx @@ -25,7 +25,7 @@ import { UserFollowButton } from './follow-button' import { GroupsButton } from 'web/components/groups/groups-button' import { PortfolioValueSection } from './portfolio/portfolio-value-section' import { ReferralsButton } from 'web/components/referrals-button' -import { formatMoney } from 'common/util/format' +import { capitalFirst, formatMoney } from 'common/util/format' import { ShareIconButton } from 'web/components/share-icon-button' import { ENV_CONFIG } from 'common/envs/constants' import { @@ -35,6 +35,7 @@ import { import { REFERRAL_AMOUNT } from 'common/economy' import { LoansModal } from './profile/loans-modal' import { UserLikesButton } from 'web/components/profile/user-likes-button' +import { PAST_BETS } from 'common/user' export function UserPage(props: { user: User }) { const { user } = props @@ -269,7 +270,7 @@ export function UserPage(props: { user: User }) { ), }, { - title: 'Trades', + title: capitalFirst(PAST_BETS), content: ( <> <BetsList user={user} /> diff --git a/web/pages/contract-search-firestore.tsx b/web/pages/contract-search-firestore.tsx index 4691030c..4d6ada1d 100644 --- a/web/pages/contract-search-firestore.tsx +++ b/web/pages/contract-search-firestore.tsx @@ -8,6 +8,7 @@ import { usePersistentState, urlParamStore, } from 'web/hooks/use-persistent-state' +import { PAST_BETS } from 'common/user' const MAX_CONTRACTS_RENDERED = 100 @@ -101,7 +102,7 @@ export default function ContractSearchFirestore(props: { > <option value="score">Trending</option> <option value="newest">Newest</option> - <option value="most-traded">Most traded</option> + <option value="most-traded">Most ${PAST_BETS}</option> <option value="24-hour-vol">24h volume</option> <option value="close-date">Closing soon</option> </select> diff --git a/web/pages/group/[...slugs]/index.tsx b/web/pages/group/[...slugs]/index.tsx index f1521b42..70b06ac5 100644 --- a/web/pages/group/[...slugs]/index.tsx +++ b/web/pages/group/[...slugs]/index.tsx @@ -50,6 +50,7 @@ import { usePost } from 'web/hooks/use-post' import { useAdmin } from 'web/hooks/use-admin' import { track } from '@amplitude/analytics-browser' import { SelectMarketsModal } from 'web/components/contract-select-modal' +import { BETTORS } from 'common/user' export const getStaticProps = fromPropz(getStaticPropz) export async function getStaticPropz(props: { params: { slugs: string[] } }) { @@ -155,7 +156,7 @@ export default function GroupPage(props: { <div className="mt-4 flex flex-col gap-8 px-4 md:flex-row"> <GroupLeaderboard topUsers={topTraders} - title="🏅 Top traders" + title={`🏅 Top ${BETTORS}`} header="Profit" maxToShow={maxLeaderboardSize} /> diff --git a/web/pages/leaderboards.tsx b/web/pages/leaderboards.tsx index 08819833..4f1e9437 100644 --- a/web/pages/leaderboards.tsx +++ b/web/pages/leaderboards.tsx @@ -14,6 +14,7 @@ import { Title } from 'web/components/title' import { Tabs } from 'web/components/layout/tabs' import { useTracking } from 'web/hooks/use-tracking' import { SEO } from 'web/components/SEO' +import { BETTORS } from 'common/user' export async function getStaticProps() { const props = await fetchProps() @@ -79,7 +80,7 @@ export default function Leaderboards(_props: { <> <Col className="mx-4 items-center gap-10 lg:flex-row"> <Leaderboard - title="🏅 Top traders" + title={`🏅 Top ${BETTORS}`} users={topTraders} columns={[ { @@ -126,7 +127,7 @@ export default function Leaderboards(_props: { <Page> <SEO title="Leaderboards" - description="Manifold's leaderboards show the top traders and market creators." + description={`Manifold's leaderboards show the top ${BETTORS} and market creators.`} url="/leaderboards" /> <Title text={'Leaderboards'} className={'hidden md:block'} /> diff --git a/web/pages/stats.tsx b/web/pages/stats.tsx index bca0525a..057d47ef 100644 --- a/web/pages/stats.tsx +++ b/web/pages/stats.tsx @@ -13,6 +13,7 @@ import { SiteLink } from 'web/components/site-link' import { Linkify } from 'web/components/linkify' import { getStats } from 'web/lib/firebase/stats' import { Stats } from 'common/stats' +import { PAST_BETS } from 'common/user' export default function Analytics() { const [stats, setStats] = useState<Stats | undefined>(undefined) @@ -156,7 +157,7 @@ export function CustomAnalytics(props: { defaultIndex={0} tabs={[ { - title: 'Trades', + title: PAST_BETS, content: ( <DailyCountChart dailyCounts={dailyBetCounts} From be91d5d5e025c343270485a968f992dc3ac2cafa Mon Sep 17 00:00:00 2001 From: Ian Philips <iansphilips@gmail.com> Date: Thu, 15 Sep 2022 09:51:52 -0600 Subject: [PATCH 16/42] Avatars don't link during contract selection --- common/txn.ts | 4 +--- web/components/contract-search.tsx | 7 ++++--- web/components/contract-select-modal.tsx | 6 +++++- web/components/contract/contract-card.tsx | 10 +++++++++- web/components/contract/contract-details.tsx | 11 +++++++++-- web/components/contract/contracts-grid.tsx | 8 +++++--- web/components/user-link.tsx | 9 +++++++-- 7 files changed, 40 insertions(+), 15 deletions(-) diff --git a/common/txn.ts b/common/txn.ts index 9c83761f..2b7a32e8 100644 --- a/common/txn.ts +++ b/common/txn.ts @@ -72,11 +72,10 @@ type UniqueBettorBonus = { fromType: 'BANK' toType: 'USER' category: 'UNIQUE_BETTOR_BONUS' - // This data was mistakenly stored as a stringified JSON object in description previously data: { contractId: string uniqueNewBettorId?: string - // Previously stored all unique bettor ids in description + // Old unique bettor bonus txns stored all unique bettor ids uniqueBettorIds?: string[] } } @@ -85,7 +84,6 @@ type BettingStreakBonus = { fromType: 'BANK' toType: 'USER' category: 'BETTING_STREAK_BONUS' - // This data was mistakenly stored as a stringified JSON object in description previously data: { currentBettingStreak?: number } diff --git a/web/components/contract-search.tsx b/web/components/contract-search.tsx index a5e86545..6044178e 100644 --- a/web/components/contract-search.tsx +++ b/web/components/contract-search.tsx @@ -80,9 +80,10 @@ export function ContractSearch(props: { highlightOptions?: ContractHighlightOptions onContractClick?: (contract: Contract) => void hideOrderSelector?: boolean - cardHideOptions?: { + cardUIOptions?: { hideGroupLink?: boolean hideQuickBet?: boolean + noLinkAvatar?: boolean } headerClassName?: string persistPrefix?: string @@ -102,7 +103,7 @@ export function ContractSearch(props: { additionalFilter, onContractClick, hideOrderSelector, - cardHideOptions, + cardUIOptions, highlightOptions, headerClassName, persistPrefix, @@ -223,7 +224,7 @@ export function ContractSearch(props: { showTime={state.showTime ?? undefined} onContractClick={onContractClick} highlightOptions={highlightOptions} - cardHideOptions={cardHideOptions} + cardUIOptions={cardUIOptions} /> )} </Col> diff --git a/web/components/contract-select-modal.tsx b/web/components/contract-select-modal.tsx index 9e23264a..2e534172 100644 --- a/web/components/contract-select-modal.tsx +++ b/web/components/contract-select-modal.tsx @@ -85,7 +85,11 @@ export function SelectMarketsModal(props: { <ContractSearch hideOrderSelector onContractClick={addContract} - cardHideOptions={{ hideGroupLink: true, hideQuickBet: true }} + cardUIOptions={{ + hideGroupLink: true, + hideQuickBet: true, + noLinkAvatar: true, + }} highlightOptions={{ contractIds: contracts.map((c) => c.id), highlightClassName: diff --git a/web/components/contract/contract-card.tsx b/web/components/contract/contract-card.tsx index dab92a7a..367a5401 100644 --- a/web/components/contract/contract-card.tsx +++ b/web/components/contract/contract-card.tsx @@ -42,6 +42,7 @@ export function ContractCard(props: { hideQuickBet?: boolean hideGroupLink?: boolean trackingPostfix?: string + noLinkAvatar?: boolean }) { const { showTime, @@ -51,6 +52,7 @@ export function ContractCard(props: { hideQuickBet, hideGroupLink, trackingPostfix, + noLinkAvatar, } = props const contract = useContractWithPreload(props.contract) ?? props.contract const { question, outcomeType } = contract @@ -78,6 +80,7 @@ export function ContractCard(props: { <AvatarDetails contract={contract} className={'hidden md:inline-flex'} + noLink={noLinkAvatar} /> <p className={clsx( @@ -142,7 +145,12 @@ export function ContractCard(props: { showQuickBet ? 'w-[85%]' : 'w-full' )} > - <AvatarDetails contract={contract} short={true} className="md:hidden" /> + <AvatarDetails + contract={contract} + short={true} + className="md:hidden" + noLink={noLinkAvatar} + /> <MiscDetails contract={contract} showTime={showTime} diff --git a/web/components/contract/contract-details.tsx b/web/components/contract/contract-details.tsx index e28ab41a..0a65d4d9 100644 --- a/web/components/contract/contract-details.tsx +++ b/web/components/contract/contract-details.tsx @@ -86,8 +86,9 @@ export function AvatarDetails(props: { contract: Contract className?: string short?: boolean + noLink?: boolean }) { - const { contract, short, className } = props + const { contract, short, className, noLink } = props const { creatorName, creatorUsername, creatorAvatarUrl } = contract return ( @@ -98,8 +99,14 @@ export function AvatarDetails(props: { username={creatorUsername} avatarUrl={creatorAvatarUrl} size={6} + noLink={noLink} + /> + <UserLink + name={creatorName} + username={creatorUsername} + short={short} + noLink={noLink} /> - <UserLink name={creatorName} username={creatorUsername} short={short} /> </Row> ) } diff --git a/web/components/contract/contracts-grid.tsx b/web/components/contract/contracts-grid.tsx index c6356fdd..fcf20f02 100644 --- a/web/components/contract/contracts-grid.tsx +++ b/web/components/contract/contracts-grid.tsx @@ -21,9 +21,10 @@ export function ContractsGrid(props: { loadMore?: () => void showTime?: ShowTime onContractClick?: (contract: Contract) => void - cardHideOptions?: { + cardUIOptions?: { hideQuickBet?: boolean hideGroupLink?: boolean + noLinkAvatar?: boolean } highlightOptions?: ContractHighlightOptions trackingPostfix?: string @@ -34,11 +35,11 @@ export function ContractsGrid(props: { showTime, loadMore, onContractClick, - cardHideOptions, + cardUIOptions, highlightOptions, trackingPostfix, } = props - const { hideQuickBet, hideGroupLink } = cardHideOptions || {} + const { hideQuickBet, hideGroupLink, noLinkAvatar } = cardUIOptions || {} const { contractIds, highlightClassName } = highlightOptions || {} const onVisibilityUpdated = useCallback( (visible) => { @@ -80,6 +81,7 @@ export function ContractsGrid(props: { onClick={ onContractClick ? () => onContractClick(contract) : undefined } + noLinkAvatar={noLinkAvatar} hideQuickBet={hideQuickBet} hideGroupLink={hideGroupLink} trackingPostfix={trackingPostfix} diff --git a/web/components/user-link.tsx b/web/components/user-link.tsx index e1b675a0..4b05ccd0 100644 --- a/web/components/user-link.tsx +++ b/web/components/user-link.tsx @@ -20,13 +20,18 @@ export function UserLink(props: { username: string className?: string short?: boolean + noLink?: boolean }) { - const { name, username, className, short } = props + const { name, username, className, short, noLink } = props const shortName = short ? shortenName(name) : name return ( <SiteLink href={`/${username}`} - className={clsx('z-10 truncate', className)} + className={clsx( + 'z-10 truncate', + className, + noLink ? 'pointer-events-none' : '' + )} > {shortName} </SiteLink> From b3e6dce31ef08bd9c51c6c1687d95d9844a6fb8b Mon Sep 17 00:00:00 2001 From: Ian Philips <iansphilips@gmail.com> Date: Thu, 15 Sep 2022 09:57:14 -0600 Subject: [PATCH 17/42] Capitalize --- common/util/format.ts | 4 ---- web/components/contract/contract-tabs.tsx | 3 ++- web/components/user-page.tsx | 5 +++-- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/common/util/format.ts b/common/util/format.ts index 9b9ee1df..4f123535 100644 --- a/common/util/format.ts +++ b/common/util/format.ts @@ -16,10 +16,6 @@ export function formatMoneyWithDecimals(amount: number) { return ENV_CONFIG.moneyMoniker + amount.toFixed(2) } -export function capitalFirst(s: string) { - return s.charAt(0).toUpperCase() + s.slice(1) -} - export function formatWithCommas(amount: number) { return formatter.format(Math.floor(amount)).replace('$', '') } diff --git a/web/components/contract/contract-tabs.tsx b/web/components/contract/contract-tabs.tsx index 5b88e005..0796dcb2 100644 --- a/web/components/contract/contract-tabs.tsx +++ b/web/components/contract/contract-tabs.tsx @@ -18,6 +18,7 @@ import { useLiquidity } from 'web/hooks/use-liquidity' import { BetSignUpPrompt } from '../sign-up-prompt' import { PlayMoneyDisclaimer } from '../play-money-disclaimer' import BetButton from '../bet-button' +import { capitalize } from 'lodash' export function ContractTabs(props: { contract: Contract @@ -114,7 +115,7 @@ export function ContractTabs(props: { badge: `${comments.length}`, }, { - title: PAST_BETS, + title: capitalize(PAST_BETS), content: betActivity, badge: `${visibleBets.length}`, }, diff --git a/web/components/user-page.tsx b/web/components/user-page.tsx index 9dfd3491..6d7f0b2c 100644 --- a/web/components/user-page.tsx +++ b/web/components/user-page.tsx @@ -25,7 +25,7 @@ import { UserFollowButton } from './follow-button' import { GroupsButton } from 'web/components/groups/groups-button' import { PortfolioValueSection } from './portfolio/portfolio-value-section' import { ReferralsButton } from 'web/components/referrals-button' -import { capitalFirst, formatMoney } from 'common/util/format' +import { formatMoney } from 'common/util/format' import { ShareIconButton } from 'web/components/share-icon-button' import { ENV_CONFIG } from 'common/envs/constants' import { @@ -36,6 +36,7 @@ import { REFERRAL_AMOUNT } from 'common/economy' import { LoansModal } from './profile/loans-modal' import { UserLikesButton } from 'web/components/profile/user-likes-button' import { PAST_BETS } from 'common/user' +import { capitalize } from 'lodash' export function UserPage(props: { user: User }) { const { user } = props @@ -270,7 +271,7 @@ export function UserPage(props: { user: User }) { ), }, { - title: capitalFirst(PAST_BETS), + title: capitalize(PAST_BETS), content: ( <> <BetsList user={user} /> From 69c2570ff97d71d48f463604acaa44757f673e6d Mon Sep 17 00:00:00 2001 From: Sinclair Chen <abc.sinclair@gmail.com> Date: Thu, 15 Sep 2022 12:29:57 -0700 Subject: [PATCH 18/42] fix copy to make clear referrals aren't limited --- web/components/user-page.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/web/components/user-page.tsx b/web/components/user-page.tsx index 6d7f0b2c..8dc7928a 100644 --- a/web/components/user-page.tsx +++ b/web/components/user-page.tsx @@ -242,7 +242,8 @@ export function UserPage(props: { user: User }) { <SiteLink href="/referrals"> Earn {formatMoney(REFERRAL_AMOUNT)} when you refer a friend! </SiteLink>{' '} - You have <ReferralsButton user={user} currentUser={currentUser} /> + You've gotten + <ReferralsButton user={user} currentUser={currentUser} /> </span> <ShareIconButton copyPayload={`https://${ENV_CONFIG.domain}?referrer=${currentUser.username}`} From 8c6a40bab7300e5c6da459da5f8091643e807e70 Mon Sep 17 00:00:00 2001 From: Ian Philips <iansphilips@gmail.com> Date: Thu, 15 Sep 2022 13:39:46 -0600 Subject: [PATCH 19/42] Enrich limit order notification --- common/notification.ts | 17 +- functions/src/create-notification.ts | 7 + .../scripts/backfill-contract-followers.ts | 8 +- web/pages/notifications.tsx | 233 +++++++++++++----- 4 files changed, 190 insertions(+), 75 deletions(-) diff --git a/common/notification.ts b/common/notification.ts index c34f5b9c..2f03467d 100644 --- a/common/notification.ts +++ b/common/notification.ts @@ -92,11 +92,6 @@ export type notification_reason_types = | 'your_contract_closed' | 'subsidized_your_market' -export type BettingStreakData = { - streak: number - bonusAmount: number -} - type notification_descriptions = { [key in notification_preference]: { simple: string @@ -241,3 +236,15 @@ export const NOTIFICATION_DESCRIPTIONS: notification_descriptions = { detailed: `Answers on markets that you're watching and that you're invested in`, }, } + +export type BettingStreakData = { + streak: number + bonusAmount: number +} + +export type BetFillData = { + betOutcome: string + creatorOutcome: string + probability: number + fillAmount: number +} diff --git a/functions/src/create-notification.ts b/functions/src/create-notification.ts index ba9fa5c4..390a8cd8 100644 --- a/functions/src/create-notification.ts +++ b/functions/src/create-notification.ts @@ -1,5 +1,6 @@ import * as admin from 'firebase-admin' import { + BetFillData, BettingStreakData, Notification, notification_reason_types, @@ -542,6 +543,12 @@ export const createBetFillNotification = async ( sourceContractTitle: contract.question, sourceContractSlug: contract.slug, sourceContractId: contract.id, + data: { + betOutcome: bet.outcome, + creatorOutcome: userBet.outcome, + fillAmount, + probability: userBet.limitProb, + } as BetFillData, } return await notificationRef.set(removeUndefinedProps(notification)) diff --git a/functions/src/scripts/backfill-contract-followers.ts b/functions/src/scripts/backfill-contract-followers.ts index 9b936654..9b5834bc 100644 --- a/functions/src/scripts/backfill-contract-followers.ts +++ b/functions/src/scripts/backfill-contract-followers.ts @@ -4,14 +4,14 @@ import { initAdmin } from './script-init' initAdmin() import { getValues } from '../utils' -import { Contract } from 'common/lib/contract' -import { Comment } from 'common/lib/comment' +import { Contract } from 'common/contract' +import { Comment } from 'common/comment' import { uniq } from 'lodash' -import { Bet } from 'common/lib/bet' +import { Bet } from 'common/bet' import { DEV_HOUSE_LIQUIDITY_PROVIDER_ID, HOUSE_LIQUIDITY_PROVIDER_ID, -} from 'common/lib/antes' +} from 'common/antes' const firestore = admin.firestore() diff --git a/web/pages/notifications.tsx b/web/pages/notifications.tsx index 008f5df1..bc5e8cc6 100644 --- a/web/pages/notifications.tsx +++ b/web/pages/notifications.tsx @@ -1,7 +1,11 @@ import { ControlledTabs } from 'web/components/layout/tabs' import React, { useEffect, useMemo, useState } from 'react' import Router, { useRouter } from 'next/router' -import { Notification, notification_source_types } from 'common/notification' +import { + BetFillData, + Notification, + notification_source_types, +} from 'common/notification' import { Avatar, EmptyAvatar } from 'web/components/avatar' import { Row } from 'web/components/layout/row' import { Page } from 'web/components/page' @@ -141,6 +145,7 @@ function RenderNotificationGroups(props: { <NotificationItem notification={notification.notifications[0]} key={notification.notifications[0].id} + justSummary={false} /> ) : ( <NotificationGroupItem @@ -697,20 +702,11 @@ function NotificationGroupItem(props: { function NotificationItem(props: { notification: Notification - justSummary?: boolean + justSummary: boolean isChildOfGroup?: boolean }) { const { notification, justSummary, isChildOfGroup } = props - const { - sourceType, - sourceUserName, - sourceUserAvatarUrl, - sourceUpdateType, - reasonText, - reason, - sourceUserUsername, - sourceText, - } = notification + const { sourceType, reason } = notification const [highlighted] = useState(!notification.isSeen) @@ -718,39 +714,103 @@ function NotificationItem(props: { setNotificationsAsSeen([notification]) }, [notification]) - const questionNeedsResolution = sourceUpdateType == 'closed' + // TODO Any new notification should be its own component + if (reason === 'bet_fill') { + return ( + <BetFillNotification + notification={notification} + isChildOfGroup={isChildOfGroup} + highlighted={highlighted} + justSummary={justSummary} + /> + ) + } + // TODO Add new notification components here if (justSummary) { return ( - <Row className={'items-center text-sm text-gray-500 sm:justify-start'}> - <div className={'line-clamp-1 flex-1 overflow-hidden sm:flex'}> - <div className={'flex pl-1 sm:pl-0'}> - <UserLink - name={sourceUserName || ''} - username={sourceUserUsername || ''} - className={'mr-0 flex-shrink-0'} - short={true} - /> - <div className={'inline-flex overflow-hidden text-ellipsis pl-1'}> - <span className={'flex-shrink-0'}> - {sourceType && - reason && - getReasonForShowingNotification(notification, true)} - </span> - <div className={'ml-1 text-black'}> - <NotificationTextLabel - className={'line-clamp-1'} - notification={notification} - justSummary={true} - /> - </div> - </div> - </div> - </div> - </Row> + <NotificationSummaryFrame + notification={notification} + subtitle={ + (sourceType && + reason && + getReasonForShowingNotification(notification, true)) ?? + '' + } + > + <NotificationTextLabel + className={'line-clamp-1'} + notification={notification} + justSummary={true} + /> + </NotificationSummaryFrame> ) } + return ( + <NotificationFrame + notification={notification} + subtitle={getReasonForShowingNotification( + notification, + isChildOfGroup ?? false + )} + highlighted={highlighted} + > + <div className={'mt-1 ml-1 md:text-base'}> + <NotificationTextLabel notification={notification} /> + </div> + </NotificationFrame> + ) +} + +function NotificationSummaryFrame(props: { + notification: Notification + subtitle: string + children: React.ReactNode +}) { + const { notification, subtitle, children } = props + const { sourceUserName, sourceUserUsername } = notification + return ( + <Row className={'items-center text-sm text-gray-500 sm:justify-start'}> + <div className={'line-clamp-1 flex-1 overflow-hidden sm:flex'}> + <div className={'flex pl-1 sm:pl-0'}> + <UserLink + name={sourceUserName || ''} + username={sourceUserUsername || ''} + className={'mr-0 flex-shrink-0'} + short={true} + /> + <div className={'inline-flex overflow-hidden text-ellipsis pl-1'}> + <span className={'flex-shrink-0'}>{subtitle}</span> + <div className={'line-clamp-1 ml-1 text-black'}>{children}</div> + </div> + </div> + </div> + </Row> + ) +} + +function NotificationFrame(props: { + notification: Notification + highlighted: boolean + subtitle: string + children: React.ReactNode + isChildOfGroup?: boolean +}) { + const { notification, isChildOfGroup, highlighted, subtitle, children } = + props + const { + sourceType, + sourceUserName, + sourceUserAvatarUrl, + sourceUpdateType, + reason, + reasonText, + sourceUserUsername, + sourceText, + } = notification + const questionNeedsResolution = sourceUpdateType == 'closed' + return ( <div className={clsx( @@ -796,18 +856,13 @@ function NotificationItem(props: { } > <div> - {!questionNeedsResolution && ( - <UserLink - name={sourceUserName || ''} - username={sourceUserUsername || ''} - className={'relative mr-1 flex-shrink-0'} - short={true} - /> - )} - {getReasonForShowingNotification( - notification, - isChildOfGroup ?? false - )} + <UserLink + name={sourceUserName || ''} + username={sourceUserUsername || ''} + className={'relative mr-1 flex-shrink-0'} + short={true} + /> + {subtitle} {isChildOfGroup ? ( <RelativeTimestamp time={notification.createdTime} /> ) : ( @@ -822,9 +877,7 @@ function NotificationItem(props: { )} </div> </Row> - <div className={'mt-1 ml-1 md:text-base'}> - <NotificationTextLabel notification={notification} /> - </div> + <div className={'mt-1 ml-1 md:text-base'}>{children}</div> <div className={'mt-6 border-b border-gray-300'} /> </div> @@ -832,6 +885,66 @@ function NotificationItem(props: { ) } +function BetFillNotification(props: { + notification: Notification + highlighted: boolean + justSummary: boolean + isChildOfGroup?: boolean +}) { + const { notification, isChildOfGroup, highlighted, justSummary } = props + const { sourceText, data } = notification + const { creatorOutcome, probability } = (data as BetFillData) ?? {} + const subtitle = 'bet against you' + const amount = formatMoney(parseInt(sourceText ?? '0')) + const description = + creatorOutcome && probability ? ( + <span> + of your{' '} + <span + className={ + creatorOutcome === 'YES' + ? 'text-primary' + : creatorOutcome === 'NO' + ? 'text-red-500' + : 'text-blue-500' + } + > + {creatorOutcome}{' '} + </span> + limit order at {Math.round(probability * 100)}% was filled + </span> + ) : ( + <span>of your limit order was filled</span> + ) + + if (justSummary) { + return ( + <NotificationSummaryFrame notification={notification} subtitle={subtitle}> + <Row className={'line-clamp-1'}> + <span className={'text-primary mr-1'}>{amount}</span> + <span>{description}</span> + </Row> + </NotificationSummaryFrame> + ) + } + + return ( + <NotificationFrame + notification={notification} + isChildOfGroup={isChildOfGroup} + highlighted={highlighted} + subtitle={subtitle} + > + <Row> + <span> + <span className="text-primary mr-1">{amount}</span> + {description} + </span> + </Row> + </NotificationFrame> + ) +} + export const setNotificationsAsSeen = async (notifications: Notification[]) => { const unseenNotifications = notifications.filter((n) => !n.isSeen) return await Promise.all( @@ -1002,15 +1115,6 @@ function NotificationTextLabel(props: { return ( <span className="text-blue-400">{formatMoney(parseInt(sourceText))}</span> ) - } else if (sourceType === 'bet' && sourceText) { - return ( - <> - <span className="text-primary"> - {formatMoney(parseInt(sourceText))} - </span>{' '} - <span>of your limit order was filled</span> - </> - ) } else if (sourceType === 'challenge' && sourceText) { return ( <> @@ -1074,9 +1178,6 @@ function getReasonForShowingNotification( else if (sourceSlug) reasonText = 'joined because you shared' else reasonText = 'joined because of you' break - case 'bet': - reasonText = 'bet against you' - break case 'challenge': reasonText = 'accepted your challenge' break From 1476f669d3b08f55632336570fdcadc068068c55 Mon Sep 17 00:00:00 2001 From: Austin Chen <akrolsmir@gmail.com> Date: Thu, 15 Sep 2022 13:45:49 -0700 Subject: [PATCH 20/42] Fix capitalization --- web/pages/stats.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/web/pages/stats.tsx b/web/pages/stats.tsx index 057d47ef..08fb5498 100644 --- a/web/pages/stats.tsx +++ b/web/pages/stats.tsx @@ -14,6 +14,7 @@ import { Linkify } from 'web/components/linkify' import { getStats } from 'web/lib/firebase/stats' import { Stats } from 'common/stats' import { PAST_BETS } from 'common/user' +import { capitalize } from 'lodash' export default function Analytics() { const [stats, setStats] = useState<Stats | undefined>(undefined) @@ -157,7 +158,7 @@ export function CustomAnalytics(props: { defaultIndex={0} tabs={[ { - title: PAST_BETS, + title: capitalize(PAST_BETS), content: ( <DailyCountChart dailyCounts={dailyBetCounts} From b903183fff9f8c00a0f372ccb2ca05141250a184 Mon Sep 17 00:00:00 2001 From: Marshall Polaris <marshall@pol.rs> Date: Thu, 15 Sep 2022 13:47:07 -0700 Subject: [PATCH 21/42] Paginate contract bets tab (#881) * Apply pagination to bets list on contract * Make contract trades tab number actually match number of entries --- web/components/contract/contract-tabs.tsx | 16 ++++++++-- web/components/feed/contract-activity.tsx | 39 ++++++++++++++++------- web/components/feed/feed-liquidity.tsx | 13 +------- 3 files changed, 42 insertions(+), 26 deletions(-) diff --git a/web/components/contract/contract-tabs.tsx b/web/components/contract/contract-tabs.tsx index 0796dcb2..e4b95d97 100644 --- a/web/components/contract/contract-tabs.tsx +++ b/web/components/contract/contract-tabs.tsx @@ -19,6 +19,10 @@ import { BetSignUpPrompt } from '../sign-up-prompt' import { PlayMoneyDisclaimer } from '../play-money-disclaimer' import BetButton from '../bet-button' import { capitalize } from 'lodash' +import { + DEV_HOUSE_LIQUIDITY_PROVIDER_ID, + HOUSE_LIQUIDITY_PROVIDER_ID, +} from 'common/antes' export function ContractTabs(props: { contract: Contract @@ -37,13 +41,19 @@ export function ContractTabs(props: { const visibleBets = bets.filter( (bet) => !bet.isAnte && !bet.isRedemption && bet.amount !== 0 ) - const visibleLps = lps?.filter((l) => !l.isAnte && l.amount > 0) + const visibleLps = (lps ?? []).filter( + (l) => + !l.isAnte && + l.userId !== HOUSE_LIQUIDITY_PROVIDER_ID && + l.userId !== DEV_HOUSE_LIQUIDITY_PROVIDER_ID && + l.amount > 0 + ) // Load comments here, so the badge count will be correct const updatedComments = useComments(contract.id) const comments = updatedComments ?? props.comments - const betActivity = visibleLps && ( + const betActivity = lps != null && ( <ContractBetsActivity contract={contract} bets={visibleBets} @@ -117,7 +127,7 @@ export function ContractTabs(props: { { title: capitalize(PAST_BETS), content: betActivity, - badge: `${visibleBets.length}`, + badge: `${visibleBets.length + visibleLps.length}`, }, ...(!user || !userBets?.length ? [] diff --git a/web/components/feed/contract-activity.tsx b/web/components/feed/contract-activity.tsx index 55b8a958..b8a003fa 100644 --- a/web/components/feed/contract-activity.tsx +++ b/web/components/feed/contract-activity.tsx @@ -1,8 +1,10 @@ +import { useState } from 'react' import { Contract, FreeResponseContract } from 'common/contract' import { ContractComment } from 'common/comment' import { Answer } from 'common/answer' import { Bet } from 'common/bet' import { getOutcomeProbability } from 'common/calculate' +import { Pagination } from 'web/components/pagination' import { FeedBet } from './feed-bets' import { FeedLiquidity } from './feed-liquidity' import { FeedAnswerCommentGroup } from './feed-answer-comment-group' @@ -19,6 +21,10 @@ export function ContractBetsActivity(props: { lps: LiquidityProvision[] }) { const { contract, bets, lps } = props + const [page, setPage] = useState(0) + const ITEMS_PER_PAGE = 50 + const start = page * ITEMS_PER_PAGE + const end = start + ITEMS_PER_PAGE const items = [ ...bets.map((bet) => ({ @@ -33,24 +39,35 @@ export function ContractBetsActivity(props: { })), ] - const sortedItems = sortBy(items, (item) => + const pageItems = sortBy(items, (item) => item.type === 'bet' ? -item.bet.createdTime : item.type === 'liquidity' ? -item.lp.createdTime : undefined - ) + ).slice(start, end) return ( - <Col className="gap-4"> - {sortedItems.map((item) => - item.type === 'bet' ? ( - <FeedBet key={item.id} contract={contract} bet={item.bet} /> - ) : ( - <FeedLiquidity key={item.id} liquidity={item.lp} /> - ) - )} - </Col> + <> + <Col className="mb-4 gap-4"> + {pageItems.map((item) => + item.type === 'bet' ? ( + <FeedBet key={item.id} contract={contract} bet={item.bet} /> + ) : ( + <FeedLiquidity key={item.id} liquidity={item.lp} /> + ) + )} + </Col> + <Pagination + page={page} + itemsPerPage={50} + totalItems={items.length} + setPage={setPage} + scrollToTop + nextTitle={'Older'} + prevTitle={'Newer'} + /> + </> ) } diff --git a/web/components/feed/feed-liquidity.tsx b/web/components/feed/feed-liquidity.tsx index 181eb4b7..f4870a4e 100644 --- a/web/components/feed/feed-liquidity.tsx +++ b/web/components/feed/feed-liquidity.tsx @@ -9,17 +9,13 @@ import { RelativeTimestamp } from 'web/components/relative-timestamp' import React from 'react' import { LiquidityProvision } from 'common/liquidity-provision' import { UserLink } from 'web/components/user-link' -import { - DEV_HOUSE_LIQUIDITY_PROVIDER_ID, - HOUSE_LIQUIDITY_PROVIDER_ID, -} from 'common/antes' export function FeedLiquidity(props: { className?: string liquidity: LiquidityProvision }) { const { liquidity } = props - const { userId, createdTime, isAnte } = liquidity + const { userId, createdTime } = liquidity const isBeforeJune2022 = dayjs(createdTime).isBefore('2022-06-01') // eslint-disable-next-line react-hooks/rules-of-hooks @@ -28,13 +24,6 @@ export function FeedLiquidity(props: { const user = useUser() const isSelf = user?.id === userId - if ( - isAnte || - userId === HOUSE_LIQUIDITY_PROVIDER_ID || - userId === DEV_HOUSE_LIQUIDITY_PROVIDER_ID - ) - return <></> - return ( <Row className="items-center gap-2 pt-3"> {isSelf ? ( From 7628713c4b43a99992b9184be6346d0b21df8b39 Mon Sep 17 00:00:00 2001 From: Ian Philips <iansphilips@gmail.com> Date: Thu, 15 Sep 2022 15:25:19 -0600 Subject: [PATCH 22/42] Enrich contract resolved notification --- common/follow.ts | 5 + common/notification.ts | 6 + common/user-notification-preferences.ts | 1 + functions/src/create-notification.ts | 168 +++++++++++++++++++----- functions/src/resolve-market.ts | 32 +---- functions/src/utils.ts | 2 +- web/pages/notifications.tsx | 117 +++++++++++++---- 7 files changed, 243 insertions(+), 88 deletions(-) diff --git a/common/follow.ts b/common/follow.ts index 04ca6899..7ff6e7f2 100644 --- a/common/follow.ts +++ b/common/follow.ts @@ -2,3 +2,8 @@ export type Follow = { userId: string timestamp: number } + +export type ContractFollow = { + id: string // user id + createdTime: number +} diff --git a/common/notification.ts b/common/notification.ts index 2f03467d..804ec68e 100644 --- a/common/notification.ts +++ b/common/notification.ts @@ -248,3 +248,9 @@ export type BetFillData = { probability: number fillAmount: number } + +export type ContractResolutionData = { + outcome: string + userPayout: number + userInvestment: number +} diff --git a/common/user-notification-preferences.ts b/common/user-notification-preferences.ts index e2402ea9..f585f373 100644 --- a/common/user-notification-preferences.ts +++ b/common/user-notification-preferences.ts @@ -218,6 +218,7 @@ const notificationReasonToSubscriptionType: Partial< export const getNotificationDestinationsForUser = ( privateUser: PrivateUser, + // TODO: accept reasons array from most to least important and work backwards reason: notification_reason_types | notification_preference ) => { const notificationSettings = privateUser.notificationPreferences diff --git a/functions/src/create-notification.ts b/functions/src/create-notification.ts index 390a8cd8..ebd3f26c 100644 --- a/functions/src/create-notification.ts +++ b/functions/src/create-notification.ts @@ -2,6 +2,7 @@ import * as admin from 'firebase-admin' import { BetFillData, BettingStreakData, + ContractResolutionData, Notification, notification_reason_types, } from '../../common/notification' @@ -28,6 +29,7 @@ import { } from './emails' import { filterDefined } from '../../common/util/array' import { getNotificationDestinationsForUser } from '../../common/user-notification-preferences' +import { ContractFollow } from '../../common/follow' const firestore = admin.firestore() type recipients_to_reason_texts = { @@ -159,7 +161,7 @@ export type replied_users_info = { export const createCommentOrAnswerOrUpdatedContractNotification = async ( sourceId: string, sourceType: 'comment' | 'answer' | 'contract', - sourceUpdateType: 'created' | 'updated' | 'resolved', + sourceUpdateType: 'created' | 'updated', sourceUser: User, idempotencyKey: string, sourceText: string, @@ -167,17 +169,6 @@ export const createCommentOrAnswerOrUpdatedContractNotification = async ( miscData?: { repliedUsersInfo: replied_users_info taggedUserIds: string[] - }, - resolutionData?: { - bets: Bet[] - userInvestments: { [userId: string]: number } - userPayouts: { [userId: string]: number } - creator: User - creatorPayout: number - contract: Contract - outcome: string - resolutionProbability?: number - resolutions?: { [outcome: string]: number } } ) => { const { repliedUsersInfo, taggedUserIds } = miscData ?? {} @@ -230,11 +221,7 @@ export const createCommentOrAnswerOrUpdatedContractNotification = async ( userId: string, reason: notification_reason_types ) => { - if ( - !stillFollowingContract(sourceContract.creatorId) || - sourceUser.id == userId - ) - return + if (!stillFollowingContract(userId) || sourceUser.id == userId) return const privateUser = await getPrivateUser(userId) if (!privateUser) return const { sendToBrowser, sendToEmail } = getNotificationDestinationsForUser( @@ -276,24 +263,6 @@ export const createCommentOrAnswerOrUpdatedContractNotification = async ( sourceUser.avatarUrl ) emailRecipientIdsList.push(userId) - } else if ( - sourceType === 'contract' && - sourceUpdateType === 'resolved' && - resolutionData - ) { - await sendMarketResolutionEmail( - reason, - privateUser, - resolutionData.userInvestments[userId] ?? 0, - resolutionData.userPayouts[userId] ?? 0, - sourceUser, - resolutionData.creatorPayout, - sourceContract, - resolutionData.outcome, - resolutionData.resolutionProbability, - resolutionData.resolutions - ) - emailRecipientIdsList.push(userId) } } @@ -447,6 +416,8 @@ export const createCommentOrAnswerOrUpdatedContractNotification = async ( ) } + //TODO: store all possible reasons why the user might be getting the notification and choose the most lenient that they + // have enabled so they will unsubscribe from the least important notifications await notifyRepliedUser() await notifyTaggedUsers() await notifyContractCreator() @@ -943,3 +914,130 @@ export const createNewContractNotification = async ( await sendNotificationsIfSettingsAllow(mentionedUserId, 'tagged_user') } } + +export const createContractResolvedNotifications = async ( + contract: Contract, + creator: User, + outcome: string, + probabilityInt: number | undefined, + resolutionValue: number | undefined, + resolutionData: { + bets: Bet[] + userInvestments: { [userId: string]: number } + userPayouts: { [userId: string]: number } + creator: User + creatorPayout: number + contract: Contract + outcome: string + resolutionProbability?: number + resolutions?: { [outcome: string]: number } + } +) => { + let resolutionText = outcome ?? contract.question + if ( + contract.outcomeType === 'FREE_RESPONSE' || + contract.outcomeType === 'MULTIPLE_CHOICE' + ) { + const answerText = contract.answers.find( + (answer) => answer.id === outcome + )?.text + if (answerText) resolutionText = answerText + } else if (contract.outcomeType === 'BINARY') { + if (resolutionText === 'MKT' && probabilityInt) + resolutionText = `${probabilityInt}%` + else if (resolutionText === 'MKT') resolutionText = 'PROB' + } else if (contract.outcomeType === 'PSEUDO_NUMERIC') { + if (resolutionText === 'MKT' && resolutionValue) + resolutionText = `${resolutionValue}` + } + + const idempotencyKey = contract.id + '-resolved' + const createBrowserNotification = async ( + userId: string, + reason: notification_reason_types + ) => { + const notificationRef = firestore + .collection(`/users/${userId}/notifications`) + .doc(idempotencyKey) + const notification: Notification = { + id: idempotencyKey, + userId, + reason, + createdTime: Date.now(), + isSeen: false, + sourceId: contract.id, + sourceType: 'contract', + sourceUpdateType: 'resolved', + sourceContractId: contract.id, + sourceUserName: creator.name, + sourceUserUsername: creator.username, + sourceUserAvatarUrl: creator.avatarUrl, + sourceText: resolutionText, + sourceContractCreatorUsername: contract.creatorUsername, + sourceContractTitle: contract.question, + sourceContractSlug: contract.slug, + sourceSlug: contract.slug, + sourceTitle: contract.question, + data: { + outcome, + userInvestment: resolutionData.userInvestments[userId] ?? 0, + userPayout: resolutionData.userPayouts[userId] ?? 0, + } as ContractResolutionData, + } + return await notificationRef.set(removeUndefinedProps(notification)) + } + + const sendNotificationsIfSettingsPermit = async ( + userId: string, + reason: notification_reason_types + ) => { + if (!stillFollowingContract(userId) || creator.id == userId) return + const privateUser = await getPrivateUser(userId) + if (!privateUser) return + const { sendToBrowser, sendToEmail } = getNotificationDestinationsForUser( + privateUser, + reason + ) + + // Browser notifications + if (sendToBrowser) { + await createBrowserNotification(userId, reason) + } + + // Emails notifications + if (sendToEmail) + await sendMarketResolutionEmail( + reason, + privateUser, + resolutionData.userInvestments[userId] ?? 0, + resolutionData.userPayouts[userId] ?? 0, + creator, + resolutionData.creatorPayout, + contract, + resolutionData.outcome, + resolutionData.resolutionProbability, + resolutionData.resolutions + ) + } + + const contractFollowersIds = ( + await getValues<ContractFollow>( + firestore.collection(`contracts/${contract.id}/follows`) + ) + ).map((follow) => follow.id) + + const stillFollowingContract = (userId: string) => { + return contractFollowersIds.includes(userId) + } + + await Promise.all( + contractFollowersIds.map((id) => + sendNotificationsIfSettingsPermit( + id, + resolutionData.userInvestments[id] + ? 'resolution_on_contract_with_users_shares_in' + : 'resolution_on_contract_you_follow' + ) + ) + ) +} diff --git a/functions/src/resolve-market.ts b/functions/src/resolve-market.ts index b99b5c87..feddd67c 100644 --- a/functions/src/resolve-market.ts +++ b/functions/src/resolve-market.ts @@ -21,7 +21,7 @@ import { removeUndefinedProps } from '../../common/util/object' import { LiquidityProvision } from '../../common/liquidity-provision' import { APIError, newEndpoint, validate } from './api' import { getContractBetMetrics } from '../../common/calculate' -import { createCommentOrAnswerOrUpdatedContractNotification } from './create-notification' +import { createContractResolvedNotifications } from './create-notification' import { CancelUniqueBettorBonusTxn, Txn } from '../../common/txn' import { runTxn, TxnData } from './transact' import { @@ -177,33 +177,13 @@ export const resolvemarket = newEndpoint(opts, async (req, auth) => { groupBy(bets, (bet) => bet.userId), (bets) => getContractBetMetrics(contract, bets).invested ) - let resolutionText = outcome ?? contract.question - if ( - contract.outcomeType === 'FREE_RESPONSE' || - contract.outcomeType === 'MULTIPLE_CHOICE' - ) { - const answerText = contract.answers.find( - (answer) => answer.id === outcome - )?.text - if (answerText) resolutionText = answerText - } else if (contract.outcomeType === 'BINARY') { - if (resolutionText === 'MKT' && probabilityInt) - resolutionText = `${probabilityInt}%` - else if (resolutionText === 'MKT') resolutionText = 'PROB' - } else if (contract.outcomeType === 'PSEUDO_NUMERIC') { - if (resolutionText === 'MKT' && value) resolutionText = `${value}` - } - // TODO: this actually may be too slow to complete with a ton of users to notify? - await createCommentOrAnswerOrUpdatedContractNotification( - contract.id, - 'contract', - 'resolved', - creator, - contract.id + '-resolution', - resolutionText, + await createContractResolvedNotifications( contract, - undefined, + creator, + outcome, + probabilityInt, + value, { bets, userInvestments, diff --git a/functions/src/utils.ts b/functions/src/utils.ts index a0878e4f..23f7257a 100644 --- a/functions/src/utils.ts +++ b/functions/src/utils.ts @@ -4,7 +4,7 @@ import { chunk } from 'lodash' import { Contract } from '../../common/contract' import { PrivateUser, User } from '../../common/user' import { Group } from '../../common/group' -import { Post } from 'common/post' +import { Post } from '../../common/post' export const log = (...args: unknown[]) => { console.log(`[${new Date().toISOString()}]`, ...args) diff --git a/web/pages/notifications.tsx b/web/pages/notifications.tsx index bc5e8cc6..14f14ea4 100644 --- a/web/pages/notifications.tsx +++ b/web/pages/notifications.tsx @@ -3,6 +3,7 @@ import React, { useEffect, useMemo, useState } from 'react' import Router, { useRouter } from 'next/router' import { BetFillData, + ContractResolutionData, Notification, notification_source_types, } from 'common/notification' @@ -706,7 +707,7 @@ function NotificationItem(props: { isChildOfGroup?: boolean }) { const { notification, justSummary, isChildOfGroup } = props - const { sourceType, reason } = notification + const { sourceType, reason, sourceUpdateType } = notification const [highlighted] = useState(!notification.isSeen) @@ -724,6 +725,15 @@ function NotificationItem(props: { justSummary={justSummary} /> ) + } else if (sourceType === 'contract' && sourceUpdateType === 'resolved') { + return ( + <ContractResolvedNotification + notification={notification} + isChildOfGroup={isChildOfGroup} + highlighted={highlighted} + justSummary={justSummary} + /> + ) } // TODO Add new notification components here @@ -810,7 +820,8 @@ function NotificationFrame(props: { sourceText, } = notification const questionNeedsResolution = sourceUpdateType == 'closed' - + const { width } = useWindowSize() + const isMobile = (width ?? 0) < 600 return ( <div className={clsx( @@ -860,7 +871,7 @@ function NotificationFrame(props: { name={sourceUserName || ''} username={sourceUserUsername || ''} className={'relative mr-1 flex-shrink-0'} - short={true} + short={isMobile} /> {subtitle} {isChildOfGroup ? ( @@ -945,6 +956,83 @@ function BetFillNotification(props: { ) } +function ContractResolvedNotification(props: { + notification: Notification + highlighted: boolean + justSummary: boolean + isChildOfGroup?: boolean +}) { + const { notification, isChildOfGroup, highlighted, justSummary } = props + const { sourceText, data } = notification + const { userInvestment, userPayout } = (data as ContractResolutionData) ?? {} + const subtitle = 'resolved the market' + const resolutionDescription = () => { + if (!sourceText) return <div /> + if (sourceText === 'YES' || sourceText == 'NO') { + return <BinaryOutcomeLabel outcome={sourceText as any} /> + } + if (sourceText.includes('%')) + return <ProbPercentLabel prob={parseFloat(sourceText.replace('%', ''))} /> + if (sourceText === 'CANCEL') return <CancelLabel /> + if (sourceText === 'MKT' || sourceText === 'PROB') return <MultiLabel /> + + // Numeric market + if (parseFloat(sourceText)) + return <NumericValueLabel value={parseFloat(sourceText)} /> + + // Free response market + return ( + <div className={'line-clamp-1 text-blue-400'}> + <Linkify text={sourceText} /> + </div> + ) + } + + const description = + userInvestment && userPayout ? ( + <Row className={'gap-1 '}> + {resolutionDescription()} + Invested: + <span className={'text-primary'}>{formatMoney(userInvestment)} </span> + Payout: + <span + className={clsx( + userPayout > 0 ? 'text-primary' : 'text-red-500', + 'truncate' + )} + > + {formatMoney(userPayout)} + {` (${userPayout > 0 ? '+' : '-'}${Math.round( + ((userPayout - userInvestment) / userInvestment) * 100 + )}%)`} + </span> + </Row> + ) : ( + <span>{resolutionDescription()}</span> + ) + + if (justSummary) { + return ( + <NotificationSummaryFrame notification={notification} subtitle={subtitle}> + <Row className={'line-clamp-1'}>{description}</Row> + </NotificationSummaryFrame> + ) + } + + return ( + <NotificationFrame + notification={notification} + isChildOfGroup={isChildOfGroup} + highlighted={highlighted} + subtitle={subtitle} + > + <Row> + <span>{description}</span> + </Row> + </NotificationFrame> + ) +} + export const setNotificationsAsSeen = async (notifications: Notification[]) => { const unseenNotifications = notifications.filter((n) => !n.isSeen) return await Promise.all( @@ -1064,30 +1152,7 @@ function NotificationTextLabel(props: { if (sourceType === 'contract') { if (justSummary || !sourceText) return <div /> // Resolved contracts - if (sourceType === 'contract' && sourceUpdateType === 'resolved') { - { - if (sourceText === 'YES' || sourceText == 'NO') { - return <BinaryOutcomeLabel outcome={sourceText as any} /> - } - if (sourceText.includes('%')) - return ( - <ProbPercentLabel prob={parseFloat(sourceText.replace('%', ''))} /> - ) - if (sourceText === 'CANCEL') return <CancelLabel /> - if (sourceText === 'MKT' || sourceText === 'PROB') return <MultiLabel /> - // Numeric market - if (parseFloat(sourceText)) - return <NumericValueLabel value={parseFloat(sourceText)} /> - - // Free response market - return ( - <div className={className ? className : 'line-clamp-1 text-blue-400'}> - <Linkify text={sourceText} /> - </div> - ) - } - } // Close date will be a number - it looks better without it if (sourceUpdateType === 'closed') { return <div /> From 61c672ce4c959f26451158219086b98faccc2f39 Mon Sep 17 00:00:00 2001 From: Ian Philips <iansphilips@gmail.com> Date: Thu, 15 Sep 2022 15:50:26 -0600 Subject: [PATCH 23/42] Show negative payouts --- web/pages/notifications.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/web/pages/notifications.tsx b/web/pages/notifications.tsx index 14f14ea4..a0c1ede5 100644 --- a/web/pages/notifications.tsx +++ b/web/pages/notifications.tsx @@ -989,7 +989,7 @@ function ContractResolvedNotification(props: { } const description = - userInvestment && userPayout ? ( + userInvestment && userPayout !== undefined ? ( <Row className={'gap-1 '}> {resolutionDescription()} Invested: @@ -1002,7 +1002,7 @@ function ContractResolvedNotification(props: { )} > {formatMoney(userPayout)} - {` (${userPayout > 0 ? '+' : '-'}${Math.round( + {` (${userPayout > 0 ? '+' : ''}${Math.round( ((userPayout - userInvestment) / userInvestment) * 100 )}%)`} </span> From 3362b2f953639a74621ae2d06c19d4f51dea6de1 Mon Sep 17 00:00:00 2001 From: Ian Philips <iansphilips@gmail.com> Date: Thu, 15 Sep 2022 15:51:39 -0600 Subject: [PATCH 24/42] Capitalize --- web/components/contract/contract-info-dialog.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/web/components/contract/contract-info-dialog.tsx b/web/components/contract/contract-info-dialog.tsx index 9027d38a..76a48277 100644 --- a/web/components/contract/contract-info-dialog.tsx +++ b/web/components/contract/contract-info-dialog.tsx @@ -19,6 +19,7 @@ import ShortToggle from '../widgets/short-toggle' import { DuplicateContractButton } from '../copy-contract-button' import { Row } from '../layout/row' import { BETTORS } from 'common/user' +import { capitalize } from 'lodash' export const contractDetailsButtonClassName = 'group flex items-center rounded-md px-3 py-2 text-sm font-medium cursor-pointer hover:bg-gray-100 text-gray-400 hover:text-gray-500' @@ -136,7 +137,7 @@ export function ContractInfoDialog(props: { </tr> */} <tr> - <td>{BETTORS}</td> + <td>{capitalize(BETTORS)}</td> <td>{bettorsCount}</td> </tr> From e9fcf5a352626b293c281fa49275154c4918b7fb Mon Sep 17 00:00:00 2001 From: Ian Philips <iansphilips@gmail.com> Date: Thu, 15 Sep 2022 16:12:05 -0600 Subject: [PATCH 25/42] Space --- web/components/user-page.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/components/user-page.tsx b/web/components/user-page.tsx index 8dc7928a..2b24fa60 100644 --- a/web/components/user-page.tsx +++ b/web/components/user-page.tsx @@ -242,7 +242,7 @@ export function UserPage(props: { user: User }) { <SiteLink href="/referrals"> Earn {formatMoney(REFERRAL_AMOUNT)} when you refer a friend! </SiteLink>{' '} - You've gotten + You've gotten{' '} <ReferralsButton user={user} currentUser={currentUser} /> </span> <ShareIconButton From 140628692f9e09b6f2e582b31f88974dac581524 Mon Sep 17 00:00:00 2001 From: Austin Chen <akrolsmir@gmail.com> Date: Thu, 15 Sep 2022 15:12:26 -0700 Subject: [PATCH 26/42] Use %mention to embed a contract card in rich text editor (#869) * Bring up a list of contracts with @ * Fix hot reload for RichContent * Render contracts as half-size cards * Use % as the prompt; allow for spaces * WIP: When there's no matching question, create a new contract * Revert "WIP: When there's no matching question, create a new contract" This reverts commit efae1bf715dfe02b88169d181a22d6f0fe7ad480. * Rename to contract-mention * WIP: Try to merge in @ and % side by side * Add a different pluginKey * Track the prosemirror-state dep --- web/components/editor.tsx | 19 ++++- .../editor/contract-mention-list.tsx | 68 +++++++++++++++++ .../editor/contract-mention-suggestion.ts | 76 +++++++++++++++++++ web/components/editor/contract-mention.tsx | 41 ++++++++++ web/hooks/use-contracts.ts | 9 ++- web/package.json | 1 + 6 files changed, 211 insertions(+), 3 deletions(-) create mode 100644 web/components/editor/contract-mention-list.tsx create mode 100644 web/components/editor/contract-mention-suggestion.ts create mode 100644 web/components/editor/contract-mention.tsx diff --git a/web/components/editor.tsx b/web/components/editor.tsx index 745fc3c5..95f18b3f 100644 --- a/web/components/editor.tsx +++ b/web/components/editor.tsx @@ -21,6 +21,8 @@ import { FileUploadButton } from './file-upload-button' import { linkClass } from './site-link' import { mentionSuggestion } from './editor/mention-suggestion' import { DisplayMention } from './editor/mention' +import { contractMentionSuggestion } from './editor/contract-mention-suggestion' +import { DisplayContractMention } from './editor/contract-mention' import Iframe from 'common/util/tiptap-iframe' import TiptapTweet from './editor/tiptap-tweet' import { EmbedModal } from './editor/embed-modal' @@ -97,7 +99,12 @@ export function useTextEditor(props: { CharacterCount.configure({ limit: max }), simple ? DisplayImage : Image, DisplayLink, - DisplayMention.configure({ suggestion: mentionSuggestion }), + DisplayMention.configure({ + suggestion: mentionSuggestion, + }), + DisplayContractMention.configure({ + suggestion: contractMentionSuggestion, + }), Iframe, TiptapTweet, ], @@ -316,13 +323,21 @@ export function RichContent(props: { smallImage ? DisplayImage : Image, DisplayLink.configure({ openOnClick: false }), // stop link opening twice (browser still opens) DisplayMention, + DisplayContractMention.configure({ + // Needed to set a different PluginKey for Prosemirror + suggestion: contractMentionSuggestion, + }), Iframe, TiptapTweet, ], content, editable: false, }) - useEffect(() => void editor?.commands?.setContent(content), [editor, content]) + useEffect( + // Check isDestroyed here so hot reload works, see https://github.com/ueberdosis/tiptap/issues/1451#issuecomment-941988769 + () => void !editor?.isDestroyed && editor?.commands?.setContent(content), + [editor, content] + ) return <EditorContent className={className} editor={editor} /> } diff --git a/web/components/editor/contract-mention-list.tsx b/web/components/editor/contract-mention-list.tsx new file mode 100644 index 00000000..bda9d2fc --- /dev/null +++ b/web/components/editor/contract-mention-list.tsx @@ -0,0 +1,68 @@ +import { SuggestionProps } from '@tiptap/suggestion' +import clsx from 'clsx' +import { Contract } from 'common/contract' +import { forwardRef, useEffect, useImperativeHandle, useState } from 'react' +import { contractPath } from 'web/lib/firebase/contracts' +import { Avatar } from '../avatar' + +// copied from https://tiptap.dev/api/nodes/mention#usage +const M = forwardRef((props: SuggestionProps<Contract>, ref) => { + const { items: contracts, command } = props + + const [selectedIndex, setSelectedIndex] = useState(0) + useEffect(() => setSelectedIndex(0), [contracts]) + + const submitUser = (index: number) => { + const contract = contracts[index] + if (contract) + command({ id: contract.id, label: contractPath(contract) } as any) + } + + const onUp = () => + setSelectedIndex((i) => (i + contracts.length - 1) % contracts.length) + const onDown = () => setSelectedIndex((i) => (i + 1) % contracts.length) + const onEnter = () => submitUser(selectedIndex) + + useImperativeHandle(ref, () => ({ + onKeyDown: ({ event }: any) => { + if (event.key === 'ArrowUp') { + onUp() + return true + } + if (event.key === 'ArrowDown') { + onDown() + return true + } + if (event.key === 'Enter') { + onEnter() + return true + } + return false + }, + })) + + return ( + <div className="w-42 absolute z-10 overflow-x-hidden rounded-md bg-white py-1 shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none"> + {!contracts.length ? ( + <span className="m-1 whitespace-nowrap">No results...</span> + ) : ( + contracts.map((contract, i) => ( + <button + className={clsx( + 'flex h-8 w-full cursor-pointer select-none items-center gap-2 truncate px-4 hover:bg-indigo-200', + selectedIndex === i ? 'bg-indigo-500 text-white' : 'text-gray-900' + )} + onClick={() => submitUser(i)} + key={contract.id} + > + <Avatar avatarUrl={contract.creatorAvatarUrl} size="xs" /> + {contract.question} + </button> + )) + )} + </div> + ) +}) + +// Just to keep the formatting pretty +export { M as MentionList } diff --git a/web/components/editor/contract-mention-suggestion.ts b/web/components/editor/contract-mention-suggestion.ts new file mode 100644 index 00000000..79525cfc --- /dev/null +++ b/web/components/editor/contract-mention-suggestion.ts @@ -0,0 +1,76 @@ +import type { MentionOptions } from '@tiptap/extension-mention' +import { ReactRenderer } from '@tiptap/react' +import { searchInAny } from 'common/util/parse' +import { orderBy } from 'lodash' +import tippy from 'tippy.js' +import { getCachedContracts } from 'web/hooks/use-contracts' +import { MentionList } from './contract-mention-list' +import { PluginKey } from 'prosemirror-state' + +type Suggestion = MentionOptions['suggestion'] + +const beginsWith = (text: string, query: string) => + text.toLocaleLowerCase().startsWith(query.toLocaleLowerCase()) + +// copied from https://tiptap.dev/api/nodes/mention#usage +// TODO: merge with mention-suggestion.ts? +export const contractMentionSuggestion: Suggestion = { + char: '%', + allowSpaces: true, + pluginKey: new PluginKey('contract-mention'), + items: async ({ query }) => + orderBy( + (await getCachedContracts()).filter((c) => + searchInAny(query, c.question) + ), + [(c) => [c.question].some((s) => beginsWith(s, query))], + ['desc', 'desc'] + ).slice(0, 5), + render: () => { + let component: ReactRenderer + let popup: ReturnType<typeof tippy> + return { + onStart: (props) => { + component = new ReactRenderer(MentionList, { + props, + editor: props.editor, + }) + if (!props.clientRect) { + return + } + + popup = tippy('body', { + getReferenceClientRect: props.clientRect as any, + appendTo: () => document.body, + content: component?.element, + showOnCreate: true, + interactive: true, + trigger: 'manual', + placement: 'bottom-start', + }) + }, + onUpdate(props) { + component?.updateProps(props) + + if (!props.clientRect) { + return + } + + popup?.[0].setProps({ + getReferenceClientRect: props.clientRect as any, + }) + }, + onKeyDown(props) { + if (props.event.key === 'Escape') { + popup?.[0].hide() + return true + } + return (component?.ref as any)?.onKeyDown(props) + }, + onExit() { + popup?.[0].destroy() + component?.destroy() + }, + } + }, +} diff --git a/web/components/editor/contract-mention.tsx b/web/components/editor/contract-mention.tsx new file mode 100644 index 00000000..9e967044 --- /dev/null +++ b/web/components/editor/contract-mention.tsx @@ -0,0 +1,41 @@ +import Mention from '@tiptap/extension-mention' +import { + mergeAttributes, + NodeViewWrapper, + ReactNodeViewRenderer, +} from '@tiptap/react' +import clsx from 'clsx' +import { useContract } from 'web/hooks/use-contract' +import { ContractCard } from '../contract/contract-card' + +const name = 'contract-mention-component' + +const ContractMentionComponent = (props: any) => { + const contract = useContract(props.node.attrs.id) + + return ( + <NodeViewWrapper className={clsx(name, 'not-prose')}> + {contract && ( + <ContractCard + contract={contract} + className="my-2 w-full border border-gray-100" + /> + )} + </NodeViewWrapper> + ) +} + +/** + * Mention extension that renders React. See: + * https://tiptap.dev/guide/custom-extensions#extend-existing-extensions + * https://tiptap.dev/guide/node-views/react#render-a-react-component + */ +export const DisplayContractMention = Mention.extend({ + parseHTML: () => [{ tag: name }], + renderHTML: ({ HTMLAttributes }) => [name, mergeAttributes(HTMLAttributes)], + addNodeView: () => + ReactNodeViewRenderer(ContractMentionComponent, { + // On desktop, render cards below half-width so you can stack two + className: 'inline-block sm:w-[calc(50%-1rem)] sm:mr-1', + }), +}) diff --git a/web/hooks/use-contracts.ts b/web/hooks/use-contracts.ts index 1ea2f232..87eefa38 100644 --- a/web/hooks/use-contracts.ts +++ b/web/hooks/use-contracts.ts @@ -9,8 +9,9 @@ import { listenForNewContracts, getUserBetContracts, getUserBetContractsQuery, + listAllContracts, } from 'web/lib/firebase/contracts' -import { useQueryClient } from 'react-query' +import { QueryClient, useQueryClient } from 'react-query' import { MINUTE_MS } from 'common/util/time' export const useContracts = () => { @@ -23,6 +24,12 @@ export const useContracts = () => { return contracts } +const q = new QueryClient() +export const getCachedContracts = async () => + q.fetchQuery(['contracts'], () => listAllContracts(1000), { + staleTime: Infinity, + }) + export const useActiveContracts = () => { const [activeContracts, setActiveContracts] = useState< Contract[] | undefined diff --git a/web/package.json b/web/package.json index 114ded1e..ba25a6e1 100644 --- a/web/package.json +++ b/web/package.json @@ -48,6 +48,7 @@ "nanoid": "^3.3.4", "next": "12.2.5", "node-fetch": "3.2.4", + "prosemirror-state": "1.4.1", "react": "17.0.2", "react-beautiful-dnd": "13.1.1", "react-confetti": "6.0.1", From ebbb8905e2653d69120adb864ad1fd5a2e0c99ab Mon Sep 17 00:00:00 2001 From: Sinclair Chen <abc.sinclair@gmail.com> Date: Thu, 15 Sep 2022 16:05:56 -0700 Subject: [PATCH 27/42] Add clearer thinking Regrant to tournaments (#883) --- web/pages/tournaments/index.tsx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/web/pages/tournaments/index.tsx b/web/pages/tournaments/index.tsx index e81c239f..8ce11284 100644 --- a/web/pages/tournaments/index.tsx +++ b/web/pages/tournaments/index.tsx @@ -76,6 +76,13 @@ const Salem = { } const tourneys: Tourney[] = [ + { + title: 'Clearer Thinking Regrant Project', + blurb: 'Which projects will Clearer Thinking give a grant to?', + award: '$13,000', + endTime: toDate('Sep 22, 2022'), + groupId: 'fhksfIgqyWf7OxsV9nkM', + }, { title: 'Manifold F2P Tournament', blurb: @@ -99,13 +106,6 @@ const tourneys: Tourney[] = [ endTime: toDate('Jan 6, 2023'), groupId: 'SxGRqXRpV3RAQKudbcNb', }, - // { - // title: 'Clearer Thinking Regrant Project', - // blurb: 'Something amazing', - // award: '$10,000', - // endTime: toDate('Sep 22, 2022'), - // groupId: '2VsVVFGhKtIdJnQRAXVb', - // }, // Tournaments without awards get featured belows { From e0634cea6d7c0a169829c04ed061f602b4fcfb1e Mon Sep 17 00:00:00 2001 From: James Grugett <jahooma@gmail.com> Date: Thu, 15 Sep 2022 18:19:22 -0500 Subject: [PATCH 28/42] Revert "Use %mention to embed a contract card in rich text editor (#869)" This reverts commit 140628692f9e09b6f2e582b31f88974dac581524. --- web/components/editor.tsx | 19 +---- .../editor/contract-mention-list.tsx | 68 ----------------- .../editor/contract-mention-suggestion.ts | 76 ------------------- web/components/editor/contract-mention.tsx | 41 ---------- web/hooks/use-contracts.ts | 9 +-- web/package.json | 1 - 6 files changed, 3 insertions(+), 211 deletions(-) delete mode 100644 web/components/editor/contract-mention-list.tsx delete mode 100644 web/components/editor/contract-mention-suggestion.ts delete mode 100644 web/components/editor/contract-mention.tsx diff --git a/web/components/editor.tsx b/web/components/editor.tsx index 95f18b3f..745fc3c5 100644 --- a/web/components/editor.tsx +++ b/web/components/editor.tsx @@ -21,8 +21,6 @@ import { FileUploadButton } from './file-upload-button' import { linkClass } from './site-link' import { mentionSuggestion } from './editor/mention-suggestion' import { DisplayMention } from './editor/mention' -import { contractMentionSuggestion } from './editor/contract-mention-suggestion' -import { DisplayContractMention } from './editor/contract-mention' import Iframe from 'common/util/tiptap-iframe' import TiptapTweet from './editor/tiptap-tweet' import { EmbedModal } from './editor/embed-modal' @@ -99,12 +97,7 @@ export function useTextEditor(props: { CharacterCount.configure({ limit: max }), simple ? DisplayImage : Image, DisplayLink, - DisplayMention.configure({ - suggestion: mentionSuggestion, - }), - DisplayContractMention.configure({ - suggestion: contractMentionSuggestion, - }), + DisplayMention.configure({ suggestion: mentionSuggestion }), Iframe, TiptapTweet, ], @@ -323,21 +316,13 @@ export function RichContent(props: { smallImage ? DisplayImage : Image, DisplayLink.configure({ openOnClick: false }), // stop link opening twice (browser still opens) DisplayMention, - DisplayContractMention.configure({ - // Needed to set a different PluginKey for Prosemirror - suggestion: contractMentionSuggestion, - }), Iframe, TiptapTweet, ], content, editable: false, }) - useEffect( - // Check isDestroyed here so hot reload works, see https://github.com/ueberdosis/tiptap/issues/1451#issuecomment-941988769 - () => void !editor?.isDestroyed && editor?.commands?.setContent(content), - [editor, content] - ) + useEffect(() => void editor?.commands?.setContent(content), [editor, content]) return <EditorContent className={className} editor={editor} /> } diff --git a/web/components/editor/contract-mention-list.tsx b/web/components/editor/contract-mention-list.tsx deleted file mode 100644 index bda9d2fc..00000000 --- a/web/components/editor/contract-mention-list.tsx +++ /dev/null @@ -1,68 +0,0 @@ -import { SuggestionProps } from '@tiptap/suggestion' -import clsx from 'clsx' -import { Contract } from 'common/contract' -import { forwardRef, useEffect, useImperativeHandle, useState } from 'react' -import { contractPath } from 'web/lib/firebase/contracts' -import { Avatar } from '../avatar' - -// copied from https://tiptap.dev/api/nodes/mention#usage -const M = forwardRef((props: SuggestionProps<Contract>, ref) => { - const { items: contracts, command } = props - - const [selectedIndex, setSelectedIndex] = useState(0) - useEffect(() => setSelectedIndex(0), [contracts]) - - const submitUser = (index: number) => { - const contract = contracts[index] - if (contract) - command({ id: contract.id, label: contractPath(contract) } as any) - } - - const onUp = () => - setSelectedIndex((i) => (i + contracts.length - 1) % contracts.length) - const onDown = () => setSelectedIndex((i) => (i + 1) % contracts.length) - const onEnter = () => submitUser(selectedIndex) - - useImperativeHandle(ref, () => ({ - onKeyDown: ({ event }: any) => { - if (event.key === 'ArrowUp') { - onUp() - return true - } - if (event.key === 'ArrowDown') { - onDown() - return true - } - if (event.key === 'Enter') { - onEnter() - return true - } - return false - }, - })) - - return ( - <div className="w-42 absolute z-10 overflow-x-hidden rounded-md bg-white py-1 shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none"> - {!contracts.length ? ( - <span className="m-1 whitespace-nowrap">No results...</span> - ) : ( - contracts.map((contract, i) => ( - <button - className={clsx( - 'flex h-8 w-full cursor-pointer select-none items-center gap-2 truncate px-4 hover:bg-indigo-200', - selectedIndex === i ? 'bg-indigo-500 text-white' : 'text-gray-900' - )} - onClick={() => submitUser(i)} - key={contract.id} - > - <Avatar avatarUrl={contract.creatorAvatarUrl} size="xs" /> - {contract.question} - </button> - )) - )} - </div> - ) -}) - -// Just to keep the formatting pretty -export { M as MentionList } diff --git a/web/components/editor/contract-mention-suggestion.ts b/web/components/editor/contract-mention-suggestion.ts deleted file mode 100644 index 79525cfc..00000000 --- a/web/components/editor/contract-mention-suggestion.ts +++ /dev/null @@ -1,76 +0,0 @@ -import type { MentionOptions } from '@tiptap/extension-mention' -import { ReactRenderer } from '@tiptap/react' -import { searchInAny } from 'common/util/parse' -import { orderBy } from 'lodash' -import tippy from 'tippy.js' -import { getCachedContracts } from 'web/hooks/use-contracts' -import { MentionList } from './contract-mention-list' -import { PluginKey } from 'prosemirror-state' - -type Suggestion = MentionOptions['suggestion'] - -const beginsWith = (text: string, query: string) => - text.toLocaleLowerCase().startsWith(query.toLocaleLowerCase()) - -// copied from https://tiptap.dev/api/nodes/mention#usage -// TODO: merge with mention-suggestion.ts? -export const contractMentionSuggestion: Suggestion = { - char: '%', - allowSpaces: true, - pluginKey: new PluginKey('contract-mention'), - items: async ({ query }) => - orderBy( - (await getCachedContracts()).filter((c) => - searchInAny(query, c.question) - ), - [(c) => [c.question].some((s) => beginsWith(s, query))], - ['desc', 'desc'] - ).slice(0, 5), - render: () => { - let component: ReactRenderer - let popup: ReturnType<typeof tippy> - return { - onStart: (props) => { - component = new ReactRenderer(MentionList, { - props, - editor: props.editor, - }) - if (!props.clientRect) { - return - } - - popup = tippy('body', { - getReferenceClientRect: props.clientRect as any, - appendTo: () => document.body, - content: component?.element, - showOnCreate: true, - interactive: true, - trigger: 'manual', - placement: 'bottom-start', - }) - }, - onUpdate(props) { - component?.updateProps(props) - - if (!props.clientRect) { - return - } - - popup?.[0].setProps({ - getReferenceClientRect: props.clientRect as any, - }) - }, - onKeyDown(props) { - if (props.event.key === 'Escape') { - popup?.[0].hide() - return true - } - return (component?.ref as any)?.onKeyDown(props) - }, - onExit() { - popup?.[0].destroy() - component?.destroy() - }, - } - }, -} diff --git a/web/components/editor/contract-mention.tsx b/web/components/editor/contract-mention.tsx deleted file mode 100644 index 9e967044..00000000 --- a/web/components/editor/contract-mention.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import Mention from '@tiptap/extension-mention' -import { - mergeAttributes, - NodeViewWrapper, - ReactNodeViewRenderer, -} from '@tiptap/react' -import clsx from 'clsx' -import { useContract } from 'web/hooks/use-contract' -import { ContractCard } from '../contract/contract-card' - -const name = 'contract-mention-component' - -const ContractMentionComponent = (props: any) => { - const contract = useContract(props.node.attrs.id) - - return ( - <NodeViewWrapper className={clsx(name, 'not-prose')}> - {contract && ( - <ContractCard - contract={contract} - className="my-2 w-full border border-gray-100" - /> - )} - </NodeViewWrapper> - ) -} - -/** - * Mention extension that renders React. See: - * https://tiptap.dev/guide/custom-extensions#extend-existing-extensions - * https://tiptap.dev/guide/node-views/react#render-a-react-component - */ -export const DisplayContractMention = Mention.extend({ - parseHTML: () => [{ tag: name }], - renderHTML: ({ HTMLAttributes }) => [name, mergeAttributes(HTMLAttributes)], - addNodeView: () => - ReactNodeViewRenderer(ContractMentionComponent, { - // On desktop, render cards below half-width so you can stack two - className: 'inline-block sm:w-[calc(50%-1rem)] sm:mr-1', - }), -}) diff --git a/web/hooks/use-contracts.ts b/web/hooks/use-contracts.ts index 87eefa38..1ea2f232 100644 --- a/web/hooks/use-contracts.ts +++ b/web/hooks/use-contracts.ts @@ -9,9 +9,8 @@ import { listenForNewContracts, getUserBetContracts, getUserBetContractsQuery, - listAllContracts, } from 'web/lib/firebase/contracts' -import { QueryClient, useQueryClient } from 'react-query' +import { useQueryClient } from 'react-query' import { MINUTE_MS } from 'common/util/time' export const useContracts = () => { @@ -24,12 +23,6 @@ export const useContracts = () => { return contracts } -const q = new QueryClient() -export const getCachedContracts = async () => - q.fetchQuery(['contracts'], () => listAllContracts(1000), { - staleTime: Infinity, - }) - export const useActiveContracts = () => { const [activeContracts, setActiveContracts] = useState< Contract[] | undefined diff --git a/web/package.json b/web/package.json index ba25a6e1..114ded1e 100644 --- a/web/package.json +++ b/web/package.json @@ -48,7 +48,6 @@ "nanoid": "^3.3.4", "next": "12.2.5", "node-fetch": "3.2.4", - "prosemirror-state": "1.4.1", "react": "17.0.2", "react-beautiful-dnd": "13.1.1", "react-confetti": "6.0.1", From 5a1cc4c19d3444a32764f811131530a5dd8889e0 Mon Sep 17 00:00:00 2001 From: mantikoros <sgrugett@gmail.com> Date: Thu, 15 Sep 2022 18:32:30 -0500 Subject: [PATCH 29/42] getCpmmInvested: fix NaN issue --- common/calculate.ts | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/common/calculate.ts b/common/calculate.ts index da4ce13a..e4c9ed07 100644 --- a/common/calculate.ts +++ b/common/calculate.ts @@ -142,17 +142,20 @@ function getCpmmInvested(yourBets: Bet[]) { const { outcome, shares, amount } = bet if (floatingEqual(shares, 0)) continue + const spent = totalSpent[outcome] ?? 0 + const position = totalShares[outcome] ?? 0 + if (amount > 0) { - totalShares[outcome] = (totalShares[outcome] ?? 0) + shares - totalSpent[outcome] = (totalSpent[outcome] ?? 0) + amount + totalShares[outcome] = position + shares + totalSpent[outcome] = spent + amount } else if (amount < 0) { - const averagePrice = totalSpent[outcome] / totalShares[outcome] - totalShares[outcome] = totalShares[outcome] + shares - totalSpent[outcome] = totalSpent[outcome] + averagePrice * shares + const averagePrice = position === 0 ? 0 : spent / position + totalShares[outcome] = position + shares + totalSpent[outcome] = spent + averagePrice * shares } } - return sum(Object.values(totalSpent)) + return sum([0, ...Object.values(totalSpent)]) } function getDpmInvested(yourBets: Bet[]) { From 1ce989f3d64ed6ffc5b68a6be49eba4f519cae6f Mon Sep 17 00:00:00 2001 From: ingawei <46611122+ingawei@users.noreply.github.com> Date: Thu, 15 Sep 2022 19:41:25 -0500 Subject: [PATCH 30/42] Inga/bettingfix embedfix (#885) * Revert "Revert "Inga/bettingfix (#879)"" This reverts commit 176acf959fe9fe092dfd84fb446062bf916e5734. * added embed fix --- web/components/button.tsx | 5 +- web/components/contract/contract-details.tsx | 307 +++++++++++------- .../contract/contract-info-dialog.tsx | 11 +- web/components/contract/contract-overview.tsx | 12 +- .../contract/extra-contract-actions-row.tsx | 57 +--- .../contract/like-market-button.tsx | 20 +- web/components/follow-button.tsx | 67 +++- web/components/follow-market-button.tsx | 16 +- web/pages/[username]/[contractSlug].tsx | 2 - web/pages/embed/[username]/[contractSlug].tsx | 64 ++-- web/tailwind.config.js | 2 + 11 files changed, 328 insertions(+), 235 deletions(-) diff --git a/web/components/button.tsx b/web/components/button.tsx index cb39cba8..ea9a3e88 100644 --- a/web/components/button.tsx +++ b/web/components/button.tsx @@ -11,6 +11,7 @@ export type ColorType = | 'gray' | 'gradient' | 'gray-white' + | 'highlight-blue' export function Button(props: { className?: string @@ -56,7 +57,9 @@ export function Button(props: { color === 'gradient' && 'border-none bg-gradient-to-r from-indigo-500 to-blue-500 text-white hover:from-indigo-700 hover:to-blue-700', color === 'gray-white' && - 'border-none bg-white text-gray-500 shadow-none hover:bg-gray-200', + 'text-greyscale-6 hover:bg-greyscale-2 border-none shadow-none', + color === 'highlight-blue' && + 'text-highlight-blue border-none shadow-none', className )} disabled={disabled} diff --git a/web/components/contract/contract-details.tsx b/web/components/contract/contract-details.tsx index 0a65d4d9..d5b7b796 100644 --- a/web/components/contract/contract-details.tsx +++ b/web/components/contract/contract-details.tsx @@ -1,9 +1,4 @@ -import { - ClockIcon, - DatabaseIcon, - PencilIcon, - UserGroupIcon, -} from '@heroicons/react/outline' +import { ClockIcon } from '@heroicons/react/outline' import clsx from 'clsx' import { Editor } from '@tiptap/react' import dayjs from 'dayjs' @@ -16,9 +11,8 @@ import { DateTimeTooltip } from '../datetime-tooltip' import { fromNow } from 'web/lib/util/time' import { Avatar } from '../avatar' import { useState } from 'react' -import { ContractInfoDialog } from './contract-info-dialog' import NewContractBadge from '../new-contract-badge' -import { UserFollowButton } from '../follow-button' +import { MiniUserFollowButton } from '../follow-button' import { DAY_MS } from 'common/util/time' import { useUser } from 'web/hooks/use-user' import { exhibitExts } from 'common/util/parse' @@ -34,6 +28,9 @@ import { UserLink } from 'web/components/user-link' import { FeaturedContractBadge } from 'web/components/contract/featured-contract-badge' import { Tooltip } from 'web/components/tooltip' import { useWindowSize } from 'web/hooks/use-window-size' +import { ExtraContractActionsRow } from './extra-contract-actions-row' +import { PlusCircleIcon } from '@heroicons/react/solid' +import { GroupLink } from 'common/group' export type ShowTime = 'resolve-date' | 'close-date' @@ -111,90 +108,157 @@ export function AvatarDetails(props: { ) } +export function useIsMobile() { + const { width } = useWindowSize() + return (width ?? 0) < 600 +} + export function ContractDetails(props: { contract: Contract disabled?: boolean }) { const { contract, disabled } = props - const { - closeTime, - creatorName, - creatorUsername, - creatorId, - creatorAvatarUrl, - resolutionTime, - } = contract - const { volumeLabel, resolvedDate } = contractMetrics(contract) - const user = useUser() - const isCreator = user?.id === creatorId - const [open, setOpen] = useState(false) - const { width } = useWindowSize() - const isMobile = (width ?? 0) < 600 - const groupToDisplay = getGroupLinkToDisplay(contract) - const groupInfo = groupToDisplay ? ( - <Link prefetch={false} href={groupPath(groupToDisplay.slug)}> - <a - className={clsx( - linkClass, - 'flex flex-row items-center truncate pr-0 sm:pr-2', - isMobile ? 'max-w-[140px]' : 'max-w-[250px]' - )} - > - <UserGroupIcon className="mx-1 inline h-5 w-5 shrink-0" /> - <span className="items-center truncate">{groupToDisplay.name}</span> - </a> - </Link> - ) : ( - <Button - size={'xs'} - className={'max-w-[200px] pr-2'} - color={'gray-white'} - onClick={() => !groupToDisplay && setOpen(true)} - > - <Row> - <UserGroupIcon className="mx-1 inline h-5 w-5 shrink-0" /> - <span className="truncate">No Group</span> - </Row> - </Button> - ) + const isMobile = useIsMobile() return ( - <Row className="flex-1 flex-wrap items-center gap-2 text-sm text-gray-500 md:gap-x-4 md:gap-y-2"> - <Row className="items-center gap-2"> - <Avatar - username={creatorUsername} - avatarUrl={creatorAvatarUrl} - noLink={disabled} - size={6} - /> - {disabled ? ( - creatorName - ) : ( - <UserLink - className="whitespace-nowrap" - name={creatorName} - username={creatorUsername} - short={isMobile} - /> - )} - {!disabled && <UserFollowButton userId={creatorId} small />} + <Col> + <Row className="justify-between"> + <MarketSubheader contract={contract} disabled={disabled} /> + <div className="mt-0"> + <ExtraContractActionsRow contract={contract} /> + </div> </Row> - <Row> - {disabled ? ( - groupInfo - ) : !groupToDisplay && !user ? ( - <div /> - ) : ( + {/* GROUPS */} + {isMobile && ( + <div className="mt-2"> + <MarketGroups + contract={contract} + isMobile={isMobile} + disabled={disabled} + /> + </div> + )} + </Col> + ) +} + +export function MarketSubheader(props: { + contract: Contract + disabled?: boolean +}) { + const { contract, disabled } = props + const { creatorName, creatorUsername, creatorId, creatorAvatarUrl } = contract + const { resolvedDate } = contractMetrics(contract) + const user = useUser() + const isCreator = user?.id === creatorId + const isMobile = useIsMobile() + return ( + <Row> + <Avatar + username={creatorUsername} + avatarUrl={creatorAvatarUrl} + noLink={disabled} + size={9} + className="mr-1.5" + /> + {!disabled && ( + <div className="absolute mt-3 ml-[11px]"> + <MiniUserFollowButton userId={creatorId} /> + </div> + )} + <Col className="text-greyscale-6 ml-2 flex-1 flex-wrap text-sm"> + <Row className="w-full justify-between "> + {disabled ? ( + creatorName + ) : ( + <UserLink + className="my-auto whitespace-nowrap" + name={creatorName} + username={creatorUsername} + short={isMobile} + /> + )} + </Row> + <Row className="text-2xs text-greyscale-4 gap-2 sm:text-xs"> + <CloseOrResolveTime + contract={contract} + resolvedDate={resolvedDate} + isCreator={isCreator} + /> + {!isMobile && ( + <MarketGroups + contract={contract} + isMobile={isMobile} + disabled={disabled} + /> + )} + </Row> + </Col> + </Row> + ) +} + +export function CloseOrResolveTime(props: { + contract: Contract + resolvedDate: any + isCreator: boolean +}) { + const { contract, resolvedDate, isCreator } = props + const { resolutionTime, closeTime } = contract + console.log(closeTime, resolvedDate) + if (!!closeTime || !!resolvedDate) { + return ( + <Row className="select-none items-center gap-1"> + {resolvedDate && resolutionTime ? ( + <> + <DateTimeTooltip text="Market resolved:" time={resolutionTime}> + <Row> + <div>resolved </div> + {resolvedDate} + </Row> + </DateTimeTooltip> + </> + ) : null} + + {!resolvedDate && closeTime && ( <Row> - {groupInfo} - {user && groupToDisplay && ( - <Button - size={'xs'} - color={'gray-white'} + {dayjs().isBefore(closeTime) && <div>closes </div>} + {!dayjs().isBefore(closeTime) && <div>closed </div>} + <EditableCloseDate + closeTime={closeTime} + contract={contract} + isCreator={isCreator ?? false} + /> + </Row> + )} + </Row> + ) + } else return <></> +} + +export function MarketGroups(props: { + contract: Contract + isMobile: boolean | undefined + disabled: boolean | undefined +}) { + const [open, setOpen] = useState(false) + const user = useUser() + const { contract, isMobile, disabled } = props + const groupToDisplay = getGroupLinkToDisplay(contract) + + return ( + <> + <Row className="align-middle"> + <GroupDisplay groupToDisplay={groupToDisplay} isMobile={isMobile} /> + {!disabled && ( + <Row> + {user && ( + <button + className="text-greyscale-4 hover:text-greyscale-3" onClick={() => setOpen(!open)} > - <PencilIcon className="mb-0.5 mr-0.5 inline h-4 w-4 shrink-0" /> - </Button> + <PlusCircleIcon className="mb-0.5 mr-0.5 inline h-4 w-4 shrink-0" /> + </button> )} </Row> )} @@ -208,45 +272,7 @@ export function ContractDetails(props: { <ContractGroupsList contract={contract} user={user} /> </Col> </Modal> - - {(!!closeTime || !!resolvedDate) && ( - <Row className="hidden items-center gap-1 md:inline-flex"> - {resolvedDate && resolutionTime ? ( - <> - <ClockIcon className="h-5 w-5" /> - <DateTimeTooltip text="Market resolved:" time={resolutionTime}> - {resolvedDate} - </DateTimeTooltip> - </> - ) : null} - - {!resolvedDate && closeTime && user && ( - <> - <ClockIcon className="h-5 w-5" /> - <EditableCloseDate - closeTime={closeTime} - contract={contract} - isCreator={isCreator ?? false} - /> - </> - )} - </Row> - )} - {user && ( - <> - <Row className="hidden items-center gap-1 md:inline-flex"> - <DatabaseIcon className="h-5 w-5" /> - <div className="whitespace-nowrap">{volumeLabel}</div> - </Row> - {!disabled && ( - <ContractInfoDialog - contract={contract} - className={'hidden md:inline-flex'} - /> - )} - </> - )} - </Row> + </> ) } @@ -287,12 +313,12 @@ export function ExtraMobileContractDetails(props: { !resolvedDate && closeTime && ( <Col className={'items-center text-sm text-gray-500'}> + <Row className={'text-gray-400'}>Closes </Row> <EditableCloseDate closeTime={closeTime} contract={contract} isCreator={creatorId === user?.id} /> - <Row className={'text-gray-400'}>Ends</Row> </Col> ) )} @@ -312,6 +338,45 @@ export function ExtraMobileContractDetails(props: { ) } +export function GroupDisplay(props: { + groupToDisplay?: GroupLink | null + isMobile?: boolean +}) { + const { groupToDisplay, isMobile } = props + if (groupToDisplay) { + return ( + <Link prefetch={false} href={groupPath(groupToDisplay.slug)}> + <a + className={clsx( + 'flex flex-row items-center truncate pr-1', + isMobile ? 'max-w-[140px]' : 'max-w-[250px]' + )} + > + <div className="bg-greyscale-4 hover:bg-greyscale-3 text-2xs items-center truncate rounded-full px-2 text-white sm:text-xs"> + {groupToDisplay.name} + </div> + </a> + </Link> + ) + } else + return ( + <Row + className={clsx( + 'cursor-default select-none items-center truncate pr-1', + isMobile ? 'max-w-[140px]' : 'max-w-[250px]' + )} + > + <div + className={clsx( + 'bg-greyscale-4 text-2xs items-center truncate rounded-full px-2 text-white sm:text-xs' + )} + > + No Group + </div> + </Row> + ) +} + function EditableCloseDate(props: { closeTime: number contract: Contract diff --git a/web/components/contract/contract-info-dialog.tsx b/web/components/contract/contract-info-dialog.tsx index 76a48277..26c18484 100644 --- a/web/components/contract/contract-info-dialog.tsx +++ b/web/components/contract/contract-info-dialog.tsx @@ -19,6 +19,7 @@ import ShortToggle from '../widgets/short-toggle' import { DuplicateContractButton } from '../copy-contract-button' import { Row } from '../layout/row' import { BETTORS } from 'common/user' +import { Button } from '../button' import { capitalize } from 'lodash' export const contractDetailsButtonClassName = @@ -69,19 +70,21 @@ export function ContractInfoDialog(props: { return ( <> - <button + <Button + size="sm" + color="gray-white" className={clsx(contractDetailsButtonClassName, className)} onClick={() => setOpen(true)} > <DotsHorizontalIcon - className={clsx('h-6 w-6 flex-shrink-0')} + className={clsx('h-5 w-5 flex-shrink-0')} aria-hidden="true" /> - </button> + </Button> <Modal open={open} setOpen={setOpen}> <Col className="gap-4 rounded bg-white p-6"> - <Title className="!mt-0 !mb-0" text="Market info" /> + <Title className="!mt-0 !mb-0" text="This Market" /> <table className="table-compact table-zebra table w-full text-gray-500"> <tbody> diff --git a/web/components/contract/contract-overview.tsx b/web/components/contract/contract-overview.tsx index 1bfe84de..bfb4829f 100644 --- a/web/components/contract/contract-overview.tsx +++ b/web/components/contract/contract-overview.tsx @@ -25,11 +25,11 @@ import { NumericContract, PseudoNumericContract, } from 'common/contract' -import { ContractDetails, ExtraMobileContractDetails } from './contract-details' +import { ContractDetails } from './contract-details' import { NumericGraph } from './numeric-graph' const OverviewQuestion = (props: { text: string }) => ( - <Linkify className="text-2xl text-indigo-700 md:text-3xl" text={props.text} /> + <Linkify className="text-lg text-indigo-700 sm:text-2xl" text={props.text} /> ) const BetWidget = (props: { contract: CPMMContract }) => { @@ -73,7 +73,7 @@ const BinaryOverview = (props: { contract: BinaryContract; bets: Bet[] }) => { const { contract, bets } = props return ( <Col className="gap-1 md:gap-2"> - <Col className="gap-3 px-2 sm:gap-4"> + <Col className="gap-1 px-2"> <ContractDetails contract={contract} /> <Row className="justify-between gap-4"> <OverviewQuestion text={contract.question} /> @@ -85,7 +85,6 @@ const BinaryOverview = (props: { contract: BinaryContract; bets: Bet[] }) => { </Row> <Row className="items-center justify-between gap-4 xl:hidden"> <BinaryResolutionOrChance contract={contract} /> - <ExtraMobileContractDetails contract={contract} /> {tradingAllowed(contract) && ( <BetWidget contract={contract as CPMMBinaryContract} /> )} @@ -113,10 +112,6 @@ const ChoiceOverview = (props: { </Col> <Col className={'mb-1 gap-y-2'}> <AnswersGraph contract={contract} bets={[...bets].reverse()} /> - <ExtraMobileContractDetails - contract={contract} - forceShowVolume={true} - /> </Col> </Col> ) @@ -140,7 +135,6 @@ const PseudoNumericOverview = (props: { </Row> <Row className="items-center justify-between gap-4 xl:hidden"> <PseudoNumericResolutionOrExpectation contract={contract} /> - <ExtraMobileContractDetails contract={contract} /> {tradingAllowed(contract) && <BetWidget contract={contract} />} </Row> </Col> diff --git a/web/components/contract/extra-contract-actions-row.tsx b/web/components/contract/extra-contract-actions-row.tsx index 5d5ee4d8..af5db9c3 100644 --- a/web/components/contract/extra-contract-actions-row.tsx +++ b/web/components/contract/extra-contract-actions-row.tsx @@ -11,38 +11,29 @@ import { FollowMarketButton } from 'web/components/follow-market-button' import { LikeMarketButton } from 'web/components/contract/like-market-button' import { ContractInfoDialog } from 'web/components/contract/contract-info-dialog' import { Col } from 'web/components/layout/col' -import { withTracking } from 'web/lib/service/analytics' -import { CreateChallengeModal } from 'web/components/challenges/create-challenge-modal' -import { CHALLENGES_ENABLED } from 'common/challenge' -import ChallengeIcon from 'web/lib/icons/challenge-icon' export function ExtraContractActionsRow(props: { contract: Contract }) { const { contract } = props - const { outcomeType, resolution } = contract const user = useUser() const [isShareOpen, setShareOpen] = useState(false) - const [openCreateChallengeModal, setOpenCreateChallengeModal] = - useState(false) - const showChallenge = - user && outcomeType === 'BINARY' && !resolution && CHALLENGES_ENABLED return ( - <Row className={'mt-0.5 justify-around sm:mt-2 lg:justify-start'}> + <Row> + <FollowMarketButton contract={contract} user={user} /> + {user?.id !== contract.creatorId && ( + <LikeMarketButton contract={contract} user={user} /> + )} <Button - size="lg" + size="sm" color="gray-white" className={'flex'} onClick={() => { setShareOpen(true) }} > - <Col className={'items-center sm:flex-row'}> - <ShareIcon - className={clsx('h-[24px] w-5 sm:mr-2')} - aria-hidden="true" - /> - <span>Share</span> - </Col> + <Row> + <ShareIcon className={clsx('h-5 w-5')} aria-hidden="true" /> + </Row> <ShareModal isOpen={isShareOpen} setOpen={setShareOpen} @@ -50,35 +41,7 @@ export function ExtraContractActionsRow(props: { contract: Contract }) { user={user} /> </Button> - - {showChallenge && ( - <Button - size="lg" - color="gray-white" - className="max-w-xs self-center" - onClick={withTracking( - () => setOpenCreateChallengeModal(true), - 'click challenge button' - )} - > - <Col className="items-center sm:flex-row"> - <ChallengeIcon className="mx-auto h-[24px] w-5 text-gray-500 sm:mr-2" /> - <span>Challenge</span> - </Col> - <CreateChallengeModal - isOpen={openCreateChallengeModal} - setOpen={setOpenCreateChallengeModal} - user={user} - contract={contract} - /> - </Button> - )} - - <FollowMarketButton contract={contract} user={user} /> - {user?.id !== contract.creatorId && ( - <LikeMarketButton contract={contract} user={user} /> - )} - <Col className={'justify-center md:hidden'}> + <Col className={'justify-center'}> <ContractInfoDialog contract={contract} /> </Col> </Row> diff --git a/web/components/contract/like-market-button.tsx b/web/components/contract/like-market-button.tsx index e35e3e7e..01dce32f 100644 --- a/web/components/contract/like-market-button.tsx +++ b/web/components/contract/like-market-button.tsx @@ -38,15 +38,16 @@ export function LikeMarketButton(props: { return ( <Button - size={'lg'} + size={'sm'} className={'max-w-xs self-center'} color={'gray-white'} onClick={onLike} > - <Col className={'items-center sm:flex-row'}> + <Col className={'relative items-center sm:flex-row'}> <HeartIcon className={clsx( - 'h-[24px] w-5 sm:mr-2', + 'h-5 w-5 sm:h-6 sm:w-6', + totalTipped > 0 ? 'mr-2' : '', user && (userLikedContractIds?.includes(contract.id) || (!likes && contract.likedByUserIds?.includes(user.id))) @@ -54,7 +55,18 @@ export function LikeMarketButton(props: { : '' )} /> - Tip {totalTipped > 0 ? `(${formatMoney(totalTipped)})` : ''} + {totalTipped > 0 && ( + <div + className={clsx( + 'bg-greyscale-6 absolute ml-3.5 mt-2 h-4 w-4 rounded-full align-middle text-white sm:mt-3 sm:h-5 sm:w-5 sm:px-1', + totalTipped > 99 + ? 'text-[0.4rem] sm:text-[0.5rem]' + : 'sm:text-2xs text-[0.5rem]' + )} + > + {totalTipped} + </div> + )} </Col> </Button> ) diff --git a/web/components/follow-button.tsx b/web/components/follow-button.tsx index 09495169..6344757d 100644 --- a/web/components/follow-button.tsx +++ b/web/components/follow-button.tsx @@ -1,4 +1,6 @@ +import { CheckCircleIcon, PlusCircleIcon } from '@heroicons/react/solid' import clsx from 'clsx' +import { useEffect, useRef, useState } from 'react' import { useFollows } from 'web/hooks/use-follows' import { useUser } from 'web/hooks/use-user' import { follow, unfollow } from 'web/lib/firebase/users' @@ -54,18 +56,73 @@ export function FollowButton(props: { export function UserFollowButton(props: { userId: string; small?: boolean }) { const { userId, small } = props - const currentUser = useUser() - const following = useFollows(currentUser?.id) + const user = useUser() + const following = useFollows(user?.id) const isFollowing = following?.includes(userId) - if (!currentUser || currentUser.id === userId) return null + if (!user || user.id === userId) return null return ( <FollowButton isFollowing={isFollowing} - onFollow={() => follow(currentUser.id, userId)} - onUnfollow={() => unfollow(currentUser.id, userId)} + onFollow={() => follow(user.id, userId)} + onUnfollow={() => unfollow(user.id, userId)} small={small} /> ) } + +export function MiniUserFollowButton(props: { userId: string }) { + const { userId } = props + const user = useUser() + const following = useFollows(user?.id) + const isFollowing = following?.includes(userId) + const isFirstRender = useRef(true) + const [justFollowed, setJustFollowed] = useState(false) + + useEffect(() => { + if (isFirstRender.current) { + if (isFollowing != undefined) { + isFirstRender.current = false + } + return + } + if (isFollowing) { + setJustFollowed(true) + setTimeout(() => { + setJustFollowed(false) + }, 1000) + } + }, [isFollowing]) + + if (justFollowed) { + return ( + <CheckCircleIcon + className={clsx( + 'text-highlight-blue ml-3 mt-2 h-5 w-5 rounded-full bg-white sm:mr-2' + )} + aria-hidden="true" + /> + ) + } + if ( + !user || + user.id === userId || + isFollowing || + !user || + isFollowing === undefined + ) + return null + return ( + <> + <button onClick={withTracking(() => follow(user.id, userId), 'follow')}> + <PlusCircleIcon + className={clsx( + 'text-highlight-blue hover:text-hover-blue mt-2 ml-3 h-5 w-5 rounded-full bg-white sm:mr-2' + )} + aria-hidden="true" + /> + </button> + </> + ) +} diff --git a/web/components/follow-market-button.tsx b/web/components/follow-market-button.tsx index 1dd261cb..0e65165b 100644 --- a/web/components/follow-market-button.tsx +++ b/web/components/follow-market-button.tsx @@ -25,7 +25,7 @@ export const FollowMarketButton = (props: { return ( <Button - size={'lg'} + size={'sm'} color={'gray-white'} onClick={async () => { if (!user) return firebaseLogin() @@ -56,13 +56,19 @@ export const FollowMarketButton = (props: { > {followers?.includes(user?.id ?? 'nope') ? ( <Col className={'items-center gap-x-2 sm:flex-row'}> - <EyeOffIcon className={clsx('h-6 w-6')} aria-hidden="true" /> - Unwatch + <EyeOffIcon + className={clsx('h-5 w-5 sm:h-6 sm:w-6')} + aria-hidden="true" + /> + {/* Unwatch */} </Col> ) : ( <Col className={'items-center gap-x-2 sm:flex-row'}> - <EyeIcon className={clsx('h-6 w-6')} aria-hidden="true" /> - Watch + <EyeIcon + className={clsx('h-5 w-5 sm:h-6 sm:w-6')} + aria-hidden="true" + /> + {/* Watch */} </Col> )} <WatchMarketModal diff --git a/web/pages/[username]/[contractSlug].tsx b/web/pages/[username]/[contractSlug].tsx index 2c011c90..a0b2ed50 100644 --- a/web/pages/[username]/[contractSlug].tsx +++ b/web/pages/[username]/[contractSlug].tsx @@ -37,7 +37,6 @@ import { User } from 'common/user' import { ContractComment } from 'common/comment' import { getOpenGraphProps } from 'common/contract-details' import { ContractDescription } from 'web/components/contract/contract-description' -import { ExtraContractActionsRow } from 'web/components/contract/extra-contract-actions-row' import { ContractLeaderboard, ContractTopTrades, @@ -257,7 +256,6 @@ export function ContractPageContent( )} <ContractOverview contract={contract} bets={nonChallengeBets} /> - <ExtraContractActionsRow contract={contract} /> <ContractDescription className="mb-6 px-2" contract={contract} /> {outcomeType === 'NUMERIC' && ( diff --git a/web/pages/embed/[username]/[contractSlug].tsx b/web/pages/embed/[username]/[contractSlug].tsx index fbeef88f..62dd1ae1 100644 --- a/web/pages/embed/[username]/[contractSlug].tsx +++ b/web/pages/embed/[username]/[contractSlug].tsx @@ -11,7 +11,7 @@ import { NumericResolutionOrExpectation, PseudoNumericResolutionOrExpectation, } from 'web/components/contract/contract-card' -import { ContractDetails } from 'web/components/contract/contract-details' +import { MarketSubheader } from 'web/components/contract/contract-details' import { ContractProbGraph } from 'web/components/contract/contract-prob-graph' import { NumericGraph } from 'web/components/contract/numeric-graph' import { Col } from 'web/components/layout/col' @@ -102,50 +102,40 @@ export function ContractEmbed(props: { contract: Contract; bets: Bet[] }) { return ( <Col className="h-[100vh] w-full bg-white"> - <div className="relative flex flex-col pt-2"> - <div className="px-3 text-xl text-indigo-700 md:text-2xl"> + <Row className="justify-between gap-4 px-2"> + <div className="text-xl text-indigo-700 md:text-2xl"> <SiteLink href={href}>{question}</SiteLink> </div> + {isBinary && ( + <BinaryResolutionOrChance contract={contract} probAfter={probAfter} /> + )} - <Spacer h={3} /> + {isPseudoNumeric && ( + <PseudoNumericResolutionOrExpectation contract={contract} /> + )} - <Row className="items-center justify-between gap-4 px-2"> - <ContractDetails contract={contract} disabled /> + {outcomeType === 'FREE_RESPONSE' && ( + <FreeResponseResolutionOrChance contract={contract} truncate="long" /> + )} - {(isBinary || isPseudoNumeric) && - tradingAllowed(contract) && - !betPanelOpen && ( - <Button color="gradient" onClick={() => setBetPanelOpen(true)}> - Predict - </Button> - )} + {outcomeType === 'NUMERIC' && ( + <NumericResolutionOrExpectation contract={contract} /> + )} + </Row> + <Spacer h={3} /> + <Row className="items-center justify-between gap-4 px-2"> + <MarketSubheader contract={contract} disabled /> - {isBinary && ( - <BinaryResolutionOrChance - contract={contract} - probAfter={probAfter} - className="items-center" - /> + {(isBinary || isPseudoNumeric) && + tradingAllowed(contract) && + !betPanelOpen && ( + <Button color="gradient" onClick={() => setBetPanelOpen(true)}> + Predict + </Button> )} + </Row> - {isPseudoNumeric && ( - <PseudoNumericResolutionOrExpectation contract={contract} /> - )} - - {outcomeType === 'FREE_RESPONSE' && ( - <FreeResponseResolutionOrChance - contract={contract} - truncate="long" - /> - )} - - {outcomeType === 'NUMERIC' && ( - <NumericResolutionOrExpectation contract={contract} /> - )} - </Row> - - <Spacer h={2} /> - </div> + <Spacer h={2} /> {(isBinary || isPseudoNumeric) && betPanelOpen && ( <BetInline diff --git a/web/tailwind.config.js b/web/tailwind.config.js index eb411216..7bea3ec2 100644 --- a/web/tailwind.config.js +++ b/web/tailwind.config.js @@ -26,6 +26,8 @@ module.exports = { 'greyscale-5': '#9191A7', 'greyscale-6': '#66667C', 'greyscale-7': '#111140', + 'highlight-blue': '#5BCEFF', + 'hover-blue': '#90DEFF', }, typography: { quoteless: { From 430ad1acb035f25db7c88ac6e7fe0be604942b1c Mon Sep 17 00:00:00 2001 From: mantikoros <sgrugett@gmail.com> Date: Thu, 15 Sep 2022 23:08:31 -0500 Subject: [PATCH 31/42] "unique bettors"; "Unknown" => "0" --- .../contract/contract-info-dialog.tsx | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/web/components/contract/contract-info-dialog.tsx b/web/components/contract/contract-info-dialog.tsx index 26c18484..5187030d 100644 --- a/web/components/contract/contract-info-dialog.tsx +++ b/web/components/contract/contract-info-dialog.tsx @@ -2,6 +2,7 @@ import { DotsHorizontalIcon } from '@heroicons/react/outline' import clsx from 'clsx' import dayjs from 'dayjs' import { useState } from 'react' +import { capitalize } from 'lodash' import { Contract } from 'common/contract' import { formatMoney } from 'common/util/format' @@ -20,7 +21,6 @@ import { DuplicateContractButton } from '../copy-contract-button' import { Row } from '../layout/row' import { BETTORS } from 'common/user' import { Button } from '../button' -import { capitalize } from 'lodash' export const contractDetailsButtonClassName = 'group flex items-center rounded-md px-3 py-2 text-sm font-medium cursor-pointer hover:bg-gray-100 text-gray-400 hover:text-gray-500' @@ -40,10 +40,16 @@ export function ContractInfoDialog(props: { const formatTime = (dt: number) => dayjs(dt).format('MMM DD, YYYY hh:mm a') - const { createdTime, closeTime, resolutionTime, mechanism, outcomeType, id } = - contract + const { + createdTime, + closeTime, + resolutionTime, + uniqueBettorCount, + mechanism, + outcomeType, + id, + } = contract - const bettorsCount = contract.uniqueBettorCount ?? 'Unknown' const typeDisplay = outcomeType === 'BINARY' ? 'YES / NO' @@ -134,14 +140,9 @@ export function ContractInfoDialog(props: { <td>{formatMoney(contract.volume)}</td> </tr> - {/* <tr> - <td>Creator earnings</td> - <td>{formatMoney(contract.collectedFees.creatorFee)}</td> - </tr> */} - <tr> <td>{capitalize(BETTORS)}</td> - <td>{bettorsCount}</td> + <td>{uniqueBettorCount ?? '0'}</td> </tr> <tr> From ca4a2bc7db44db7ebf7f739092a006680d733785 Mon Sep 17 00:00:00 2001 From: Austin Chen <akrolsmir@gmail.com> Date: Thu, 15 Sep 2022 22:01:51 -0700 Subject: [PATCH 32/42] Remove console log --- web/components/contract/contract-details.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/web/components/contract/contract-details.tsx b/web/components/contract/contract-details.tsx index d5b7b796..b6623625 100644 --- a/web/components/contract/contract-details.tsx +++ b/web/components/contract/contract-details.tsx @@ -205,7 +205,6 @@ export function CloseOrResolveTime(props: { }) { const { contract, resolvedDate, isCreator } = props const { resolutionTime, closeTime } = contract - console.log(closeTime, resolvedDate) if (!!closeTime || !!resolvedDate) { return ( <Row className="select-none items-center gap-1"> From 1321b95eb16f0fd5154d50c0a7614a3a80bea5c2 Mon Sep 17 00:00:00 2001 From: Austin Chen <akrolsmir@gmail.com> Date: Thu, 15 Sep 2022 23:37:17 -0700 Subject: [PATCH 33/42] %mentions for embedding contract card, take 2 (#884) * Revert "Revert "Use %mention to embed a contract card in rich text editor (#869)"" This reverts commit e0634cea6d7c0a169829c04ed061f602b4fcfb1e. * Overwrite name to prevent breakages * Fix '%' mentioning if you escape out * Cleanup: merge render functions --- web/components/editor.tsx | 19 +++++- .../editor/contract-mention-list.tsx | 68 +++++++++++++++++++ .../editor/contract-mention-suggestion.ts | 27 ++++++++ web/components/editor/contract-mention.tsx | 42 ++++++++++++ web/components/editor/mention-suggestion.ts | 25 +++++-- web/hooks/use-contracts.ts | 9 ++- web/package.json | 1 + 7 files changed, 181 insertions(+), 10 deletions(-) create mode 100644 web/components/editor/contract-mention-list.tsx create mode 100644 web/components/editor/contract-mention-suggestion.ts create mode 100644 web/components/editor/contract-mention.tsx diff --git a/web/components/editor.tsx b/web/components/editor.tsx index 745fc3c5..95f18b3f 100644 --- a/web/components/editor.tsx +++ b/web/components/editor.tsx @@ -21,6 +21,8 @@ import { FileUploadButton } from './file-upload-button' import { linkClass } from './site-link' import { mentionSuggestion } from './editor/mention-suggestion' import { DisplayMention } from './editor/mention' +import { contractMentionSuggestion } from './editor/contract-mention-suggestion' +import { DisplayContractMention } from './editor/contract-mention' import Iframe from 'common/util/tiptap-iframe' import TiptapTweet from './editor/tiptap-tweet' import { EmbedModal } from './editor/embed-modal' @@ -97,7 +99,12 @@ export function useTextEditor(props: { CharacterCount.configure({ limit: max }), simple ? DisplayImage : Image, DisplayLink, - DisplayMention.configure({ suggestion: mentionSuggestion }), + DisplayMention.configure({ + suggestion: mentionSuggestion, + }), + DisplayContractMention.configure({ + suggestion: contractMentionSuggestion, + }), Iframe, TiptapTweet, ], @@ -316,13 +323,21 @@ export function RichContent(props: { smallImage ? DisplayImage : Image, DisplayLink.configure({ openOnClick: false }), // stop link opening twice (browser still opens) DisplayMention, + DisplayContractMention.configure({ + // Needed to set a different PluginKey for Prosemirror + suggestion: contractMentionSuggestion, + }), Iframe, TiptapTweet, ], content, editable: false, }) - useEffect(() => void editor?.commands?.setContent(content), [editor, content]) + useEffect( + // Check isDestroyed here so hot reload works, see https://github.com/ueberdosis/tiptap/issues/1451#issuecomment-941988769 + () => void !editor?.isDestroyed && editor?.commands?.setContent(content), + [editor, content] + ) return <EditorContent className={className} editor={editor} /> } diff --git a/web/components/editor/contract-mention-list.tsx b/web/components/editor/contract-mention-list.tsx new file mode 100644 index 00000000..bda9d2fc --- /dev/null +++ b/web/components/editor/contract-mention-list.tsx @@ -0,0 +1,68 @@ +import { SuggestionProps } from '@tiptap/suggestion' +import clsx from 'clsx' +import { Contract } from 'common/contract' +import { forwardRef, useEffect, useImperativeHandle, useState } from 'react' +import { contractPath } from 'web/lib/firebase/contracts' +import { Avatar } from '../avatar' + +// copied from https://tiptap.dev/api/nodes/mention#usage +const M = forwardRef((props: SuggestionProps<Contract>, ref) => { + const { items: contracts, command } = props + + const [selectedIndex, setSelectedIndex] = useState(0) + useEffect(() => setSelectedIndex(0), [contracts]) + + const submitUser = (index: number) => { + const contract = contracts[index] + if (contract) + command({ id: contract.id, label: contractPath(contract) } as any) + } + + const onUp = () => + setSelectedIndex((i) => (i + contracts.length - 1) % contracts.length) + const onDown = () => setSelectedIndex((i) => (i + 1) % contracts.length) + const onEnter = () => submitUser(selectedIndex) + + useImperativeHandle(ref, () => ({ + onKeyDown: ({ event }: any) => { + if (event.key === 'ArrowUp') { + onUp() + return true + } + if (event.key === 'ArrowDown') { + onDown() + return true + } + if (event.key === 'Enter') { + onEnter() + return true + } + return false + }, + })) + + return ( + <div className="w-42 absolute z-10 overflow-x-hidden rounded-md bg-white py-1 shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none"> + {!contracts.length ? ( + <span className="m-1 whitespace-nowrap">No results...</span> + ) : ( + contracts.map((contract, i) => ( + <button + className={clsx( + 'flex h-8 w-full cursor-pointer select-none items-center gap-2 truncate px-4 hover:bg-indigo-200', + selectedIndex === i ? 'bg-indigo-500 text-white' : 'text-gray-900' + )} + onClick={() => submitUser(i)} + key={contract.id} + > + <Avatar avatarUrl={contract.creatorAvatarUrl} size="xs" /> + {contract.question} + </button> + )) + )} + </div> + ) +}) + +// Just to keep the formatting pretty +export { M as MentionList } diff --git a/web/components/editor/contract-mention-suggestion.ts b/web/components/editor/contract-mention-suggestion.ts new file mode 100644 index 00000000..39d024e7 --- /dev/null +++ b/web/components/editor/contract-mention-suggestion.ts @@ -0,0 +1,27 @@ +import type { MentionOptions } from '@tiptap/extension-mention' +import { searchInAny } from 'common/util/parse' +import { orderBy } from 'lodash' +import { getCachedContracts } from 'web/hooks/use-contracts' +import { MentionList } from './contract-mention-list' +import { PluginKey } from 'prosemirror-state' +import { makeMentionRender } from './mention-suggestion' + +type Suggestion = MentionOptions['suggestion'] + +const beginsWith = (text: string, query: string) => + text.toLocaleLowerCase().startsWith(query.toLocaleLowerCase()) + +export const contractMentionSuggestion: Suggestion = { + char: '%', + allowSpaces: true, + pluginKey: new PluginKey('contract-mention'), + items: async ({ query }) => + orderBy( + (await getCachedContracts()).filter((c) => + searchInAny(query, c.question) + ), + [(c) => [c.question].some((s) => beginsWith(s, query))], + ['desc', 'desc'] + ).slice(0, 5), + render: makeMentionRender(MentionList), +} diff --git a/web/components/editor/contract-mention.tsx b/web/components/editor/contract-mention.tsx new file mode 100644 index 00000000..ddc81bc0 --- /dev/null +++ b/web/components/editor/contract-mention.tsx @@ -0,0 +1,42 @@ +import Mention from '@tiptap/extension-mention' +import { + mergeAttributes, + NodeViewWrapper, + ReactNodeViewRenderer, +} from '@tiptap/react' +import clsx from 'clsx' +import { useContract } from 'web/hooks/use-contract' +import { ContractCard } from '../contract/contract-card' + +const name = 'contract-mention-component' + +const ContractMentionComponent = (props: any) => { + const contract = useContract(props.node.attrs.id) + + return ( + <NodeViewWrapper className={clsx(name, 'not-prose')}> + {contract && ( + <ContractCard + contract={contract} + className="my-2 w-full border border-gray-100" + /> + )} + </NodeViewWrapper> + ) +} + +/** + * Mention extension that renders React. See: + * https://tiptap.dev/guide/custom-extensions#extend-existing-extensions + * https://tiptap.dev/guide/node-views/react#render-a-react-component + */ +export const DisplayContractMention = Mention.extend({ + name: 'contract-mention', + parseHTML: () => [{ tag: name }], + renderHTML: ({ HTMLAttributes }) => [name, mergeAttributes(HTMLAttributes)], + addNodeView: () => + ReactNodeViewRenderer(ContractMentionComponent, { + // On desktop, render cards below half-width so you can stack two + className: 'inline-block sm:w-[calc(50%-1rem)] sm:mr-1', + }), +}) diff --git a/web/components/editor/mention-suggestion.ts b/web/components/editor/mention-suggestion.ts index 9f016d47..b4eeeebe 100644 --- a/web/components/editor/mention-suggestion.ts +++ b/web/components/editor/mention-suggestion.ts @@ -5,6 +5,7 @@ import { orderBy } from 'lodash' import tippy from 'tippy.js' import { getCachedUsers } from 'web/hooks/use-users' import { MentionList } from './mention-list' +type Render = Suggestion['render'] type Suggestion = MentionOptions['suggestion'] @@ -24,12 +25,16 @@ export const mentionSuggestion: Suggestion = { ], ['desc', 'desc'] ).slice(0, 5), - render: () => { + render: makeMentionRender(MentionList), +} + +export function makeMentionRender(mentionList: any): Render { + return () => { let component: ReactRenderer let popup: ReturnType<typeof tippy> return { onStart: (props) => { - component = new ReactRenderer(MentionList, { + component = new ReactRenderer(mentionList, { props, editor: props.editor, }) @@ -59,10 +64,16 @@ export const mentionSuggestion: Suggestion = { }) }, onKeyDown(props) { - if (props.event.key === 'Escape') { - popup?.[0].hide() - return true - } + if (props.event.key) + if ( + props.event.key === 'Escape' || + // Also break out of the mention if the tooltip isn't visible + (props.event.key === 'Enter' && !popup?.[0].state.isShown) + ) { + popup?.[0].destroy() + component?.destroy() + return false + } return (component?.ref as any)?.onKeyDown(props) }, onExit() { @@ -70,5 +81,5 @@ export const mentionSuggestion: Suggestion = { component?.destroy() }, } - }, + } } diff --git a/web/hooks/use-contracts.ts b/web/hooks/use-contracts.ts index 1ea2f232..87eefa38 100644 --- a/web/hooks/use-contracts.ts +++ b/web/hooks/use-contracts.ts @@ -9,8 +9,9 @@ import { listenForNewContracts, getUserBetContracts, getUserBetContractsQuery, + listAllContracts, } from 'web/lib/firebase/contracts' -import { useQueryClient } from 'react-query' +import { QueryClient, useQueryClient } from 'react-query' import { MINUTE_MS } from 'common/util/time' export const useContracts = () => { @@ -23,6 +24,12 @@ export const useContracts = () => { return contracts } +const q = new QueryClient() +export const getCachedContracts = async () => + q.fetchQuery(['contracts'], () => listAllContracts(1000), { + staleTime: Infinity, + }) + export const useActiveContracts = () => { const [activeContracts, setActiveContracts] = useState< Contract[] | undefined diff --git a/web/package.json b/web/package.json index 114ded1e..ba25a6e1 100644 --- a/web/package.json +++ b/web/package.json @@ -48,6 +48,7 @@ "nanoid": "^3.3.4", "next": "12.2.5", "node-fetch": "3.2.4", + "prosemirror-state": "1.4.1", "react": "17.0.2", "react-beautiful-dnd": "13.1.1", "react-confetti": "6.0.1", From 833ec518b42b82e53a5a1ae3010ecfba75171adb Mon Sep 17 00:00:00 2001 From: Phil <phil.bladen@gmail.com> Date: Fri, 16 Sep 2022 08:22:13 +0100 Subject: [PATCH 34/42] Twitch prerelease (#882) * Bot linking button functional. * Implemented initial prototype of new Twitch signup page. * Removed old Twitch signup page. * Moved new Twitch page to correct URL. * Twitch account linking functional. * Fixed charity link. * Changed to point to live bot server. * Slightly improve spacing and alignment on Twitch page * Tidy up, handle some errors when talking to bot * Seriously do the thing where Twitch link is hidden by default Co-authored-by: Marshall Polaris <marshall@pol.rs> --- web/components/profile/twitch-panel.tsx | 95 +++++++--- web/lib/twitch/link-twitch-account.ts | 53 ++++-- web/pages/profile.tsx | 6 +- web/pages/twitch.tsx | 230 ++++++++++++++++++++++-- web/public/twitch-glitch.svg | 21 +++ 5 files changed, 347 insertions(+), 58 deletions(-) create mode 100644 web/public/twitch-glitch.svg diff --git a/web/components/profile/twitch-panel.tsx b/web/components/profile/twitch-panel.tsx index b284b242..a37b21dc 100644 --- a/web/components/profile/twitch-panel.tsx +++ b/web/components/profile/twitch-panel.tsx @@ -6,38 +6,101 @@ import { LinkIcon } from '@heroicons/react/solid' import { usePrivateUser, useUser } from 'web/hooks/use-user' import { updatePrivateUser } from 'web/lib/firebase/users' import { track } from 'web/lib/service/analytics' -import { linkTwitchAccountRedirect } from 'web/lib/twitch/link-twitch-account' +import { + linkTwitchAccountRedirect, + updateBotEnabledForUser, +} from 'web/lib/twitch/link-twitch-account' import { copyToClipboard } from 'web/lib/util/copy' import { Button, ColorType } from './../button' import { Row } from './../layout/row' import { LoadingIndicator } from './../loading-indicator' +import { PrivateUser } from 'common/user' function BouncyButton(props: { children: ReactNode onClick?: MouseEventHandler<any> color?: ColorType + className?: string }) { - const { children, onClick, color } = props + const { children, onClick, color, className } = props return ( <Button color={color} size="lg" onClick={onClick} - className="btn h-[inherit] flex-shrink-[inherit] border-none font-normal normal-case" + className={clsx( + 'btn h-[inherit] flex-shrink-[inherit] border-none font-normal normal-case', + className + )} > {children} </Button> ) } +function BotConnectButton(props: { + privateUser: PrivateUser | null | undefined +}) { + const { privateUser } = props + const [loading, setLoading] = useState(false) + + const updateBotConnected = (connected: boolean) => async () => { + if (!privateUser) return + const twitchInfo = privateUser.twitchInfo + if (!twitchInfo) return + + const error = connected + ? 'Failed to add bot to your channel' + : 'Failed to remove bot from your channel' + const success = connected + ? 'Added bot to your channel' + : 'Removed bot from your channel' + + setLoading(true) + toast.promise( + updateBotEnabledForUser(privateUser, connected).then(() => + updatePrivateUser(privateUser.id, { + twitchInfo: { ...twitchInfo, botEnabled: connected }, + }) + ), + { loading: 'Updating bot settings...', error, success } + ) + try { + } finally { + setLoading(false) + } + } + + return ( + <> + {privateUser?.twitchInfo?.botEnabled ? ( + <BouncyButton + color="red" + onClick={updateBotConnected(false)} + className={clsx(loading && 'btn-disabled')} + > + Remove bot from your channel + </BouncyButton> + ) : ( + <BouncyButton + color="green" + onClick={updateBotConnected(true)} + className={clsx(loading && 'btn-disabled')} + > + Add bot to your channel + </BouncyButton> + )} + </> + ) +} + export function TwitchPanel() { const user = useUser() const privateUser = usePrivateUser() const twitchInfo = privateUser?.twitchInfo - const twitchName = privateUser?.twitchInfo?.twitchName - const twitchToken = privateUser?.twitchInfo?.controlToken - const twitchBotConnected = privateUser?.twitchInfo?.botEnabled + const twitchName = twitchInfo?.twitchName + const twitchToken = twitchInfo?.controlToken const linkIcon = <LinkIcon className="mr-2 h-6 w-6" aria-hidden="true" /> @@ -55,13 +118,6 @@ export function TwitchPanel() { }) } - const updateBotConnected = (connected: boolean) => async () => { - if (user && twitchInfo) { - twitchInfo.botEnabled = connected - await updatePrivateUser(user.id, { twitchInfo }) - } - } - const [twitchLoading, setTwitchLoading] = useState(false) const createLink = async () => { @@ -115,17 +171,12 @@ export function TwitchPanel() { <BouncyButton color="indigo" onClick={copyDockLink}> Copy dock link </BouncyButton> - {twitchBotConnected ? ( - <BouncyButton color="red" onClick={updateBotConnected(false)}> - Remove bot from your channel - </BouncyButton> - ) : ( - <BouncyButton color="green" onClick={updateBotConnected(true)}> - Add bot to your channel - </BouncyButton> - )} </div> </div> + <div className="mt-4" /> + <div className="flex w-full"> + <BotConnectButton privateUser={privateUser} /> + </div> </div> )} </> diff --git a/web/lib/twitch/link-twitch-account.ts b/web/lib/twitch/link-twitch-account.ts index 36fb12b5..71bc847d 100644 --- a/web/lib/twitch/link-twitch-account.ts +++ b/web/lib/twitch/link-twitch-account.ts @@ -3,29 +3,33 @@ import { generateNewApiKey } from '../api/api-key' const TWITCH_BOT_PUBLIC_URL = 'https://king-prawn-app-5btyw.ondigitalocean.app' // TODO: Add this to env config appropriately +async function postToBot(url: string, body: unknown) { + const result = await fetch(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }) + const json = await result.json() + if (!result.ok) { + throw new Error(json.message) + } else { + return json + } +} + export async function initLinkTwitchAccount( manifoldUserID: string, manifoldUserAPIKey: string ): Promise<[string, Promise<{ twitchName: string; controlToken: string }>]> { - const response = await fetch(`${TWITCH_BOT_PUBLIC_URL}/api/linkInit`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - manifoldID: manifoldUserID, - apiKey: manifoldUserAPIKey, - redirectURL: window.location.href, - }), + const response = await postToBot(`${TWITCH_BOT_PUBLIC_URL}/api/linkInit`, { + manifoldID: manifoldUserID, + apiKey: manifoldUserAPIKey, + redirectURL: window.location.href, }) - const responseData = await response.json() - if (!response.ok) { - throw new Error(responseData.message) - } const responseFetch = fetch( `${TWITCH_BOT_PUBLIC_URL}/api/linkResult?userID=${manifoldUserID}` ) - return [responseData.twitchAuthURL, responseFetch.then((r) => r.json())] + return [response.twitchAuthURL, responseFetch.then((r) => r.json())] } export async function linkTwitchAccountRedirect( @@ -39,3 +43,22 @@ export async function linkTwitchAccountRedirect( window.location.href = twitchAuthURL } + +export async function updateBotEnabledForUser( + privateUser: PrivateUser, + botEnabled: boolean +) { + if (botEnabled) { + return postToBot(`${TWITCH_BOT_PUBLIC_URL}/registerchanneltwitch`, { + apiKey: privateUser.apiKey, + }).then((r) => { + if (!r.success) throw new Error(r.message) + }) + } else { + return postToBot(`${TWITCH_BOT_PUBLIC_URL}/unregisterchanneltwitch`, { + apiKey: privateUser.apiKey, + }).then((r) => { + if (!r.success) throw new Error(r.message) + }) + } +} diff --git a/web/pages/profile.tsx b/web/pages/profile.tsx index 6b70b5d2..44a63b2d 100644 --- a/web/pages/profile.tsx +++ b/web/pages/profile.tsx @@ -1,6 +1,6 @@ import React, { useState } from 'react' import { RefreshIcon } from '@heroicons/react/outline' - +import { useRouter } from 'next/router' import { AddFundsButton } from 'web/components/add-funds-button' import { Page } from 'web/components/page' import { SEO } from 'web/components/SEO' @@ -64,6 +64,7 @@ function EditUserField(props: { export default function ProfilePage(props: { auth: { user: User; privateUser: PrivateUser } }) { + const router = useRouter() const { user, privateUser } = props.auth const [avatarUrl, setAvatarUrl] = useState(user.avatarUrl || '') const [avatarLoading, setAvatarLoading] = useState(false) @@ -237,8 +238,7 @@ export default function ProfilePage(props: { </button> </div> </div> - - <TwitchPanel /> + {router.query.twitch && <TwitchPanel />} </Col> </Col> </Page> diff --git a/web/pages/twitch.tsx b/web/pages/twitch.tsx index 7ca892e8..a21c1105 100644 --- a/web/pages/twitch.tsx +++ b/web/pages/twitch.tsx @@ -1,29 +1,34 @@ +import { PrivateUser, User } from 'common/user' +import Link from 'next/link' import { useState } from 'react' -import { Page } from 'web/components/page' +import toast from 'react-hot-toast' +import { Button } from 'web/components/button' import { Col } from 'web/components/layout/col' -import { ManifoldLogo } from 'web/components/nav/manifold-logo' -import { useSaveReferral } from 'web/hooks/use-save-referral' -import { SEO } from 'web/components/SEO' +import { Row } from 'web/components/layout/row' import { Spacer } from 'web/components/layout/spacer' +import { LoadingIndicator } from 'web/components/loading-indicator' +import { ManifoldLogo } from 'web/components/nav/manifold-logo' +import { Page } from 'web/components/page' +import { SEO } from 'web/components/SEO' +import { Title } from 'web/components/title' +import { useSaveReferral } from 'web/hooks/use-save-referral' +import { useTracking } from 'web/hooks/use-tracking' +import { usePrivateUser, useUser } from 'web/hooks/use-user' import { firebaseLogin, getUserAndPrivateUser } from 'web/lib/firebase/users' import { track } from 'web/lib/service/analytics' -import { Row } from 'web/components/layout/row' -import { Button } from 'web/components/button' -import { useTracking } from 'web/hooks/use-tracking' import { linkTwitchAccountRedirect } from 'web/lib/twitch/link-twitch-account' -import { usePrivateUser, useUser } from 'web/hooks/use-user' -import { LoadingIndicator } from 'web/components/loading-indicator' -import toast from 'react-hot-toast' -export default function TwitchLandingPage() { - useSaveReferral() - useTracking('view twitch landing page') +function TwitchPlaysManifoldMarkets(props: { + user?: User | null + privateUser?: PrivateUser | null +}) { + const { user, privateUser } = props - const user = useUser() - const privateUser = usePrivateUser() const twitchUser = privateUser?.twitchInfo?.twitchName + const [isLoading, setLoading] = useState(false) + const callback = user && privateUser ? () => linkTwitchAccountRedirect(user, privateUser) @@ -37,8 +42,6 @@ export default function TwitchLandingPage() { await linkTwitchAccountRedirect(user, privateUser) } - const [isLoading, setLoading] = useState(false) - const getStarted = async () => { try { setLoading(true) @@ -53,6 +56,191 @@ export default function TwitchLandingPage() { } } + return ( + <div> + <Row className="mb-4"> + <img + src="/twitch-glitch.svg" + className="mb-[0.4rem] mr-4 inline h-10 w-10" + ></img> + <Title + text={'Twitch plays Manifold Markets'} + className={'!-my-0 md:block'} + /> + </Row> + <Col className="gap-4"> + <div> + Similar to Twitch channel point predictions, Manifold Markets allows + you to create and feature on stream any question you like with users + predicting to earn play money. + </div> + <div> + The key difference is that Manifold's questions function more like a + stock market and viewers can buy and sell shares over the course of + the event and not just at the start. The market will eventually + resolve to yes or no at which point the winning shareholders will + receive their profit. + </div> + Start playing now by logging in with Google and typing commands in chat! + {twitchUser ? ( + <Button size="xl" color="green" className="btn-disabled self-center"> + Account connected: {twitchUser} + </Button> + ) : isLoading ? ( + <LoadingIndicator spinnerClassName="!w-11 !h-11" /> + ) : ( + <Button + size="xl" + color="gradient" + className="my-4 self-center !px-16" + onClick={getStarted} + > + Start playing + </Button> + )} + <div> + Instead of Twitch channel points we use our play money, mana (m$). All + viewers start with M$1000 and more can be earned for free and then{' '} + <Link href="/charity" className="underline"> + donated to a charity + </Link>{' '} + of their choice at no cost! + </div> + </Col> + </div> + ) +} + +function Subtitle(props: { text: string }) { + const { text } = props + return <div className="text-2xl">{text}</div> +} + +function Command(props: { command: string; desc: string }) { + const { command, desc } = props + return ( + <div> + <p className="inline font-bold">{'!' + command}</p> + {' - '} + <p className="inline">{desc}</p> + </div> + ) +} + +function TwitchChatCommands() { + return ( + <div> + <Title text="Twitch Chat Commands" className="md:block" /> + <Col className="gap-4"> + <Subtitle text="For Chat" /> + <Command command="bet yes#" desc="Bets a # of Mana on yes." /> + <Command command="bet no#" desc="Bets a # of Mana on no." /> + <Command + command="sell" + desc="Sells all shares you own. Using this command causes you to + cash out early before the market resolves. This could be profitable + (if the probability has moved towards the direction you bet) or cause + a loss, although at least you keep some Mana. For maximum profit (but + also risk) it is better to not sell and wait for a favourable + resolution." + /> + <Command command="balance" desc="Shows how much Mana you own." /> + <Command command="allin yes" desc="Bets your entire balance on yes." /> + <Command command="allin no" desc="Bets your entire balance on no." /> + + <Subtitle text="For Mods/Streamer" /> + <Command + command="create <question>" + desc="Creates and features the question. Be careful... this will override any question that is currently featured." + /> + <Command command="resolve yes" desc="Resolves the market as 'Yes'." /> + <Command command="resolve no" desc="Resolves the market as 'No'." /> + <Command + command="resolve n/a" + desc="Resolves the market as 'N/A' and refunds everyone their Mana." + /> + </Col> + </div> + ) +} + +function BotSetupStep(props: { + stepNum: number + buttonName?: string + text: string +}) { + const { stepNum, buttonName, text } = props + return ( + <Col className="flex-1"> + {buttonName && ( + <> + <Button color="green">{buttonName}</Button> + <Spacer h={4} /> + </> + )} + <div> + <p className="inline font-bold">Step {stepNum}. </p> + {text} + </div> + </Col> + ) +} + +function SetUpBot(props: { privateUser?: PrivateUser | null }) { + const { privateUser } = props + const twitchLinked = privateUser?.twitchInfo?.twitchName + return ( + <> + <Title + text={'Set up the bot for your own stream'} + className={'!mb-4 md:block'} + /> + <Col className="gap-4"> + <img + src="https://raw.githubusercontent.com/PhilBladen/ManifoldTwitchIntegration/master/docs/OBS.png" + className="!-my-2" + ></img> + To add the bot to your stream make sure you have logged in then follow + the steps below. + {!twitchLinked && ( + <Button + size="xl" + color="gradient" + className="my-4 self-center !px-16" + // onClick={getStarted} + > + Start playing + </Button> + )} + <div className="flex flex-col gap-6 sm:flex-row"> + <BotSetupStep + stepNum={1} + buttonName={twitchLinked && 'Add bot to channel'} + text="Use the button above to add the bot to your channel. Then mod it by typing in your Twitch chat: /mod ManifoldBot (or whatever you named the bot) If the bot is modded it will not work properly on the backend." + /> + <BotSetupStep + stepNum={2} + buttonName={twitchLinked && 'Overlay link'} + text="Create a new browser source in your streaming software such as OBS. Paste in the above link and resize it to your liking. We recommend setting the size to 400x400." + /> + <BotSetupStep + stepNum={3} + buttonName={twitchLinked && 'Control dock link'} + text="The bot can be controlled entirely through chat. But we made an easy to use control panel. Share the link with your mods or embed it into your OBS as a custom dock." + /> + </div> + </Col> + </> + ) +} + +export default function TwitchLandingPage() { + useSaveReferral() + useTracking('view twitch landing page') + + const user = useUser() + const privateUser = usePrivateUser() + return ( <Page> <SEO @@ -62,7 +250,7 @@ export default function TwitchLandingPage() { <div className="px-4 pt-2 md:mt-0 lg:hidden"> <ManifoldLogo /> </div> - <Col className="items-center"> + {/* <Col className="items-center"> <Col className="max-w-3xl"> <Col className="mb-6 rounded-xl sm:m-12 sm:mt-0"> <Row className="self-center"> @@ -114,6 +302,12 @@ export default function TwitchLandingPage() { )} </Col> </Col> + </Col> */} + + <Col className="max-w-3xl gap-8 rounded bg-white p-10 text-gray-600 shadow-md sm:mx-auto"> + <TwitchPlaysManifoldMarkets user={user} privateUser={privateUser} /> + <TwitchChatCommands /> + <SetUpBot privateUser={privateUser} /> </Col> </Page> ) diff --git a/web/public/twitch-glitch.svg b/web/public/twitch-glitch.svg new file mode 100644 index 00000000..3120fea7 --- /dev/null +++ b/web/public/twitch-glitch.svg @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Generator: Adobe Illustrator 23.0.6, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> +<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" + viewBox="0 0 2400 2800" style="enable-background:new 0 0 2400 2800;" xml:space="preserve"> +<style type="text/css"> + .st0{fill:#FFFFFF;} + .st1{fill:#9146FF;} +</style> +<title>Asset 2 + + + + + + + + + + + From 256fd89fd29e1f323a77cde85a978570e35268d9 Mon Sep 17 00:00:00 2001 From: ingawei <46611122+ingawei@users.noreply.github.com> Date: Fri, 16 Sep 2022 02:38:09 -0500 Subject: [PATCH 35/42] market close fix oopsies (#886) * market close fix --- web/components/contract/contract-details.tsx | 89 +++++++++++--------- 1 file changed, 51 insertions(+), 38 deletions(-) diff --git a/web/components/contract/contract-details.tsx b/web/components/contract/contract-details.tsx index b6623625..36a83f49 100644 --- a/web/components/contract/contract-details.tsx +++ b/web/components/contract/contract-details.tsx @@ -31,6 +31,7 @@ import { useWindowSize } from 'web/hooks/use-window-size' import { ExtraContractActionsRow } from './extra-contract-actions-row' import { PlusCircleIcon } from '@heroicons/react/solid' import { GroupLink } from 'common/group' +import { Subtitle } from '../subtitle' export type ShowTime = 'resolve-date' | 'close-date' @@ -427,47 +428,59 @@ function EditableCloseDate(props: { return ( <> - {isEditingCloseTime ? ( - - e.stopPropagation()} - onChange={(e) => setCloseDate(e.target.value)} - min={Date.now()} - value={closeDate} - /> - e.stopPropagation()} - onChange={(e) => setCloseHoursMinutes(e.target.value)} - min="00:00" - value={closeHoursMinutes} - /> - - - ) : ( - Date.now() ? 'Trading ends:' : 'Trading ended:'} - time={closeTime} + + + Date.now() ? 'Trading ends:' : 'Trading ended:'} + time={closeTime} + > + isCreator && setIsEditingCloseTime(true)} > - isCreator && setIsEditingCloseTime(true)} - > - {isSameDay ? ( - {fromNow(closeTime)} - ) : isSameYear ? ( - dayJsCloseTime.format('MMM D') - ) : ( - dayJsCloseTime.format('MMM D, YYYY') - )} - - - )} + {isSameDay ? ( + {fromNow(closeTime)} + ) : isSameYear ? ( + dayJsCloseTime.format('MMM D') + ) : ( + dayJsCloseTime.format('MMM D, YYYY') + )} + + ) } From 456aed467c5e0df0b6ea87e00c82901ffe3ebc4e Mon Sep 17 00:00:00 2001 From: FRC Date: Fri, 16 Sep 2022 14:32:15 +0100 Subject: [PATCH 36/42] Move tabs to sidebar (#873) * Move tabs to sidebar * Address all feedback Fix icon names Extract navbar component into a separate function Rm arrow and indentation Move group name under logo Fix visual sidebar stretchy thing Fix visual bug * Extra nits --- web/components/contract-search.tsx | 4 +- web/components/contract-select-modal.tsx | 4 +- web/components/contract/contracts-grid.tsx | 1 + web/components/nav/group-nav-bar.tsx | 94 ++++++++++++ web/components/nav/group-sidebar.tsx | 90 +++++++++++ web/components/nav/nav-bar.tsx | 34 +++-- web/components/nav/sidebar.tsx | 82 ++++++---- web/lib/icons/corner-down-right-icon.tsx | 19 +++ web/pages/experimental/home/index.tsx | 2 + web/pages/group/[...slugs]/index.tsx | 167 ++++++++++++++------- web/pages/home.tsx | 1 + 11 files changed, 389 insertions(+), 109 deletions(-) create mode 100644 web/components/nav/group-nav-bar.tsx create mode 100644 web/components/nav/group-sidebar.tsx create mode 100644 web/lib/icons/corner-down-right-icon.tsx diff --git a/web/components/contract-search.tsx b/web/components/contract-search.tsx index 6044178e..a0126b2e 100644 --- a/web/components/contract-search.tsx +++ b/web/components/contract-search.tsx @@ -389,9 +389,7 @@ function ContractSearchControls(props: { } return ( - + )} -
+
diff --git a/web/components/contract/contracts-grid.tsx b/web/components/contract/contracts-grid.tsx index fcf20f02..3da9a5d5 100644 --- a/web/components/contract/contracts-grid.tsx +++ b/web/components/contract/contracts-grid.tsx @@ -110,6 +110,7 @@ export function CreatorContractsList(props: { return ( void +}) { + const { currentPage } = props + const user = useUser() + + return ( + + ) +} + +function NavBarItem(props: { + item: Item + currentPage: string + onClick: (key: string) => void +}) { + const { item, currentPage } = props + const track = trackCallback( + `group navbar: ${item.trackingEventName ?? item.name}` + ) + + return ( + + ) +} diff --git a/web/components/nav/group-sidebar.tsx b/web/components/nav/group-sidebar.tsx new file mode 100644 index 00000000..3735adc7 --- /dev/null +++ b/web/components/nav/group-sidebar.tsx @@ -0,0 +1,90 @@ +import { ClipboardIcon, HomeIcon } from '@heroicons/react/outline' +import clsx from 'clsx' +import { useUser } from 'web/hooks/use-user' +import { ManifoldLogo } from './manifold-logo' +import { ProfileSummary } from './profile-menu' +import React from 'react' +import TrophyIcon from 'web/lib/icons/trophy-icon' +import { SignInButton } from '../sign-in-button' +import CornerDownRightIcon from 'web/lib/icons/corner-down-right-icon' +import NotificationsIcon from '../notifications-icon' +import { SidebarItem } from './sidebar' +import { buildArray } from 'common/util/array' +import { User } from 'common/user' +import { Row } from '../layout/row' +import { Col } from '../layout/col' + +const groupNavigation = [ + { name: 'Markets', key: 'markets', icon: HomeIcon }, + { name: 'About', key: 'about', icon: ClipboardIcon }, + { name: 'Leaderboard', key: 'leaderboards', icon: TrophyIcon }, +] + +const generalNavigation = (user?: User | null) => + buildArray( + user && { + name: 'Notifications', + href: `/notifications`, + key: 'notifications', + icon: NotificationsIcon, + } + ) + +export function GroupSidebar(props: { + groupName: string + className?: string + onClick: (key: string) => void + joinOrAddQuestionsButton: React.ReactNode + currentKey: string +}) { + const { className, groupName, currentKey } = props + + const user = useUser() + + return ( + + ) +} diff --git a/web/components/nav/nav-bar.tsx b/web/components/nav/nav-bar.tsx index a07fa0ad..778cdd1a 100644 --- a/web/components/nav/nav-bar.tsx +++ b/web/components/nav/nav-bar.tsx @@ -17,6 +17,8 @@ import { useRouter } from 'next/router' import NotificationsIcon from 'web/components/notifications-icon' import { useIsIframe } from 'web/hooks/use-is-iframe' import { trackCallback } from 'web/lib/service/analytics' +import { User } from 'common/user' + import { PAST_BETS } from 'common/user' function getNavigation() { @@ -35,6 +37,21 @@ const signedOutNavigation = [ { name: 'Explore', href: '/home', icon: SearchIcon }, ] +export const userProfileItem = (user: User) => ({ + name: formatMoney(user.balance), + trackingEventName: 'profile', + href: `/${user.username}?tab=${PAST_BETS}`, + icon: () => ( + + ), +}) + // From https://codepen.io/chris__sev/pen/QWGvYbL export function BottomNavBar() { const [sidebarOpen, setSidebarOpen] = useState(false) @@ -62,20 +79,7 @@ export function BottomNavBar() { ( - - ), - }} + item={userProfileItem(user)} /> )}
+ ( + return buildArray( CHALLENGES_ENABLED && { name: 'Challenges', href: '/challenges' }, [ { name: 'Groups', href: '/groups' }, @@ -156,39 +156,59 @@ function getMoreMobileNav() { export type Item = { name: string trackingEventName?: string - href: string + href?: string + key?: string icon?: React.ComponentType<{ className?: string }> } -function SidebarItem(props: { item: Item; currentPage: string }) { - const { item, currentPage } = props - return ( - - - {item.icon && ( - - +export function SidebarItem(props: { + item: Item + currentPage: string + onClick?: (key: string) => void +}) { + const { item, currentPage, onClick } = props + const isCurrentPage = + item.href != null ? item.href === currentPage : item.key === currentPage + + const sidebarItem = ( + + {item.icon && ( + ) + + if (item.href) { + return ( + + {sidebarItem} + + ) + } else { + return onClick ? ( + + ) : ( + <> + ) + } } function SidebarButton(props: { diff --git a/web/lib/icons/corner-down-right-icon.tsx b/web/lib/icons/corner-down-right-icon.tsx new file mode 100644 index 00000000..37d61afa --- /dev/null +++ b/web/lib/icons/corner-down-right-icon.tsx @@ -0,0 +1,19 @@ +export default function CornerDownRightIcon(props: { className?: string }) { + return ( + + + + + ) +} diff --git a/web/pages/experimental/home/index.tsx b/web/pages/experimental/home/index.tsx index f5734918..2d3270aa 100644 --- a/web/pages/experimental/home/index.tsx +++ b/web/pages/experimental/home/index.tsx @@ -114,6 +114,7 @@ function SearchSection(props: { } noControls maxResults={6} + headerClassName="sticky" persistPrefix={`experimental-home-${sort}`} /> @@ -135,6 +136,7 @@ function GroupSection(props: { additionalFilter={{ groupSlug: group.slug }} noControls maxResults={6} + headerClassName="sticky" persistPrefix={`experimental-home-${group.slug}`} /> diff --git a/web/pages/group/[...slugs]/index.tsx b/web/pages/group/[...slugs]/index.tsx index 70b06ac5..1edcc638 100644 --- a/web/pages/group/[...slugs]/index.tsx +++ b/web/pages/group/[...slugs]/index.tsx @@ -1,10 +1,9 @@ import React, { useState } from 'react' import Link from 'next/link' import { useRouter } from 'next/router' -import { toast } from 'react-hot-toast' +import { toast, Toaster } from 'react-hot-toast' import { Group, GROUP_CHAT_SLUG } from 'common/group' -import { Page } from 'web/components/page' import { Contract, listContractsByGroupSlug } from 'web/lib/firebase/contracts' import { addContractToGroup, @@ -30,7 +29,7 @@ import Custom404 from '../../404' import { SEO } from 'web/components/SEO' import { Linkify } from 'web/components/linkify' import { fromPropz, usePropz } from 'web/hooks/use-propz' -import { Tabs } from 'web/components/layout/tabs' + import { ChoicesToggleGroup } from 'web/components/choices-toggle-group' import { ContractSearch } from 'web/components/contract-search' import { JoinOrLeaveGroupButton } from 'web/components/groups/groups-button' @@ -49,6 +48,9 @@ import { Spacer } from 'web/components/layout/spacer' import { usePost } from 'web/hooks/use-post' import { useAdmin } from 'web/hooks/use-admin' import { track } from '@amplitude/analytics-browser' +import { GroupNavBar } from 'web/components/nav/group-nav-bar' +import { ArrowLeftIcon } from '@heroicons/react/solid' +import { GroupSidebar } from 'web/components/nav/group-sidebar' import { SelectMarketsModal } from 'web/components/contract-select-modal' import { BETTORS } from 'common/user' @@ -138,6 +140,7 @@ export default function GroupPage(props: { const user = useUser() const isAdmin = useAdmin() const memberIds = useMemberIds(group?.id ?? null) ?? props.memberIds + const [sidebarIndex, setSidebarIndex] = useState(0) useSaveReferral(user, { defaultReferrerUsername: creator.username, @@ -151,7 +154,7 @@ export default function GroupPage(props: { const isMember = user && memberIds.includes(user.id) const maxLeaderboardSize = 50 - const leaderboard = ( + const leaderboardPage = (
) - const aboutTab = ( + const aboutPage = ( {(group.aboutPostId != null || isCreator || isAdmin) && ( ) - const questionsTab = ( - + const questionsPage = ( + <> + {/* align the divs to the right */} +
+
+ +
+
+ + ) - const tabs = [ + const sidebarPages = [ { title: 'Markets', - content: questionsTab, + content: questionsPage, href: groupPath(group.slug, 'markets'), + key: 'markets', }, { title: 'Leaderboards', - content: leaderboard, + content: leaderboardPage, href: groupPath(group.slug, 'leaderboards'), + key: 'leaderboards', }, { title: 'About', - content: aboutTab, + content: aboutPage, href: groupPath(group.slug, 'about'), + key: 'about', }, ] - const tabIndex = tabs - .map((t) => t.title.toLowerCase()) - .indexOf(page ?? 'markets') + const pageContent = sidebarPages[sidebarIndex].content + const onSidebarClick = (key: string) => { + const index = sidebarPages.findIndex((t) => t.key === key) + setSidebarIndex(index) + } + + const joinOrAddQuestionsButton = ( + + ) return ( - - - - -
-
- {group.name} -
-
- -
-
-
- -
-
- - 0 ? tabIndex : 0} - tabs={tabs} - /> -
+ <> + +
+
+ + + + +
+ {pageContent} +
+
+ +
+ + ) +} + +export function TopGroupNavBar(props: { group: Group }) { + return ( +
+
+
+ + + + +
+
+

+ {props.group.name} +

+
+
+
) } @@ -264,10 +312,11 @@ function JoinOrAddQuestionsButtons(props: { group: Group user: User | null | undefined isMember: boolean + className?: string }) { const { group, user, isMember } = props return user && isMember ? ( - + ) : group.anyoneCanJoin ? ( @@ -411,9 +460,9 @@ function AddContractButton(props: { group: Group; user: User }) { return ( <> -
+
diff --git a/web/pages/home.tsx b/web/pages/home.tsx index 972aa639..50e2c35f 100644 --- a/web/pages/home.tsx +++ b/web/pages/home.tsx @@ -26,6 +26,7 @@ const Home = () => { user={user} persistPrefix="home-search" useQueryUrlParam={true} + headerClassName="sticky" /> - ) -} - -function BotConnectButton(props: { - privateUser: PrivateUser | null | undefined -}) { - const { privateUser } = props - const [loading, setLoading] = useState(false) - - const updateBotConnected = (connected: boolean) => async () => { - if (!privateUser) return - const twitchInfo = privateUser.twitchInfo - if (!twitchInfo) return - - const error = connected - ? 'Failed to add bot to your channel' - : 'Failed to remove bot from your channel' - const success = connected - ? 'Added bot to your channel' - : 'Removed bot from your channel' - - setLoading(true) - toast.promise( - updateBotEnabledForUser(privateUser, connected).then(() => - updatePrivateUser(privateUser.id, { - twitchInfo: { ...twitchInfo, botEnabled: connected }, - }) - ), - { loading: 'Updating bot settings...', error, success } - ) - try { - } finally { - setLoading(false) - } - } - - return ( - <> - {privateUser?.twitchInfo?.botEnabled ? ( - - Remove bot from your channel - - ) : ( - - Add bot to your channel - - )} - - ) -} - -export function TwitchPanel() { - const user = useUser() - const privateUser = usePrivateUser() - - const twitchInfo = privateUser?.twitchInfo - const twitchName = twitchInfo?.twitchName - const twitchToken = twitchInfo?.controlToken - - const linkIcon =